randomly wondering: are there C++ codebases out there that have bounded number t...

@jann@infosec.exchange

randomly wondering: are there C++ codebases out there that have bounded number types with __builtin_assume()? like:

#include <utility>
[[noreturn]] static inline void ud2() {
asm volatile("ud2");
std::unreachable();
}
template<typename T, T min, T max>
class bounded {
T val;
public:
inline bounded(T val) : val(val){
if (val < min || val > max)
ud2();
}
inline operator T() {
T val_ = val;
__builtin_assume(val_ >= min);
__builtin_assume(val_ <= max);
return val;
}
};
inline int checked_add_int(int a, int b) {
int sum;
if (__builtin_add_overflow(a, b, &sum))
ud2();
return sum;
}

typedef bounded<int, 0, 1024> small_int;
typedef bounded<int, 0, 2048> medium_int;

medium_int add_small_ints(small_int a, small_int b) {
return checked_add_int(a, b);
}

compiles to a simple addition with no checks with clang -O3, while changing the return type to small_int adds a branch because the bounds can't be proven statically