add FreeHashTable function

This commit is contained in:
Matthew 2026-06-24 04:07:08 +10:00
parent d5399fdbac
commit f3d1f551cc

View File

@ -2,6 +2,7 @@ module dlib.util;
import dlib.aliases; import dlib.aliases;
import dlib.alloc; import dlib.alloc;
import dlib.alloc : Free;
import std.traits : isIntegral, hasMember, isArray; import std.traits : isIntegral, hasMember, isArray;
@ -540,13 +541,13 @@ CreateHashTable(K, V)(usize size)
auto lists = Alloc!(LinkedList!(KVPair!(K, V)))(&arena, size); auto lists = Alloc!(LinkedList!(KVPair!(K, V)))(&arena, size);
HashTable!(K, V) table = { HashTable!(K, V) table = {
arena: arena, arena: arena,
lists: lists, lists: lists,
list_count: size, list_count: size,
nil: nil, nil: nil,
free_lists: { free_lists: {
first: nil, first: nil,
last: nil, last: nil,
}, },
}; };
@ -559,7 +560,7 @@ CreateHashTable(K, V)(usize size)
return table; return table;
} }
pragma(inline) void void
Clear(K, V)(HashTable!(K, V)* ht) Clear(K, V)(HashTable!(K, V)* ht)
{ {
table.count = 0; table.count = 0;
@ -569,7 +570,7 @@ Clear(K, V)(HashTable!(K, V)* ht)
} }
} }
pragma(inline) KVPair!(K, V)* KVPair!(K, V)*
Push(K, V)(HashTable!(K, V)* ht, K key, V value) Push(K, V)(HashTable!(K, V)* ht, K key, V value)
{ {
alias P = KVPair!(K, V); alias P = KVPair!(K, V);
@ -596,7 +597,7 @@ Push(K, V)(HashTable!(K, V)* ht, K key, V value)
return node; return node;
} }
pragma(inline) KVPair!(K, V)* KVPair!(K, V)*
Search(K, V)(HashTable!(K, V)* ht, K key) Search(K, V)(HashTable!(K, V)* ht, K key)
{ {
KVPair!(K, V)* result = null; KVPair!(K, V)* result = null;
@ -614,7 +615,7 @@ Search(K, V)(HashTable!(K, V)* ht, K key)
return result; return result;
} }
pragma(inline) LinkedList!(KVPair!(K, V))* LinkedList!(KVPair!(K, V))*
GetList(K, V)(HashTable!(K, V)* ht, K key) GetList(K, V)(HashTable!(K, V)* ht, K key)
{ {
u64 hash = Hash(&key); u64 hash = Hash(&key);
@ -644,7 +645,7 @@ GetAllNodes(K, V)(Arena* arena, HashTable!(K, V)* ht)
return pairs; return pairs;
} }
pragma(inline) Result!(V) Result!(V)
Delete(K, V)(HashTable!(K, V)* ht, K key) Delete(K, V)(HashTable!(K, V)* ht, K key)
{ {
Result!(V) result = { ok: false }; Result!(V) result = { ok: false };
@ -673,6 +674,13 @@ Delete(K, V)(HashTable!(K, V)* ht, K key)
return result; return result;
} }
void
FreeHashTable(K, V)(ref HashTable!(K, V) hash_table)
{
Free(&hash_table.arena);
memset(&hash_table, 0, HashTable!(K, V).sizeof);
}
const u64 HASH_SEED = 5995; const u64 HASH_SEED = 5995;
pragma(inline) u64 pragma(inline) u64
@ -1340,6 +1348,10 @@ version(DLIB_TEST)
auto table = CreateHashTable!(u64, u64)(10); auto table = CreateHashTable!(u64, u64)(10);
table[100] = 100; table[100] = 100;
FreeHashTable(table);
assert(table.nil == null);
} }
{ // Hash { // Hash