Skip to content

Commit 1de96a2

Browse files
chrboeschVexu
authored andcommitted
Add the two functions 'getLast' and 'getLastOrNull' to ArrayListAligned/ArrayListAlignedUnmanaged.
1 parent 8094fa5 commit 1de96a2

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

lib/std/array_list.zig

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,20 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
468468
pub fn unusedCapacitySlice(self: Self) Slice {
469469
return self.allocatedSlice()[self.items.len..];
470470
}
471+
472+
/// Return the last element from the list.
473+
/// Asserts the list has at least one item.
474+
pub fn getLast(self: *Self) T {
475+
const val = self.items[self.items.len - 1];
476+
return val;
477+
}
478+
479+
/// Return the last element from the list, or
480+
/// return `null` if list is empty.
481+
pub fn getLastOrNull(self: *Self) ?T {
482+
if (self.items.len == 0) return null;
483+
return self.getLast();
484+
}
471485
};
472486
}
473487

@@ -913,6 +927,20 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
913927
pub fn unusedCapacitySlice(self: Self) Slice {
914928
return self.allocatedSlice()[self.items.len..];
915929
}
930+
931+
/// Return the last element from the list.
932+
/// Asserts the list has at least one item.
933+
pub fn getLast(self: *Self) T {
934+
const val = self.items[self.items.len - 1];
935+
return val;
936+
}
937+
938+
/// Return the last element from the list, or
939+
/// return `null` if list is empty.
940+
pub fn getLastOrNull(self: *Self) ?T {
941+
if (self.items.len == 0) return null;
942+
return self.getLast();
943+
}
916944
};
917945
}
918946

0 commit comments

Comments
 (0)