lib: add hash table

Signed-off-by: Michael Shaw <m@michaelsshaw.com>
This commit is contained in:
Michael Shaw 2026-08-12 20:06:48 -04:00
commit 0aec18db63
Signed by: michaelsshaw
GPG key ID: 5A5E0FB20708A9E7
3 changed files with 157 additions and 0 deletions

View file

@ -8,3 +8,4 @@ obj-y += string.o
obj-y += list.o
obj-y += sem.o
obj-y += rwlock.o
obj-y += hashchain.o

128
lib/hashchain.c Normal file
View file

@ -0,0 +1,128 @@
/* SPDX-License-Identifier: GPL-2.0-only */
#include <kernel/common.h>
#include <kernel/slab.h>
#include <lib/hashchain.h>
#include <lib/math.h>
#include <lib/string.h>
#define ht_MIN 32
static u64 hash_str(const char *str)
{
u64 hash = 5381;
for (const char *p = str; *p; p++)
hash = ((hash << 5) + hash) + (u64)*p;
return hash;
}
ht_t *ht_create(size_t capacity)
{
size_t cap = npow2(capacity);
if (cap < ht_MIN)
cap = ht_MIN;
ht_t *ht = kzalloc(sizeof(ht_t), ALLOC_KERN);
if (!ht)
return NULL;
ht->buckets = kzalloc(sizeof(ht_entry_t *) * cap, ALLOC_KERN);
if (!ht->buckets) {
kfree(ht);
return NULL;
}
ht->capacity = cap;
ht->size = 0;
return ht;
}
void ht_destroy(ht_t *ht)
{
if (!ht)
return;
for (size_t i = 0; i < ht->capacity; i++) {
ht_entry_t *entry = ht->buckets[i];
while (entry) {
ht_entry_t *next = entry->next;
kfree(entry->key);
kfree(entry);
entry = next;
}
}
kfree(ht->buckets);
kfree(ht);
}
int ht_insert(ht_t *ht, const char *key, void *value)
{
u64 hash = hash_str(key);
size_t idx = hash & (ht->capacity - 1);
ht_entry_t *entry = ht->buckets[idx];
while (entry) {
if (strcmp(entry->key, key) == 0) {
entry->ptr = value;
return 0;
}
entry = entry->next;
}
entry = kzalloc(sizeof(ht_entry_t), ALLOC_KERN);
if (!entry)
return -1;
entry->key = strdup(key);
if (!entry->key) {
kfree(entry);
return -1;
}
entry->ptr = value;
entry->next = ht->buckets[idx];
ht->buckets[idx] = entry;
ht->size++;
return 0;
}
void *ht_lookup(ht_t *ht, const char *key)
{
u64 hash = hash_str(key);
size_t idx = hash & (ht->capacity - 1);
ht_entry_t *entry = ht->buckets[idx];
while (entry) {
if (strcmp(entry->key, key) == 0)
return entry->ptr;
entry = entry->next;
}
return NULL;
}
int ht_delete(ht_t *ht, const char *key)
{
u64 hash = hash_str(key);
size_t idx = hash & (ht->capacity - 1);
ht_entry_t *entry = ht->buckets[idx];
ht_entry_t *prev = NULL;
while (entry) {
if (strcmp(entry->key, key) == 0) {
if (prev)
prev->next = entry->next;
else
ht->buckets[idx] = entry->next;
kfree(entry->key);
kfree(entry);
ht->size--;
return 0;
}
prev = entry;
entry = entry->next;
}
return -1;
}