BAN: Implement will_{addition,multiplication}_overflow

This commit is contained in:
2024-06-14 11:04:29 +03:00
parent ea7fc7f6c4
commit 05e9d76c77
2 changed files with 25 additions and 24 deletions

View File

@@ -1,5 +1,6 @@
#pragma once
#include <BAN/Limits.h>
#include <BAN/Traits.h>
#include <stddef.h>
@@ -65,6 +66,27 @@ namespace BAN::Math
return (value & (value - 1)) == 0;
}
template<BAN::integral T>
static constexpr bool will_multiplication_overflow(T a, T b)
{
if (a == 0 || b == 0)
return false;
if ((a > 0) == (b > 0))
return a > BAN::numeric_limits<T>::max() / b;
else
return a < BAN::numeric_limits<T>::min() / b;
}
template<BAN::integral T>
static constexpr bool will_addition_overflow(T a, T b)
{
if (a > 0 && b > 0)
return a > BAN::numeric_limits<T>::max() - b;
if (a < 0 && b < 0)
return a < BAN::numeric_limits<T>::min() - b;
return false;
}
template<typename T>
requires is_same_v<T, unsigned int> || is_same_v<T, unsigned long> || is_same_v<T, unsigned long long>
inline constexpr T ilog2(T value)