lib: c allocator can use fromZig

This commit is contained in:
Mitchell Hashimoto
2025-09-24 11:00:44 -07:00
parent fba953feeb
commit 43089a01f1

View File

@@ -216,89 +216,8 @@ const ZigAllocator = struct {
}
};
/// C allocator (libc)
pub const CAllocator = struct {
comptime {
if (!builtin.link_libc) {
@compileError("C allocator is only available when linking against libc");
}
}
const vtable: VTable = .{
.alloc = alloc,
.resize = resize,
.remap = remap,
.free = free,
};
fn alloc(
ctx: *anyopaque,
len: usize,
alignment: u8,
ra: usize,
) callconv(.c) ?[*]u8 {
return std.heap.c_allocator.vtable.alloc(
ctx,
len,
@enumFromInt(alignment),
ra,
);
}
fn resize(
ctx: *anyopaque,
memory: [*]u8,
memory_len: usize,
alignment: u8,
new_len: usize,
ra: usize,
) callconv(.c) bool {
return std.heap.c_allocator.vtable.resize(
ctx,
memory[0..memory_len],
@enumFromInt(alignment),
new_len,
ra,
);
}
fn remap(
ctx: *anyopaque,
memory: [*]u8,
memory_len: usize,
alignment: u8,
new_len: usize,
ra: usize,
) callconv(.c) ?[*]u8 {
return std.heap.c_allocator.vtable.remap(
ctx,
memory[0..memory_len],
@enumFromInt(alignment),
new_len,
ra,
);
}
fn free(
ctx: *anyopaque,
memory: [*]u8,
memory_len: usize,
alignment: u8,
ra: usize,
) callconv(.c) void {
std.heap.c_allocator.vtable.free(
ctx,
memory[0..memory_len],
@enumFromInt(alignment),
ra,
);
}
};
pub const c_allocator: Allocator = .{
.ctx = undefined,
.vtable = &CAllocator.vtable,
};
/// libc Allocator, requires linking libc
pub const c_allocator: Allocator = .fromZig(&std.heap.c_allocator);
/// Allocator that can be sent to the C API that does full
/// leak checking within Zig tests. This should only be used from