From ea6af75e8e1f6d4efe4bd18813fd6cf0d45c5a2d Mon Sep 17 00:00:00 2001 From: Michele Caini Date: Sun, 29 Aug 2021 22:45:16 +0200 Subject: [PATCH] memory: added utility function fast_mod --- src/entt/core/memory.hpp | 13 +++++++++++++ test/entt/core/memory.cpp | 6 ++++++ 2 files changed, 19 insertions(+) diff --git a/src/entt/core/memory.hpp b/src/entt/core/memory.hpp index 116ec5866..220483c25 100644 --- a/src/entt/core/memory.hpp +++ b/src/entt/core/memory.hpp @@ -89,6 +89,19 @@ template inline constexpr bool is_power_of_two_v = is_power_of_two::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 +[[nodiscard]] constexpr std::size_t fast_mod(const std::size_t value) ENTT_NOEXCEPT { + static_assert(is_power_of_two_v, "Value must be a power of two"); + return value & (Value - 1u); +} + + } diff --git a/test/entt/core/memory.cpp b/test/entt/core/memory.cpp index 0e5888712..14fe58877 100644 --- a/test/entt/core/memory.cpp +++ b/test/entt/core/memory.cpp @@ -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); +}