std: fix math.absCast on i1

This commit is contained in:
daurnimator 2020-03-05 15:59:19 +11:00
parent 4f58bfe1a8
commit 488ba1560f
No known key found for this signature in database
GPG Key ID: 45B429A8F9D9D22A
2 changed files with 25 additions and 13 deletions

View File

@ -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);

View File

@ -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);