Skip to content

Commit

Permalink
map: update N_BUCKETS and MAX_LOAD_FACTOR
Browse files Browse the repository at this point in the history
  • Loading branch information
tmzane committed Mar 4, 2024
1 parent b36c26b commit 42eaa8b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
7 changes: 4 additions & 3 deletions map.c
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
#include <stdlib.h>
#include <string.h>

#define INIT_N_BUCKETS 8
#define N_BUCKETS 4
#define MAX_LOAD_FACTOR 2

static uint64_t hash(const char* key);
static map* map_resize(map* m, size_t n_buckets);
Expand All @@ -33,7 +34,7 @@ map* map_new(void) {
if (m == NULL) {
return NULL;
}
if (map_resize(m, INIT_N_BUCKETS) == NULL) {
if (map_resize(m, N_BUCKETS) == NULL) {
free(m);
return NULL;
}
Expand All @@ -56,7 +57,7 @@ void* map_set(map* m, const char* key, const void* value) {
assert(value != NULL);

// TODO: shrink
if (m->n_entries >= m->n_buckets / 2) {
if (m->n_entries >= m->n_buckets * MAX_LOAD_FACTOR) {
if (map_resize(m, m->n_buckets * 2) == NULL) {
return NULL;
}
Expand Down
7 changes: 4 additions & 3 deletions map_test.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ void test_map_new(void) {
map* m = map_new();
assert(m != NULL);
assert(map_len(m) == 0);
assert(map_n_buckets(m) == 8);
assert(map_n_buckets(m) == 4);
map_free(m);
}

Expand Down Expand Up @@ -87,9 +87,10 @@ void test_map_resize(void) {
snprintf(keys[i], sizeof(keys[i]), "k%zu", i + 1);
map_set(m, keys[i], "");
}
assert(map_n_buckets(m) == 4);

assert(map_len(m) == 8);
assert(map_n_buckets(m) == 16);
map_set(m, "k9", "");
assert(map_n_buckets(m) == 8);

#ifdef DEBUG
printf("\n%s: ", __func__);
Expand Down

0 comments on commit 42eaa8b

Please sign in to comment.