mirror of
https://codeberg.org/ziglang/zig.git
synced 2025-12-06 13:54:21 +00:00
Add c allocator (#542)
This commit is contained in:
parent
0744c83f51
commit
09c0cf2dcf
2 changed files with 37 additions and 0 deletions
|
|
@ -43,3 +43,7 @@ pub extern "c" fn sigaction(sig: c_int, noalias act: &const Sigaction, noalias o
|
|||
pub extern "c" fn nanosleep(rqtp: &const timespec, rmtp: ?×pec) -> c_int;
|
||||
pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) -> c_int;
|
||||
pub extern "c" fn setregid(rgid: c_uint, egid: c_uint) -> c_int;
|
||||
|
||||
pub extern "c" fn malloc(usize) -> ?&c_void;
|
||||
pub extern "c" fn realloc(&c_void, usize) -> ?&c_void;
|
||||
pub extern "c" fn free(&c_void);
|
||||
|
|
|
|||
33
std/mem.zig
33
std/mem.zig
|
|
@ -5,6 +5,7 @@ const os = @import("os/index.zig");
|
|||
const io = @import("io.zig");
|
||||
const builtin = @import("builtin");
|
||||
const Os = builtin.Os;
|
||||
const c = @import("c/index.zig");
|
||||
|
||||
pub const Cmp = math.Cmp;
|
||||
|
||||
|
|
@ -84,6 +85,38 @@ pub const Allocator = struct {
|
|||
}
|
||||
};
|
||||
|
||||
pub var c_allocator = Allocator {
|
||||
.allocFn = cAlloc,
|
||||
.reallocFn = cRealloc,
|
||||
.freeFn = cFree,
|
||||
};
|
||||
|
||||
fn cAlloc(self: &Allocator, n: usize, alignment: usize) -> %[]u8 {
|
||||
if (c.malloc(usize(n))) |mem| {
|
||||
@ptrCast(&u8, mem)[0..n]
|
||||
} else {
|
||||
error.OutOfMemory
|
||||
}
|
||||
}
|
||||
|
||||
fn cRealloc(self: &Allocator, old_mem: []u8, new_size: usize, alignment: usize) -> %[]u8 {
|
||||
if (new_size <= old_mem.len) {
|
||||
old_mem[0..new_size]
|
||||
} else {
|
||||
const old_ptr = @ptrCast(&c_void, old_mem.ptr);
|
||||
if (c.realloc(old_ptr, usize(new_size))) |mem| {
|
||||
@ptrCast(&u8, mem)[0..new_size]
|
||||
} else {
|
||||
error.OutOfMemory
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cFree(self: &Allocator, old_mem: []u8) {
|
||||
const old_ptr = @ptrCast(&c_void, old_mem.ptr);
|
||||
c.free(old_ptr);
|
||||
}
|
||||
|
||||
pub const IncrementingAllocator = struct {
|
||||
allocator: Allocator,
|
||||
bytes: []u8,
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue