From 792ee472ee6b15bf9bf52c570d91470e4d5a407c Mon Sep 17 00:00:00 2001 From: Lu2i8a Date: Thu, 10 Jul 2025 00:47:56 +0200 Subject: [PATCH] add getLastPtr and getLastOrNullPtr functions to ArrayLists --- lib/std/array_list.zig | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/lib/std/array_list.zig b/lib/std/array_list.zig index 2a9159aeac71..b81c116a4d0d 100644 --- a/lib/std/array_list.zig +++ b/lib/std/array_list.zig @@ -586,11 +586,24 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?mem.Alignment) ty return val; } + /// Returns a pointer to the last element from the list. + /// Asserts that the list is not empty. + pub fn getLastPtr(self: Self) *T { + const val = &self.items[self.items.len - 1]; + return val; + } + /// Returns the last element from the list, or `null` if list is empty. pub fn getLastOrNull(self: Self) ?T { if (self.items.len == 0) return null; return self.getLast(); } + + /// Returns a pointer to the last element from the list, or `null` if list is empty. + pub fn getLastOrNullPtr(self: Self) ?*T { + if (self.items.len == 0) return null; + return self.getLastPtr(); + } }; } @@ -1208,6 +1221,13 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?mem.Alig return val; } + /// Return a pointer to the last element from the list. + /// Asserts that the list is not empty. + pub fn getLastPtr(self: Self) *T { + const val = &self.items[self.items.len - 1]; + return val; + } + /// Return the last element from the list, or /// return `null` if list is empty. pub fn getLastOrNull(self: Self) ?T { @@ -1215,6 +1235,13 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?mem.Alig return self.getLast(); } + /// Return a pointer the last element from the list, or + /// return `null` if list is empty. + pub fn getLastOrNullPtr(self: Self) ?*T { + if (self.items.len == 0) return null; + return self.getLastPtr(); + } + const init_capacity = @as(comptime_int, @max(1, std.atomic.cache_line / @sizeOf(T))); /// Called when memory growth is necessary. Returns a capacity larger than