dcleblanc / SafeInt

SafeInt is a class library for C++ that manages integer overflows.
MIT License
216 stars 37 forks source link

Unsafe shifts not do not raise an exception #63

Open bbannier opened 3 months ago

bbannier commented 3 months ago

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
dcleblanc commented 3 months ago

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

dcleblanc commented 3 months ago

See #64

Please test, then I'll commit it.