ona/source/ona/heap.zig

55 lines
1.1 KiB
Zig

const coral = @import("coral");
const ext = @import("./ext.zig");
const Context = struct {
live_allocations: usize,
const Self = @This();
const empty_allocation = [0]u8{};
fn reallocate(self: *Self, options: coral.io.AllocationOptions) ?[]u8 {
if (options.size == 0) {
if (options.allocation) |allocation| {
if (allocation.ptr != &empty_allocation) {
ext.SDL_free(allocation.ptr);
}
self.live_allocations -= 1;
return null;
}
self.live_allocations += 1;
return &empty_allocation;
}
if (options.allocation) |allocation| {
if (ext.SDL_realloc(allocation.ptr, options.size)) |reallocation| {
self.live_allocations += 1;
return @ptrCast([*]u8, reallocation)[0 .. options.size];
}
}
if (ext.SDL_malloc(options.size)) |allocation| {
self.live_allocations += 1;
return @ptrCast([*]u8, allocation)[0 .. options.size];
}
return null;
}
};
var context = Context{
.live_allocations = 0,
};
///
/// Heap allocator.
///
pub const allocator = coral.io.Allocator.bind(Context, &context, Context.reallocate);