diff options
| author | hryx <codroid@gmail.com> | 2019-05-12 02:00:49 -0700 |
|---|---|---|
| committer | hryx <codroid@gmail.com> | 2019-05-12 02:00:49 -0700 |
| commit | 3787f3428625e830fd852a8f5a40c7d8a2d429f6 (patch) | |
| tree | 23fb493b9d2f07c7abe57955874682959936319a /std/array_list.zig | |
| parent | 16aee1f58a80295f7599a8290d764a5c7040c373 (diff) | |
| parent | edcc7c72d1a684a8a16ca23ad26689f2cce4e803 (diff) | |
| download | zig-3787f3428625e830fd852a8f5a40c7d8a2d429f6.tar.gz zig-3787f3428625e830fd852a8f5a40c7d8a2d429f6.zip | |
Merge branch 'master' into rebased
Diffstat (limited to 'std/array_list.zig')
| -rw-r--r-- | std/array_list.zig | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/std/array_list.zig b/std/array_list.zig index b173dab747..ca7d5f911e 100644 --- a/std/array_list.zig +++ b/std/array_list.zig @@ -111,6 +111,17 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { new_item_ptr.* = item; } + pub fn orderedRemove(self: *Self, i: usize) T { + const newlen = self.len - 1; + if (newlen == i) return self.pop(); + + const old_item = self.at(i); + for (self.items[i..newlen]) |*b, j| b.* = self.items[i + 1 + j]; + self.items[newlen] = undefined; + self.len = newlen; + return old_item; + } + /// Removes the element at the specified index and returns it. /// The empty slot is filled from the end of the list. pub fn swapRemove(self: *Self, i: usize) T { @@ -279,6 +290,33 @@ test "std.ArrayList.basic" { testing.expect(list.pop() == 33); } +test "std.ArrayList.orderedRemove" { + var list = ArrayList(i32).init(debug.global_allocator); + defer list.deinit(); + + try list.append(1); + try list.append(2); + try list.append(3); + try list.append(4); + try list.append(5); + try list.append(6); + try list.append(7); + + //remove from middle + testing.expectEqual(i32(4), list.orderedRemove(3)); + testing.expectEqual(i32(5), list.at(3)); + testing.expectEqual(usize(6), list.len); + + //remove from end + testing.expectEqual(i32(7), list.orderedRemove(5)); + testing.expectEqual(usize(5), list.len); + + //remove from front + testing.expectEqual(i32(1), list.orderedRemove(0)); + testing.expectEqual(i32(2), list.at(0)); + testing.expectEqual(usize(4), list.len); +} + test "std.ArrayList.swapRemove" { var list = ArrayList(i32).init(debug.global_allocator); defer list.deinit(); |
