EnTT 3.14.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 ENTT_ASSERT_CONSTEXPR(value < (Type{1u} << (std::numeric_limits<Type>::digits - 1)), "Numeric limits exceeded");
45 Type curr = value - (value != 0u);
46
47 for(int next = 1; next < std::numeric_limits<Type>::digits; next = next * 2) {
48 curr |= (curr >> next);
49 }
50
51 return ++curr;
52}
53
61template<typename Type>
62[[nodiscard]] constexpr std::enable_if_t<std::is_unsigned_v<Type>, Type> fast_mod(const Type value, const std::size_t mod) noexcept {
63 ENTT_ASSERT_CONSTEXPR(has_single_bit(mod), "Value must be a power of two");
64 return value & (mod - 1u);
65}
66
67} // namespace entt
68
69#endif
EnTT default namespace.
Definition dense_map.hpp:22
constexpr Type make_obj_using_allocator(const Allocator &allocator, Args &&...args)
Uses-allocator construction utility (waiting for C++20).
Definition memory.hpp:219
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:62
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