7 #define DEFAULT_CAPACITY 64
30 _hm_free_pair(void *x, void *aux)
33 struct map_pair *p = x;
35 h->key_dtor(p->k, h->dtor_aux);
37 h->val_dtor(p->v, h->dtor_aux);
42 hm_new(size_t capacity, hashfn *hash,
43 comparator *cmp, void *cmp_aux)
48 capacity = DEFAULT_CAPACITY;
49 hashmap *h = malloc(sizeof *h);
54 .buckets = malloc(capacity * sizeof *h->buckets),
63 for (i = 0; i < capacity; i++)
64 h->buckets[i] = NULL; /* in case allocation fails part-way */
65 for (i = 0; i < capacity; i++)
67 if (!(h->buckets[i] = l_new()))
69 l_dtor(h->buckets[i], _hm_free_pair, h);
80 hm_dtor(hashmap *h, dtor *key_dtor, dtor *val_dtor, void *dtor_aux)
84 h->key_dtor = key_dtor;
85 h->val_dtor = val_dtor;
86 h->dtor_aux = dtor_aux;
96 for (size_t i = 0; i < h->capacity; i++)
97 l_free(h->buckets[i]);
104 hm_length(const hashmap *h)
109 for (n = i = 0; i < h->capacity; i++)
110 n += l_length(h->buckets[i]);
115 hm_is_empty(const hashmap *h)
117 return hm_length(h) == 0;
120 /* kinda weird assumption: p is struct pair*, k is type of p->k */
122 _hm_cmp(const void *p, const void *k, void *aux)
124 assert(p); assert(k); assert(aux);
126 return h->cmp(((const struct map_pair *)p)->k, k, h->cmp_aux);
130 hm_at(const hashmap *h, const void *key)
134 list *bucket = h->buckets[h->hash(key) % h->capacity];
135 list_item *li = l_find(bucket, key, _hm_cmp, (void*)h);
138 return ((struct map_pair*)li->data)->v;
142 hm_insert(hashmap *h, void *key, void *val)
146 list *bucket = h->buckets[h->hash(key) % h->capacity];
147 list_item *li = l_find(bucket, key, _hm_cmp, h);
150 struct map_pair *p = (struct map_pair*)li->data;
151 if (p->v != val && h->val_dtor)
152 h->val_dtor(p->v, h->dtor_aux);
157 struct map_pair *p = malloc(sizeof *p);
160 *p = (struct map_pair){.k = key, .v = val};
167 hm_remove(hashmap *h, void *key)
171 list *bucket = h->buckets[h->hash(key) % h->capacity];
172 list_item *li = l_find(bucket, key, _hm_cmp, h);
175 _hm_free_pair(li->data, h);
176 l_remove(bucket, li);
185 for (size_t i = 0; i < h->capacity; i++)
186 l_clear(h->buckets[i]);
190 hm_iter_begin(hashmap *h)
194 hm_iter *i = malloc(sizeof *i);
197 *i = (hm_iter){.h = h};
202 hm_iter_next(hm_iter *i)
206 while (!i->offset && i->bucket < i->h->capacity)
207 i->offset = l_first(i->h->buckets[i->bucket++]);
210 struct map_pair *p = i->offset->data;
211 i->offset = i->offset->next;
216 hm_iter_free(hm_iter *i)