Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make ArenaAllocator try to resize first #6413

Merged
merged 1 commit into from
Sep 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions lib/std/heap.zig
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,13 @@ pub fn testAllocator(base_allocator: *mem.Allocator) !void {
const zero_bit_ptr = try allocator.create(u0);
zero_bit_ptr.* = 0;
allocator.destroy(zero_bit_ptr);

const oversize = try allocator.allocAdvanced(u32, null, 5, .at_least);
testing.expect(oversize.len >= 5);
for (oversize) |*item| {
item.* = 0xDEADBEEF;
}
allocator.free(oversize);
}

pub fn testAllocatorAligned(base_allocator: *mem.Allocator, comptime alignment: u29) !void {
Expand Down
21 changes: 15 additions & 6 deletions lib/std/heap/arena_allocator.zig
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,22 @@ 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;
}
const result = cur_buf[adjusted_index..new_end_index];
self.state.end_index = new_end_index;
return result;

const bigger_buf_size = @sizeOf(BufNode) + new_end_index;
// Try to grow the buffer in-place
cur_node.data = self.child_allocator.resize(cur_node.data, bigger_buf_size) catch |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);
continue;
},
};
}
}

Expand Down