From 4223904b183eae4e444e8af4d8eb5c9d1f937c71 Mon Sep 17 00:00:00 2001 From: Jake Date: Sat, 3 Aug 2024 20:51:48 -0700 Subject: [PATCH] Add rehash after double --- src/util/hashmap.c | 35 +++++++++++++++++++++++++++++++---- src/util/hashmap.h | 1 + src/util/test_util.c | 1 + 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/util/hashmap.c b/src/util/hashmap.c index 4b43521..1cb3e9a 100644 --- a/src/util/hashmap.c +++ b/src/util/hashmap.c @@ -93,11 +93,20 @@ int hm_set(struct Hashmap *h, char *key, void *value) { } void double_cap(struct Hashmap *h) { - // TODO: rehash all the old elements - // They will be in the wrong spot after this - h->buckets = realloc(h->buckets, h->cap * 2 * sizeof(struct BucketNode *)); + struct BucketNode **new_buckets = + calloc(h->cap * 2, sizeof(struct BucketNode *)); + + for (int i = 0; i < h->cap; i++) { + + if (h->buckets[i] != NULL) { + struct BucketNode *b = h->buckets[i]; + unsigned a = h->hash(b->key) % h->cap; + new_buckets[a] = b; + } + } + + h->buckets = new_buckets; - h->size = 0; h->cap = h->cap * 2; } @@ -145,3 +154,21 @@ int test_hash_set_and_get() { return 0; } + +int test_hash_set_and_double_get() { + testing_func_setup(); + struct Hashmap *h = create_hashmap(100); + + char name[100] = "jake"; + char key[10] = "test"; + + int ret = hm_set(h, key, name); + tassert(ret != -1); + + double_cap(h); + + struct BucketNode *got = hm_get(h, "test"); + tassert(strcmp(got->value, "jake") == 0); + + return 0; +} diff --git a/src/util/hashmap.h b/src/util/hashmap.h index ef57a3b..80c9b03 100644 --- a/src/util/hashmap.h +++ b/src/util/hashmap.h @@ -29,3 +29,4 @@ void double_cap(struct Hashmap *h); int test_hash_init(); int test_hash_init_and_store(); int test_hash_set_and_get(); +int test_hash_set_and_double_get(); diff --git a/src/util/test_util.c b/src/util/test_util.c index 83ea4c1..413a5f3 100644 --- a/src/util/test_util.c +++ b/src/util/test_util.c @@ -7,6 +7,7 @@ int test_util() { test_hash_init(); test_hash_init_and_store(); test_hash_set_and_get(); + test_hash_set_and_double_get(); testing_module_cleanup(); return 0;