@@ -43,25 +43,42 @@ public final class FixedBitSet extends BitSet {
4343 private final int numBits ; // The number of bits in use
4444 private final int numWords ; // The exact number of longs needed to hold numBits (<= bits.length)
4545
46- /**
47- * If the given {@link FixedBitSet} is large enough to hold {@code numBits+1}, returns the given
48- * bits, otherwise returns a new {@link FixedBitSet} which can hold {@code numBits+1} bits. That
49- * means the bitset returned by this method can be safely called with {@code bits.set(numBits)}
50- *
51- * <p><b>NOTE:</b> the returned bitset reuses the underlying {@code long[]} of the given {@code
52- * bits} if possible. Also, calling {@link #length()} on the returned bits may return a value
53- * greater than {@code numBits+1}.
54- */
55- public static FixedBitSet ensureCapacity (FixedBitSet bits , int numBits ) {
56- if (numBits < bits .numBits ) {
46+ /// Ensure the given `bits` can store a value at `desiredBit` index. If the current [#length()] is
47+ /// sufficient, `bits` is simply returned. Otherwise, a new, larger bitset is allocated, with
48+ /// contents of `bits` copied.
49+ ///
50+ /// @see #ensureCapacityAndClear(FixedBitSet, int)
51+ public static FixedBitSet ensureCapacity (FixedBitSet bits , int desiredBit ) {
52+ return ensureCapacityInternal (bits , desiredBit , true );
53+ }
54+
55+ /// Clear the given `bits` and ensure it can store a value at `desiredBit` index. If the current
56+ /// [#length()] is sufficient, `bits` is simply cleared and returned. Otherwise, a new, larger
57+ /// bitset is allocated.
58+ ///
59+ /// @see #ensureCapacity(FixedBitSet, int)
60+ public static FixedBitSet ensureCapacityAndClear (FixedBitSet bits , int desiredBit ) {
61+ return ensureCapacityInternal (bits , desiredBit , false );
62+ }
63+
64+ private static FixedBitSet ensureCapacityInternal (
65+ FixedBitSet bits , int desiredBit , boolean preserveData ) {
66+ if (desiredBit < bits .numBits ) {
67+ if (!preserveData ) {
68+ bits .clear ();
69+ }
5770 return bits ;
5871 } else {
5972 // Depends on the ghost bits being clear!
6073 // (Otherwise, they may become visible in the new instance)
61- int numWords = bits2words (numBits );
74+ int numWords = bits2words (desiredBit );
6275 long [] arr = bits .getBits ();
6376 if (numWords >= arr .length ) {
64- arr = ArrayUtil .grow (arr , numWords + 1 );
77+ if (preserveData ) {
78+ arr = ArrayUtil .grow (arr , numWords + 1 );
79+ } else {
80+ arr = new long [ArrayUtil .oversize (numWords + 1 , Long .BYTES )];
81+ }
6582 }
6683 return new FixedBitSet (arr , arr .length << 6 );
6784 }
0 commit comments