Skip to content

Commit

Permalink
Add rehash after double
Browse files Browse the repository at this point in the history
  • Loading branch information
JakeRoggenbuck committed Aug 4, 2024
1 parent 3a45451 commit 4223904
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
35 changes: 31 additions & 4 deletions src/util/hashmap.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -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;
}
1 change: 1 addition & 0 deletions src/util/hashmap.h
Original file line number Diff line number Diff line change
Expand Up @@ -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();
1 change: 1 addition & 0 deletions src/util/test_util.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 4223904

Please sign in to comment.