Simple allocator interface, to avoid pulling in the while std allocator implementation.
const simple_allocator = struct
const simple_allocator = struct {
/// Allocate a memory chunk for requested type. Return a pointer on the data.
pub fn alloc(comptime T: type) *T {
return @ptrCast(@alignCast(advancedAlloc(@alignOf(T), @sizeOf(T))));
}
/// Allocate a slice of T, with len elements.
pub fn allocSlice(comptime T: type, len: usize) []T {
return @as([*]T, @ptrCast(@alignCast(
advancedAlloc(@alignOf(T), @sizeOf(T) * len),
)))[0 .. len - 1];
}
/// Allocate a memory chunk.
pub fn advancedAlloc(alignment: u29, size: usize) [*]u8 {
const minimal_alignment = @max(@alignOf(usize), alignment);
var aligned_ptr: ?*anyopaque = undefined;
if (std.c.posix_memalign(&aligned_ptr, minimal_alignment, size) != 0) {
abort();
}
return @ptrCast(aligned_ptr);
}
/// Resize a slice.
pub fn reallocSlice(comptime T: type, slice: []T, len: usize) []T {
const c_ptr: *anyopaque = @ptrCast(slice.ptr);
const new_array: [*]T = @ptrCast(@alignCast(std.c.realloc(c_ptr, @sizeOf(T) * len) orelse abort()));
return new_array[0..len];
}
/// Free a memory chunk allocated with simple_allocator.
pub fn free(ptr: anytype) void {
std.c.free(@ptrCast(ptr));
}
}