| 1 | /// absv - absolute oVerflow |
| 2 | /// * @panic if value can not be represented |
| 3 | pub inline fn absv(comptime ST: type, a: ST) ST { |
| 4 | const UT = switch (ST) { |
| 5 | i32 => u32, |
| 6 | i64 => u64, |
| 7 | i128 => u128, |
| 8 | else => unreachable, |
| 9 | }; |
| 10 | // taken from Bit Twiddling Hacks |
| 11 | // compute the integer absolute value (abs) without branching |
| 12 | var x: ST = a; |
| 13 | const N: UT = @bitSizeOf(ST); |
| 14 | const sign: ST = a >> N - 1; |
| 15 | x +%= sign; |
| 16 | x ^= sign; |
| 17 | if (x < 0) @panic("integer overflow"); |
| 18 | return x; |
| 19 | } |
| 20 | |
| 21 | test { |
| 22 | _ = @import("absvsi2_test.zig"); |
| 23 | _ = @import("absvdi2_test.zig"); |
| 24 | _ = @import("absvti2_test.zig"); |
| 25 | } |