absv.zig (671B) - Raw
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) 18 @panic("compiler_rt absv: overflow"); 19 return x; 20 } 21 22 test { 23 _ = @import("absvsi2_test.zig"); 24 _ = @import("absvdi2_test.zig"); 25 _ = @import("absvti2_test.zig"); 26 }