| ... | @@ -5,6 +5,7 @@ const os = @import("os/index.zig"); | ... | @@ -5,6 +5,7 @@ const os = @import("os/index.zig"); |
| 5 | const io = @import("io.zig"); | 5 | const io = @import("io.zig"); |
| 6 | const builtin = @import("builtin"); | 6 | const builtin = @import("builtin"); |
| 7 | const Os = builtin.Os; | 7 | const Os = builtin.Os; |
| | 8 | const c = @import("c/index.zig"); |
| 8 | | 9 | |
| 9 | pub const Cmp = math.Cmp; | 10 | pub const Cmp = math.Cmp; |
| 10 | | 11 | |
| ... | @@ -84,6 +85,38 @@ pub const Allocator = struct { | ... | @@ -84,6 +85,38 @@ pub const Allocator = struct { |
| 84 | } | 85 | } |
| 85 | }; | 86 | }; |
| 86 | | 87 | |
| | 88 | pub var c_allocator = Allocator { |
| | 89 | .allocFn = cAlloc, |
| | 90 | .reallocFn = cRealloc, |
| | 91 | .freeFn = cFree, |
| | 92 | }; |
| | 93 | |
| | 94 | fn 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 | |
| | 102 | fn 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 | |
| | 115 | fn cFree(self: &Allocator, old_mem: []u8) { |
| | 116 | const old_ptr = @ptrCast(&c_void, old_mem.ptr); |
| | 117 | c.free(old_ptr); |
| | 118 | } |
| | 119 | |
| 87 | pub const IncrementingAllocator = struct { | 120 | pub const IncrementingAllocator = struct { |
| 88 | allocator: Allocator, | 121 | allocator: Allocator, |
| 89 | bytes: []u8, | 122 | bytes: []u8, |