allocation related primitives
This commit is contained in:
+44
-7
@@ -6,14 +6,51 @@ Allocator :: struct {
|
||||
free @func(context ?*mut anyopaque, memory ?*mut u8, size usize, alignment usize) void
|
||||
}
|
||||
|
||||
heap Allocator :: Allocator {
|
||||
_malloc_alignment usize :: 16 # ponytail: aarch64-macos libc malloc alignment assumption.
|
||||
|
||||
_power_of_two func(value usize) bool {
|
||||
if value == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
current usize = value
|
||||
while current > 1 {
|
||||
half usize = current / 2
|
||||
if half * 2 != current {
|
||||
return false
|
||||
}
|
||||
current = half
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
_c_alloc func(_ ?*mut anyopaque, size usize, alignment usize) ?*mut u8 {
|
||||
if _power_of_two(alignment) == false {
|
||||
return none
|
||||
}
|
||||
|
||||
if alignment <= _malloc_alignment {
|
||||
return ptr_cast(u8, c.malloc(c_ulong(size)))
|
||||
}
|
||||
|
||||
memory [1]mut ?*mut anyopaque = [none]
|
||||
status c_int = c.posix_memalign((&memory).ptr, c_ulong(alignment), c_ulong(size))
|
||||
if status != 0 {
|
||||
return none
|
||||
}
|
||||
|
||||
return ptr_cast(u8, memory[0])
|
||||
}
|
||||
|
||||
_c_free func(_ ?*mut anyopaque, memory ?*mut u8, _ usize, _ usize) void {
|
||||
c.free(memory)
|
||||
}
|
||||
|
||||
c_allocator Allocator :: Allocator {
|
||||
context = none,
|
||||
alloc = func(_ ?*mut anyopaque, size usize, _ usize) ?*mut u8 {
|
||||
return ptr_cast(u8, c.malloc(size))
|
||||
},
|
||||
free = func(_ ?*mut anyopaque, memory ?*mut u8, _ usize, _ usize) void {
|
||||
c.free(memory)
|
||||
},
|
||||
alloc = _c_alloc,
|
||||
free = _c_free,
|
||||
}
|
||||
|
||||
alloc func(allocator Allocator, size usize, alignment usize) ?*mut u8 {
|
||||
|
||||
Reference in New Issue
Block a user