From 1fa99f4f640d56ce81e2799fe63396762be96127 Mon Sep 17 00:00:00 2001 From: apio Date: Tue, 6 Dec 2022 15:53:06 +0100 Subject: [PATCH] Make {add,sub,mul}_will_overflow more compiler-independent --- luna/include/luna/SafeArithmetic.h | 42 +++++++++++++++++++----------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/luna/include/luna/SafeArithmetic.h b/luna/include/luna/SafeArithmetic.h index 31d59856..90cc3897 100644 --- a/luna/include/luna/SafeArithmetic.h +++ b/luna/include/luna/SafeArithmetic.h @@ -1,21 +1,6 @@ #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) { T result; @@ -41,4 +26,31 @@ template Result safe_mul(T a, T b) if (__builtin_mul_overflow(a, b, &result)) return err(EOVERFLOW); return result; +} + +template bool add_will_overflow(T a, T b) +{ +#ifdef __GNUC__ + return __builtin_add_overflow_p(a, b, (T)0); +#else + return safe_add(a, b).has_error(); +#endif +} + +template bool sub_will_overflow(T a, T b) +{ +#ifdef __GNUC__ + return __builtin_sub_overflow_p(a, b, (T)0); +#else + return safe_sub(a, b).has_error(); +#endif +} + +template bool mul_will_overflow(T a, T b) +{ +#ifdef __GNUC__ + return __builtin_mul_overflow_p(a, b, (T)0); +#else + return safe_mul(a, b).has_error(); +#endif } \ No newline at end of file