From 3cbf59b4c1a431ebd1ccb0cf46fa37e367b8106e Mon Sep 17 00:00:00 2001 From: Wink Saville Date: Tue, 17 Jul 2018 07:29:42 -0700 Subject: [PATCH] Add swapRemoveOrError (#1254) * Add swapRemoveOrError, this mirrors setOrError. --- std/array_list.zig | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/std/array_list.zig b/std/array_list.zig index 8a9037a033..298026d11c 100644 --- a/std/array_list.zig +++ b/std/array_list.zig @@ -113,6 +113,14 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { return old_item; } + /// Removes the element at the specified index and returns it + /// or an error.OutOfBounds is returned. If no error then + /// the empty slot is filled from the end of the list. + pub fn swapRemoveOrError(self: *Self, i: usize) !T { + if (i >= self.len) return error.OutOfBounds; + return self.swapRemove(i); + } + pub fn appendSlice(self: *Self, items: []align(A) const T) !void { try self.ensureCapacity(self.len + items.len); mem.copy(T, self.items[self.len..], items); @@ -270,6 +278,34 @@ test "std.ArrayList.swapRemove" { assert(list.len == 4); } +test "std.ArrayList.swapRemoveOrError" { + var list = ArrayList(i32).init(debug.global_allocator); + defer list.deinit(); + + // Test just after initialization + assertError(list.swapRemoveOrError(0), error.OutOfBounds); + + // Test after adding one item and remote it + try list.append(1); + assert((try list.swapRemoveOrError(0)) == 1); + assertError(list.swapRemoveOrError(0), error.OutOfBounds); + + // Test after adding two items and remote both + try list.append(1); + try list.append(2); + assert((try list.swapRemoveOrError(1)) == 2); + assert((try list.swapRemoveOrError(0)) == 1); + assertError(list.swapRemoveOrError(0), error.OutOfBounds); + + // Test out of bounds with one item + try list.append(1); + assertError(list.swapRemoveOrError(1), error.OutOfBounds); + + // Test out of bounds with two items + try list.append(2); + assertError(list.swapRemoveOrError(2), error.OutOfBounds); +} + test "std.ArrayList.iterator" { var list = ArrayList(i32).init(debug.global_allocator); defer list.deinit();