std.ArrayList - rename remove to swapRemove

This commit is contained in:
Andrew Kelley
2018-07-14 10:01:45 -04:00
parent a0c1498e65
commit b44332f5a6

View File

@@ -41,8 +41,8 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
return self.items[0..self.len];
}
pub fn at(self: Self, n: usize) T {
return self.toSliceConst()[n];
pub fn at(self: Self, i: usize) T {
return self.toSliceConst()[i];
}
/// Sets the value at index `i`, or returns `error.OutOfBounds` if
@@ -101,21 +101,22 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
const new_item_ptr = try self.addOne();
new_item_ptr.* = item;
}
/// Removes the element at the specified index and returns it.
// The empty slot is filled from the end of the list.
pub fn remove(self: *Self, n: usize) T {
if(self.len - 1 == n) return self.pop();
var old_item = self.at(n);
self.set(n, self.pop());
/// The empty slot is filled from the end of the list.
pub fn swapRemove(self: *Self, i: usize) T {
if (self.len - 1 == i) return self.pop();
const slice = self.toSlice();
const old_item = slice[i];
slice[i] = self.pop();
return old_item;
}
pub fn removeOrError(self: *Self, n: usize) !T {
if(n >= self.len) return error.OutOfBounds;
if(self.len - 1 == n) return self.pop();
if (n >= self.len) return error.OutOfBounds;
if (self.len - 1 == n) return self.pop();
var old_item = self.at(n);
try self.setOrError(n, self.pop());
return old_item;
@@ -176,7 +177,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
it.count += 1;
return val;
}
pub fn reset(it: *Iterator) void {
it.count = 0;
}
@@ -251,7 +252,7 @@ test "basic ArrayList test" {
assert(list.pop() == 33);
}
test "remove ArrayList test" {
test "std.ArrayList.swapRemove" {
var list = ArrayList(i32).init(debug.global_allocator);
defer list.deinit();
@@ -262,18 +263,18 @@ test "remove ArrayList test" {
try list.append(5);
try list.append(6);
try list.append(7);
//remove from middle
assert(list.remove(3) == 4);
assert(list.swapRemove(3) == 4);
assert(list.at(3) == 7);
assert(list.len == 6);
//remove from end
assert(list.remove(5) == 6);
assert(list.swapRemove(5) == 6);
assert(list.len == 5);
//remove from front
assert(list.remove(0) == 1);
assert(list.swapRemove(0) == 1);
assert(list.at(0) == 5);
assert(list.len == 4);
}