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