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