troydhanson / uthash

C macros for hash tables and more

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use UT_string as key in uthash?

icpz opened this issue · comments

Hi, thanks for this amazing work!

I'm wondering if I can make UT_string as key of a hash table? I looked for the doc but didn't find a work around.

I think an interface like this would be very convenient:

HASH_ADD_KEYFUNCTION(hh, head, key_func, key_len_func, item)

then I can define:

struct myitem {
    /* hh, */
    UT_string *key,
    /* values */
};

void *myitem_key(void *item) {
    struct myitem *p = (struct myitem *)item;
    return utstring_body(p->key);
}

size_t myitem_keylen(void *item) {
    struct myitem *p = (struct myitem *)item;
    return utstring_len(p->key);
}

and then add item as:

struct myitem *head = NULL;
HASH_ADD_KEYFUNCTION(hh, head, myitem_key, myitem_keylen, newitem);

As of 89168ce, you can achieve this goal by redefining HASH_KEYCMP and HASH_FUNCTION. Take a look at this part of the docs and see if that answers your question.

It's still not very easy or robust to do what you're trying to do, but hey, it's C. :)

I think your proposed interface is reasonably good, btw; but I would resist adding it in addition to the existing way. The existing way can (clumsily) handle keys containing padding bytes, whereas your way is less flexible because it still relies on getting a contiguous range of bytes [key, key+keylen) which must be bitwise hashable and bitwise comparable.

@Quuxplusone

Thanks for the detailed reply. I'm comprehending it. 😄

I came from C++ btw, and I'm trying to get familiar with C. :)

Thanks again.