Worked on hash table initialization

This commit is contained in:
Kyler Olsen 2025-11-28 16:20:35 -07:00
parent e94d316af8
commit 20434b20ab
1 changed files with 41 additions and 3 deletions

View File

@ -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