1 #include <kiba/containers/hash_table.h>
3 #include <kiba/core/hash.h>
11 b8 hash_table_create(
hash_table *table, usize initial_capacity, f64 max_load,
allocator *alloc) {
14 KB_ASSERT(initial_capacity != 0,
"initial capacity must not be 0");
15 KB_ASSERT(max_load <= 1.0 && max_load > 0.0,
"max load must be in range (0, 1] but is {f64}", max_load);
17 table->capacity = initial_capacity;
18 table->max_load = max_load;
26 "table must have initialized state");
31 b8 hash_table_set(
hash_table *table,
const void *key, usize key_size, uptr value) {
33 if (new_entry->key_size == 0) {
35 if ((f64) table->size / (f64) table->capacity >= table->max_load) {
38 if (!hash_table_create(&new_table, table->capacity * 2, table->max_load, table->alloc)) {
39 KB_ERROR(
"could not expand hash table");
42 hash_table_for_each(*table) {
43 KB_ASSERT(hash_table_set(&new_table, entry->key, entry->key_size, entry->value),
44 "migration of old values must work");
46 KB_ASSERT(table->size == new_table.size + 1,
"size between tables must not change");
48 table->capacity = new_table.capacity;
49 table->data = new_table.data;
52 new_entry->key_size = key_size;
53 new_entry->key = (
void *) key;
54 new_entry->value = value;
58 b8 hash_table_get(
hash_table *table,
const void *key, usize key_size,
void *value_ptr) {
60 if (entry->key_size != 0) {
61 memory_copy(value_ptr, &entry->value,
sizeof(uptr));
69 "table must have initialized state");
71 u64 hash = hash_fnv_1a(key, key_size);
72 usize index = hash % table->capacity;
74 while (entry->key_size != 0
75 && !(key_size == entry->key_size && hash == entry->hash && memcmp(key, entry->key, key_size) == 0)) {
76 index = (index + 1) % table->capacity;
77 entry = table->data + index;
void * allocator_allocate(allocator *alloc, usize size)
Allocate unaligned memory.
void allocator_free(allocator *alloc, void *mem)
Give back memory to the allocator.
void * memory_copy(void *dst, const void *src, usize size)
Copy memory.
void * memory_zero(void *mem, usize size)
Zero out memory.
Lightweight layer between platform and other engine components to enable tracing/monitoring.
#define KB_NULL
Value of an invalid ptr (nullptr).
#define KB_ASSERT(expr,...)
Perform runtime assertion and log failures.
#define KB_ERROR(...)
Log entry with error log level.
Central allocator structure.