troydhanson / uthash

C macros for hash tables and more
Other
4.18k stars 926 forks source link

Use UT_string as key in uthash? #170

Closed icpz closed 5 years ago

icpz commented 5 years ago

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);
Quuxplusone commented 5 years ago

As of 89168cea308ebc410461725adece985c78b162f3, 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.

icpz commented 5 years ago

@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.