Add resize for arena allocator

This commit is contained in:
Mark Barbone 2020-09-07 23:24:35 -04:00 committed by Andrew Kelley
parent 5bf3e54018
commit 42b1b6be90

View File

@ -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;
}
}
};