Skip to content

std.math.sign: Narrow integer return types to possible values #23595

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
16 changes: 14 additions & 2 deletions lib/std/math.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1735,12 +1735,24 @@ pub const F80 = struct {
}
};

fn Sign(T: type) type {
return switch (@typeInfo(T)) {
.int => |int| IntFittingRange(if (int.signedness == .signed) -1 else 0, 1),
.vector => |vec| switch (@typeInfo(vec.child)) {
.int => |int| @Vector(vec.len, IntFittingRange(if (int.signedness == .signed) -1 else 0, 1)),
else => T,
},
else => T,
};
}

/// Returns -1, 0, or 1.
/// Supports integer and float types and vectors of integer and float types.
/// Unsigned integer types will always return 0 or 1.
/// Returned integer types are narrowed to fit the possible values.
/// Branchless.
pub inline fn sign(i: anytype) @TypeOf(i) {
const T = @TypeOf(i);
pub inline fn sign(i: anytype) Sign(@TypeOf(i)) {
const T = Sign(@TypeOf(i));
return switch (@typeInfo(T)) {
.int, .comptime_int => @as(T, @intFromBool(i > 0)) - @as(T, @intFromBool(i < 0)),
.float, .comptime_float => @as(T, @floatFromInt(@intFromBool(i > 0))) - @as(T, @floatFromInt(@intFromBool(i < 0))),
Expand Down
Loading