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