Worked on hash table initialization
This commit is contained in:
parent
e94d316af8
commit
20434b20ab
|
|
@ -8,11 +8,49 @@
|
||||||
#include "sls/hash_table.h"
|
#include "sls/hash_table.h"
|
||||||
#include "sls/string.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) {
|
static inline uint32_t sls_hash_a(SlsStr key) {
|
||||||
// FNV-1a
|
// FNV-1a
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue