hashmap.hon commit Merge branch 'sd/stash-wo-user-name' (eacdb4d)
   1#ifndef HASHMAP_H
   2#define HASHMAP_H
   3
   4/*
   5 * Generic implementation of hash-based key-value mappings.
   6 *
   7 * An example that maps long to a string:
   8 * For the sake of the example this allows to lookup exact values, too
   9 * (i.e. it is operated as a set, the value is part of the key)
  10 * -------------------------------------
  11 *
  12 * struct hashmap map;
  13 * struct long2string {
  14 *     struct hashmap_entry ent; // must be the first member!
  15 *     long key;
  16 *     char value[FLEX_ARRAY];   // be careful with allocating on stack!
  17 * };
  18 *
  19 * #define COMPARE_VALUE 1
  20 *
  21 * static int long2string_cmp(const void *hashmap_cmp_fn_data,
  22 *                            const struct long2string *e1,
  23 *                            const struct long2string *e2,
  24 *                            const void *keydata)
  25 * {
  26 *     const char *string = keydata;
  27 *     unsigned flags = *(unsigned *)hashmap_cmp_fn_data;
  28 *
  29 *     if (flags & COMPARE_VALUE)
  30 *         return e1->key != e2->key ||
  31 *                  strcmp(e1->value, string ? string : e2->value);
  32 *     else
  33 *         return e1->key != e2->key;
  34 * }
  35 *
  36 * int main(int argc, char **argv)
  37 * {
  38 *     long key;
  39 *     char value[255], action[32];
  40 *     unsigned flags = 0;
  41 *
  42 *     hashmap_init(&map, (hashmap_cmp_fn) long2string_cmp, &flags, 0);
  43 *
  44 *     while (scanf("%s %ld %s", action, &key, value)) {
  45 *
  46 *         if (!strcmp("add", action)) {
  47 *             struct long2string *e;
  48 *             FLEX_ALLOC_STR(e, value, value);
  49 *             hashmap_entry_init(e, memhash(&key, sizeof(long)));
  50 *             e->key = key;
  51 *             hashmap_add(&map, e);
  52 *         }
  53 *
  54 *         if (!strcmp("print_all_by_key", action)) {
  55 *             struct long2string k, *e;
  56 *             hashmap_entry_init(&k, memhash(&key, sizeof(long)));
  57 *             k.key = key;
  58 *
  59 *             flags &= ~COMPARE_VALUE;
  60 *             e = hashmap_get(&map, &k, NULL);
  61 *             if (e) {
  62 *                 printf("first: %ld %s\n", e->key, e->value);
  63 *                 while ((e = hashmap_get_next(&map, e)))
  64 *                     printf("found more: %ld %s\n", e->key, e->value);
  65 *             }
  66 *         }
  67 *
  68 *         if (!strcmp("has_exact_match", action)) {
  69 *             struct long2string *e;
  70 *             FLEX_ALLOC_STR(e, value, value);
  71 *             hashmap_entry_init(e, memhash(&key, sizeof(long)));
  72 *             e->key = key;
  73 *
  74 *             flags |= COMPARE_VALUE;
  75 *             printf("%sfound\n", hashmap_get(&map, e, NULL) ? "" : "not ");
  76 *             free(e);
  77 *         }
  78 *
  79 *         if (!strcmp("has_exact_match_no_heap_alloc", action)) {
  80 *             struct long2string k;
  81 *             hashmap_entry_init(&k, memhash(&key, sizeof(long)));
  82 *             k.key = key;
  83 *
  84 *             flags |= COMPARE_VALUE;
  85 *             printf("%sfound\n", hashmap_get(&map, &k, value) ? "" : "not ");
  86 *         }
  87 *
  88 *         if (!strcmp("end", action)) {
  89 *             hashmap_free(&map, 1);
  90 *             break;
  91 *         }
  92 *     }
  93 *
  94 *     return 0;
  95 * }
  96 */
  97
  98/*
  99 * Ready-to-use hash functions for strings, using the FNV-1 algorithm (see
 100 * http://www.isthe.com/chongo/tech/comp/fnv).
 101 * `strhash` and `strihash` take 0-terminated strings, while `memhash` and
 102 * `memihash` operate on arbitrary-length memory.
 103 * `strihash` and `memihash` are case insensitive versions.
 104 * `memihash_cont` is a variant of `memihash` that allows a computation to be
 105 * continued with another chunk of data.
 106 */
 107extern unsigned int strhash(const char *buf);
 108extern unsigned int strihash(const char *buf);
 109extern unsigned int memhash(const void *buf, size_t len);
 110extern unsigned int memihash(const void *buf, size_t len);
 111extern unsigned int memihash_cont(unsigned int hash_seed, const void *buf, size_t len);
 112
 113/*
 114 * Converts a cryptographic hash (e.g. SHA-1) into an int-sized hash code
 115 * for use in hash tables. Cryptographic hashes are supposed to have
 116 * uniform distribution, so in contrast to `memhash()`, this just copies
 117 * the first `sizeof(int)` bytes without shuffling any bits. Note that
 118 * the results will be different on big-endian and little-endian
 119 * platforms, so they should not be stored or transferred over the net.
 120 */
 121static inline unsigned int sha1hash(const unsigned char *sha1)
 122{
 123        /*
 124         * Equivalent to 'return *(unsigned int *)sha1;', but safe on
 125         * platforms that don't support unaligned reads.
 126         */
 127        unsigned int hash;
 128        memcpy(&hash, sha1, sizeof(hash));
 129        return hash;
 130}
 131
 132/*
 133 * struct hashmap_entry is an opaque structure representing an entry in the
 134 * hash table, which must be used as first member of user data structures.
 135 * Ideally it should be followed by an int-sized member to prevent unused
 136 * memory on 64-bit systems due to alignment.
 137 */
 138struct hashmap_entry {
 139        /*
 140         * next points to the next entry in case of collisions (i.e. if
 141         * multiple entries map to the same bucket)
 142         */
 143        struct hashmap_entry *next;
 144
 145        /* entry's hash code */
 146        unsigned int hash;
 147};
 148
 149/*
 150 * User-supplied function to test two hashmap entries for equality. Shall
 151 * return 0 if the entries are equal.
 152 *
 153 * This function is always called with non-NULL `entry` and `entry_or_key`
 154 * parameters that have the same hash code.
 155 *
 156 * When looking up an entry, the `key` and `keydata` parameters to hashmap_get
 157 * and hashmap_remove are always passed as second `entry_or_key` and third
 158 * argument `keydata`, respectively. Otherwise, `keydata` is NULL.
 159 *
 160 * When it is too expensive to allocate a user entry (either because it is
 161 * large or varialbe sized, such that it is not on the stack), then the
 162 * relevant data to check for equality should be passed via `keydata`.
 163 * In this case `key` can be a stripped down version of the user key data
 164 * or even just a hashmap_entry having the correct hash.
 165 *
 166 * The `hashmap_cmp_fn_data` entry is the pointer given in the init function.
 167 */
 168typedef int (*hashmap_cmp_fn)(const void *hashmap_cmp_fn_data,
 169                              const void *entry, const void *entry_or_key,
 170                              const void *keydata);
 171
 172/*
 173 * struct hashmap is the hash table structure. Members can be used as follows,
 174 * but should not be modified directly.
 175 */
 176struct hashmap {
 177        struct hashmap_entry **table;
 178
 179        /* Stores the comparison function specified in `hashmap_init()`. */
 180        hashmap_cmp_fn cmpfn;
 181        const void *cmpfn_data;
 182
 183        /* total number of entries (0 means the hashmap is empty) */
 184        unsigned int private_size; /* use hashmap_get_size() */
 185
 186        /*
 187         * tablesize is the allocated size of the hash table. A non-0 value
 188         * indicates that the hashmap is initialized. It may also be useful
 189         * for statistical purposes (i.e. `size / tablesize` is the current
 190         * load factor).
 191         */
 192        unsigned int tablesize;
 193
 194        unsigned int grow_at;
 195        unsigned int shrink_at;
 196
 197        unsigned int do_count_items : 1;
 198};
 199
 200/* hashmap functions */
 201
 202/*
 203 * Initializes a hashmap structure.
 204 *
 205 * `map` is the hashmap to initialize.
 206 *
 207 * The `equals_function` can be specified to compare two entries for equality.
 208 * If NULL, entries are considered equal if their hash codes are equal.
 209 *
 210 * The `equals_function_data` parameter can be used to provide additional data
 211 * (a callback cookie) that will be passed to `equals_function` each time it
 212 * is called. This allows a single `equals_function` to implement multiple
 213 * comparison functions.
 214 *
 215 * If the total number of entries is known in advance, the `initial_size`
 216 * parameter may be used to preallocate a sufficiently large table and thus
 217 * prevent expensive resizing. If 0, the table is dynamically resized.
 218 */
 219extern void hashmap_init(struct hashmap *map,
 220                         hashmap_cmp_fn equals_function,
 221                         const void *equals_function_data,
 222                         size_t initial_size);
 223
 224/*
 225 * Frees a hashmap structure and allocated memory.
 226 *
 227 * If `free_entries` is true, each hashmap_entry in the map is freed as well
 228 * using stdlibs free().
 229 */
 230extern void hashmap_free(struct hashmap *map, int free_entries);
 231
 232/* hashmap_entry functions */
 233
 234/*
 235 * Initializes a hashmap_entry structure.
 236 *
 237 * `entry` points to the entry to initialize.
 238 * `hash` is the hash code of the entry.
 239 *
 240 * The hashmap_entry structure does not hold references to external resources,
 241 * and it is safe to just discard it once you are done with it (i.e. if
 242 * your structure was allocated with xmalloc(), you can just free(3) it,
 243 * and if it is on stack, you can just let it go out of scope).
 244 */
 245static inline void hashmap_entry_init(void *entry, unsigned int hash)
 246{
 247        struct hashmap_entry *e = entry;
 248        e->hash = hash;
 249        e->next = NULL;
 250}
 251
 252/*
 253 * Return the number of items in the map.
 254 */
 255static inline unsigned int hashmap_get_size(struct hashmap *map)
 256{
 257        if (map->do_count_items)
 258                return map->private_size;
 259
 260        BUG("hashmap_get_size: size not set");
 261        return 0;
 262}
 263
 264/*
 265 * Returns the hashmap entry for the specified key, or NULL if not found.
 266 *
 267 * `map` is the hashmap structure.
 268 *
 269 * `key` is a user data structure that starts with hashmap_entry that has at
 270 * least been initialized with the proper hash code (via `hashmap_entry_init`).
 271 *
 272 * `keydata` is a data structure that holds just enough information to check
 273 * for equality to a given entry.
 274 *
 275 * If the key data is variable-sized (e.g. a FLEX_ARRAY string) or quite large,
 276 * it is undesirable to create a full-fledged entry structure on the heap and
 277 * copy all the key data into the structure.
 278 *
 279 * In this case, the `keydata` parameter can be used to pass
 280 * variable-sized key data directly to the comparison function, and the `key`
 281 * parameter can be a stripped-down, fixed size entry structure allocated on the
 282 * stack.
 283 *
 284 * If an entry with matching hash code is found, `key` and `keydata` are passed
 285 * to `hashmap_cmp_fn` to decide whether the entry matches the key.
 286 */
 287extern void *hashmap_get(const struct hashmap *map, const void *key,
 288                         const void *keydata);
 289
 290/*
 291 * Returns the hashmap entry for the specified hash code and key data,
 292 * or NULL if not found.
 293 *
 294 * `map` is the hashmap structure.
 295 * `hash` is the hash code of the entry to look up.
 296 *
 297 * If an entry with matching hash code is found, `keydata` is passed to
 298 * `hashmap_cmp_fn` to decide whether the entry matches the key. The
 299 * `entry_or_key` parameter of `hashmap_cmp_fn` points to a hashmap_entry
 300 * structure that should not be used in the comparison.
 301 */
 302static inline void *hashmap_get_from_hash(const struct hashmap *map,
 303                                          unsigned int hash,
 304                                          const void *keydata)
 305{
 306        struct hashmap_entry key;
 307        hashmap_entry_init(&key, hash);
 308        return hashmap_get(map, &key, keydata);
 309}
 310
 311/*
 312 * Returns the next equal hashmap entry, or NULL if not found. This can be
 313 * used to iterate over duplicate entries (see `hashmap_add`).
 314 *
 315 * `map` is the hashmap structure.
 316 * `entry` is the hashmap_entry to start the search from, obtained via a previous
 317 * call to `hashmap_get` or `hashmap_get_next`.
 318 */
 319extern void *hashmap_get_next(const struct hashmap *map, const void *entry);
 320
 321/*
 322 * Adds a hashmap entry. This allows to add duplicate entries (i.e.
 323 * separate values with the same key according to hashmap_cmp_fn).
 324 *
 325 * `map` is the hashmap structure.
 326 * `entry` is the entry to add.
 327 */
 328extern void hashmap_add(struct hashmap *map, void *entry);
 329
 330/*
 331 * Adds or replaces a hashmap entry. If the hashmap contains duplicate
 332 * entries equal to the specified entry, only one of them will be replaced.
 333 *
 334 * `map` is the hashmap structure.
 335 * `entry` is the entry to add or replace.
 336 * Returns the replaced entry, or NULL if not found (i.e. the entry was added).
 337 */
 338extern void *hashmap_put(struct hashmap *map, void *entry);
 339
 340/*
 341 * Removes a hashmap entry matching the specified key. If the hashmap contains
 342 * duplicate entries equal to the specified key, only one of them will be
 343 * removed. Returns the removed entry, or NULL if not found.
 344 *
 345 * Argument explanation is the same as in `hashmap_get`.
 346 */
 347extern void *hashmap_remove(struct hashmap *map, const void *key,
 348                const void *keydata);
 349
 350/*
 351 * Returns the `bucket` an entry is stored in.
 352 * Useful for multithreaded read access.
 353 */
 354int hashmap_bucket(const struct hashmap *map, unsigned int hash);
 355
 356/*
 357 * Used to iterate over all entries of a hashmap. Note that it is
 358 * not safe to add or remove entries to the hashmap while
 359 * iterating.
 360 */
 361struct hashmap_iter {
 362        struct hashmap *map;
 363        struct hashmap_entry *next;
 364        unsigned int tablepos;
 365};
 366
 367/* Initializes a `hashmap_iter` structure. */
 368extern void hashmap_iter_init(struct hashmap *map, struct hashmap_iter *iter);
 369
 370/* Returns the next hashmap_entry, or NULL if there are no more entries. */
 371extern void *hashmap_iter_next(struct hashmap_iter *iter);
 372
 373/* Initializes the iterator and returns the first entry, if any. */
 374static inline void *hashmap_iter_first(struct hashmap *map,
 375                struct hashmap_iter *iter)
 376{
 377        hashmap_iter_init(map, iter);
 378        return hashmap_iter_next(iter);
 379}
 380
 381/*
 382 * Disable item counting and automatic rehashing when adding/removing items.
 383 *
 384 * Normally, the hashmap keeps track of the number of items in the map
 385 * and uses it to dynamically resize it.  This (both the counting and
 386 * the resizing) can cause problems when the map is being used by
 387 * threaded callers (because the hashmap code does not know about the
 388 * locking strategy used by the threaded callers and therefore, does
 389 * not know how to protect the "private_size" counter).
 390 */
 391static inline void hashmap_disable_item_counting(struct hashmap *map)
 392{
 393        map->do_count_items = 0;
 394}
 395
 396/*
 397 * Re-enable item couting when adding/removing items.
 398 * If counting is currently disabled, it will force count them.
 399 * It WILL NOT automatically rehash them.
 400 */
 401static inline void hashmap_enable_item_counting(struct hashmap *map)
 402{
 403        unsigned int n = 0;
 404        struct hashmap_iter iter;
 405
 406        if (map->do_count_items)
 407                return;
 408
 409        hashmap_iter_init(map, &iter);
 410        while (hashmap_iter_next(&iter))
 411                n++;
 412
 413        map->do_count_items = 1;
 414        map->private_size = n;
 415}
 416
 417/* String interning */
 418
 419/*
 420 * Returns the unique, interned version of the specified string or data,
 421 * similar to the `String.intern` API in Java and .NET, respectively.
 422 * Interned strings remain valid for the entire lifetime of the process.
 423 *
 424 * Can be used as `[x]strdup()` or `xmemdupz` replacement, except that interned
 425 * strings / data must not be modified or freed.
 426 *
 427 * Interned strings are best used for short strings with high probability of
 428 * duplicates.
 429 *
 430 * Uses a hashmap to store the pool of interned strings.
 431 */
 432extern const void *memintern(const void *data, size_t len);
 433static inline const char *strintern(const char *string)
 434{
 435        return memintern(string, strlen(string));
 436}
 437
 438#endif