3 ms·
const diff = if (order == .asc) b_int - a_int else a_int - b_int; const sign_bit: u1 = @truncate(@as(UWInt, @bitCast(diff)) >> @intCast(bits)); var mask
by rep_lodsb 8mo ago
const diff = if (order == .asc) b_int - a_int else a_int - b_int;
const sign_bit: u1 = @truncate(@as(UWInt, @bitCast(diff)) >> @intCast(bits));
var mask_word = @as(usize, 0) -% @as(usize, sign_bit);
This code in the fallback path (when no constant-time @min/@max is available) will only work if the subtraction doesn't overflow. Or is this not a problem for some reason?
- jedisct1 8mo agoa_int and b_int are signed values.
- rep_lodsb 8mo agoIt makes no difference whether they're signed or unsigned. Unless the subtraction is checking for overflow, or using a wider integer type than the numbers being compared, the high bit will not in every case indicate which number is smaller. e.g. 0x8000_0000 < 0x0000_0001 for signed numbers 0x8000_0000 - 0x0000_0001 = 0x7fff_ffff, high bit clear
- jedisct1 8mo agoThey are using a wider type.
- rep_lodsb 8mo agoYes, looking at the source code on GitHub now cleared that up! Didn't see it mentioned in the article though, maybe I missed it. If not, I think that this detail would be a good thing to include, both since it's a common mistake that others with less experience might make, and to get ahead of nitpicky comments like mine :)