BitSet64: Fix iterator incrementation

Use 1 of the same type as the stored value when shifting left. This
prevents undefined behavior caused by shifting an int more than 31 bits.

Previously iterator incrementation could either hang or prematurely
report it had reached the end of the bitset.
This commit is contained in:
Dentomologist 2023-12-31 11:57:16 -08:00
parent 58c5ae3de9
commit 7dbf463ddf
2 changed files with 9 additions and 1 deletions

View File

@ -73,7 +73,7 @@ public:
else
{
int bit = std::countr_zero(m_val);
m_val &= ~(1 << bit);
m_val &= ~(IntTy{1} << bit);
m_bit = bit;
}
return *this;

View File

@ -41,6 +41,10 @@ TEST(BitSet, Count)
{
const auto bitset = BitSet32(number);
EXPECT_EQ(bitset.Count(), bitcount);
u32 iterating_count = 0;
for (auto iter = bitset.begin(); iter != bitset.end(); ++iter)
++iterating_count;
EXPECT_EQ(iterating_count, bitcount);
}
constexpr std::array<std::pair<u64, u32>, 9> random_64bit_number_bitcount_pairs = {
@ -57,6 +61,10 @@ TEST(BitSet, Count)
{
const auto bitset = BitSet64(number);
EXPECT_EQ(bitset.Count(), bitcount);
u32 iterating_count = 0;
for (auto iter = bitset.begin(); iter != bitset.end(); ++iter)
++iterating_count;
EXPECT_EQ(iterating_count, bitcount);
}
}