Skip to content

Commit 288198e

Browse files
authored
Merge pull request #6413 from LemonBoy/fix-5116
Make ArenaAllocator try to resize first
2 parents f8b3543 + bd9003e commit 288198e

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

lib/std/heap.zig

+7
Original file line numberDiff line numberDiff line change
@@ -919,6 +919,13 @@ pub fn testAllocator(base_allocator: *mem.Allocator) !void {
919919
const zero_bit_ptr = try allocator.create(u0);
920920
zero_bit_ptr.* = 0;
921921
allocator.destroy(zero_bit_ptr);
922+
923+
const oversize = try allocator.allocAdvanced(u32, null, 5, .at_least);
924+
testing.expect(oversize.len >= 5);
925+
for (oversize) |*item| {
926+
item.* = 0xDEADBEEF;
927+
}
928+
allocator.free(oversize);
922929
}
923930

924931
pub fn testAllocatorAligned(base_allocator: *mem.Allocator, comptime alignment: u29) !void {

lib/std/heap/arena_allocator.zig

+15-6
Original file line numberDiff line numberDiff line change
@@ -75,13 +75,22 @@ pub const ArenaAllocator = struct {
7575
const adjusted_addr = mem.alignForward(addr, ptr_align);
7676
const adjusted_index = self.state.end_index + (adjusted_addr - addr);
7777
const new_end_index = adjusted_index + n;
78-
if (new_end_index > cur_buf.len) {
79-
cur_node = try self.createNode(cur_buf.len, n + ptr_align);
80-
continue;
78+
79+
if (new_end_index <= cur_buf.len) {
80+
const result = cur_buf[adjusted_index..new_end_index];
81+
self.state.end_index = new_end_index;
82+
return result;
8183
}
82-
const result = cur_buf[adjusted_index..new_end_index];
83-
self.state.end_index = new_end_index;
84-
return result;
84+
85+
const bigger_buf_size = @sizeOf(BufNode) + new_end_index;
86+
// Try to grow the buffer in-place
87+
cur_node.data = self.child_allocator.resize(cur_node.data, bigger_buf_size) catch |err| switch (err) {
88+
error.OutOfMemory => {
89+
// Allocate a new node if that's not possible
90+
cur_node = try self.createNode(cur_buf.len, n + ptr_align);
91+
continue;
92+
},
93+
};
8594
}
8695
}
8796

0 commit comments

Comments
 (0)