From e91c04b1d110bb1739afefb4e5f9bd25db47934f Mon Sep 17 00:00:00 2001 From: apio Date: Tue, 6 Dec 2022 15:40:18 +0100 Subject: [PATCH] luna: Introduce safe arithmetic operations, which return an error if an operation would overflow --- luna/include/luna/SafeArithmetic.h | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 luna/include/luna/SafeArithmetic.h 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