Skip to content

Commit

Permalink
std.MultiArrayList: popOrNull() -> pop()
Browse files Browse the repository at this point in the history
  • Loading branch information
nektro authored and andrewrk committed Feb 8, 2025
1 parent a06a710 commit 84d2c6d
Showing 1 changed file with 8 additions and 16 deletions.
24 changes: 8 additions & 16 deletions lib/std/multi_array_list.zig
Original file line number Diff line number Diff line change
Expand Up @@ -263,23 +263,15 @@ pub fn MultiArrayList(comptime T: type) type {
return index;
}

/// Remove and return the last element from the list.
/// Asserts the list has at least one item.
/// Remove and return the last element from the list, or return `null` if list is empty.
/// Invalidates pointers to fields of the removed element.
pub fn pop(self: *Self) T {
pub fn pop(self: *Self) ?T {
if (self.len == 0) return null;
const val = self.get(self.len - 1);
self.len -= 1;
return val;
}

/// Remove and return the last element from the list, or
/// return `null` if list is empty.
/// Invalidates pointers to fields of the removed element, if any.
pub fn popOrNull(self: *Self) ?T {
if (self.len == 0) return null;
return self.pop();
}

/// Inserts an item into an ordered list. Shifts all elements
/// after and including the specified index back by one and
/// sets the given index to the specified element. May reallocate
Expand Down Expand Up @@ -685,11 +677,11 @@ test "basic usage" {
.b = "xnopyt",
.c = 'd',
});
try testing.expectEqualStrings("xnopyt", list.pop().b);
try testing.expectEqual(@as(?u8, 'c'), if (list.popOrNull()) |elem| elem.c else null);
try testing.expectEqual(@as(u32, 2), list.pop().a);
try testing.expectEqual(@as(u8, 'a'), list.pop().c);
try testing.expectEqual(@as(?Foo, null), list.popOrNull());
try testing.expectEqualStrings("xnopyt", list.pop().?.b);
try testing.expectEqual(@as(?u8, 'c'), if (list.pop()) |elem| elem.c else null);
try testing.expectEqual(@as(u32, 2), list.pop().?.a);
try testing.expectEqual(@as(u8, 'a'), list.pop().?.c);
try testing.expectEqual(@as(?Foo, null), list.pop());

list.clearRetainingCapacity();
try testing.expectEqual(0, list.len);
Expand Down

0 comments on commit 84d2c6d

Please sign in to comment.