From 0c34e6f63da673e78c1a207c50ca59ce245c5f65 Mon Sep 17 00:00:00 2001 From: Mineplay Date: Sun, 25 May 2025 15:14:28 -0500 Subject: [PATCH] fix(hash table): fixed resizing of hash table by adding rehashing --- Src/Core/HashTable.c | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/Src/Core/HashTable.c b/Src/Core/HashTable.c index 57894a6..aefc69a 100644 --- a/Src/Core/HashTable.c +++ b/Src/Core/HashTable.c @@ -21,10 +21,12 @@ * ----------------------------------------------------------------------------- */ #include "../../Include/Fledasty/Core/HashTable.h" +#include "Fledasty/Core/DynamicArray.h" #include #include #include +#include static const int FLEDASTY_HASH_TABLE_SIZE_THRESHOLD = 75; @@ -73,17 +75,36 @@ FledastyError fledasty_hash_table_insert(FledastyHashTable *current_hash_table, current_hash_table->size += 1; if (current_hash_table->size >= (current_hash_table->capacity * FLEDASTY_HASH_TABLE_SIZE_THRESHOLD) / 100) { + size_t old_capacity = current_hash_table->capacity; current_hash_table->capacity += current_hash_table->capacity; FledastyDynamicArray *previous_table = current_hash_table->Table; - current_hash_table->Table = (FledastyDynamicArray*)hallocy_realloc(current_hash_table->Table, current_hash_table->capacity * sizeof(FledastyDynamicArray)); + current_hash_table->Table = (FledastyDynamicArray*)hallocy_calloc(sizeof(FledastyDynamicArray), current_hash_table->capacity); if (current_hash_table->Table == NULL) { return FLEDASTY_ERROR_FAILED_ALLOCATION; } - if (previous_table != current_hash_table->Table) { - hallocy_set_memory(current_hash_table->Table + (current_hash_table->size - 2), 0, current_hash_table->capacity); + for (size_t index = 0; index < old_capacity; index += 1) { + if (previous_table[index].buffer != NULL) { + for (size_t list_index = 0; list_index < previous_table[index].size; list_index += 1) { + FledastyHashTablePair *pair = (FledastyHashTablePair*)fledasty_dynamic_array_get(previous_table + index, list_index); + + size_t key_index = current_hash_table->hash_function(pair->key) % current_hash_table->capacity; + if (current_hash_table->Table[key_index].buffer == NULL) { + FledastyError result = fledasty_dynamic_array_initialize(current_hash_table->Table + key_index, NULL, 0, sizeof(FledastyHashTablePair)); + if (result != FLEDASTY_ERROR_NONE) { + return result; + } + } + + fledasty_dynamic_array_append(current_hash_table->Table + key_index, pair); + } + + fledasty_dynamic_array_destroy(previous_table + index); + } } + + hallocy_free(previous_table); } size_t index = current_hash_table->hash_function(key) % current_hash_table->capacity;