authorgravatar for kuon@goyman.comNicolas Goy <kuon@goyman.com> 2023-02-04 03:01:47+01:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-02-04 15:24:45-05:00
logb7c96c3bbdc0e2172cf9edb0c9c7c52f86c2311e
tree06a84973a7a392377ca74f9efc786385f4e5111d
parent7f249937727fd58b66c00b53338e99bd8bf45e5b

Allow const for ArrayList.getLast, fix #14522


1 files changed, 28 insertions(+), 4 deletions(-)

lib/std/array_list.zig+28-4
......@@ -482,14 +482,14 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
482482
483483 /// Return the last element from the list.
484484 /// Asserts the list has at least one item.
485 pub fn getLast(self: *Self) T {
485 pub fn getLast(self: Self) T {
486486 const val = self.items[self.items.len - 1];
487487 return val;
488488 }
489489
490490 /// Return the last element from the list, or
491491 /// return `null` if list is empty.
492 pub fn getLastOrNull(self: *Self) ?T {
492 pub fn getLastOrNull(self: Self) ?T {
493493 if (self.items.len == 0) return null;
494494 return self.getLast();
495495 }
......@@ -961,14 +961,14 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
961961
962962 /// Return the last element from the list.
963963 /// Asserts the list has at least one item.
964 pub fn getLast(self: *Self) T {
964 pub fn getLast(self: Self) T {
965965 const val = self.items[self.items.len - 1];
966966 return val;
967967 }
968968
969969 /// Return the last element from the list, or
970970 /// return `null` if list is empty.
971 pub fn getLastOrNull(self: *Self) ?T {
971 pub fn getLastOrNull(self: Self) ?T {
972972 if (self.items.len == 0) return null;
973973 return self.getLast();
974974 }
......@@ -1719,3 +1719,27 @@ test "std.ArrayList(?u32).popOrNull()" {
17191719 try testing.expect(list.popOrNull().? == null);
17201720 try testing.expect(list.popOrNull() == null);
17211721}
1722
1723test "std.ArrayList(u32).getLast()" {
1724 const a = testing.allocator;
1725
1726 var list = ArrayList(u32).init(a);
1727 defer list.deinit();
1728
1729 try list.append(2);
1730 const const_list = list;
1731 try testing.expectEqual(const_list.getLast(), 2);
1732}
1733
1734test "std.ArrayList(u32).getLastOrNull()" {
1735 const a = testing.allocator;
1736
1737 var list = ArrayList(u32).init(a);
1738 defer list.deinit();
1739
1740 try testing.expectEqual(list.getLastOrNull(), null);
1741
1742 try list.append(2);
1743 const const_list = list;
1744 try testing.expectEqual(const_list.getLastOrNull().?, 2);
1745}