From 62454373db4cd2add82ded0cf7b21f7d69ade597 Mon Sep 17 00:00:00 2001 From: spl3g Date: Sat, 22 Mar 2025 21:41:16 +0300 Subject: Reorganize the lib --- src/hashmap.c | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/hashmap.c (limited to 'src/hashmap.c') diff --git a/src/hashmap.c b/src/hashmap.c new file mode 100644 index 0000000..c68d110 --- /dev/null +++ b/src/hashmap.c @@ -0,0 +1,43 @@ +#include + +size_t hash_str(const_string str, size_t cap) { + size_t hash = 0; + for (int i = 0; i < str.len; i++) { + hash = (HASHMAP_DEFAULT_R * hash + str.data[i]) % cap; + } + return hash; +} + +hashmap *hashmap_init(arena *a, size_t cap) { + hashmap *map = arena_alloc(a, sizeof(hashmap) + sizeof(ptrdiff_t) * cap); + map->cap = cap; + return map; +} + +size_t hashmap_kstr_insert(arena *a, hashmap* map, const_string key, void* val) { + size_t hash = hash_str(key, map->cap); + if (map->data[hash].key.len > 0) { + map->data[hash].next = arena_alloc(a, sizeof(hashitem)); + map->data[hash].next->key = key; + map->data[hash].next->val = val; + } else { + map->data[hash].key = key; + map->data[hash].val = val; + } + + return hash; +} + +void *hashmap_kstr_get(hashmap *map, const_string key) { + size_t hash = hash_str(key, map->cap); + hashitem *item = &map->data[hash]; + while (item->next != NULL && !cs_eq(item->key, key)) { + item = item->next; + } + + if (!cs_eq(item->key, key)) { + return NULL; + } + + return item->val; +} -- cgit v1.2.3