From 4e63c251d8f06a5ca73e988badbdf8a0f7a28f90 Mon Sep 17 00:00:00 2001 From: Nathan Fisher Date: Tue, 15 Aug 2023 01:11:57 -0400 Subject: [PATCH] Added test for replacing a hashmap entry --- hmap.c | 11 ++++++----- test/Makefile | 1 + test/hmap_replace.c | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 5 deletions(-) create mode 100644 test/hmap_replace.c diff --git a/hmap.c b/hmap.c index ed843ef..7653315 100644 --- a/hmap.c +++ b/hmap.c @@ -32,6 +32,7 @@ #include #include +#include #include #include #include @@ -174,7 +175,7 @@ int hmap_expand(hmap *map) { void* hmap_insert(hmap *map, void *key, void *data) { hmap_node *node; size_t idx; - hmap_node *ret = NULL; + void *ret = NULL; if (map->len >= map->capacity / 2) { if (hmap_expand(map)) return NULL; @@ -187,11 +188,11 @@ void* hmap_insert(hmap *map, void *key, void *data) { } else { ret = hmap_node_attach(&map->buckets[idx], node, map->keysize); } - map->len++; - if (ret == NULL) + if (ret == NULL) { + map->len++; return NULL; - else - return ret->data; + } else + return ret; } void* hmap_get(hmap *map, void *key) { diff --git a/test/Makefile b/test/Makefile index 4b3bbf9..f08cb04 100644 --- a/test/Makefile +++ b/test/Makefile @@ -64,6 +64,7 @@ tests += fnv1a_hash_str tests += init_hmap tests += hmap_insert tests += hmap_get +tests += hmap_replace total != echo $(tests) | wc -w | awk '{ print $$1 }' diff --git a/test/hmap_replace.c b/test/hmap_replace.c new file mode 100644 index 0000000..d9216b8 --- /dev/null +++ b/test/hmap_replace.c @@ -0,0 +1,37 @@ +#include "haggis.h" +#include "haggis_private.h" +#include +#include +#include +#include +#include + +int main() { + hmap *map; + struct stat st; + char *data; + union { + ino_t val; + u8 bytes[sizeof(ino_t)]; + } nod; + char * ret = NULL; + + map = hmap_init(sizeof(ino_t)); + assert(map != NULL); + data = "Makefile"; + stat(data, &st); + nod.val = st.st_ino; + ret = hmap_insert(map, &nod.bytes[0], data); + assert(ret == NULL); + assert(map->len == 1); + ret = hmap_get(map, &nod.bytes[0]); + assert(memcmp(ret, data, 7) == 0); + ret = hmap_insert(map, &nod.bytes[0], "testdata"); + assert(ret != NULL); + assert(memcmp(ret, data, 8) == 0); + assert(map->len == 1); + ret = hmap_get(map, &nod.bytes[0]); + assert(memcmp(ret, "testdata", 9) == 0); + hmap_deinit(map); + return 0; +}