Merge branch 'sg/t4051-fix'
[git/debian.git] / hashmap.h
blobd375d9cce779952057e3c5dc6340edd12fb3f99d
1 #ifndef HASHMAP_H
2 #define HASHMAP_H
4 /*
5 * Generic implementation of hash-based key-value mappings.
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 * -------------------------------------
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 * };
19 * #define COMPARE_VALUE 1
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;
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 * }
36 * int main(int argc, char **argv)
37 * {
38 * long key;
39 * char value[255], action[32];
40 * unsigned flags = 0;
42 * hashmap_init(&map, (hashmap_cmp_fn) long2string_cmp, &flags, 0);
44 * while (scanf("%s %ld %s", action, &key, value)) {
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 * }
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;
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 * }
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;
74 * flags |= COMPARE_VALUE;
75 * printf("%sfound\n", hashmap_get(&map, e, NULL) ? "" : "not ");
76 * free(e);
77 * }
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;
84 * flags |= COMPARE_VALUE;
85 * printf("%sfound\n", hashmap_get(&map, &k, value) ? "" : "not ");
86 * }
88 * if (!strcmp("end", action)) {
89 * hashmap_free(&map, 1);
90 * break;
91 * }
92 * }
94 * return 0;
95 * }
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.
107 extern unsigned int strhash(const char *buf);
108 extern unsigned int strihash(const char *buf);
109 extern unsigned int memhash(const void *buf, size_t len);
110 extern unsigned int memihash(const void *buf, size_t len);
111 extern unsigned int memihash_cont(unsigned int hash_seed, const void *buf, size_t len);
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.
121 static inline unsigned int sha1hash(const unsigned char *sha1)
124 * Equivalent to 'return *(unsigned int *)sha1;', but safe on
125 * platforms that don't support unaligned reads.
127 unsigned int hash;
128 memcpy(&hash, sha1, sizeof(hash));
129 return hash;
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.
138 struct hashmap_entry {
140 * next points to the next entry in case of collisions (i.e. if
141 * multiple entries map to the same bucket)
143 struct hashmap_entry *next;
145 /* entry's hash code */
146 unsigned int hash;
150 * User-supplied function to test two hashmap entries for equality. Shall
151 * return 0 if the entries are equal.
153 * This function is always called with non-NULL `entry` and `entry_or_key`
154 * parameters that have the same hash code.
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.
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.
166 * The `hashmap_cmp_fn_data` entry is the pointer given in the init function.
168 typedef int (*hashmap_cmp_fn)(const void *hashmap_cmp_fn_data,
169 const void *entry, const void *entry_or_key,
170 const void *keydata);
173 * struct hashmap is the hash table structure. Members can be used as follows,
174 * but should not be modified directly.
176 struct hashmap {
177 struct hashmap_entry **table;
179 /* Stores the comparison function specified in `hashmap_init()`. */
180 hashmap_cmp_fn cmpfn;
181 const void *cmpfn_data;
183 /* total number of entries (0 means the hashmap is empty) */
184 unsigned int private_size; /* use hashmap_get_size() */
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).
192 unsigned int tablesize;
194 unsigned int grow_at;
195 unsigned int shrink_at;
197 unsigned int do_count_items : 1;
200 /* hashmap functions */
203 * Initializes a hashmap structure.
205 * `map` is the hashmap to initialize.
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.
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.
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.
219 extern void hashmap_init(struct hashmap *map,
220 hashmap_cmp_fn equals_function,
221 const void *equals_function_data,
222 size_t initial_size);
225 * Frees a hashmap structure and allocated memory.
227 * If `free_entries` is true, each hashmap_entry in the map is freed as well
228 * using stdlibs free().
230 extern void hashmap_free(struct hashmap *map, int free_entries);
232 /* hashmap_entry functions */
235 * Initializes a hashmap_entry structure.
237 * `entry` points to the entry to initialize.
238 * `hash` is the hash code of the entry.
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).
245 static inline void hashmap_entry_init(void *entry, unsigned int hash)
247 struct hashmap_entry *e = entry;
248 e->hash = hash;
249 e->next = NULL;
253 * Return the number of items in the map.
255 static inline unsigned int hashmap_get_size(struct hashmap *map)
257 if (map->do_count_items)
258 return map->private_size;
260 BUG("hashmap_get_size: size not set");
261 return 0;
265 * Returns the hashmap entry for the specified key, or NULL if not found.
267 * `map` is the hashmap structure.
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`).
272 * `keydata` is a data structure that holds just enough information to check
273 * for equality to a given entry.
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.
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.
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.
287 extern void *hashmap_get(const struct hashmap *map, const void *key,
288 const void *keydata);
291 * Returns the hashmap entry for the specified hash code and key data,
292 * or NULL if not found.
294 * `map` is the hashmap structure.
295 * `hash` is the hash code of the entry to look up.
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.
302 static inline void *hashmap_get_from_hash(const struct hashmap *map,
303 unsigned int hash,
304 const void *keydata)
306 struct hashmap_entry key;
307 hashmap_entry_init(&key, hash);
308 return hashmap_get(map, &key, keydata);
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`).
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`.
319 extern void *hashmap_get_next(const struct hashmap *map, const void *entry);
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).
325 * `map` is the hashmap structure.
326 * `entry` is the entry to add.
328 extern void hashmap_add(struct hashmap *map, void *entry);
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.
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).
338 extern void *hashmap_put(struct hashmap *map, void *entry);
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.
345 * Argument explanation is the same as in `hashmap_get`.
347 extern void *hashmap_remove(struct hashmap *map, const void *key,
348 const void *keydata);
351 * Returns the `bucket` an entry is stored in.
352 * Useful for multithreaded read access.
354 int hashmap_bucket(const struct hashmap *map, unsigned int hash);
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.
361 struct hashmap_iter {
362 struct hashmap *map;
363 struct hashmap_entry *next;
364 unsigned int tablepos;
367 /* Initializes a `hashmap_iter` structure. */
368 extern void hashmap_iter_init(struct hashmap *map, struct hashmap_iter *iter);
370 /* Returns the next hashmap_entry, or NULL if there are no more entries. */
371 extern void *hashmap_iter_next(struct hashmap_iter *iter);
373 /* Initializes the iterator and returns the first entry, if any. */
374 static inline void *hashmap_iter_first(struct hashmap *map,
375 struct hashmap_iter *iter)
377 hashmap_iter_init(map, iter);
378 return hashmap_iter_next(iter);
382 * Disable item counting and automatic rehashing when adding/removing items.
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).
391 static inline void hashmap_disable_item_counting(struct hashmap *map)
393 map->do_count_items = 0;
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.
401 static inline void hashmap_enable_item_counting(struct hashmap *map)
403 unsigned int n = 0;
404 struct hashmap_iter iter;
406 if (map->do_count_items)
407 return;
409 hashmap_iter_init(map, &iter);
410 while (hashmap_iter_next(&iter))
411 n++;
413 map->do_count_items = 1;
414 map->private_size = n;
417 /* String interning */
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.
424 * Can be used as `[x]strdup()` or `xmemdupz` replacement, except that interned
425 * strings / data must not be modified or freed.
427 * Interned strings are best used for short strings with high probability of
428 * duplicates.
430 * Uses a hashmap to store the pool of interned strings.
432 extern const void *memintern(const void *data, size_t len);
433 static inline const char *strintern(const char *string)
435 return memintern(string, strlen(string));
438 #endif