aboutsummaryrefslogtreecommitdiff
path: root/src/hashmap.c
diff options
context:
space:
mode:
authorYaroslav de la Peña Smirnov <yps@yaroslavps.com>2021-11-28 01:27:24 +0300
committerYaroslav de la Peña Smirnov <yps@yaroslavps.com>2021-11-28 01:27:24 +0300
commitbf330c19cd3813da8a9c0ae4f48316747f3fa93a (patch)
tree653e78e541412ff2bdd3a29a2950d4d1ae5be756 /src/hashmap.c
parent282914669483405a34000ed24b541201f8d29c4b (diff)
downloadunja-bf330c19cd3813da8a9c0ae4f48316747f3fa93a.tar.gz
unja-bf330c19cd3813da8a9c0ae4f48316747f3fa93a.zip
hashmap: hashma_destroyrevela
Added function to free all of a hashmap's content before freeing the hashmap's own memory.
Diffstat (limited to 'src/hashmap.c')
-rw-r--r--src/hashmap.c47
1 files changed, 24 insertions, 23 deletions
diff --git a/src/hashmap.c b/src/hashmap.c
index 2787435..6b51d3e 100644
--- a/src/hashmap.c
+++ b/src/hashmap.c
@@ -215,37 +215,38 @@ hashmap_remove(struct hashmap *hm, const char *key)
return NULL;
}
+#define HASHMAP_WALK(hm, ...) \
+ struct node *node; \
+ struct node *next; \
+ for (size_t i = 0; i < hm->cur_cap; i++) { \
+ node = hm->buckets[i]; \
+ while (node) { \
+ next = node->next; \
+ __VA_ARGS__; \
+ node = next; \
+ } \
+ }
+
void
-hashmap_walk(struct hashmap *hm, void (*fn)(const void *key, void *value))
+hashmap_walk(struct hashmap *hm, hashmap_cb cb)
{
- struct node *node;
- struct node *next;
+ HASHMAP_WALK(hm, cb(node->key, node->value));
+}
- for (int i=0; i < hm->cur_cap; i++) {
- node = hm->buckets[i];
- while (node) {
- next = node->next;
- fn(node->key, node->value);
- node = next;
- }
- }
+void
+hashmap_destroy(struct hashmap *hm, hashmap_cb cb)
+{
+ HASHMAP_WALK(hm, cb(node->key, node->value), free(node));
+
+ free(hm->buckets);
+ free(hm);
}
void
hashmap_free(struct hashmap *hm)
{
- struct node *node;
- struct node *next;
-
- for (int i=0; i < hm->cur_cap; i++) {
- node = hm->buckets[i];
- while (node) {
- next = node->next;
- free(node);
- node = next;
- }
- }
+ HASHMAP_WALK(hm, free(node));
free(hm->buckets);
- free(hm);
+ free(hm);
}