From 537b26034925bf7452db2ff4cd6b29de92d77471 Mon Sep 17 00:00:00 2001 From: Tetralux Date: Mon, 16 Sep 2019 01:35:01 +0000 Subject: [PATCH 1/2] Add FixedBufferAllocator.reset --- std/heap.zig | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/std/heap.zig b/std/heap.zig index d14f34dd6e..046103c445 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -480,6 +480,10 @@ pub const FixedBufferAllocator = struct { fn shrink(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 { return old_mem[0..new_size]; } + + pub inline fn reset(self: *FixedBufferAllocator) void { + self.end_index = 0; + } }; // FIXME: Exposed LLVM intrinsics is a bug @@ -775,6 +779,26 @@ test "FixedBufferAllocator" { try testAllocatorAlignedShrink(&fixed_buffer_allocator.allocator); } +test "FixedBufferAllocator.reset" { + var buf: [8]u8 align(@alignOf(usize)) = undefined; + var fba = FixedBufferAllocator.init(buf[0..]); + + const X = 0xeeeeeeeeeeeeeeee; + const Y = 0xffffffffffffffff; + + var x = try fba.allocator.create(u64); + x.* = X; + testing.expectError(error.OutOfMemory, fba.allocator.create(u64)); + + fba.reset(); + var y = try fba.allocator.create(u64); + y.* = Y; + + // we expect Y to have overwritten X. + testing.expect(x.* == y.*); + testing.expect(y.* == Y); +} + test "FixedBufferAllocator Reuse memory on realloc" { var small_fixed_buffer: [10]u8 = undefined; // check if we re-use the memory From 86b6790b6a7fc7fb6b85d5e970259af60ddd0290 Mon Sep 17 00:00:00 2001 From: Tetralux Date: Sat, 21 Sep 2019 15:42:26 +0000 Subject: [PATCH 2/2] Remove 'inline', as per @andrewrk --- std/heap.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/std/heap.zig b/std/heap.zig index 046103c445..a07f750567 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -481,7 +481,7 @@ pub const FixedBufferAllocator = struct { return old_mem[0..new_size]; } - pub inline fn reset(self: *FixedBufferAllocator) void { + pub fn reset(self: *FixedBufferAllocator) void { self.end_index = 0; } };