diff options
Diffstat (limited to 'include/hmap.h')
-rw-r--r-- | include/hmap.h | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/include/hmap.h b/include/hmap.h new file mode 100644 index 0000000..853df1c --- /dev/null +++ b/include/hmap.h @@ -0,0 +1,53 @@ +#ifndef UNJA_HASHMAP_H +#define UNJA_HASHMAP_H +#include <stdbool.h> +#include <sys/types.h> + +#include "slice.h" + +#ifndef HASHMAP_CAP +#define HASHMAP_CAP 32 +#endif + +typedef void (hmap_cb)(const void *key, void *value); + +struct hmap { + struct hnode **buckets; + size_t cap; + size_t size; +}; + +/* allocate a new hmap */ +struct hmap *hmap_new_with_cap(size_t cap); + +#define hmap_new() hmap_new_with_cap(HASHMAP_CAP) + + +/* + * Inserts a key-value pair into the map. Returns NULL if map did not have key, + * old value if it did. + */ +void *hmap_sets(struct hmap *hm, struct slice key, void *value); +void *hmap_set(struct hmap *hm, const char *key, void *value); + +/* Returns a pointer to the value corresponding to the key. */ +void *hmap_gets(struct hmap *hm, const struct slice *key); +void *hmap_get(struct hmap *hm, const char *key); + +/* + * Removes a key from the map, returning the value at the key if the key was + * previously in the map. + */ +void *hmap_removes(struct hmap *hm, const struct slice *key); +void *hmap_remove(struct hmap *hm, const char *key); + +/* Iterate over keys in the hmap */ +void hmap_walk(struct hmap *hm, hmap_cb); + +/* free hmap related memory calling a function before freeing each node */ +void hmap_destroy(struct hmap *hm, hmap_cb cb); + +/* free hmap related memory */ +void hmap_free(struct hmap *hm); + +#endif |