diff --git a/include/Nazara/Core/Bitset.hpp b/include/Nazara/Core/Bitset.hpp index a3aea9c0d..491bf8937 100644 --- a/include/Nazara/Core/Bitset.hpp +++ b/include/Nazara/Core/Bitset.hpp @@ -66,6 +66,8 @@ namespace Nz void Reset(); void Reset(std::size_t bit); + void Reverse(); + void Set(bool val = true); void Set(std::size_t bit, bool val = true); void SetBlock(std::size_t i, Block block); diff --git a/include/Nazara/Core/Bitset.inl b/include/Nazara/Core/Bitset.inl index 6a3d1a76d..5e64bbbf4 100644 --- a/include/Nazara/Core/Bitset.inl +++ b/include/Nazara/Core/Bitset.inl @@ -581,6 +581,30 @@ namespace Nz Set(bit, false); } + /*! + * \brief Reverse the order of bits in a bitset + * + * Reverse the order of bits in the bitset (first bit swap with the last one, etc.) + */ + template + void Bitset::Reverse() + { + if (m_bitCount == 0) + return; + + std::size_t i = 0; + std::size_t j = m_bitCount - 1; + + while (i < j) + { + bool bit1 = Test(i); + bool bit2 = Test(j); + + Set(i++, bit2); + Set(j--, bit1); + } + } + /*! * \brief Sets the bitset to val * diff --git a/tests/Engine/Core/Bitset.cpp b/tests/Engine/Core/Bitset.cpp index a5410da3c..2cefd69df 100644 --- a/tests/Engine/Core/Bitset.cpp +++ b/tests/Engine/Core/Bitset.cpp @@ -11,6 +11,7 @@ template void CheckBitOps(const char* title); template void CheckConstructor(const char* title); template void CheckCopyMoveSwap(const char* title); template void CheckRead(const char* title); +template void CheckReverse(const char* title); SCENARIO("Bitset", "[CORE][BITSET]") { @@ -30,6 +31,7 @@ void Check(const char* title) CheckAppend(title); CheckRead(title); + CheckReverse(title); } template @@ -115,6 +117,7 @@ void CheckBitOps(const char* title) } } } + template void CheckConstructor(const char* title) { @@ -271,3 +274,36 @@ void CheckRead(const char* title) } } } + +template +void CheckReverse(const char* title) +{ + SECTION(title) + { + GIVEN("A bitset") + { + Nz::String bits = "010011100010001101001111"; + Nz::Bitset expected(bits); + + WHEN("We reverse the order of bits") + { + Nz::Bitset bitset(bits); + bitset.Reverse(); + + THEN("The order of bits should be reversed") + { + CHECK(bitset == Nz::Bitset(bits.Reversed())); + } + AND_WHEN("We reverse the bit order again") + { + bitset.Reverse(); + + THEN("It should be back to normal") + { + CHECK(bitset == expected); + } + } + } + } + } +}