Commit 488ba1560f

daurnimator <quae@daurnimator.com>
2020-03-05 05:59:19
std: fix math.absCast on i1
1 parent 4f58bfe
Changed files (2)
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);
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);