Skip to content

Commit

Permalink
added shrink_to_fit for bitset builder
Browse files Browse the repository at this point in the history
  • Loading branch information
drexlerd committed May 24, 2024
1 parent 53903e1 commit be65e9b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
18 changes: 18 additions & 0 deletions include/flatmemory/details/types/bitset.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1062,6 +1062,24 @@ class Builder<Bitset<Block>> : public IBuilder<Builder<Bitset<Block>>>
* 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)
{
Expand Down
13 changes: 13 additions & 0 deletions tests/unit/types/bitset.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,19 @@ TEST(FlatmemoryTests, TypesBitsetEqualTest)
* Modifiers
*/

TEST(FlatmemoryTests, TypesBitsetShrinkToFitTest)
{
// Is included in TypesBitsetGetTest
auto builder = Builder<Bitset<uint64_t>>(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
Expand Down

0 comments on commit be65e9b

Please sign in to comment.