From 616ff505f666d4d162e5d2d8c0238f8af6f79c40 Mon Sep 17 00:00:00 2001 From: Danny van Kooten Date: Thu, 12 Mar 2020 14:19:24 +0100 Subject: add first template tests --- src/hashmap.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'src/hashmap.c') diff --git a/src/hashmap.c b/src/hashmap.c index 3d9edd0..b56b364 100644 --- a/src/hashmap.c +++ b/src/hashmap.c @@ -3,6 +3,8 @@ #include #include "hashmap.h" +#define HASH(v) (v[0] - 'a') % HASHMAP_CAP + struct node { char *key; void *value; @@ -12,7 +14,7 @@ struct node { struct hashmap *hashmap_new() { struct hashmap *hm = malloc(sizeof *hm); if (!hm) err(EXIT_FAILURE, "out of memory"); - for (int i=0; i < 26; i++) { + for (int i=0; i < HASHMAP_CAP; i++) { hm->buckets[i] = NULL; } @@ -20,7 +22,7 @@ struct hashmap *hashmap_new() { } void hashmap_insert(struct hashmap *hm, char *key, void *value) { - int pos = (key[0] - 'a') % 26; + int pos = HASH(key); struct node *head = hm->buckets[pos]; struct node *node = head; @@ -40,7 +42,7 @@ void hashmap_insert(struct hashmap *hm, char *key, void *value) { } void *hashmap_get(struct hashmap *hm, char *key) { - int pos = (key[0] - 'a') % 26; + int pos = HASH(key); struct node *node = hm->buckets[pos]; while (node) { if (strcmp(node->key, key) == 0) { @@ -61,7 +63,7 @@ void hashmap_free(struct hashmap *hm) { struct node *node; struct node *next; - for (int i=0; i < 26; i++) { + for (int i=0; i < HASHMAP_CAP; i++) { node = hm->buckets[i]; while (node) { next = node->next; -- cgit v1.2.3