From d3ab0eb28de5a5a94fd4ef988dd4c4b0e3ddf927 Mon Sep 17 00:00:00 2001 From: xackus <14938807+xackus@users.noreply.github.com> Date: Wed, 1 Apr 2020 21:05:46 +0200 Subject: [PATCH] new ArrayList API: fix ArrayList.shrink --- lib/std/array_list.zig | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/std/array_list.zig b/lib/std/array_list.zig index 94383c49ef..c6bb5bf3e7 100644 --- a/lib/std/array_list.zig +++ b/lib/std/array_list.zig @@ -219,7 +219,10 @@ pub fn AlignedArrayList(comptime T: type, comptime alignment: ?u29) type { assert(new_len <= self.items.len); self.items = self.allocator.realloc(self.allocatedSlice(), new_len) catch |e| switch (e) { - error.OutOfMemory => return, // no problem, capacity is still correct then. + error.OutOfMemory => { // no problem, capacity is still correct then. + self.items.len = new_len; + return; + }, }; self.capacity = new_len; } @@ -511,3 +514,18 @@ test "std.ArrayList(u8) implements outStream" { testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.span()); } + +test "std.ArrayList.shrink still sets length on error.OutOfMemory" { + // use an arena allocator to make sure realloc returns error.OutOfMemory + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + + var list = ArrayList(i32).init(&arena.allocator); + + try list.append(1); + try list.append(2); + try list.append(3); + + list.shrink(1); + testing.expect(list.items.len == 1); +}