From 42b1b6be90fc1034875a6e16cf3cbe1c9d6030ca Mon Sep 17 00:00:00 2001 From: Mark Barbone Date: Mon, 7 Sep 2020 23:24:35 -0400 Subject: [PATCH] Add resize for arena allocator --- lib/std/heap/arena_allocator.zig | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/std/heap/arena_allocator.zig b/lib/std/heap/arena_allocator.zig index e4bce8087f..0737cb2ef8 100644 --- a/lib/std/heap/arena_allocator.zig +++ b/lib/std/heap/arena_allocator.zig @@ -26,7 +26,7 @@ pub const ArenaAllocator = struct { return .{ .allocator = Allocator{ .allocFn = alloc, - .resizeFn = Allocator.noResize, + .resizeFn = resize, }, .child_allocator = child_allocator, .state = self, @@ -84,4 +84,26 @@ pub const ArenaAllocator = struct { return result; } } + + fn resize(allocator: *Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) Allocator.Error!usize { + const self = @fieldParentPtr(ArenaAllocator, "allocator", allocator); + + const cur_node = self.state.buffer_list.first orelse return error.OutOfMemory; + const cur_buf = cur_node.data[@sizeOf(BufNode)..]; + if (@ptrToInt(cur_buf.ptr) + self.state.end_index != @ptrToInt(buf.ptr) + buf.len) { + if (new_len > buf.len) + return error.OutOfMemory; + return new_len; + } + + if (buf.len >= new_len) { + self.state.end_index -= buf.len - new_len; + return new_len; + } else if (cur_buf.len - self.state.end_index >= new_len - buf.len) { + self.state.end_index += new_len - buf.len; + return new_len; + } else { + return error.OutOfMemory; + } + } };