Skip to content

Commit

Permalink
Add start of get and set
Browse files Browse the repository at this point in the history
  • Loading branch information
JakeRoggenbuck committed Jul 31, 2024
1 parent 53410bb commit 169490d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
37 changes: 34 additions & 3 deletions src/util/hashmap.c
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,39 @@ struct BucketNode *create_bucket(void *key, void *value) {
return b;
}

struct BucketNode *hm_get(void *key);
struct BucketNode *hm_get(struct Hashmap *h, void *key) {
unsigned a = h->hash(key) % h->cap;

void hm_set(void *key, void *value);
struct BucketNode *b = h->buckets[a];
if (b != NULL) {

void double_cap();
// Check if key is the same, because the hash might have collided
while (!h->equals(key, b->key)) {
b = b->next;
}
return b;
}

return NULL;
}

void hm_set(struct Hashmap *h, void *key, void *value) {
unsigned a = h->hash(key) % h->cap;

struct BucketNode *b = h->buckets[a];
if (b == NULL) {
h->buckets[a] = malloc(sizeof(struct BucketNode *));
h->buckets[a]->key = key;
h->buckets[a]->value = value;
h->buckets[a]->next = NULL;
} else {
// Handle chaining
}
}

void double_cap(struct Hashmap *h) {
h->buckets = realloc(h->buckets, h->cap * 2 * sizeof(struct BucketNode *));

h->size = 0;
h->cap = h->cap * 2;
}
8 changes: 4 additions & 4 deletions src/util/hashmap.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ struct Hashmap {
int cap;

unsigned (*hash)(void *);
unsigned (*equals)(void *);
unsigned (*equals)(void *, void *);
};

struct BucketNode *create_bucket(void *key, void *value);

// Get a value with a key
struct BucketNode *hm_get(void *key);
struct BucketNode *hm_get(struct Hashmap *h, void *key);
// Set a value with a key
void hm_set(void *key, void *value);
void hm_set(struct Hashmap *h, void *key, void *value);
// Double the capacity of the hashmap (happens automatically when size >
// capacity)
void double_cap();
void double_cap(struct Hashmap *h);

0 comments on commit 169490d

Please sign in to comment.