This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is small. It contains one pointer-sized field, which is directly used as a plain collection of bits when possible, or as a pointer to a larger heap-allocated array when necessary. This allows normal "small" cases to be fast without losing generality for large inputs.
| 32 | /// pointer to a larger heap-allocated array when necessary. This allows normal |
| 33 | /// "small" cases to be fast without losing generality for large inputs. |
| 34 | class SmallBitVector { |
| 35 | // TODO: In "large" mode, a pointer to a BitVector is used, leading to an |
| 36 | // unnecessary level of indirection. It would be more efficient to use a |
| 37 | // pointer to memory containing size, allocation size, and the array of bits. |
| 38 | uintptr_t X = 1; |
| 39 | |
| 40 | enum { |
| 41 | // The number of bits in this class. |
| 42 | NumBaseBits = sizeof(uintptr_t) * CHAR_BIT, |
| 43 | |
| 44 | // One bit is used to discriminate between small and large mode. The |
| 45 | // remaining bits are used for the small-mode representation. |
| 46 | SmallNumRawBits = NumBaseBits - 1, |
| 47 | |
| 48 | // A few more bits are used to store the size of the bit set in small mode. |
| 49 | // Theoretically this is a ceil-log2. These bits are encoded in the most |
| 50 | // significant bits of the raw bits. |
| 51 | SmallNumSizeBits = (NumBaseBits == 32 ? 5 : |
| 52 | NumBaseBits == 64 ? 6 : |
| 53 | SmallNumRawBits), |
| 54 | |
| 55 | // The remaining bits are used to store the actual set in small mode. |
| 56 | SmallNumDataBits = SmallNumRawBits - SmallNumSizeBits |
| 57 | }; |
| 58 | |
| 59 | static_assert(NumBaseBits == 64 || NumBaseBits == 32, |
| 60 | "Unsupported word size"); |
| 61 | |
| 62 | public: |
| 63 | using size_type = unsigned; |
| 64 | |
| 65 | // Encapsulation of a single bit. |
| 66 | class reference { |
| 67 | SmallBitVector &TheVector; |
| 68 | unsigned BitPos; |
| 69 | |
| 70 | public: |
| 71 | reference(SmallBitVector &b, unsigned Idx) : TheVector(b), BitPos(Idx) {} |
| 72 | |
| 73 | reference(const reference&) = default; |
| 74 | |
| 75 | reference& operator=(reference t) { |
| 76 | *this = bool(t); |
| 77 | return *this; |
| 78 | } |
| 79 | |
| 80 | reference& operator=(bool t) { |
| 81 | if (t) |
| 82 | TheVector.set(BitPos); |
| 83 | else |
| 84 | TheVector.reset(BitPos); |
| 85 | return *this; |
| 86 | } |
| 87 | |
| 88 | operator bool() const { |
| 89 | return const_cast<const SmallBitVector &>(TheVector).operator[](BitPos); |
| 90 | } |
| 91 | }; |
no test coverage detected