Index: lucene/src/java/org/apache/lucene/util/FixedBitSet.java =================================================================== --- lucene/src/java/org/apache/lucene/util/FixedBitSet.java (revision 1174017) +++ lucene/src/java/org/apache/lucene/util/FixedBitSet.java (working copy) @@ -139,9 +139,12 @@ * -1 is returned if there are no more set bits. */ public int nextSetBit(int index) { - assert index >= 0 && index < numBits; + // we allow length() as index to support the following for-loop: + // for(int i=bs.nextSetBit(0); i>=0; i=bs.nextSetBit(i+1)) {} + assert index >= 0 && index <= numBits: "index=" + index + " numBits=" + numBits; int i = index >> 6; - int subIndex = index & 0x3f; // index within the word + if (i >= bits.length) return -1; + final int subIndex = index & 0x3f; // index within the word long word = bits[i] >> subIndex; // skip all the bits to the right of index if (word!=0) { @@ -158,13 +161,17 @@ return -1; } + /** Returns the index of the last set bit before or on the index specified. + * -1 is returned if there are no more set bits. + */ public int prevSetBit(int index) { - assert index >= 0 && index < numBits: "index=" + index + " numBits=" + numBits; + // we allow -1 as index to support the following for-loop: + // for(int i=bs.prevSetBit(bs.length()-1); i>=0; i=bs.prevSetBit(i-1)) {} + assert index >= -1 && index < numBits: "index=" + index + " numBits=" + numBits; int i = index >> 6; - final int subIndex; - long word; - subIndex = index & 0x3f; // index within the word - word = (bits[i] << (63-subIndex)); // skip all the bits to the left of index + if (i < 0) return -1; + final int subIndex = index & 0x3f; // index within the word + long word = (bits[i] << (63-subIndex)); // skip all the bits to the left of index if (word != 0) { return (i << 6) + subIndex - Long.numberOfLeadingZeros(word); // See LUCENE-3197 Index: lucene/src/test/org/apache/lucene/util/TestFixedBitSet.java =================================================================== --- lucene/src/test/org/apache/lucene/util/TestFixedBitSet.java (revision 1174017) +++ lucene/src/test/org/apache/lucene/util/TestFixedBitSet.java (working copy) @@ -37,7 +37,7 @@ int aa=-1,bb=-1; do { aa = a.nextSetBit(aa+1); - bb = bb < b.length()-1 ? b.nextSetBit(bb+1) : -1; + bb = b.nextSetBit(bb+1); assertEquals(aa,bb); } while (aa>=0); } @@ -58,7 +58,7 @@ } else if (bb < 1) { bb = -1; } else { - bb = bb >= 1 ? b.prevSetBit(bb-1) : -1; + bb = b.prevSetBit(bb-1); } assertEquals(aa,bb); } while (aa>=0);