aboutsummaryrefslogtreecommitdiff
path: root/include/hmap.h
blob: 853df1cd8157018f77596a8d10ba7bcecfe2abdf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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