You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
[ADT] Fix an indexing bug in PackedVector (#158785)
PackedVector is like std::vector<int> except that we can store small
elements (e.g. 2-bit elements) in a packed manner using a BitVector as
the underlying storage.
The problem is that for bit size 3 and beyond, the calculation of
indices into the underlying BitVector is not correct. For example,
around line 50, we see a "for" loop to retrieve an unsigned integer
value:
for (unsigned i = 0; i != BitNum-1; ++i)
val = T(val | ((Bits[(Idx << (BitNum-1)) + i] ? 1UL : 0UL) << i));
Suppose that BitNum is 4 (that is, 4-bit item). Here is the mapping
between the PackedVector index and the corresponding BitVector
indices.
Idx 0: 0, 1, 2, 3
Idx 1: 8, 9, 10, 11
Idx 2: 16, 17, 18, 19
That is, we use 4 bits out of every 8 bits. This is because the index
calculation uses "<<". The index should really be Idx * BitNum + i.
FWIW, all the methods in PackedVector consistently use the shift-based
index calculation, so the user would never encounter a bug except
possibly as excessive storage use.
This patch fixes the index calculation. Now, in size(), I didn't want
to do integer division:
return Bits.size() / BitNum;
so this patch adds a separate variable NumElements to keep track of
the number of elements.
The unit test checks for the expected size of the underlying
BitVector.
0 commit comments