authorgravatar for 59504965+InKryption@users.noreply.github.comInKryption <59504965+InKryption@users.noreply.github.com> 2022-04-30 04:51:53+02:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2022-04-29 22:51:53-04:00
log609896a6e8180ec32844d2b4656b52ef41fe7757
tree40a08d2ad0a986fdf6c8d2ddd161776836e6652e
parentcc39d453c45645296cd771c94d97b8a77469be91
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

std.MultiArrayList: add functions `addOne`, `pop`, and `popOrNull` (#11553)

Update basic usage test to account for these, and by extension for addOneAssumeCapacity.

1 files changed, 36 insertions(+), 0 deletions(-)

lib/std/multi_array_list.zig+36
......@@ -178,6 +178,14 @@ pub fn MultiArrayList(comptime S: type) type {
178178 self.set(self.len - 1, elem);
179179 }
180180
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
181189 /// Extend the list by 1 element, asserting `self.capacity`
182190 /// is sufficient to hold an additional item. Returns the
183191 /// newly reserved index with uninitialized data.
......@@ -188,6 +196,23 @@ pub fn MultiArrayList(comptime S: type) type {
188196 return index;
189197 }
190198
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
191216 /// Inserts an item into an ordered list. Shifts all elements
192217 /// after and including the specified index back by one and
193218 /// sets the given index to the specified element. May reallocate
......@@ -532,6 +557,17 @@ test "basic usage" {
532557 try testing.expectEqualStrings("foobar", list.items(.b)[0]);
533558 try testing.expectEqualStrings("zigzag", list.items(.b)[1]);
534559 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());
535571}
536572
537573// This was observed to fail on aarch64 with LLVM 11, when the capacityInBytes