7 * Generic implementation of hash-based key-value mappings.
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 * -------------------------------------
15 * struct long2string {
16 * struct hashmap_entry ent; // must be the first member!
18 * char value[FLEX_ARRAY]; // be careful with allocating on stack!
21 * #define COMPARE_VALUE 1
23 * static int long2string_cmp(const void *hashmap_cmp_fn_data,
24 * const struct hashmap_entry *eptr,
25 * const struct hashmap_entry *entry_or_key,
26 * const void *keydata)
28 * const char *string = keydata;
29 * unsigned flags = *(unsigned *)hashmap_cmp_fn_data;
30 * const struct long2string *e1, *e2;
32 * e1 = container_of(eptr, const struct long2string, ent);
33 * e2 = container_of(entry_or_key, const struct long2string, ent);
35 * if (flags & COMPARE_VALUE)
36 * return e1->key != e2->key ||
37 * strcmp(e1->value, string ? string : e2->value);
39 * return e1->key != e2->key;
42 * int main(int argc, char **argv)
45 * char value[255], action[32];
48 * hashmap_init(&map, long2string_cmp, &flags, 0);
50 * while (scanf("%s %ld %s", action, &key, value)) {
52 * if (!strcmp("add", action)) {
53 * struct long2string *e;
54 * FLEX_ALLOC_STR(e, value, value);
55 * hashmap_entry_init(&e->ent, memhash(&key, sizeof(long)));
57 * hashmap_add(&map, &e->ent);
60 * if (!strcmp("print_all_by_key", action)) {
61 * struct long2string k, *e;
62 * hashmap_entry_init(&k->ent, memhash(&key, sizeof(long)));
65 * flags &= ~COMPARE_VALUE;
66 * e = hashmap_get_entry(&map, &k, NULL, struct long2string, ent);
68 * printf("first: %ld %s\n", e->key, e->value);
69 * while ((e = hashmap_get_next_entry(&map, e,
70 * struct long2string, ent))) {
71 * printf("found more: %ld %s\n", e->key, e->value);
76 * if (!strcmp("has_exact_match", action)) {
77 * struct long2string *e;
78 * FLEX_ALLOC_STR(e, value, value);
79 * hashmap_entry_init(&e->ent, memhash(&key, sizeof(long)));
82 * flags |= COMPARE_VALUE;
84 * hashmap_get(&map, &e->ent, NULL) ? "" : "not ");
88 * if (!strcmp("has_exact_match_no_heap_alloc", action)) {
89 * struct long2string k;
90 * hashmap_entry_init(&k->ent, memhash(&key, sizeof(long)));
93 * flags |= COMPARE_VALUE;
95 * hashmap_get(&map, &k->ent, value) ? "" : "not ");
98 * if (!strcmp("end", action)) {
99 * hashmap_free(&map, 1);
109 * Ready-to-use hash functions for strings, using the FNV-1 algorithm (see
110 * http://www.isthe.com/chongo/tech/comp/fnv).
111 * `strhash` and `strihash` take 0-terminated strings, while `memhash` and
112 * `memihash` operate on arbitrary-length memory.
113 * `strihash` and `memihash` are case insensitive versions.
114 * `memihash_cont` is a variant of `memihash` that allows a computation to be
115 * continued with another chunk of data.
117 unsigned int strhash(const char *buf
);
118 unsigned int strihash(const char *buf
);
119 unsigned int memhash(const void *buf
, size_t len
);
120 unsigned int memihash(const void *buf
, size_t len
);
121 unsigned int memihash_cont(unsigned int hash_seed
, const void *buf
, size_t len
);
124 * Converts a cryptographic hash (e.g. SHA-1) into an int-sized hash code
125 * for use in hash tables. Cryptographic hashes are supposed to have
126 * uniform distribution, so in contrast to `memhash()`, this just copies
127 * the first `sizeof(int)` bytes without shuffling any bits. Note that
128 * the results will be different on big-endian and little-endian
129 * platforms, so they should not be stored or transferred over the net.
131 static inline unsigned int oidhash(const struct object_id
*oid
)
134 * Equivalent to 'return *(unsigned int *)oid->hash;', but safe on
135 * platforms that don't support unaligned reads.
138 memcpy(&hash
, oid
->hash
, sizeof(hash
));
143 * struct hashmap_entry is an opaque structure representing an entry in the
144 * hash table, which must be used as first member of user data structures.
145 * Ideally it should be followed by an int-sized member to prevent unused
146 * memory on 64-bit systems due to alignment.
148 struct hashmap_entry
{
150 * next points to the next entry in case of collisions (i.e. if
151 * multiple entries map to the same bucket)
153 struct hashmap_entry
*next
;
155 /* entry's hash code */
160 * User-supplied function to test two hashmap entries for equality. Shall
161 * return 0 if the entries are equal.
163 * This function is always called with non-NULL `entry` and `entry_or_key`
164 * parameters that have the same hash code.
166 * When looking up an entry, the `key` and `keydata` parameters to hashmap_get
167 * and hashmap_remove are always passed as second `entry_or_key` and third
168 * argument `keydata`, respectively. Otherwise, `keydata` is NULL.
170 * When it is too expensive to allocate a user entry (either because it is
171 * large or varialbe sized, such that it is not on the stack), then the
172 * relevant data to check for equality should be passed via `keydata`.
173 * In this case `key` can be a stripped down version of the user key data
174 * or even just a hashmap_entry having the correct hash.
176 * The `hashmap_cmp_fn_data` entry is the pointer given in the init function.
178 typedef int (*hashmap_cmp_fn
)(const void *hashmap_cmp_fn_data
,
179 const struct hashmap_entry
*entry
,
180 const struct hashmap_entry
*entry_or_key
,
181 const void *keydata
);
184 * struct hashmap is the hash table structure. Members can be used as follows,
185 * but should not be modified directly.
188 struct hashmap_entry
**table
;
190 /* Stores the comparison function specified in `hashmap_init()`. */
191 hashmap_cmp_fn cmpfn
;
192 const void *cmpfn_data
;
194 /* total number of entries (0 means the hashmap is empty) */
195 unsigned int private_size
; /* use hashmap_get_size() */
198 * tablesize is the allocated size of the hash table. A non-0 value
199 * indicates that the hashmap is initialized. It may also be useful
200 * for statistical purposes (i.e. `size / tablesize` is the current
203 unsigned int tablesize
;
205 unsigned int grow_at
;
206 unsigned int shrink_at
;
208 unsigned int do_count_items
: 1;
211 /* hashmap functions */
214 * Initializes a hashmap structure.
216 * `map` is the hashmap to initialize.
218 * The `equals_function` can be specified to compare two entries for equality.
219 * If NULL, entries are considered equal if their hash codes are equal.
221 * The `equals_function_data` parameter can be used to provide additional data
222 * (a callback cookie) that will be passed to `equals_function` each time it
223 * is called. This allows a single `equals_function` to implement multiple
224 * comparison functions.
226 * If the total number of entries is known in advance, the `initial_size`
227 * parameter may be used to preallocate a sufficiently large table and thus
228 * prevent expensive resizing. If 0, the table is dynamically resized.
230 void hashmap_init(struct hashmap
*map
,
231 hashmap_cmp_fn equals_function
,
232 const void *equals_function_data
,
233 size_t initial_size
);
236 * Frees a hashmap structure and allocated memory.
238 * If `free_entries` is true, each hashmap_entry in the map is freed as well
239 * using stdlibs free().
241 void hashmap_free(struct hashmap
*map
, int free_entries
);
243 /* hashmap_entry functions */
246 * Initializes a hashmap_entry structure.
248 * `entry` points to the entry to initialize.
249 * `hash` is the hash code of the entry.
251 * The hashmap_entry structure does not hold references to external resources,
252 * and it is safe to just discard it once you are done with it (i.e. if
253 * your structure was allocated with xmalloc(), you can just free(3) it,
254 * and if it is on stack, you can just let it go out of scope).
256 static inline void hashmap_entry_init(struct hashmap_entry
*e
,
264 * Return the number of items in the map.
266 static inline unsigned int hashmap_get_size(struct hashmap
*map
)
268 if (map
->do_count_items
)
269 return map
->private_size
;
271 BUG("hashmap_get_size: size not set");
276 * Returns the hashmap entry for the specified key, or NULL if not found.
278 * `map` is the hashmap structure.
280 * `key` is a user data structure that starts with hashmap_entry that has at
281 * least been initialized with the proper hash code (via `hashmap_entry_init`).
283 * `keydata` is a data structure that holds just enough information to check
284 * for equality to a given entry.
286 * If the key data is variable-sized (e.g. a FLEX_ARRAY string) or quite large,
287 * it is undesirable to create a full-fledged entry structure on the heap and
288 * copy all the key data into the structure.
290 * In this case, the `keydata` parameter can be used to pass
291 * variable-sized key data directly to the comparison function, and the `key`
292 * parameter can be a stripped-down, fixed size entry structure allocated on the
295 * If an entry with matching hash code is found, `key` and `keydata` are passed
296 * to `hashmap_cmp_fn` to decide whether the entry matches the key.
298 struct hashmap_entry
*hashmap_get(const struct hashmap
*map
,
299 const struct hashmap_entry
*key
,
300 const void *keydata
);
303 * Returns the hashmap entry for the specified hash code and key data,
304 * or NULL if not found.
306 * `map` is the hashmap structure.
307 * `hash` is the hash code of the entry to look up.
309 * If an entry with matching hash code is found, `keydata` is passed to
310 * `hashmap_cmp_fn` to decide whether the entry matches the key. The
311 * `entry_or_key` parameter of `hashmap_cmp_fn` points to a hashmap_entry
312 * structure that should not be used in the comparison.
314 static inline struct hashmap_entry
*hashmap_get_from_hash(
315 const struct hashmap
*map
,
319 struct hashmap_entry key
;
320 hashmap_entry_init(&key
, hash
);
321 return hashmap_get(map
, &key
, keydata
);
325 * Returns the next equal hashmap entry, or NULL if not found. This can be
326 * used to iterate over duplicate entries (see `hashmap_add`).
328 * `map` is the hashmap structure.
329 * `entry` is the hashmap_entry to start the search from, obtained via a previous
330 * call to `hashmap_get` or `hashmap_get_next`.
332 struct hashmap_entry
*hashmap_get_next(const struct hashmap
*map
,
333 const struct hashmap_entry
*entry
);
336 * Adds a hashmap entry. This allows to add duplicate entries (i.e.
337 * separate values with the same key according to hashmap_cmp_fn).
339 * `map` is the hashmap structure.
340 * `entry` is the entry to add.
342 void hashmap_add(struct hashmap
*map
, struct hashmap_entry
*entry
);
345 * Adds or replaces a hashmap entry. If the hashmap contains duplicate
346 * entries equal to the specified entry, only one of them will be replaced.
348 * `map` is the hashmap structure.
349 * `entry` is the entry to add or replace.
350 * Returns the replaced entry, or NULL if not found (i.e. the entry was added).
352 void *hashmap_put(struct hashmap
*map
, struct hashmap_entry
*entry
);
355 * Removes a hashmap entry matching the specified key. If the hashmap contains
356 * duplicate entries equal to the specified key, only one of them will be
357 * removed. Returns the removed entry, or NULL if not found.
359 * Argument explanation is the same as in `hashmap_get`.
361 void *hashmap_remove(struct hashmap
*map
, const struct hashmap_entry
*key
,
362 const void *keydata
);
365 * Returns the `bucket` an entry is stored in.
366 * Useful for multithreaded read access.
368 int hashmap_bucket(const struct hashmap
*map
, unsigned int hash
);
371 * Used to iterate over all entries of a hashmap. Note that it is
372 * not safe to add or remove entries to the hashmap while
375 struct hashmap_iter
{
377 struct hashmap_entry
*next
;
378 unsigned int tablepos
;
381 /* Initializes a `hashmap_iter` structure. */
382 void hashmap_iter_init(struct hashmap
*map
, struct hashmap_iter
*iter
);
384 /* Returns the next hashmap_entry, or NULL if there are no more entries. */
385 struct hashmap_entry
*hashmap_iter_next(struct hashmap_iter
*iter
);
387 /* Initializes the iterator and returns the first entry, if any. */
388 static inline struct hashmap_entry
*hashmap_iter_first(struct hashmap
*map
,
389 struct hashmap_iter
*iter
)
391 hashmap_iter_init(map
, iter
);
392 return hashmap_iter_next(iter
);
395 #define hashmap_iter_next_entry(iter, type, member) \
396 container_of_or_null(hashmap_iter_next(iter), type, member)
398 #define hashmap_iter_first_entry(map, iter, type, member) \
399 container_of_or_null(hashmap_iter_first(map, iter), type, member)
401 #define hashmap_for_each_entry(map, iter, var, type, member) \
402 for (var = hashmap_iter_first_entry(map, iter, type, member); \
404 var = hashmap_iter_next_entry(iter, type, member))
407 * returns a @pointer of @type matching @keyvar, or NULL if nothing found.
408 * @keyvar is a pointer of @type
409 * @member is the name of the "struct hashmap_entry" field in @type
411 #define hashmap_get_entry(map, keyvar, keydata, type, member) \
412 container_of_or_null(hashmap_get(map, &(keyvar)->member, keydata), \
415 #define hashmap_get_entry_from_hash(map, hash, keydata, type, member) \
416 container_of_or_null(hashmap_get_from_hash(map, hash, keydata), \
419 * returns the next equal @type pointer to @var, or NULL if not found.
420 * @var is a pointer of @type
421 * @member is the name of the "struct hashmap_entry" field in @type
423 #define hashmap_get_next_entry(map, var, type, member) \
424 container_of_or_null(hashmap_get_next(map, &(var)->member), \
428 * iterate @map starting from @var, where @var is a pointer of @type
429 * and @member is the name of the "struct hashmap_entry" field in @type
431 #define hashmap_for_each_entry_from(map, var, type, member) \
434 var = hashmap_get_next_entry(map, var, type, member))
437 * Disable item counting and automatic rehashing when adding/removing items.
439 * Normally, the hashmap keeps track of the number of items in the map
440 * and uses it to dynamically resize it. This (both the counting and
441 * the resizing) can cause problems when the map is being used by
442 * threaded callers (because the hashmap code does not know about the
443 * locking strategy used by the threaded callers and therefore, does
444 * not know how to protect the "private_size" counter).
446 static inline void hashmap_disable_item_counting(struct hashmap
*map
)
448 map
->do_count_items
= 0;
452 * Re-enable item couting when adding/removing items.
453 * If counting is currently disabled, it will force count them.
454 * It WILL NOT automatically rehash them.
456 static inline void hashmap_enable_item_counting(struct hashmap
*map
)
459 struct hashmap_iter iter
;
461 if (map
->do_count_items
)
464 hashmap_iter_init(map
, &iter
);
465 while (hashmap_iter_next(&iter
))
468 map
->do_count_items
= 1;
469 map
->private_size
= n
;
472 /* String interning */
475 * Returns the unique, interned version of the specified string or data,
476 * similar to the `String.intern` API in Java and .NET, respectively.
477 * Interned strings remain valid for the entire lifetime of the process.
479 * Can be used as `[x]strdup()` or `xmemdupz` replacement, except that interned
480 * strings / data must not be modified or freed.
482 * Interned strings are best used for short strings with high probability of
485 * Uses a hashmap to store the pool of interned strings.
487 const void *memintern(const void *data
, size_t len
);
488 static inline const char *strintern(const char *string
)
490 return memintern(string
, strlen(string
));