From 09d19a004b0c2e7ad522e282dd11fa3a691035a2 Mon Sep 17 00:00:00 2001 From: LemonBoy Date: Fri, 25 Sep 2020 00:24:20 +0200 Subject: [PATCH] std: Add a test for allocations requesting at least N bytes --- lib/std/heap.zig | 7 +++++++ lib/std/heap/arena_allocator.zig | 5 +++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/std/heap.zig b/lib/std/heap.zig index 16de215cc2e1..cf32cff645a8 100644 --- a/lib/std/heap.zig +++ b/lib/std/heap.zig @@ -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 { diff --git a/lib/std/heap/arena_allocator.zig b/lib/std/heap/arena_allocator.zig index 8e22efb7d3fc..5da00c3c5af8 100644 --- a/lib/std/heap/arena_allocator.zig +++ b/lib/std/heap/arena_allocator.zig @@ -82,16 +82,17 @@ pub const ArenaAllocator = struct { return result; } + const bigger_buf_size = @sizeOf(BufNode) + new_end_index; // Try to grow the buffer in-place if (self.child_allocator.resizeFn( self.child_allocator, cur_node.data, @alignOf(BufNode), - new_end_index, + bigger_buf_size, 1, @returnAddress(), )) |new_size| { - assert(new_size >= new_end_index); + assert(new_size >= bigger_buf_size); } else |err| switch (err) { error.OutOfMemory => { // Allocate a new node if that's not possible