Luna/libluna/include/luna/SafeArithmetic.h

57 lines
1.0 KiB
C
Raw Normal View History

#pragma once
#include <luna/Result.h>
template <typename T> Result<T> safe_add(T a, T b)
{
T result;
if (__builtin_add_overflow(a, b, &result)) return err(EOVERFLOW);
return result;
}
template <typename T> Result<T> safe_sub(T a, T b)
{
T result;
if (__builtin_sub_overflow(a, b, &result)) return err(EOVERFLOW);
return result;
}
template <typename T> Result<T> safe_mul(T a, T b)
{
T result;
if (__builtin_mul_overflow(a, b, &result)) return err(EOVERFLOW);
return result;
}
template <typename T> bool add_will_overflow(T a, T b)
{
#ifdef __GNUC__
return __builtin_add_overflow_p(a, b, (T)0);
#else
return safe_add(a, b).has_error();
#endif
}
template <typename T> bool sub_will_overflow(T a, T b)
{
#ifdef __GNUC__
return __builtin_sub_overflow_p(a, b, (T)0);
#else
return safe_sub(a, b).has_error();
#endif
}
template <typename T> bool mul_will_overflow(T a, T b)
{
#ifdef __GNUC__
return __builtin_mul_overflow_p(a, b, (T)0);
#else
return safe_mul(a, b).has_error();
#endif
2023-01-02 12:07:29 +00:00
}