From 20434b20abefbd247df05a2a364a35baabbaa9d8 Mon Sep 17 00:00:00 2001 From: Kyler Date: Fri, 28 Nov 2025 16:20:35 -0700 Subject: [PATCH] Worked on hash table initialization --- SLS_C/src/hash_table.c | 44 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/SLS_C/src/hash_table.c b/SLS_C/src/hash_table.c index 2debda8..93961bf 100644 --- a/SLS_C/src/hash_table.c +++ b/SLS_C/src/hash_table.c @@ -8,11 +8,49 @@ #include "sls/hash_table.h" #include "sls/string.h" -static size_t next_power_of_two(size_t n); +static size_t next_power_of_two(size_t n) { + if (n < 2) return 2; + n--; + n |= n >> 1; + n |= n >> 2; + n |= n >> 4; + n |= n >> 8; + n |= n >> 16; +#if SIZE_MAX > UINT32_MAX + n |= n >> 32; +#endif + n++; + return n; +} -HashTable *init_hash_table(size_t min_buckets_count); +HashTable *init_hash_table(size_t min_buckets_count) { + HashTable *ht = (HashTable *)malloc(sizeof(HashTable)); + if (!ht) return NULL; -void del_hash_table(HashTable *ht); + ht->buckets_count = next_power_of_two(min_buckets_count); + + ht->buckets = (Bucket **)calloc(ht->buckets_count, sizeof(Bucket *)); + if (!ht->buckets) { + free(ht); + return NULL; + } + + return ht; +} + +void del_hash_table(HashTable *ht) { + for (size_t i = 0; i < ht->buckets_count; i++) { + Bucket *next, *head; + head = (ht->buckets)+i; + while (head) { + next = head->next; + free(head); + head = next; + } + } + free(ht->buckets); + free(ht); +} static inline uint32_t sls_hash_a(SlsStr key) { // FNV-1a