2022-01-27 12:22:23 +00:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2022, Leon Albrecht <leon2002.la@gmail.com>
|
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
2022-01-29 15:51:02 +00:00
|
|
|
#include <AK/BuiltinWrappers.h>
|
2022-01-27 12:22:23 +00:00
|
|
|
#include <AK/Concepts.h>
|
|
|
|
#include <AK/Types.h>
|
|
|
|
|
|
|
|
namespace AK {
|
|
|
|
|
2022-01-29 15:51:02 +00:00
|
|
|
template<Integral T>
|
|
|
|
constexpr T exp2(T exponent)
|
|
|
|
{
|
2023-10-27 21:02:18 +00:00
|
|
|
return static_cast<T>(1) << exponent;
|
2022-01-29 15:51:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
template<Integral T>
|
|
|
|
constexpr T log2(T x)
|
|
|
|
{
|
|
|
|
return x ? (8 * sizeof(T) - 1) - count_leading_zeroes(static_cast<MakeUnsigned<T>>(x)) : 0;
|
|
|
|
}
|
|
|
|
|
2022-06-29 17:56:39 +00:00
|
|
|
template<Integral T>
|
|
|
|
constexpr T ceil_log2(T x)
|
|
|
|
{
|
2024-05-13 17:57:38 +00:00
|
|
|
if (x <= 1)
|
2022-06-29 17:56:39 +00:00
|
|
|
return 0;
|
|
|
|
|
2024-05-13 17:57:38 +00:00
|
|
|
return AK::log2(x - 1) + 1;
|
2022-06-29 17:56:39 +00:00
|
|
|
}
|
|
|
|
|
2022-01-27 12:22:23 +00:00
|
|
|
template<Integral I>
|
|
|
|
constexpr I pow(I base, I exponent)
|
|
|
|
{
|
|
|
|
// https://en.wikipedia.org/wiki/Exponentiation_by_squaring
|
|
|
|
if (exponent < 0)
|
|
|
|
return 0;
|
|
|
|
if (exponent == 0)
|
|
|
|
return 1;
|
|
|
|
|
|
|
|
I res = 1;
|
|
|
|
while (exponent > 0) {
|
|
|
|
if (exponent & 1)
|
|
|
|
res *= base;
|
|
|
|
base *= base;
|
|
|
|
exponent /= 2u;
|
|
|
|
}
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
2023-07-18 15:38:04 +00:00
|
|
|
template<auto base, Unsigned U = decltype(base)>
|
|
|
|
constexpr bool is_power_of(U x)
|
|
|
|
{
|
2024-05-05 02:48:07 +00:00
|
|
|
if constexpr (base == 1)
|
|
|
|
return x == 1;
|
|
|
|
else if constexpr (base == 2)
|
2023-07-18 15:38:04 +00:00
|
|
|
return is_power_of_two(x);
|
|
|
|
|
2024-05-05 02:48:07 +00:00
|
|
|
if (base == 0 && x == 0)
|
|
|
|
return true;
|
|
|
|
if (base == 0 || x == 0)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
while (x != 1) {
|
|
|
|
if (x % base != 0)
|
|
|
|
return false;
|
|
|
|
x /= base;
|
2023-07-18 15:38:04 +00:00
|
|
|
}
|
2024-05-05 02:48:07 +00:00
|
|
|
return true;
|
2023-07-18 15:38:04 +00:00
|
|
|
}
|
|
|
|
|
2024-04-29 14:12:36 +00:00
|
|
|
template<Unsigned T>
|
|
|
|
constexpr T reinterpret_as_octal(T decimal)
|
|
|
|
{
|
|
|
|
T result = 0;
|
|
|
|
T n = 0;
|
|
|
|
while (decimal > 0) {
|
|
|
|
result += pow<T>(8, n++) * (decimal % 10);
|
|
|
|
decimal /= 10;
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2022-01-27 12:22:23 +00:00
|
|
|
}
|