luna: Introduce safe arithmetic operations, which return an error if an operation would overflow

This commit is contained in:
apio 2022-12-06 15:40:18 +01:00
parent 8ff9cb4b96
commit e91c04b1d1
Signed by: apio
GPG Key ID: B8A7D06E42258954

View File

@ -0,0 +1,38 @@
#pragma once
#include <luna/Result.h>
template <typename T> constexpr bool add_will_overflow(T a, T b)
{
return __builtin_add_overflow_p(a, b, (T)0);
}
template <typename T> constexpr bool sub_will_overflow(T a, T b)
{
return __builtin_sub_overflow_p(a, b, (T)0);
}
template <typename T> constexpr bool mul_will_overflow(T a, T b)
{
return __builtin_mul_overflow_p(a, b, (T)0);
}
template <typename T> Result<T> safe_add(T a, T b)
{
if (add_will_overflow(a, b)) return err(EOVERFLOW);
return a + b;
}
template <typename T> Result<T> safe_sub(T a, T b)
{
if (sub_will_overflow(a, b)) return err(EOVERFLOW);
return a - b;
}
template <typename T> Result<T> safe_mul(T a, T b)
{
if (mul_will_overflow(a, b)) return err(EOVERFLOW);
return a * b;
}