Change safe_{sub,add,mul} so they perform the operation only once
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
apio 2022-12-06 15:47:59 +01:00
parent b338126854
commit 26b44e651d
Signed by: apio
GPG Key ID: B8A7D06E42258954

View File

@ -18,21 +18,27 @@ template <typename T> constexpr bool mul_will_overflow(T a, T b)
template <typename T> Result<T> safe_add(T a, T b) template <typename T> Result<T> 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 <typename T> Result<T> safe_sub(T a, T b) template <typename T> Result<T> 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 <typename T> Result<T> safe_mul(T a, T b) template <typename T> Result<T> 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;
} }