stash: remove now superfluos help for "stash push"
[git.git] / hashmap.h
blob7cb29a6aede8e24320555e1845f8e4eb2032ade9
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 struct long2string *e1,
22 * const struct long2string *e2,
23 * const void *keydata, const void *userdata)
24 * {
25 * char *string = keydata;
26 * unsigned *flags = (unsigned*)userdata;
28 * if (flags & COMPARE_VALUE)
29 * return !(e1->key == e2->key) || (keydata ?
30 * strcmp(e1->value, keydata) : strcmp(e1->value, e2->value));
31 * else
32 * return !(e1->key == e2->key);
33 * }
35 * int main(int argc, char **argv)
36 * {
37 * long key;
38 * char *value, *action;
40 * unsigned flags = ALLOW_DUPLICATE_KEYS;
42 * hashmap_init(&map, (hashmap_cmp_fn) long2string_cmp, &flags, 0);
44 * while (scanf("%s %l %s", action, key, value)) {
46 * if (!strcmp("add", action)) {
47 * struct long2string *e;
48 * e = malloc(sizeof(struct long2string) + strlen(value));
49 * hashmap_entry_init(e, memhash(&key, sizeof(long)));
50 * e->key = key;
51 * memcpy(e->value, value, strlen(value));
52 * hashmap_add(&map, e);
53 * }
55 * if (!strcmp("print_all_by_key", action)) {
56 * flags &= ~COMPARE_VALUE;
58 * struct long2string k;
59 * hashmap_entry_init(&k, memhash(&key, sizeof(long)));
60 * k.key = key;
62 * struct long2string *e = hashmap_get(&map, &k, NULL);
63 * if (e) {
64 * printf("first: %l %s\n", e->key, e->value);
65 * while (e = hashmap_get_next(&map, e))
66 * printf("found more: %l %s\n", e->key, e->value);
67 * }
68 * }
70 * if (!strcmp("has_exact_match", action)) {
71 * flags |= COMPARE_VALUE;
73 * struct long2string *e;
74 * e = malloc(sizeof(struct long2string) + strlen(value));
75 * hashmap_entry_init(e, memhash(&key, sizeof(long)));
76 * e->key = key;
77 * memcpy(e->value, value, strlen(value));
79 * printf("%s found\n", hashmap_get(&map, e, NULL) ? "" : "not");
80 * }
82 * if (!strcmp("has_exact_match_no_heap_alloc", action)) {
83 * flags |= COMPARE_VALUE;
85 * struct long2string e;
86 * hashmap_entry_init(e, memhash(&key, sizeof(long)));
87 * e.key = key;
89 * printf("%s found\n", hashmap_get(&map, e, value) ? "" : "not");
90 * }
92 * if (!strcmp("end", action)) {
93 * hashmap_free(&map, 1);
94 * break;
95 * }
96 * }
97 * }
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.
109 extern unsigned int strhash(const char *buf);
110 extern unsigned int strihash(const char *buf);
111 extern unsigned int memhash(const void *buf, size_t len);
112 extern unsigned int memihash(const void *buf, size_t len);
113 extern unsigned int memihash_cont(unsigned int hash_seed, const void *buf, size_t len);
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.
123 static inline unsigned int sha1hash(const unsigned char *sha1)
126 * Equivalent to 'return *(unsigned int *)sha1;', but safe on
127 * platforms that don't support unaligned reads.
129 unsigned int hash;
130 memcpy(&hash, sha1, sizeof(hash));
131 return hash;
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.
140 struct hashmap_entry {
142 * next points to the next entry in case of collisions (i.e. if
143 * multiple entries map to the same bucket)
145 struct hashmap_entry *next;
147 /* entry's hash code */
148 unsigned int hash;
152 * User-supplied function to test two hashmap entries for equality. Shall
153 * return 0 if the entries are equal.
155 * This function is always called with non-NULL `entry` and `entry_or_key`
156 * parameters that have the same hash code.
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.
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.
168 * The `hashmap_cmp_fn_data` entry is the pointer given in the init function.
170 typedef int (*hashmap_cmp_fn)(const void *hashmap_cmp_fn_data,
171 const void *entry, const void *entry_or_key,
172 const void *keydata);
175 * struct hashmap is the hash table structure. Members can be used as follows,
176 * but should not be modified directly.
178 struct hashmap {
179 struct hashmap_entry **table;
181 /* Stores the comparison function specified in `hashmap_init()`. */
182 hashmap_cmp_fn cmpfn;
183 const void *cmpfn_data;
185 /* total number of entries (0 means the hashmap is empty) */
186 unsigned int private_size; /* use hashmap_get_size() */
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).
194 unsigned int tablesize;
196 unsigned int grow_at;
197 unsigned int shrink_at;
199 unsigned int do_count_items : 1;
202 /* hashmap functions */
205 * Initializes a hashmap structure.
207 * `map` is the hashmap to initialize.
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.
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.
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.
221 extern void hashmap_init(struct hashmap *map,
222 hashmap_cmp_fn equals_function,
223 const void *equals_function_data,
224 size_t initial_size);
227 * Frees a hashmap structure and allocated memory.
229 * If `free_entries` is true, each hashmap_entry in the map is freed as well
230 * using stdlibs free().
232 extern void hashmap_free(struct hashmap *map, int free_entries);
234 /* hashmap_entry functions */
237 * Initializes a hashmap_entry structure.
239 * `entry` points to the entry to initialize.
240 * `hash` is the hash code of the entry.
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).
247 static inline void hashmap_entry_init(void *entry, unsigned int hash)
249 struct hashmap_entry *e = entry;
250 e->hash = hash;
251 e->next = NULL;
255 * Return the number of items in the map.
257 static inline unsigned int hashmap_get_size(struct hashmap *map)
259 if (map->do_count_items)
260 return map->private_size;
262 BUG("hashmap_get_size: size not set");
263 return 0;
267 * Returns the hashmap entry for the specified key, or NULL if not found.
269 * `map` is the hashmap structure.
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`).
274 * `keydata` is a data structure that holds just enough information to check
275 * for equality to a given entry.
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.
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.
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.
289 extern void *hashmap_get(const struct hashmap *map, const void *key,
290 const void *keydata);
293 * Returns the hashmap entry for the specified hash code and key data,
294 * or NULL if not found.
296 * `map` is the hashmap structure.
297 * `hash` is the hash code of the entry to look up.
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.
304 static inline void *hashmap_get_from_hash(const struct hashmap *map,
305 unsigned int hash,
306 const void *keydata)
308 struct hashmap_entry key;
309 hashmap_entry_init(&key, hash);
310 return hashmap_get(map, &key, keydata);
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`).
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`.
321 extern void *hashmap_get_next(const struct hashmap *map, const void *entry);
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).
327 * `map` is the hashmap structure.
328 * `entry` is the entry to add.
330 extern void hashmap_add(struct hashmap *map, void *entry);
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.
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).
340 extern void *hashmap_put(struct hashmap *map, void *entry);
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.
347 * Argument explanation is the same as in `hashmap_get`.
349 extern void *hashmap_remove(struct hashmap *map, const void *key,
350 const void *keydata);
353 * Returns the `bucket` an entry is stored in.
354 * Useful for multithreaded read access.
356 int hashmap_bucket(const struct hashmap *map, unsigned int hash);
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.
363 struct hashmap_iter {
364 struct hashmap *map;
365 struct hashmap_entry *next;
366 unsigned int tablepos;
369 /* Initializes a `hashmap_iter` structure. */
370 extern void hashmap_iter_init(struct hashmap *map, struct hashmap_iter *iter);
372 /* Returns the next hashmap_entry, or NULL if there are no more entries. */
373 extern void *hashmap_iter_next(struct hashmap_iter *iter);
375 /* Initializes the iterator and returns the first entry, if any. */
376 static inline void *hashmap_iter_first(struct hashmap *map,
377 struct hashmap_iter *iter)
379 hashmap_iter_init(map, iter);
380 return hashmap_iter_next(iter);
384 * Disable item counting and automatic rehashing when adding/removing items.
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).
393 static inline void hashmap_disable_item_counting(struct hashmap *map)
395 map->do_count_items = 0;
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.
403 static inline void hashmap_enable_item_counting(struct hashmap *map)
405 void *item;
406 unsigned int n = 0;
407 struct hashmap_iter iter;
409 if (map->do_count_items)
410 return;
412 hashmap_iter_init(map, &iter);
413 while ((item = hashmap_iter_next(&iter)))
414 n++;
416 map->do_count_items = 1;
417 map->private_size = n;
420 /* String interning */
423 * Returns the unique, interned version of the specified string or data,
424 * similar to the `String.intern` API in Java and .NET, respectively.
425 * Interned strings remain valid for the entire lifetime of the process.
427 * Can be used as `[x]strdup()` or `xmemdupz` replacement, except that interned
428 * strings / data must not be modified or freed.
430 * Interned strings are best used for short strings with high probability of
431 * duplicates.
433 * Uses a hashmap to store the pool of interned strings.
435 extern const void *memintern(const void *data, size_t len);
436 static inline const char *strintern(const char *string)
438 return memintern(string, strlen(string));
441 #endif