authorgravatar for red.black.liquorice@gmail.comHila Friedman <red.black.liquorice@gmail.com> 2026-03-17 02:10:27+01:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-03-17 02:10:27+01:00
logbfd2cc5a3fb05fb45496df544a1f075606aac270
treefc943dc0adf971ab30bacc3a2eab94097b60536f
parent097ca369d57a816512b726423ca97e07875a20c8

even tighter return type for `std.math.sign` (#31485)

The code in #31475 does not return the "smallest integer type that fits possible values" for very small integer types, namely `u0`, `i0`, and `i1` - which all end up with a return type one bit too long. Fixed in this commit. Reviewed-on: https://codeberg.org/ziglang/zig/pulls/31485 Reviewed-by: Andrew Kelley <andrew@ziglang.org> Co-authored-by: Hila Friedman <red.black.liquorice@gmail.com> Co-committed-by: Hila Friedman <red.black.liquorice@gmail.com>

1 files changed, 5 insertions(+), 12 deletions(-)

lib/std/math.zig+5-12
......@@ -1775,10 +1775,7 @@ pub const F80 = struct {
17751775fn SignOf(T: type) type {
17761776 return switch (@typeInfo(T)) {
17771777 .comptime_int, .comptime_float => comptime_int,
1778 .int => |int| switch (int.signedness) {
1779 .signed => IntFittingRange(-1, 1),
1780 .unsigned => IntFittingRange(0, 1),
1781 },
1778 .int => IntFittingRange(@max(minInt(T), -1), @min(maxInt(T), 1)),
17821779 .float => IntFittingRange(-1, 1),
17831780 .vector => |vec| @Vector(vec.len, SignOf(vec.child)),
17841781 else => @compileError("Expected an int, float, or a vector of one, found " ++ @typeName(T)),
......@@ -1792,14 +1789,10 @@ fn SignOf(T: type) type {
17921789/// Branchless.
17931790pub inline fn sign(n: anytype) SignOf(@TypeOf(n)) {
17941791 const T = SignOf(@TypeOf(n));
1795 return switch (@typeInfo(T)) {
1796 .vector => |vec| blk: {
1797 const zero: T = @splat(0);
1798 const one: T = @splat(1);
1799 break :blk @select(vec.child, n > zero, one, zero) - @select(vec.child, n < zero, one, zero);
1800 },
1801 else => @as(T, @intFromBool(n > 0)) - @as(T, @intFromBool(n < 0)),
1802 };
1792 const zero: T = if (@typeInfo(T) == .vector) @splat(0) else 0;
1793 const pos: T = @intCast(@intFromBool(n > zero));
1794 const neg: T = @intCast(@intFromBool(n < zero));
1795 return pos - neg;
18031796}
18041797
18051798fn testSign() !void {