13#define HT_INITIAL_CAPACITY 16
14#define HT_MAX_LOAD 0.75
31static uint64_t
djb2(
const char *s) {
34 while ((c = (
unsigned char)*s++)) h = ((h << 5) + h) + (uint64_t)c;
46 if (!ht->
slots) { free(ht);
return NULL; }
52 for (
size_t i = 0; i < ht->
capacity; i++) {
61 size_t mask = cap - 1;
62 size_t i = (size_t)
djb2(key) & mask;
63 size_t first_tombstone = (size_t)-1;
66 if (slots[i].state ==
SLOT_OCCUPIED && strcmp(slots[i].key, key) == 0) {
69 if (slots[i].state ==
SLOT_TOMBSTONE && first_tombstone == (
size_t)-1) {
74 return first_tombstone == (size_t)-1 ? i : first_tombstone;
78 if (!ht || !key)
return false;
90 char *dup = strdup(key);
91 if (!dup)
return false;
100 if (!ht || !key)
return false;
108 if (!ht || !key)
return false;
119 return ht_get(ht, key, NULL);
126 ht_slot_t *new_slots = calloc(new_cap,
sizeof(*new_slots));
127 if (!new_slots)
return false;
131 for (
size_t i = 0; i < ht->
capacity; i++) {
134 new_slots[j] = ht->
slots[i];
138 ht->
slots = new_slots;
static bool ht_resize(hash_table_t *ht, size_t new_cap)
bool ht_contains(const hash_table_t *ht, const char *key)
size_t ht_capacity(const hash_table_t *ht)
static uint64_t djb2(const char *s)
bool ht_set(hash_table_t *ht, const char *key, int value)
static size_t probe(const ht_slot_t *slots, size_t cap, const char *key)
#define HT_INITIAL_CAPACITY
bool ht_remove(hash_table_t *ht, const char *key)
hash_table_t * ht_create(void)
bool ht_get(const hash_table_t *ht, const char *key, int *out)
size_t ht_size(const hash_table_t *ht)
void ht_destroy(hash_table_t *ht)
Open-addressing string→int hash table with linear probing.