chiark / gitweb /
s/name/unit
[elogind.git] / hashmap.h
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
3 #ifndef foohashmaphfoo
4 #define foohashmaphfoo
5
6 #include <stdbool.h>
7
8 /* Pretty straightforward hash table implementation. As a minor
9  * optimization a NULL hashmap object will be treated as empty hashmap
10  * for all read operations. That way it is not necessary to
11  * instantiate an object for each Hashmap use. */
12
13 typedef struct Hashmap Hashmap;
14 typedef struct _IteratorStruct _IteratorStruct;
15 typedef _IteratorStruct* Iterator;
16
17 #define ITERATOR_FIRST ((Iterator) 0)
18 #define ITERATOR_LAST ((Iterator) -1)
19
20 typedef unsigned (*hash_func_t)(const void *p);
21 typedef int (*compare_func_t)(const void *a, const void *b);
22
23 unsigned string_hash_func(const void *p);
24 int string_compare_func(const void *a, const void *b);
25
26 unsigned trivial_hash_func(const void *p);
27 int trivial_compare_func(const void *a, const void *b);
28
29 Hashmap *hashmap_new(hash_func_t hash_func, compare_func_t compare_func);
30 void hashmap_free(Hashmap *h);
31 Hashmap *hashmap_copy(Hashmap *h);
32 int hashmap_ensure_allocated(Hashmap **h, hash_func_t hash_func, compare_func_t compare_func);
33
34 int hashmap_put(Hashmap *h, const void *key, void *value);
35 int hashmap_replace(Hashmap *h, const void *key, void *value);
36 void* hashmap_get(Hashmap *h, const void *key);
37 void* hashmap_remove(Hashmap *h, const void *key);
38 void* hashmap_remove_value(Hashmap *h, const void *key, void *value);
39
40 int hashmap_merge(Hashmap *h, Hashmap *other);
41
42 unsigned hashmap_size(Hashmap *h);
43 bool hashmap_isempty(Hashmap *h);
44
45 void *hashmap_iterate(Hashmap *h, Iterator *i, const void **key);
46 void *hashmap_iterate_backwards(Hashmap *h, Iterator *i, const void **key);
47 void *hashmap_iterate_skip(Hashmap *h, const void *key, Iterator *i);
48
49 void hashmap_clear(Hashmap *h);
50 void *hashmap_steal_first(Hashmap *h);
51 void* hashmap_first(Hashmap *h);
52 void* hashmap_last(Hashmap *h);
53
54 #define HASHMAP_FOREACH(e, h, i) \
55         for ((i) = ITERATOR_FIRST, (e) = hashmap_iterate((h), &(i), NULL); (e); (e) = hashmap_iterate((h), &(i), NULL))
56
57 #define HASHMAP_FOREACH_KEY(e, k, h, i) \
58         for ((i) = ITERATOR_FIRST, (e) = hashmap_iterate((h), &(i), (const void**) &(k)); (e); (e) = hashmap_iterate((h), &(i), (const void**) &(k)))
59
60 #define HASHMAP_FOREACH_BACKWARDS(e, h, i) \
61         for ((i) = ITERATE_LAST, (e) = hashmap_iterate_backwards((h), &(i), NULL); (e); (e) = hashmap_iterate_backwards((h), &(i), NULL))
62
63 #endif