7 #define DEFAULT_CAPACITY 64
20 void (*key_dtor)(void *);
21 void (*val_dtor)(void *);
28 hm_new(size_t capacity, hashfn *hash,
29 comparator *cmp, void *aux,
30 void (*key_dtor)(void *),
31 void (*val_dtor)(void *))
36 capacity = DEFAULT_CAPACITY;
37 hashmap *h = malloc(sizeof *h);
42 .buckets = malloc(capacity * sizeof *h->buckets),
53 for (i = 0; i < capacity; i++)
54 h->buckets[i] = NULL; /* in case allocation fails part-way */
55 for (i = 0; i < capacity; i++)
56 if (!(h->buckets[i] = l_new(NULL))) /* XXX: proper dtor */
72 for (size_t i = 0; i < h->capacity; i++)
73 l_free(h->buckets[i]);
80 hm_length(const hashmap *h)
85 for (n = i = 0; i < h->capacity; i++)
86 n += l_length(h->buckets[i]);
91 hm_is_empty(const hashmap *h)
93 return hm_length(h) == 0;
97 hm_at(const hashmap *h, const void *key)
101 list *bucket = h->buckets[h->hash(key) % h->capacity];
102 list_item *li = l_find(bucket, key, h->cmp, h->cmp_aux);
105 return ((struct pair*)li->data)->v;
109 hm_insert(hashmap *h, void *key, void *val)
113 list *bucket = h->buckets[h->hash(key) % h->capacity];
114 list_item *li = l_find(bucket, key, h->cmp, h->cmp_aux);
117 struct pair *p = (struct pair*)li->data;
118 if (p->v != val && h->val_dtor)
125 struct pair *p = malloc(sizeof *p);
128 *p = (struct pair){.k = key, .v = val};
135 hm_remove(hashmap *h, void *key)
139 list *bucket = h->buckets[h->hash(key) % h->capacity];
140 list_item *li = l_find(bucket, key, h->cmp, h->cmp_aux);
143 l_remove(bucket, li);
144 /* XXX: free li and pair */
153 for (size_t i = 0; i < h->capacity; i++)
154 l_clear(h->buckets[i]);