Change safe_{sub,add,mul} so they perform the operation only once
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
parent
b338126854
commit
26b44e651d
@ -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;
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user