feat(hash table): implemented get function

This commit is contained in:
Mineplay 2025-05-01 14:51:27 -05:00
parent 39010a65bc
commit c83015c52f
3 changed files with 37 additions and 1 deletions

View file

@ -48,4 +48,6 @@ FledastyError fledasty_hash_table_destroy(FledastyHashTable *current_hash_table)
FledastyError fledasty_hash_table_insert(FledastyHashTable *current_hash_table, void *key, void *value);
void *fledasty_hash_table_get(FledastyHashTable *current_hash_table, void *key);
#endif

View file

@ -58,6 +58,7 @@ FledastyError fledasty_hash_table_destroy(FledastyHashTable *current_hash_table)
hallocy_free(current_hash_table->Table);
return FLEDASTY_ERROR_NONE;
}
#include <stdio.h>
FledastyError fledasty_hash_table_insert(FledastyHashTable *current_hash_table, void *key, void *value) {
if (current_hash_table == NULL || key == NULL || value == NULL) {
@ -81,8 +82,35 @@ FledastyError fledasty_hash_table_insert(FledastyHashTable *current_hash_table,
fledasty_dynamic_array_initialize(&current_hash_table->Table[index], NULL, 0, sizeof(FledastyHashTablePair));
}
FledastyHashTablePair pair = { .key=key, .value=value };
FledastyHashTablePair pair;
pair.key = hallocy_malloc(current_hash_table->key_byte_size);
hallocy_copy_memory(pair.key, key, current_hash_table->key_byte_size);
pair.value = hallocy_malloc(current_hash_table->value_byte_size);
hallocy_copy_memory(pair.value, value, current_hash_table->value_byte_size);
fledasty_dynamic_array_append(&current_hash_table->Table[index], &pair);
return FLEDASTY_ERROR_NONE;
}
void *fledasty_hash_table_get(FledastyHashTable *current_hash_table, void *key) {
if (current_hash_table == NULL || key == NULL) {
return NULL;
}
size_t index = current_hash_table->hash_function(key) % current_hash_table->capacity;
size_t list_index = 0;
while (list_index < current_hash_table->Table[list_index].size) {
FledastyHashTablePair *value = (FledastyHashTablePair*)fledasty_dynamic_array_get(&current_hash_table->Table[index], list_index);
if (value != NULL && hallocy_compare_memory(value->key, key, current_hash_table->key_byte_size)) {
return value->value;
}
list_index += 1;
}
return NULL;
}

View file

@ -191,6 +191,12 @@ int main() {
fledasty_hash_table_insert(&test_hash_table, &pow_value, &i);
}
for (int i = 0; i < 10; i += 1) {
int pow_value = i * i;
int *hash_table_value = (int*)fledasty_hash_table_get(&test_hash_table, &pow_value);
printf("Hash table get: %d\n", *hash_table_value);
}
fledasty_hash_table_destroy(&test_hash_table);
printf("Done\n");
return 0;