simple hashmap implementation

This commit is contained in:
2026-07-16 23:14:42 +02:00
parent c541496db5
commit 709d977436
5 changed files with 197 additions and 11 deletions
+21 -11
View File
@@ -41,17 +41,7 @@ eql func($T type, left, right []T) bool {
return true
}
hide empty_storage [1]mut u64 = [0]
hide empty_slice func($T type, count usize) []mut T {
pointer *mut T :: ptrcast!(T, (&empty_storage).ptr)
return pointer[..count]
}
empty func($T type) []mut T {
return empty_slice(T, 0)
}
# allocate memory for a slice of type `T` with `count` elements.
alloc func($T type, allocator Allocator, count usize) []mut T ! AllocError {
if count == 0 {
return empty_slice(T, 0)
@@ -73,10 +63,14 @@ alloc func($T type, allocator Allocator, count usize) []mut T ! AllocError {
return .out_of_memory
}
# reallocate memory for a slice of type `T` with `new_count` elements.
# reallocating with `new_count == 0` will free the memory and return an empty slice.
# note: memory must be reallocated with the same allocator that was used to allocate it.
realloc func($T type, allocator Allocator, memory []mut T, new_count usize) []mut T ! AllocError {
if new_count == memory.len {
return memory
}
if new_count == 0 {
free(allocator, memory)
return empty_slice(T, 0)
@@ -107,15 +101,31 @@ realloc func($T type, allocator Allocator, memory []mut T, new_count usize) []mu
pointer *mut T :: ptrcast!(T, bytes)
return pointer[..new_count]
}
return .out_of_memory
}
# free memory allocated for a slice of type `T`.
# note: memory must be freed with the same allocator that was used to allocate it.
free func($T type, allocator Allocator, memory []mut T) void {
if memory.len != 0 and sizeof!(T) != 0 {
raw_free(allocator, ptrcast!(u8, memory.ptr), memory.len * sizeof!(T), alignof!(T))
}
}
# get an empty slice of type `T` with `count` elements.
empty_slice func($T type, count usize) []mut T {
pointer *mut T :: ptrcast!(T, (&empty_storage).ptr)
return pointer[..count]
}
# get an empty slice of type `T` with 0 elements.
empty func($T type) []mut T {
return empty_slice(T, 0)
}
hide empty_storage [1]mut u64 = [0]
hide malloc_alignment usize :: 16 # ponytail: aarch64-macos libc malloc alignment assumption.
hide power_of_two func(value usize) bool {