diff options
| author | daurnimator <quae@daurnimator.com> | 2020-03-05 15:59:19 +1100 |
|---|---|---|
| committer | daurnimator <quae@daurnimator.com> | 2020-03-05 16:00:19 +1100 |
| commit | 488ba1560fb80c1115b3b4794031859c0063ba3e (patch) | |
| tree | 9a83d6820cc0788fb64511691c0f2789aebdfd55 /lib/std/math.zig | |
| parent | 4f58bfe1a81a385ac9120510b816ff081ab73437 (diff) | |
| download | zig-488ba1560fb80c1115b3b4794031859c0063ba3e.tar.gz zig-488ba1560fb80c1115b3b4794031859c0063ba3e.zip | |
std: fix math.absCast on i1
Diffstat (limited to 'lib/std/math.zig')
| -rw-r--r-- | lib/std/math.zig | 36 |
1 files changed, 24 insertions, 12 deletions
diff --git a/lib/std/math.zig b/lib/std/math.zig index 9a1143a17d..a411b58fac 100644 --- a/lib/std/math.zig +++ b/lib/std/math.zig @@ -670,23 +670,35 @@ fn testRem() void { /// Returns the absolute value of the integer parameter. /// Result is an unsigned integer. -pub fn absCast(x: var) t: { - if (@TypeOf(x) == comptime_int) { - break :t comptime_int; - } else { - break :t std.meta.IntType(false, @TypeOf(x).bit_count); +pub fn absCast(x: var) switch(@typeInfo(@TypeOf(x))) { + .ComptimeInt => comptime_int, + .Int => |intInfo| std.meta.IntType(false, intInfo.bits), + else => @compileError("absCast only accepts integers"), } -} { - if (@TypeOf(x) == comptime_int) { - return if (x < 0) -x else x; +{ + switch(@typeInfo(@TypeOf(x))) { + .ComptimeInt => { + if (x < 0) { + return -x; + } else { + return x; + } + }, + .Int => |intInfo| { + const Uint = std.meta.IntType(false, intInfo.bits); + if (x < 0) { + return ~@bitCast(Uint, x +% -1); + } else { + return @intCast(Uint, x); + } + }, + else => unreachable, } - const uint = std.meta.IntType(false, @TypeOf(x).bit_count); - if (x >= 0) return @intCast(uint, x); - - return @intCast(uint, -(x + 1)) + 1; } test "math.absCast" { + testing.expect(absCast(@as(i1, -1)) == 1); + testing.expect(absCast(@as(i32, -999)) == 999); testing.expect(@TypeOf(absCast(@as(i32, -999))) == u32); |
