aboutsummaryrefslogtreecommitdiff
path: root/src/hashmap.c
diff options
context:
space:
mode:
authorspl3g <spleefer6@yandex.ru>2025-03-22 21:41:16 +0300
committerspl3g <spleefer6@yandex.ru>2025-03-22 21:41:16 +0300
commit62454373db4cd2add82ded0cf7b21f7d69ade597 (patch)
tree1627133fe4567e9a3abb707af5e7289353410d5f /src/hashmap.c
parentef5f52fb739c9f0d71c579f08363ef0dfd5c227d (diff)
Reorganize the lib
Diffstat (limited to 'src/hashmap.c')
-rw-r--r--src/hashmap.c43
1 files changed, 43 insertions, 0 deletions
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 <chttp/hashmap.h>
+
+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;
+}