EnTT 3.15.0
Loading...
Searching...
No Matches
bit.hpp
1#ifndef ENTT_CORE_BIT_HPP
2#define ENTT_CORE_BIT_HPP
3
4#include <cstddef>
5#include <limits>
6#include <type_traits>
7#include "../config/config.h"
8
9namespace entt {
10
18template<typename Type>
19[[nodiscard]] constexpr std::enable_if_t<std::is_unsigned_v<Type>, int> popcount(const Type value) noexcept {
20 return value ? (int(value & 1) + popcount(static_cast<Type>(value >> 1))) : 0;
21}
22
30template<typename Type>
31[[nodiscard]] constexpr std::enable_if_t<std::is_unsigned_v<Type>, bool> has_single_bit(const Type value) noexcept {
32 return value && ((value & (value - 1)) == 0);
33}
34
42template<typename Type>
43[[nodiscard]] constexpr std::enable_if_t<std::is_unsigned_v<Type>, Type> next_power_of_two(const Type value) noexcept {
44 // NOLINTNEXTLINE(bugprone-assert-side-effect)
45 ENTT_ASSERT_CONSTEXPR(value < (Type{1u} << (std::numeric_limits<Type>::digits - 1)), "Numeric limits exceeded");
46 Type curr = value - (value != 0u);
47
48 for(int next = 1; next < std::numeric_limits<Type>::digits; next = next * 2) {
49 curr |= (curr >> next);
50 }
51
52 return ++curr;
53}
54
62template<typename Type>
63[[nodiscard]] constexpr std::enable_if_t<std::is_unsigned_v<Type>, Type> fast_mod(const Type value, const std::size_t mod) noexcept {
64 ENTT_ASSERT_CONSTEXPR(has_single_bit(mod), "Value must be a power of two");
65 return static_cast<Type>(value & (mod - 1u));
66}
67
68} // namespace entt
69
70#endif
EnTT default namespace.
Definition dense_map.hpp:22
constexpr std::enable_if_t< std::is_unsigned_v< Type >, Type > fast_mod(const Type value, const std::size_t mod) noexcept
Fast module utility function (powers of two only).
Definition bit.hpp:63
constexpr std::enable_if_t< std::is_unsigned_v< Type >, bool > has_single_bit(const Type value) noexcept
Checks whether a value is a power of two or not (waiting for C++20 and std::has_single_bit).
Definition bit.hpp:31
constexpr std::enable_if_t< std::is_unsigned_v< Type >, Type > next_power_of_two(const Type value) noexcept
Computes the smallest power of two greater than or equal to a value (waiting for C++20 and std::bit_c...
Definition bit.hpp:43
constexpr std::enable_if_t< std::is_unsigned_v< Type >, int > popcount(const Type value) noexcept
Returns the number of set bits in a value (waiting for C++20 and std::popcount).
Definition bit.hpp:19