brettwooldridge / SparseBitSet

An efficient sparse bit set implementation for Java

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bug in nextClearBit

incaseoftrouble opened this issue · comments

Hi,

consider the following:

SparseBitSet bitSet = new SparseBitSet();
bitSet.set(2047);
assert bitSet.nextClearBit(2047) == 2048; // Fails - Should be 2048 but actually is 65600! Not cool :(

Any chance of fixing this? I have no idea what is going on in these methods ... It seems that this is some kind of "off by one"-error and should be easy to fix.

I'll take a look.

I think I found the / a root of the problem, actually. If you look at nextClearBit, the w1, w2 etc. scans through the bits until a non-null entry is found - which is wrong, I think, since null entries mean "only zero".

The following snippet fixes the pasted code - I'm not sure if it fixes all problems, though.

nword = ~0L; // Important!
loop: for (; w1 != aLength; ++w1)
{
    if ((a2 = bits[w1]) == null)
        break loop;
    for (; w2 != LENGTH2; ++w2)
    {
        if ((a3 = a2[w2]) == null)
            break loop;
        for (; w3 != LENGTH3; ++w3)
            if ((nword = ~a3[w3]) != 0)
                break loop;
        w3 = 0;
    }
    w2 = w3 = 0;
}