| ... | ... | @@ -178,6 +178,14 @@ pub fn MultiArrayList(comptime S: type) type { |
| 178 | 178 | self.set(self.len - 1, elem); |
| 179 | 179 | } |
| 180 | 180 | |
| 181 | /// Extend the list by 1 element, returning the newly reserved |
| 182 | /// index with uninitialized data. |
| 183 | /// Allocates more memory as necesasry. |
| 184 | pub fn addOne(self: *Self, allocator: Allocator) Allocator.Error!usize { |
| 185 | try self.ensureUnusedCapacity(allocator, 1); |
| 186 | return self.addOneAssumeCapacity(); |
| 187 | } |
| 188 | |
| 181 | 189 | /// Extend the list by 1 element, asserting `self.capacity` |
| 182 | 190 | /// is sufficient to hold an additional item. Returns the |
| 183 | 191 | /// newly reserved index with uninitialized data. |
| ... | ... | @@ -188,6 +196,23 @@ pub fn MultiArrayList(comptime S: type) type { |
| 188 | 196 | return index; |
| 189 | 197 | } |
| 190 | 198 | |
| 199 | /// Remove and return the last element from the list. |
| 200 | /// Asserts the list has at least one item. |
| 201 | /// Invalidates pointers to fields of the removed element. |
| 202 | pub fn pop(self: *Self) S { |
| 203 | const val = self.get(self.len - 1); |
| 204 | self.len -= 1; |
| 205 | return val; |
| 206 | } |
| 207 | |
| 208 | /// Remove and return the last element from the list, or |
| 209 | /// return `null` if list is empty. |
| 210 | /// Invalidates pointers to fields of the removed element, if any. |
| 211 | pub fn popOrNull(self: *Self) ?S { |
| 212 | if (self.len == 0) return null; |
| 213 | return self.pop(); |
| 214 | } |
| 215 | |
| 191 | 216 | /// Inserts an item into an ordered list. Shifts all elements |
| 192 | 217 | /// after and including the specified index back by one and |
| 193 | 218 | /// sets the given index to the specified element. May reallocate |
| ... | ... | @@ -532,6 +557,17 @@ test "basic usage" { |
| 532 | 557 | try testing.expectEqualStrings("foobar", list.items(.b)[0]); |
| 533 | 558 | try testing.expectEqualStrings("zigzag", list.items(.b)[1]); |
| 534 | 559 | try testing.expectEqualStrings("fizzbuzz", list.items(.b)[2]); |
| 560 | |
| 561 | list.set(try list.addOne(ally), .{ |
| 562 | .a = 4, |
| 563 | .b = "xnopyt", |
| 564 | .c = 'd', |
| 565 | }); |
| 566 | try testing.expectEqualStrings("xnopyt", list.pop().b); |
| 567 | try testing.expectEqual(@as(?u8, 'c'), if (list.popOrNull()) |elem| elem.c else null); |
| 568 | try testing.expectEqual(@as(u32, 2), list.pop().a); |
| 569 | try testing.expectEqual(@as(u8, 'a'), list.pop().c); |
| 570 | try testing.expectEqual(@as(?Foo, null), list.popOrNull()); |
| 535 | 571 | } |
| 536 | 572 | |
| 537 | 573 | // This was observed to fail on aarch64 with LLVM 11, when the capacityInBytes |