Skip to content

Commit fca3e3a

Browse files
daurnimatorandrewrk
authored andcommitted
std: add std.ArrayList.orderedRemove
1 parent 3552180 commit fca3e3a

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

std/array_list.zig

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,17 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
111111
new_item_ptr.* = item;
112112
}
113113

114+
pub fn orderedRemove(self: *Self, i: usize) T {
115+
const newlen = self.len - 1;
116+
if (newlen == i) return self.pop();
117+
118+
const old_item = self.at(i);
119+
for (self.items[i..newlen]) |*b, j| b.* = self.items[i + 1 + j];
120+
self.items[newlen] = undefined;
121+
self.len = newlen;
122+
return old_item;
123+
}
124+
114125
/// Removes the element at the specified index and returns it.
115126
/// The empty slot is filled from the end of the list.
116127
pub fn swapRemove(self: *Self, i: usize) T {
@@ -279,6 +290,33 @@ test "std.ArrayList.basic" {
279290
testing.expect(list.pop() == 33);
280291
}
281292

293+
test "std.ArrayList.orderedRemove" {
294+
var list = ArrayList(i32).init(debug.global_allocator);
295+
defer list.deinit();
296+
297+
try list.append(1);
298+
try list.append(2);
299+
try list.append(3);
300+
try list.append(4);
301+
try list.append(5);
302+
try list.append(6);
303+
try list.append(7);
304+
305+
//remove from middle
306+
testing.expectEqual(i32(4), list.orderedRemove(3));
307+
testing.expectEqual(i32(5), list.at(3));
308+
testing.expectEqual(usize(6), list.len);
309+
310+
//remove from end
311+
testing.expectEqual(i32(7), list.orderedRemove(5));
312+
testing.expectEqual(usize(5), list.len);
313+
314+
//remove from front
315+
testing.expectEqual(i32(1), list.orderedRemove(0));
316+
testing.expectEqual(i32(2), list.at(0));
317+
testing.expectEqual(usize(4), list.len);
318+
}
319+
282320
test "std.ArrayList.swapRemove" {
283321
var list = ArrayList(i32).init(debug.global_allocator);
284322
defer list.deinit();

0 commit comments

Comments
 (0)