fix(hash table): fixed resizing of hash table by adding rehashing

This commit is contained in:
Mineplay 2025-05-25 15:14:28 -05:00
parent fc5f731397
commit 0c34e6f63d

View file

@ -21,10 +21,12 @@
* -----------------------------------------------------------------------------
*/
#include "../../Include/Fledasty/Core/HashTable.h"
#include "Fledasty/Core/DynamicArray.h"
#include <Hallocy/Core/Allocator.h>
#include <Hallocy/Core/Memory.h>
#include <Hallocy/Utils/Error.h>
#include <stddef.h>
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;