SafeInt icon indicating copy to clipboard operation
SafeInt copied to clipboard

Unsafe shifts not do not raise an exception

Open bbannier opened this issue 1 year ago • 3 comments
trafficstars

When shifting a safe integer beyond its width I would expect this library to raise an exception; instead I run into an assertion failure.

#include "SafeInt/SafeInt.hpp"

// Shift an integer by its width which for naked integers is UB.
auto ub_shift(auto x) {
  return SafeInt(x) << (sizeof(x) * 8);
  // Similar issue for right shift.
}

int main() { ub_shift(0); }
$ CXXFLAGS=--std=c++20 make foo && ./foo
c++ --std=c++20    foo.cc   -o foo
Assertion failed: (bits < (int)safeint_internal::int_traits< T >::bitCount), function operator<<, file SafeInt.hpp, line 5998.
[2]    52370 abort      ./foo

bbannier avatar Aug 07 '24 14:08 bbannier

I'd be glad to make a change for this - since bits is typically a compile-time constant, the assert seemed sufficient.

dcleblanc avatar Aug 07 '24 18:08 dcleblanc

See #64

Please test, then I'll commit it.

dcleblanc avatar Aug 07 '24 19:08 dcleblanc

Updated branch in #66 with a couple more fixes. I have tested that one, and it works well for us.

rsmmr avatar Dec 11 '24 08:12 rsmmr