From be65e9baa64baa501de7ac94251b8feb491560ec Mon Sep 17 00:00:00 2001 From: Dominik Drexler Date: Sat, 25 May 2024 00:42:03 +0200 Subject: [PATCH] added shrink_to_fit for bitset builder --- include/flatmemory/details/types/bitset.hpp | 18 ++++++++++++++++++ tests/unit/types/bitset.cpp | 13 +++++++++++++ 2 files changed, 31 insertions(+) diff --git a/include/flatmemory/details/types/bitset.hpp b/include/flatmemory/details/types/bitset.hpp index a6275a3..977d517 100644 --- a/include/flatmemory/details/types/bitset.hpp +++ b/include/flatmemory/details/types/bitset.hpp @@ -1062,6 +1062,24 @@ class Builder> : public IBuilder>> * Modifiers */ + /// @brief Shrink the bitset to minimum number of blocks (at least 1) to represent its bits. + void shrink_to_fit() + { + int32_t last_non_default_block_index = m_blocks.size() - 1; + + const Block default_block = m_default_bit_value ? BitsetOperator::block_ones : BitsetOperator::block_zeroes; + + for (; last_non_default_block_index >= 0; --last_non_default_block_index) + { + if (m_blocks[last_non_default_block_index] != default_block) + { + break; + } + } + + m_blocks.resize(last_non_default_block_index + 1); + } + // Set a bit at a specific position void set(std::size_t position) { diff --git a/tests/unit/types/bitset.cpp b/tests/unit/types/bitset.cpp index 8054433..e04ff72 100644 --- a/tests/unit/types/bitset.cpp +++ b/tests/unit/types/bitset.cpp @@ -232,6 +232,19 @@ TEST(FlatmemoryTests, TypesBitsetEqualTest) * Modifiers */ +TEST(FlatmemoryTests, TypesBitsetShrinkToFitTest) +{ + // Is included in TypesBitsetGetTest + auto builder = Builder>(250); + builder.unset_all(); + builder.set(42); + EXPECT_EQ(builder.get_blocks().size(), 4); + EXPECT_TRUE(builder.get(42)); + + builder.shrink_to_fit(); + EXPECT_EQ(builder.get_blocks().size(), 1); +} + TEST(FlatmemoryTests, TypesBitsetSetTest) { // Is included in TypesBitsetGetTest