From 5d9c9710602f8f2aafff8dc46f560e4079606042 Mon Sep 17 00:00:00 2001 From: Nathan Fisher Date: Sat, 12 Aug 2023 00:54:43 -0400 Subject: [PATCH] Implement expanding hashmap --- hmap.c | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/hmap.c b/hmap.c index f3763db..b4342f8 100644 --- a/hmap.c +++ b/hmap.c @@ -66,9 +66,12 @@ typedef struct _map_node hmap_node; typedef struct { size_t capacity; size_t len; + size_t keysize; hmap_node *buckets; } hmap; +hmap_node* hmap_insert(hmap * map, void *key, size_t keysize, void *data); + hmap_node* hmap_node_init(void *key, size_t keysize, void *data) { hmap_node *node; uint64_t hash; @@ -101,14 +104,15 @@ void* hmap_node_attach(hmap_node *root, hmap_node *leaf) { // todo } -hmap* hmap_init() { +hmap* hmap_init(size_t keysize) { hmap* map; map = calloc(1, sizeof(hmap)); if (map == NULL) return NULL; map->len = 0; map->capacity = 64; - map->buckets = calloc(64, sizeof(size_t)); + map->keysize = keysize; + map->buckets = calloc(64, sizeof(hmap_node)); if (map->buckets == NULL) { free(map); return NULL; @@ -117,6 +121,23 @@ hmap* hmap_init() { } int hmap_expand(hmap *map) { + hmap_node *old; + hmap_node *new; + hmap_node *current; + int i; + + new = calloc(map->capacity + 64, sizeof(hmap_node)); + if (new == NULL) return 1; + old = map->buckets; + map->buckets = new; + for (i = 0; i < map->capacity; i++) { + current = &old[i]; + while (current->key != NULL) { + hmap_insert(map, current->key, map->keysize, current->data); + current = current->next; + } + } + free(old); return 0; }