From 4188047bbc3abb13f5d37b6d66a1ed71926c6b49 Mon Sep 17 00:00:00 2001 From: Sara Date: Thu, 25 Jan 2024 00:03:27 +0100 Subject: [PATCH] chore: cleanup pass for dictionary.c --- core/src/dictionary.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/core/src/dictionary.c b/core/src/dictionary.c index 61af8f2..397297a 100644 --- a/core/src/dictionary.c +++ b/core/src/dictionary.c @@ -23,7 +23,7 @@ Key* internal_dictionary_get(Dictionary* self, uintptr_t keyhash, size_t* out_in Key* element; signed long l = 0, r = self->list.len, m; while(l <= r) { - m = round((double)(l+r)/2.0); + m = floor((double)(l+r)/2.0); if(out_index != NULL) *out_index = m; element = list_at_unchecked(&self->list, m); if(keyhash < element->hash) @@ -55,7 +55,7 @@ int dictionary_insert_kvp(Dictionary* self, Key key, void* value, size_t index) memcpy(insert_data, &key, sizeof(Key)); memcpy(insert_data + sizeof(Key), value, self->element_size); // decide add or insert based on current length of list - if(self->list.len == 0) + if(self->list.len == 0 || index >= self->list.len) list_add(&self->list, insert_data); else list_insert(&self->list, insert_data, index); @@ -71,15 +71,17 @@ int dictionary_set_raw(Dictionary* self, const char* key, void* data) { // get index of closest hash // prepare key data Key keydata = { - .hash = strhash(key), + .hash = keyhash, .key = malloc(strlen(key)+1) }; strcpy(keydata.key, key); - if(closest == NULL || keyhash < closest->hash) { // insert before + if(closest == NULL) { return dictionary_insert_kvp(self, keydata, data, closest_index); - } else if(strcmp(closest->key, key) == 0) { + } else if(closest->hash == keyhash && strcmp(closest->key, key) == 0) { memcpy(closest + 1, data, self->element_size); return 0; + } else if(keyhash < closest->hash) { // insert before + return dictionary_insert_kvp(self, keydata, data, closest_index); } else { return dictionary_insert_kvp(self, keydata, data, closest_index + 1); }