summaryrefslogtreecommitdiff
path: root/hashtable.c
diff options
context:
space:
mode:
Diffstat (limited to 'hashtable.c')
-rw-r--r--hashtable.c34
1 files changed, 34 insertions, 0 deletions
diff --git a/hashtable.c b/hashtable.c
new file mode 100644
index 0000000..ce4c65a
--- /dev/null
+++ b/hashtable.c
@@ -0,0 +1,34 @@
+#include <stdlib.h>
+#include "hashtable.h"
+
+const unsigned int fnvPrime = 16777619;
+const unsigned int fnvOffset = 2166136261U;
+
+//FNV-1a hash
+unsigned int get_hash(char* str) {
+ unsigned int hash = fnvOffset;
+ while (*str != '\0') {
+ hash = (hash ^ *str) * fnvPrime;
+ str++;
+ }
+ return hash;
+}
+hashtable_t* init_hashtable(unsigned int capacity) {
+ hashtable_t* ht = malloc(sizeof(hashtable_t));
+ ht->pairs = calloc(capacity, sizeof(pair_t*));
+ ht->capacity = capacity;
+ return ht;
+}
+/* TODO: handle collision
+TODO: return 0 if something goes wrong */
+unsigned int hashtable_add_pair(hashtable_t* hashtable, pair_t pair) {
+ unsigned int hash = get_hash(pair.key);
+ pair_t* memPair = malloc(sizeof(pair_t));
+ *memPair = pair;
+ hashtable->pairs[hash % hashtable->capacity] = memPair;
+ return hash;
+}
+pair_t* hashtable_get_pair(hashtable_t* hashtable, char* key) {
+ unsigned int hash = get_hash(key);
+ return hashtable->pairs[hash % hashtable->capacity];
+}