diff --git a/luna/include/luna/SafeArithmetic.h b/luna/include/luna/SafeArithmetic.h new file mode 100644 index 00000000..b0336d6d --- /dev/null +++ b/luna/include/luna/SafeArithmetic.h @@ -0,0 +1,38 @@ +#pragma once +#include + +template constexpr bool add_will_overflow(T a, T b) +{ + return __builtin_add_overflow_p(a, b, (T)0); +} + +template constexpr bool sub_will_overflow(T a, T b) +{ + return __builtin_sub_overflow_p(a, b, (T)0); +} + +template constexpr bool mul_will_overflow(T a, T b) +{ + return __builtin_mul_overflow_p(a, b, (T)0); +} + +template Result safe_add(T a, T b) +{ + if (add_will_overflow(a, b)) return err(EOVERFLOW); + + return a + b; +} + +template Result safe_sub(T a, T b) +{ + if (sub_will_overflow(a, b)) return err(EOVERFLOW); + + return a - b; +} + +template Result safe_mul(T a, T b) +{ + if (mul_will_overflow(a, b)) return err(EOVERFLOW); + + return a * b; +} \ No newline at end of file