authorgravatar for 14938807+xackus@users.noreply.github.comxackus <14938807+xackus@users.noreply.github.com> 2020-04-01 21:05:46+02:00
committergravatar for 14938807+xackus@users.noreply.github.comxackus <14938807+xackus@users.noreply.github.com> 2020-04-02 15:15:20+02:00
logd3ab0eb28de5a5a94fd4ef988dd4c4b0e3ddf927
tree81a9bff32e67519529b1c6ae323b851ee7626a26
parent93a20f2e825790daa487eae0ccec3d7c9126f42c

new ArrayList API: fix ArrayList.shrink


1 files changed, 19 insertions(+), 1 deletions(-)

lib/std/array_list.zig+19-1
......@@ -219,7 +219,10 @@ pub fn AlignedArrayList(comptime T: type, comptime alignment: ?u29) type {
219219 assert(new_len <= self.items.len);
220220
221221 self.items = self.allocator.realloc(self.allocatedSlice(), new_len) catch |e| switch (e) {
222 error.OutOfMemory => return, // no problem, capacity is still correct then.
222 error.OutOfMemory => { // no problem, capacity is still correct then.
223 self.items.len = new_len;
224 return;
225 },
223226 };
224227 self.capacity = new_len;
225228 }
......@@ -511,3 +514,18 @@ test "std.ArrayList(u8) implements outStream" {
511514
512515 testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.span());
513516}
517
518test "std.ArrayList.shrink still sets length on error.OutOfMemory" {
519 // use an arena allocator to make sure realloc returns error.OutOfMemory
520 var arena = std.heap.ArenaAllocator.init(testing.allocator);
521 defer arena.deinit();
522
523 var list = ArrayList(i32).init(&arena.allocator);
524
525 try list.append(1);
526 try list.append(2);
527 try list.append(3);
528
529 list.shrink(1);
530 testing.expect(list.items.len == 1);
531}