From 488ba1560fb80c1115b3b4794031859c0063ba3e Mon Sep 17 00:00:00 2001 From: daurnimator Date: Thu, 5 Mar 2020 15:59:19 +1100 Subject: [PATCH] std: fix math.absCast on i1 --- lib/std/fmt.zig | 2 +- lib/std/math.zig | 36 ++++++++++++++++++++++++------------ 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/lib/std/fmt.zig b/lib/std/fmt.zig index a439ecbdd6..240443bbde 100644 --- a/lib/std/fmt.zig +++ b/lib/std/fmt.zig @@ -947,7 +947,7 @@ fn formatIntSigned( const Uint = std.meta.IntType(false, bit_count); if (value < 0) { try output(context, "-"); - const new_value = ~@bitCast(Uint, value +% -1); + const new_value = math.absCast(value); return formatIntUnsigned(new_value, base, uppercase, new_options, context, Errors, output); } else if (options.width == null or options.width.? == 0) { return formatIntUnsigned(@intCast(Uint, value), base, uppercase, options, context, Errors, output); 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);