diff --git a/AK/IntegralMath.h b/AK/IntegralMath.h index 916d9b70cc8..415e485bf9d 100644 --- a/AK/IntegralMath.h +++ b/AK/IntegralMath.h @@ -24,6 +24,17 @@ constexpr T log2(T x) return x ? (8 * sizeof(T) - 1) - count_leading_zeroes(static_cast>(x)) : 0; } +template +constexpr T ceil_log2(T x) +{ + if (!x) + return 0; + + T log = AK::log2(x); + log += (x & ((1 << (log - 1)) - 1)) != 0; + return log; +} + template constexpr I pow(I base, I exponent) { diff --git a/AK/Math.h b/AK/Math.h index 1dd4e3c6ed8..ebf9856f933 100644 --- a/AK/Math.h +++ b/AK/Math.h @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -665,6 +666,19 @@ constexpr T pow(T x, T y) return exp2(y * log2(x)); } +template +constexpr T ceil(T num) +{ + if (is_constant_evaluated()) { + if (num < NumericLimits::min() || num > NumericLimits::max()) + return num; + return (static_cast(static_cast(num)) == num) + ? static_cast(num) + : static_cast(num) + ((num > 0) ? 1 : 0); + } + return __builtin_ceil(num); +} + #undef CONSTEXPR_STATE }