Skip to content

Add getSentinel helper to Pointer and Array builtin.Types #21993

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

Closed
wants to merge 1 commit into from
Closed
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
16 changes: 16 additions & 0 deletions lib/std/builtin.zig
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,7 @@ pub const Type = union(enum) {
/// The type of the sentinel is the element type of the pointer, which is
/// the value of the `child` field in this struct. However there is no way
/// to refer to that type here, so we use pointer to `anyopaque`.
/// See `getSentinel` for an easier way to access this value.
sentinel: ?*const anyopaque,

/// This data structure is used by the Zig language code generation and
Expand All @@ -617,6 +618,14 @@ pub const Type = union(enum) {
Slice,
C,
};

/// Returns the sentinel value casted to the child type
/// Asserts that `pointer.size` is `.Many` or `.Slice`
/// and that `pointer.sentinel` is non-null
pub fn getSentinel(pointer: Pointer) pointer.child {
std.debug.assert(pointer.size == .Many or pointer.size == .Slice);
return @as(*const pointer.child, @ptrCast(@alignCast(pointer.sentinel.?))).*;
}
};

/// This data structure is used by the Zig language code generation and
Expand All @@ -628,7 +637,14 @@ pub const Type = union(enum) {
/// The type of the sentinel is the element type of the array, which is
/// the value of the `child` field in this struct. However there is no way
/// to refer to that type here, so we use pointer to `anyopaque`.
/// See `getSentinel` for an easier way to access this value.
sentinel: ?*const anyopaque,

/// Returns the sentinel value casted to the child type
/// Asserts that `array.sentinel` is non-null
pub fn getSentinel(array: Array) array.child {
return @as(*const array.child, @ptrCast(@alignCast(array.sentinel.?))).*;
}
};

/// This data structure is used by the Zig language code generation and
Expand Down
Loading