c :: import "@ffi/c" Allocator :: struct { context ?*mut anyopaque alloc @func(context ?*mut anyopaque, size usize, alignment usize) ?*mut u8 free @func(context ?*mut anyopaque, memory ?*mut u8, size usize, alignment usize) void } _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 = _c_alloc, free = _c_free, } alloc func(allocator Allocator, size usize, alignment usize) ?*mut u8 { return allocator.alloc(allocator.context, size, alignment) } free func(allocator Allocator, memory ?*mut u8, size usize, alignment usize) void { allocator.free(allocator.context, memory, size, alignment) }