| ... | @@ -111,6 +111,17 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { | ... | @@ -111,6 +111,17 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { |
| 111 | new_item_ptr.* = item; | 111 | new_item_ptr.* = item; |
| 112 | } | 112 | } |
| 113 | | 113 | |
| | 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 | |
| 114 | /// Removes the element at the specified index and returns it. | 125 | /// Removes the element at the specified index and returns it. |
| 115 | /// The empty slot is filled from the end of the list. | 126 | /// The empty slot is filled from the end of the list. |
| 116 | pub fn swapRemove(self: *Self, i: usize) T { | 127 | pub fn swapRemove(self: *Self, i: usize) T { |
| ... | @@ -279,6 +290,33 @@ test "std.ArrayList.basic" { | ... | @@ -279,6 +290,33 @@ test "std.ArrayList.basic" { |
| 279 | testing.expect(list.pop() == 33); | 290 | testing.expect(list.pop() == 33); |
| 280 | } | 291 | } |
| 281 | | 292 | |
| | 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 | |
| 282 | test "std.ArrayList.swapRemove" { | 320 | test "std.ArrayList.swapRemove" { |
| 283 | var list = ArrayList(i32).init(debug.global_allocator); | 321 | var list = ArrayList(i32).init(debug.global_allocator); |
| 284 | defer list.deinit(); | 322 | defer list.deinit(); |