Fumofumotris/source/fumoengine/include/dictionary.c

89 lines
1.8 KiB
C
Raw Normal View History

2024-05-08 22:07:31 +00:00
#include "dictionary.h"
2024-05-09 05:32:58 +00:00
#include <stdlib.h>
2024-05-08 22:07:31 +00:00
#include <string.h>
bool CreateDictionary(DictT T, struct Dictionary *dict)
{
void *bkts = calloc(16, T->BKT_SIZE);
if (bkts == nullptr)
return false;
*dict = (struct Dictionary) {
.filled = 0,
.capacity = 16,
2024-05-09 05:32:58 +00:00
.bkts = bkts
2024-05-08 22:07:31 +00:00
};
return true;
}
void FreeDictionary(struct Dictionary *dict)
{
free(dict->bkts);
}
void *index_bkt(DictT T, struct Dictionary *dict, usize i)
{
return (u8 *)dict->bkts + i * T->BKT_SIZE;
}
2024-05-09 05:32:58 +00:00
u32 *get_key(DictT T, void *bkt)
2024-05-08 22:07:31 +00:00
{
2024-05-09 05:32:58 +00:00
return (u32 *)bkt;
2024-05-08 22:07:31 +00:00
}
void *get_val(DictT T, void *bkt)
{
return (u8 *)bkt + T->VAL_OFS;
}
2024-05-09 05:32:58 +00:00
void set_bkt(DictT T, void *bkt, u32 key, void *val)
{
*get_key(T, bkt) = key;
memcpy(get_val(T, bkt), val, T->VAL_SIZE);
}
2024-05-08 22:07:31 +00:00
void *probe_bkt(DictT T, struct Dictionary *dict, usize index, u32 key)
{
for (usize i = 0; i < dict->capacity; i++) {
void *bkt = index_bkt(T, dict, (index + i) % dict->capacity);
2024-05-09 05:32:58 +00:00
if (*get_key(T, bkt) == key)
2024-05-08 22:07:31 +00:00
return bkt;
}
return nullptr;
}
void *probe_empty_bkt(DictT T, struct Dictionary *dict, usize index, u32 key)
{
for (usize i = 0; i < dict->capacity; i++) {
void *bkt = index_bkt(T, dict, (index + i) % dict->capacity);
2024-05-09 05:32:58 +00:00
u32 k = *get_key(T, bkt);
2024-05-08 22:07:31 +00:00
if (k == 0 or k == key)
return bkt;
}
return nullptr;
}
void *DictionaryFind(DictT T, struct Dictionary *dict, u32 key)
{
usize index = key % dict->capacity;
return probe_bkt(T, dict, index, key);
}
void *DictionarySet(DictT T, struct Dictionary *dict, u32 key, void *val)
{
usize index = key % dict->capacity;
void *bkt = probe_empty_bkt(T, dict, index, key);
2024-05-10 21:59:52 +00:00
if (*get_key(T, bkt) == 0)
2024-05-08 22:07:31 +00:00
set_bkt(T, bkt, key, val);
return bkt;
}