Skip to content

add getLastPtr and getLastOrNullPtr functions to ArrayLists #24379

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions lib/std/array_list.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
};
}

Expand Down Expand Up @@ -1208,13 +1221,27 @@ 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 {
if (self.items.len == 0) return null;
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
Expand Down