From fc18e73c7e66c7a03381312937434aac7210ca6b Mon Sep 17 00:00:00 2001
From: Tom Smeding <tom.smeding@gmail.com>
Date: Sat, 8 Aug 2020 12:06:59 +0200
Subject: server: Fix bug in hashtable

---
 hashtable.c | 13 ++++++++++++-
 hashtable.h |  3 ++-
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git a/hashtable.c b/hashtable.c
index 020d281..322e69c 100644
--- a/hashtable.c
+++ b/hashtable.c
@@ -1,4 +1,5 @@
 #include <limits.h>
+#include <assert.h>
 #include "hashtable.h"
 
 
@@ -72,7 +73,7 @@ static void ht_grow(struct hashtable *ht) {
 	*ht = newht;
 }
 
-struct hashtable* ht_alloc() {
+struct hashtable* ht_alloc(void) {
 	struct hashtable *ht = malloc(1, struct hashtable);
 	ht->modulus_index = 0;
 	ht->modulus = doubling_primes[ht->modulus_index];
@@ -90,8 +91,18 @@ void ht_free(struct hashtable *ht) {
 }
 
 void ht_insert(struct hashtable *ht, u64 key, void *value) {
+	assert(value != NULL);
+
 	struct bucket *bucket = &ht->table[key % ht->modulus];
 
+	// If key already exists, overwrite that
+	for (int i = 0; i < bucket->len; i++) {
+		if (bucket->pairs[i].key == key) {
+			bucket->pairs[i].value = value;
+			return;
+		}
+	}
+
 	if (bucket->cap == 0) {
 		bucket->cap = 1;
 		bucket->pairs = malloc(bucket->cap, struct keyvalue);
diff --git a/hashtable.h b/hashtable.h
index 21467a8..5147fa5 100644
--- a/hashtable.h
+++ b/hashtable.h
@@ -5,9 +5,10 @@
 
 struct hashtable;
 
-struct hashtable* ht_alloc();
+struct hashtable* ht_alloc(void);
 void ht_free(struct hashtable *ht);
 
+// Overwrites if the key already exists in the table.
 void ht_insert(struct hashtable *ht, u64 key, void *value);
 
 // Returns NULL if key is not present in the table.
-- 
cgit v1.2.3-70-g09d2