| ... | ... | @@ -670,23 +670,35 @@ fn testRem() void { |
| 670 | 670 | |
| 671 | 671 | /// Returns the absolute value of the integer parameter. |
| 672 | 672 | /// Result is an unsigned integer. |
| 673 | | pub fn absCast(x: var) t: { |
| 674 | | if (@TypeOf(x) == comptime_int) { |
| 675 | | break :t comptime_int; |
| 676 | | } else { |
| 677 | | break :t std.meta.IntType(false, @TypeOf(x).bit_count); |
| 673 | pub fn absCast(x: var) switch(@typeInfo(@TypeOf(x))) { |
| 674 | .ComptimeInt => comptime_int, |
| 675 | .Int => |intInfo| std.meta.IntType(false, intInfo.bits), |
| 676 | else => @compileError("absCast only accepts integers"), |
| 678 | 677 | } |
| 679 | | } { |
| 680 | | if (@TypeOf(x) == comptime_int) { |
| 681 | | return if (x < 0) -x else x; |
| 678 | { |
| 679 | switch(@typeInfo(@TypeOf(x))) { |
| 680 | .ComptimeInt => { |
| 681 | if (x < 0) { |
| 682 | return -x; |
| 683 | } else { |
| 684 | return x; |
| 685 | } |
| 686 | }, |
| 687 | .Int => |intInfo| { |
| 688 | const Uint = std.meta.IntType(false, intInfo.bits); |
| 689 | if (x < 0) { |
| 690 | return ~@bitCast(Uint, x +% -1); |
| 691 | } else { |
| 692 | return @intCast(Uint, x); |
| 693 | } |
| 694 | }, |
| 695 | else => unreachable, |
| 682 | 696 | } |
| 683 | | const uint = std.meta.IntType(false, @TypeOf(x).bit_count); |
| 684 | | if (x >= 0) return @intCast(uint, x); |
| 685 | | |
| 686 | | return @intCast(uint, -(x + 1)) + 1; |
| 687 | 697 | } |
| 688 | 698 | |
| 689 | 699 | test "math.absCast" { |
| 700 | testing.expect(absCast(@as(i1, -1)) == 1); |
| 701 | |
| 690 | 702 | testing.expect(absCast(@as(i32, -999)) == 999); |
| 691 | 703 | testing.expect(@TypeOf(absCast(@as(i32, -999))) == u32); |
| 692 | 704 | |