Serenity Operating System
at master 57 lines 996 B view raw
1/* 2 * Copyright (c) 2022, Leon Albrecht <leon2002.la@gmail.com> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#pragma once 8 9#include <AK/BuiltinWrappers.h> 10#include <AK/Concepts.h> 11#include <AK/Types.h> 12 13namespace AK { 14 15template<Integral T> 16constexpr T exp2(T exponent) 17{ 18 return 1u << exponent; 19} 20 21template<Integral T> 22constexpr T log2(T x) 23{ 24 return x ? (8 * sizeof(T) - 1) - count_leading_zeroes(static_cast<MakeUnsigned<T>>(x)) : 0; 25} 26 27template<Integral T> 28constexpr T ceil_log2(T x) 29{ 30 if (!x) 31 return 0; 32 33 T log = AK::log2(x); 34 log += (x & ((((T)1) << (log - 1)) - 1)) != 0; 35 return log; 36} 37 38template<Integral I> 39constexpr I pow(I base, I exponent) 40{ 41 // https://en.wikipedia.org/wiki/Exponentiation_by_squaring 42 if (exponent < 0) 43 return 0; 44 if (exponent == 0) 45 return 1; 46 47 I res = 1; 48 while (exponent > 0) { 49 if (exponent & 1) 50 res *= base; 51 base *= base; 52 exponent /= 2u; 53 } 54 return res; 55} 56 57}