#include "hashtable.h"
hashtable_t* hash_table_new(hash_func_t hash_func, compare_func_t compare_func, free_func_t free_func)
{
hashtable_t* ht = (hashtable_t*)malloc(sizeof(hashtable_t));
int i;
for (i = 0; i < 4096; i++) {
ht->entries[i] = NULL;
}
ht->count = 0;
ht->hash_func = hash_func;
ht->compare_func = compare_func;
ht->free_func = free_func;
return ht;
}
void hash_table_destroy(hashtable_t *ht)
{
if (!ht) return;
int i = 0;
for (i = 0; i < 4096; i++) {
if (ht->entries[i]) {
hashentry_t* e = ht->entries[i];
while (e) {
if (ht->free_func) {
ht->free_func(e->value);
}
hashentry_t* old = e;
e = e->next;
free(old);
}
}
}
free(ht);
}
void hash_table_insert(hashtable_t* ht, void *key, void *value)
{
if (!ht || !key) return;
unsigned int hash = ht->hash_func(key);
int idx0 = hash & 0xFFF;
hashentry_t* e = ht->entries[idx0];
while (e) {
if (ht->compare_func(e->key, key)) {
e->value = value;
return;
}
e = e->next;
}
hashentry_t* entry = (hashentry_t*)malloc(sizeof(hashentry_t));
entry->key = key;
entry->value = value;
if (!ht->entries[idx0]) {
entry->next = NULL;
} else {
entry->next = ht->entries[idx0];
}
ht->entries[idx0] = entry;
ht->count++;
}
void* hash_table_lookup(hashtable_t* ht, void *key)
{
if (!ht || !key) return NULL;
unsigned int hash = ht->hash_func(key);
int idx0 = hash & 0xFFF;
hashentry_t* e = ht->entries[idx0];
while (e) {
if (ht->compare_func(e->key, key)) {
return e->value;
}
e = e->next;
}
return NULL;
}
void hash_table_remove(hashtable_t* ht, void *key)
{
if (!ht || !key) return;
unsigned int hash = ht->hash_func(key);
int idx0 = hash & 0xFFF;
hashentry_t* e = ht->entries[idx0];
hashentry_t* last = e;
while (e) {
if (ht->compare_func(e->key, key)) {
hashentry_t* old = e;
if (e == ht->entries[idx0]) {
ht->entries[idx0] = e->next;
} else {
last->next = e->next;
}
if (ht->free_func) {
ht->free_func(old->value);
}
free(old);
return;
}
last = e;
e = e->next;
}
}