From 26b44e651dedc2868027dcdc3ccf60f8ffbe0c25 Mon Sep 17 00:00:00 2001 From: apio Date: Tue, 6 Dec 2022 15:47:59 +0100 Subject: [PATCH] Change safe_{sub,add,mul} so they perform the operation only once --- luna/include/luna/SafeArithmetic.h | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/luna/include/luna/SafeArithmetic.h b/luna/include/luna/SafeArithmetic.h index b0336d6d..31d59856 100644 --- a/luna/include/luna/SafeArithmetic.h +++ b/luna/include/luna/SafeArithmetic.h @@ -18,21 +18,27 @@ template constexpr bool mul_will_overflow(T a, T b) template Result safe_add(T a, T b) { - if (add_will_overflow(a, b)) return err(EOVERFLOW); + T result; - return a + b; + if (__builtin_add_overflow(a, b, &result)) return err(EOVERFLOW); + + return result; } template Result safe_sub(T a, T b) { - if (sub_will_overflow(a, b)) return err(EOVERFLOW); + T result; - return a - b; + if (__builtin_sub_overflow(a, b, &result)) return err(EOVERFLOW); + + return result; } template Result safe_mul(T a, T b) { - if (mul_will_overflow(a, b)) return err(EOVERFLOW); + T result; - return a * b; + if (__builtin_mul_overflow(a, b, &result)) return err(EOVERFLOW); + + return result; } \ No newline at end of file