137 lines
2.3 KiB
C
137 lines
2.3 KiB
C
/* 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)) {
|
|
return -EEXIST;
|
|
}
|
|
entry = entry->next;
|
|
}
|
|
|
|
entry = kzalloc(sizeof(ht_entry_t), ALLOC_KERN);
|
|
if (!entry)
|
|
return -ENOMEM;
|
|
|
|
entry->key = strdup(key);
|
|
if (!entry->key) {
|
|
kfree(entry);
|
|
return -ENOMEM;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
void ht_lock(ht_t *ht)
|
|
{
|
|
mtx_lock(&ht->lock);
|
|
}
|
|
|
|
void ht_unlock(ht_t *ht)
|
|
{
|
|
mtx_unlock(&ht->lock);
|
|
}
|