From 7dbf463ddf4a89ec7158c955b421adb77670d37e Mon Sep 17 00:00:00 2001 From: Dentomologist Date: Sun, 31 Dec 2023 11:57:16 -0800 Subject: [PATCH] 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. --- Source/Core/Common/BitSet.h | 2 +- Source/UnitTests/Common/BitSetTest.cpp | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Source/Core/Common/BitSet.h b/Source/Core/Common/BitSet.h index 5d2c88294d..f14ebea9e2 100644 --- a/Source/Core/Common/BitSet.h +++ b/Source/Core/Common/BitSet.h @@ -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; diff --git a/Source/UnitTests/Common/BitSetTest.cpp b/Source/UnitTests/Common/BitSetTest.cpp index 6ec2b74bdb..397f9fecbe 100644 --- a/Source/UnitTests/Common/BitSetTest.cpp +++ b/Source/UnitTests/Common/BitSetTest.cpp @@ -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, 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); } }