From a5aa5e2b2d75ffdee2d3bee24baab2b4befbe4de Mon Sep 17 00:00:00 2001 From: Yuri Kunde Schlesner Date: Sat, 9 Dec 2017 20:16:07 -0800 Subject: [PATCH] Common: Simplify and optimize BitSet iterator Instead of doing complex machinations to keep track of the current bit index, just unset the lowest bit on each iteration, greatly simplifying the code. --- src/common/bit_set.h | 27 ++++++--------------------- 1 file changed, 6 insertions(+), 21 deletions(-) diff --git a/src/common/bit_set.h b/src/common/bit_set.h index 9c2e6b28c..749de4df0 100644 --- a/src/common/bit_set.h +++ b/src/common/bit_set.h @@ -120,20 +120,15 @@ public: // A STL-like iterator is required to be able to use range-based for loops. class Iterator { public: - Iterator(const Iterator& other) : m_val(other.m_val), m_bit(other.m_bit) {} - Iterator(IntTy val) : m_val(val), m_bit(0) {} - Iterator& operator=(Iterator other) { - new (this) Iterator(other); - return *this; - } + Iterator(const Iterator& other) : m_val(other.m_val) {} + Iterator(IntTy val) : m_val(val) {} int operator*() { - return m_bit + ComputeLsb(); + // This will never be called when m_val == 0, because that would be the end() iterator + return LeastSignificantSetBit(m_val); } Iterator& operator++() { - int lsb = ComputeLsb(); - m_val >>= lsb + 1; - m_bit += lsb + 1; - m_has_lsb = false; + // Unset least significant set bit + m_val &= m_val - IntTy(1); return *this; } Iterator operator++(int _) { @@ -149,17 +144,7 @@ public: } private: - int ComputeLsb() { - if (!m_has_lsb) { - m_lsb = LeastSignificantSetBit(m_val); - m_has_lsb = true; - } - return m_lsb; - } IntTy m_val; - int m_bit; - int m_lsb = -1; - bool m_has_lsb = false; }; BitSet() : m_val(0) {}