luna: Introduce safe arithmetic operations, which return an error if an operation would overflow
This commit is contained in:
parent
8ff9cb4b96
commit
e91c04b1d1
38
luna/include/luna/SafeArithmetic.h
Normal file
38
luna/include/luna/SafeArithmetic.h
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user