authorgravatar for marc@tiehu.isMarc Tiehuis <marc@tiehu.is> 2017-10-18 01:13:04+13:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-10-17 08:13:04-04:00
log09c0cf2dcf30774852dddfbd703cb40387f400e5
tree4e8e7f482cee7d4c142da46aad292fccbb7dc2bb
parent0744c83f515f15a40da1bf55900c51c200bff2bb

Add c allocator (#542)


2 files changed, 37 insertions(+), 0 deletions(-)

std/c/index.zig+4
...@@ -43,3 +43,7 @@ pub extern "c" fn sigaction(sig: c_int, noalias act: &const Sigaction, noalias o...@@ -43,3 +43,7 @@ pub extern "c" fn sigaction(sig: c_int, noalias act: &const Sigaction, noalias o
43pub extern "c" fn nanosleep(rqtp: &const timespec, rmtp: ?&timespec) -> c_int;43pub extern "c" fn nanosleep(rqtp: &const timespec, rmtp: ?&timespec) -> c_int;
44pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) -> c_int;44pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) -> c_int;
45pub extern "c" fn setregid(rgid: c_uint, egid: c_uint) -> c_int;45pub extern "c" fn setregid(rgid: c_uint, egid: c_uint) -> c_int;
46
47pub extern "c" fn malloc(usize) -> ?&c_void;
48pub extern "c" fn realloc(&c_void, usize) -> ?&c_void;
49pub extern "c" fn free(&c_void);
std/mem.zig+33
...@@ -5,6 +5,7 @@ const os = @import("os/index.zig");...@@ -5,6 +5,7 @@ const os = @import("os/index.zig");
5const io = @import("io.zig");5const io = @import("io.zig");
6const builtin = @import("builtin");6const builtin = @import("builtin");
7const Os = builtin.Os;7const Os = builtin.Os;
8const c = @import("c/index.zig");
89
9pub const Cmp = math.Cmp;10pub const Cmp = math.Cmp;
1011
...@@ -84,6 +85,38 @@ pub const Allocator = struct {...@@ -84,6 +85,38 @@ pub const Allocator = struct {
84 }85 }
85};86};
8687
88pub var c_allocator = Allocator {
89 .allocFn = cAlloc,
90 .reallocFn = cRealloc,
91 .freeFn = cFree,
92};
93
94fn cAlloc(self: &Allocator, n: usize, alignment: usize) -> %[]u8 {
95 if (c.malloc(usize(n))) |mem| {
96 @ptrCast(&u8, mem)[0..n]
97 } else {
98 error.OutOfMemory
99 }
100}
101
102fn cRealloc(self: &Allocator, old_mem: []u8, new_size: usize, alignment: usize) -> %[]u8 {
103 if (new_size <= old_mem.len) {
104 old_mem[0..new_size]
105 } else {
106 const old_ptr = @ptrCast(&c_void, old_mem.ptr);
107 if (c.realloc(old_ptr, usize(new_size))) |mem| {
108 @ptrCast(&u8, mem)[0..new_size]
109 } else {
110 error.OutOfMemory
111 }
112 }
113}
114
115fn cFree(self: &Allocator, old_mem: []u8) {
116 const old_ptr = @ptrCast(&c_void, old_mem.ptr);
117 c.free(old_ptr);
118}
119
87pub const IncrementingAllocator = struct {120pub const IncrementingAllocator = struct {
88 allocator: Allocator,121 allocator: Allocator,
89 bytes: []u8,122 bytes: []u8,