Skip to content

Commit

Permalink
std: ArenaAllocator tries to resize before allocating
Browse files Browse the repository at this point in the history
  • Loading branch information
LemonBoy committed Sep 24, 2020
1 parent bd89bd6 commit fe64ae5
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions lib/std/heap/arena_allocator.zig
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,29 @@ pub const ArenaAllocator = struct {
const adjusted_addr = mem.alignForward(addr, ptr_align);
const adjusted_index = self.state.end_index + (adjusted_addr - addr);
const new_end_index = adjusted_index + n;
if (new_end_index > cur_buf.len) {
cur_node = try self.createNode(cur_buf.len, n + ptr_align);
continue;

if (new_end_index <= cur_buf.len) {
const result = cur_buf[adjusted_index..new_end_index];
self.state.end_index = new_end_index;
return result;
}

// Try to grow the buffer in-place
if (self.child_allocator.resizeFn(
self.child_allocator,
cur_node.data,
@alignOf(BufNode),
new_end_index,
1,
@returnAddress(),
)) |new_size| {
assert(new_size >= new_end_index);
} else |err| switch (err) {
error.OutOfMemory => {
// Allocate a new node if that's not possible
cur_node = try self.createNode(cur_buf.len, n + ptr_align);
},
}
const result = cur_buf[adjusted_index..new_end_index];
self.state.end_index = new_end_index;
return result;
}
}

Expand Down

0 comments on commit fe64ae5

Please sign in to comment.