WPILibC++ 2025.1.1
Loading...
Searching...
No Matches
ilog2.hpp
Go to the documentation of this file.
1// Copyright (C) 2015-2023 Jonathan Müller and foonathan/memory contributors
2// SPDX-License-Identifier: Zlib
3
4#ifndef WPI_MEMORY_DETAIL_ILOG2_HPP_INCLUDED
5#define WPI_MEMORY_DETAIL_ILOG2_HPP_INCLUDED
6
7#include <climits>
8#include <cstdint>
9
10#include "../config.hpp"
11
12namespace wpi
13{
14 namespace memory
15 {
16 namespace detail
17 {
18 // undefined for 0
19 template <typename UInt>
20 constexpr bool is_power_of_two(UInt x)
21 {
22 return (x & (x - 1)) == 0;
23 }
24
25 inline std::size_t ilog2_base(std::uint64_t x)
26 {
27#if defined(__GNUC__)
28 unsigned long long value = x;
29 return sizeof(value) * CHAR_BIT - static_cast<unsigned>(__builtin_clzll(value));
30#else
31 // Adapted from https://stackoverflow.com/a/40943402
32 std::size_t clz = 64;
33 std::size_t c = 32;
34 do
35 {
36 auto tmp = x >> c;
37 if (tmp != 0)
38 {
39 clz -= c;
40 x = tmp;
41 }
42 c = c >> 1;
43 } while (c != 0);
44 clz -= x ? 1 : 0;
45
46 return 64 - clz;
47#endif
48 }
49
50 // ilog2() implementation, cuts part after the comma
51 // e.g. 1 -> 0, 2 -> 1, 3 -> 1, 4 -> 2, 5 -> 2
52 inline std::size_t ilog2(std::uint64_t x)
53 {
54 return ilog2_base(x) - 1;
55 }
56
57 // ceiling ilog2() implementation, adds one if part after comma
58 // e.g. 1 -> 0, 2 -> 1, 3 -> 2, 4 -> 2, 5 -> 3
59 inline std::size_t ilog2_ceil(std::uint64_t x)
60 {
61 // only subtract one if power of two
62 return ilog2_base(x) - std::size_t(is_power_of_two(x));
63 }
64 } // namespace detail
65 } // namespace memory
66} // namespace wpi
67
68#endif
Configuration macros.
detail namespace with internal helper functions
Definition input_adapters.h:32
std::size_t ilog2(std::uint64_t x)
Definition ilog2.hpp:52
std::size_t ilog2_ceil(std::uint64_t x)
Definition ilog2.hpp:59
constexpr bool is_power_of_two(UInt x)
Definition ilog2.hpp:20
std::size_t ilog2_base(std::uint64_t x)
Definition ilog2.hpp:25
Memory namespace.
Definition heap_allocator.hpp:20
Foonathan namespace.
Definition ntcore_cpp.h:26