memory: added utility function fast_mod

This commit is contained in:
Michele Caini
2021-08-29 22:45:16 +02:00
parent a595c6ec6f
commit ea6af75e8e
2 changed files with 19 additions and 0 deletions

View File

@@ -89,6 +89,19 @@ template<std::size_t Value>
inline constexpr bool is_power_of_two_v = is_power_of_two<Value>::value;
/**
* @brief Fast module utility function (powers of two only).
* @tparam Value Compile-time page size, it must be a power of two.
* @param value A value for which to calculate the modulus.
* @return Remainder of division.
*/
template<std::size_t Value>
[[nodiscard]] constexpr std::size_t fast_mod(const std::size_t value) ENTT_NOEXCEPT {
static_assert(is_power_of_two_v<Value>, "Value must be a power of two");
return value & (Value - 1u);
}
}

View File

@@ -41,3 +41,9 @@ TEST(Memory, IsPowerOfTwo) {
ASSERT_TRUE(entt::is_power_of_two_v<128u>);
ASSERT_FALSE(entt::is_power_of_two_v<200u>);
}
TEST(Memory, FastMod) {
ASSERT_EQ(entt::fast_mod<8u>(0u), 0u);
ASSERT_EQ(entt::fast_mod<8u>(7u), 7u);
ASSERT_EQ(entt::fast_mod<8u>(8u), 0u);
}