I'm using shl and try to check whether a specific operation is going to overflow a 64-bit int's range - either before it happens, or after it happens (as an exception).
What would you suggest?
import std/bitops
let i: uint8 = 0b0001
func checkedShl(a: SomeInteger, b: int): SomeInteger =
if countLeadingZeroBits(a) >= b:
a shl b
else:
raise
echo checkedShl(i, 7)
echo checkedShl(i, 8)
A few rough ideas of how I've approached it:
# simplistic version
proc safeShl*(a: int, b: int): int =
result = a << b
assert result > a, "shl overflow"
# more elaborate version
proc safeShl*(a: int, b: int): int =
assert b < 64, "shl overflow"
result = a << b
assert (a >> b)=result, "shl overflow"
Thanks a lot! Works beautifully! :)
I did see it, although admittedly with some delay. For some weird reason, I was able to see that you had commented but not your... reply. Weird...
Anyway, thanks again! :)