Zen C++ Libraries
Zero-dependency re-usable components for C++
Loading...
Searching...
No Matches
math.hpp
1#ifndef ZEN_MATH_HPP
2#define ZEN_MATH_HPP
3
4#include <bit>
5#include <cstdint>
6
7#include "zen/config.hpp"
8
9ZEN_NAMESPACE_START
10
11// Some definitions taken from the LLVM project
12
15constexpr bool is_power_of_2_32(uint32_t Value) {
16 return std::has_single_bit(Value);
17}
18
20constexpr bool is_power_of_2_64(uint64_t Value) {
21 return std::has_single_bit(Value);
22}
23
26inline unsigned log2_64(uint64_t Value) {
27 return 63 - std::countl_zero(Value);
28}
29
32inline unsigned log2_64_ceil(uint64_t Value) {
33 return 64 - std::countl_zero(Value - 1);
34}
35
38constexpr uint64_t next_power_of_2(uint64_t A) {
39 A |= (A >> 1);
40 A |= (A >> 2);
41 A |= (A >> 4);
42 A |= (A >> 8);
43 A |= (A >> 16);
44 A |= (A >> 32);
45 return A + 1;
46}
47
50inline uint64_t power_of_2_ceil(uint64_t A) {
51 if (!A || A > UINT64_MAX / 2)
52 return 0;
53 return UINT64_C(1) << log2_64_ceil(A);
54}
55
59template<std::integral A, std::unsigned_integral B>
60inline A ipow(A x, B p) {
61 if (p == 0) return 1;
62 if (p == 1) return x;
63 int tmp = ipow(x, p / 2);
64 if (p % 2 == 0) return tmp * tmp;
65 else return x * tmp * tmp;
66}
67
68ZEN_NAMESPACE_END
69
70#endif // of #ifndef ZEN_MATH_HPP