lib: c allocator can use fromZig

pull/8895/head
Mitchell Hashimoto 2025-09-24 11:00:44 -07:00
parent fba953feeb
commit 43089a01f1
No known key found for this signature in database
GPG Key ID: 523D5DC389D273BC
1 changed files with 2 additions and 83 deletions

View File

@ -216,89 +216,8 @@ const ZigAllocator = struct {
} }
}; };
/// C allocator (libc) /// libc Allocator, requires linking libc
pub const CAllocator = struct { pub const c_allocator: Allocator = .fromZig(&std.heap.c_allocator);
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,
};
/// Allocator that can be sent to the C API that does full /// Allocator that can be sent to the C API that does full
/// leak checking within Zig tests. This should only be used from /// leak checking within Zig tests. This should only be used from