emul/compact/src/main/java/java/util/BitSet.java
author Jaroslav Tulach <jtulach@netbeans.org>
Thu, 31 Oct 2013 11:30:29 +0100
branchjdk7-b147
changeset 1399 07587a260d68
permissions -rw-r--r--
BitSet is needed by Javac
jtulach@1399
     1
/*
jtulach@1399
     2
 * Copyright (c) 1995, 2007, Oracle and/or its affiliates. All rights reserved.
jtulach@1399
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jtulach@1399
     4
 *
jtulach@1399
     5
 * This code is free software; you can redistribute it and/or modify it
jtulach@1399
     6
 * under the terms of the GNU General Public License version 2 only, as
jtulach@1399
     7
 * published by the Free Software Foundation.  Oracle designates this
jtulach@1399
     8
 * particular file as subject to the "Classpath" exception as provided
jtulach@1399
     9
 * by Oracle in the LICENSE file that accompanied this code.
jtulach@1399
    10
 *
jtulach@1399
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jtulach@1399
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jtulach@1399
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jtulach@1399
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jtulach@1399
    15
 * accompanied this code).
jtulach@1399
    16
 *
jtulach@1399
    17
 * You should have received a copy of the GNU General Public License version
jtulach@1399
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jtulach@1399
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jtulach@1399
    20
 *
jtulach@1399
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jtulach@1399
    22
 * or visit www.oracle.com if you need additional information or have any
jtulach@1399
    23
 * questions.
jtulach@1399
    24
 */
jtulach@1399
    25
jtulach@1399
    26
package java.util;
jtulach@1399
    27
jtulach@1399
    28
import java.io.*;
jtulach@1399
    29
import java.nio.ByteBuffer;
jtulach@1399
    30
import java.nio.ByteOrder;
jtulach@1399
    31
import java.nio.LongBuffer;
jtulach@1399
    32
jtulach@1399
    33
/**
jtulach@1399
    34
 * This class implements a vector of bits that grows as needed. Each
jtulach@1399
    35
 * component of the bit set has a {@code boolean} value. The
jtulach@1399
    36
 * bits of a {@code BitSet} are indexed by nonnegative integers.
jtulach@1399
    37
 * Individual indexed bits can be examined, set, or cleared. One
jtulach@1399
    38
 * {@code BitSet} may be used to modify the contents of another
jtulach@1399
    39
 * {@code BitSet} through logical AND, logical inclusive OR, and
jtulach@1399
    40
 * logical exclusive OR operations.
jtulach@1399
    41
 *
jtulach@1399
    42
 * <p>By default, all bits in the set initially have the value
jtulach@1399
    43
 * {@code false}.
jtulach@1399
    44
 *
jtulach@1399
    45
 * <p>Every bit set has a current size, which is the number of bits
jtulach@1399
    46
 * of space currently in use by the bit set. Note that the size is
jtulach@1399
    47
 * related to the implementation of a bit set, so it may change with
jtulach@1399
    48
 * implementation. The length of a bit set relates to logical length
jtulach@1399
    49
 * of a bit set and is defined independently of implementation.
jtulach@1399
    50
 *
jtulach@1399
    51
 * <p>Unless otherwise noted, passing a null parameter to any of the
jtulach@1399
    52
 * methods in a {@code BitSet} will result in a
jtulach@1399
    53
 * {@code NullPointerException}.
jtulach@1399
    54
 *
jtulach@1399
    55
 * <p>A {@code BitSet} is not safe for multithreaded use without
jtulach@1399
    56
 * external synchronization.
jtulach@1399
    57
 *
jtulach@1399
    58
 * @author  Arthur van Hoff
jtulach@1399
    59
 * @author  Michael McCloskey
jtulach@1399
    60
 * @author  Martin Buchholz
jtulach@1399
    61
 * @since   JDK1.0
jtulach@1399
    62
 */
jtulach@1399
    63
public class BitSet implements Cloneable, java.io.Serializable {
jtulach@1399
    64
    /*
jtulach@1399
    65
     * BitSets are packed into arrays of "words."  Currently a word is
jtulach@1399
    66
     * a long, which consists of 64 bits, requiring 6 address bits.
jtulach@1399
    67
     * The choice of word size is determined purely by performance concerns.
jtulach@1399
    68
     */
jtulach@1399
    69
    private final static int ADDRESS_BITS_PER_WORD = 6;
jtulach@1399
    70
    private final static int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD;
jtulach@1399
    71
    private final static int BIT_INDEX_MASK = BITS_PER_WORD - 1;
jtulach@1399
    72
jtulach@1399
    73
    /* Used to shift left or right for a partial word mask */
jtulach@1399
    74
    private static final long WORD_MASK = 0xffffffffffffffffL;
jtulach@1399
    75
jtulach@1399
    76
    /**
jtulach@1399
    77
     * @serialField bits long[]
jtulach@1399
    78
     *
jtulach@1399
    79
     * The bits in this BitSet.  The ith bit is stored in bits[i/64] at
jtulach@1399
    80
     * bit position i % 64 (where bit position 0 refers to the least
jtulach@1399
    81
     * significant bit and 63 refers to the most significant bit).
jtulach@1399
    82
     */
jtulach@1399
    83
    private static final ObjectStreamField[] serialPersistentFields = {
jtulach@1399
    84
        new ObjectStreamField("bits", long[].class),
jtulach@1399
    85
    };
jtulach@1399
    86
jtulach@1399
    87
    /**
jtulach@1399
    88
     * The internal field corresponding to the serialField "bits".
jtulach@1399
    89
     */
jtulach@1399
    90
    private long[] words;
jtulach@1399
    91
jtulach@1399
    92
    /**
jtulach@1399
    93
     * The number of words in the logical size of this BitSet.
jtulach@1399
    94
     */
jtulach@1399
    95
    private transient int wordsInUse = 0;
jtulach@1399
    96
jtulach@1399
    97
    /**
jtulach@1399
    98
     * Whether the size of "words" is user-specified.  If so, we assume
jtulach@1399
    99
     * the user knows what he's doing and try harder to preserve it.
jtulach@1399
   100
     */
jtulach@1399
   101
    private transient boolean sizeIsSticky = false;
jtulach@1399
   102
jtulach@1399
   103
    /* use serialVersionUID from JDK 1.0.2 for interoperability */
jtulach@1399
   104
    private static final long serialVersionUID = 7997698588986878753L;
jtulach@1399
   105
jtulach@1399
   106
    /**
jtulach@1399
   107
     * Given a bit index, return word index containing it.
jtulach@1399
   108
     */
jtulach@1399
   109
    private static int wordIndex(int bitIndex) {
jtulach@1399
   110
        return bitIndex >> ADDRESS_BITS_PER_WORD;
jtulach@1399
   111
    }
jtulach@1399
   112
jtulach@1399
   113
    /**
jtulach@1399
   114
     * Every public method must preserve these invariants.
jtulach@1399
   115
     */
jtulach@1399
   116
    private void checkInvariants() {
jtulach@1399
   117
        assert(wordsInUse == 0 || words[wordsInUse - 1] != 0);
jtulach@1399
   118
        assert(wordsInUse >= 0 && wordsInUse <= words.length);
jtulach@1399
   119
        assert(wordsInUse == words.length || words[wordsInUse] == 0);
jtulach@1399
   120
    }
jtulach@1399
   121
jtulach@1399
   122
    /**
jtulach@1399
   123
     * Sets the field wordsInUse to the logical size in words of the bit set.
jtulach@1399
   124
     * WARNING:This method assumes that the number of words actually in use is
jtulach@1399
   125
     * less than or equal to the current value of wordsInUse!
jtulach@1399
   126
     */
jtulach@1399
   127
    private void recalculateWordsInUse() {
jtulach@1399
   128
        // Traverse the bitset until a used word is found
jtulach@1399
   129
        int i;
jtulach@1399
   130
        for (i = wordsInUse-1; i >= 0; i--)
jtulach@1399
   131
            if (words[i] != 0)
jtulach@1399
   132
                break;
jtulach@1399
   133
jtulach@1399
   134
        wordsInUse = i+1; // The new logical size
jtulach@1399
   135
    }
jtulach@1399
   136
jtulach@1399
   137
    /**
jtulach@1399
   138
     * Creates a new bit set. All bits are initially {@code false}.
jtulach@1399
   139
     */
jtulach@1399
   140
    public BitSet() {
jtulach@1399
   141
        initWords(BITS_PER_WORD);
jtulach@1399
   142
        sizeIsSticky = false;
jtulach@1399
   143
    }
jtulach@1399
   144
jtulach@1399
   145
    /**
jtulach@1399
   146
     * Creates a bit set whose initial size is large enough to explicitly
jtulach@1399
   147
     * represent bits with indices in the range {@code 0} through
jtulach@1399
   148
     * {@code nbits-1}. All bits are initially {@code false}.
jtulach@1399
   149
     *
jtulach@1399
   150
     * @param  nbits the initial size of the bit set
jtulach@1399
   151
     * @throws NegativeArraySizeException if the specified initial size
jtulach@1399
   152
     *         is negative
jtulach@1399
   153
     */
jtulach@1399
   154
    public BitSet(int nbits) {
jtulach@1399
   155
        // nbits can't be negative; size 0 is OK
jtulach@1399
   156
        if (nbits < 0)
jtulach@1399
   157
            throw new NegativeArraySizeException("nbits < 0: " + nbits);
jtulach@1399
   158
jtulach@1399
   159
        initWords(nbits);
jtulach@1399
   160
        sizeIsSticky = true;
jtulach@1399
   161
    }
jtulach@1399
   162
jtulach@1399
   163
    private void initWords(int nbits) {
jtulach@1399
   164
        words = new long[wordIndex(nbits-1) + 1];
jtulach@1399
   165
    }
jtulach@1399
   166
jtulach@1399
   167
    /**
jtulach@1399
   168
     * Creates a bit set using words as the internal representation.
jtulach@1399
   169
     * The last word (if there is one) must be non-zero.
jtulach@1399
   170
     */
jtulach@1399
   171
    private BitSet(long[] words) {
jtulach@1399
   172
        this.words = words;
jtulach@1399
   173
        this.wordsInUse = words.length;
jtulach@1399
   174
        checkInvariants();
jtulach@1399
   175
    }
jtulach@1399
   176
jtulach@1399
   177
    /**
jtulach@1399
   178
     * Returns a new bit set containing all the bits in the given long array.
jtulach@1399
   179
     *
jtulach@1399
   180
     * <p>More precisely,
jtulach@1399
   181
     * <br>{@code BitSet.valueOf(longs).get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)}
jtulach@1399
   182
     * <br>for all {@code n < 64 * longs.length}.
jtulach@1399
   183
     *
jtulach@1399
   184
     * <p>This method is equivalent to
jtulach@1399
   185
     * {@code BitSet.valueOf(LongBuffer.wrap(longs))}.
jtulach@1399
   186
     *
jtulach@1399
   187
     * @param longs a long array containing a little-endian representation
jtulach@1399
   188
     *        of a sequence of bits to be used as the initial bits of the
jtulach@1399
   189
     *        new bit set
jtulach@1399
   190
     * @since 1.7
jtulach@1399
   191
     */
jtulach@1399
   192
    public static BitSet valueOf(long[] longs) {
jtulach@1399
   193
        int n;
jtulach@1399
   194
        for (n = longs.length; n > 0 && longs[n - 1] == 0; n--)
jtulach@1399
   195
            ;
jtulach@1399
   196
        return new BitSet(Arrays.copyOf(longs, n));
jtulach@1399
   197
    }
jtulach@1399
   198
jtulach@1399
   199
    /**
jtulach@1399
   200
     * Returns a new bit set containing all the bits in the given long
jtulach@1399
   201
     * buffer between its position and limit.
jtulach@1399
   202
     *
jtulach@1399
   203
     * <p>More precisely,
jtulach@1399
   204
     * <br>{@code BitSet.valueOf(lb).get(n) == ((lb.get(lb.position()+n/64) & (1L<<(n%64))) != 0)}
jtulach@1399
   205
     * <br>for all {@code n < 64 * lb.remaining()}.
jtulach@1399
   206
     *
jtulach@1399
   207
     * <p>The long buffer is not modified by this method, and no
jtulach@1399
   208
     * reference to the buffer is retained by the bit set.
jtulach@1399
   209
     *
jtulach@1399
   210
     * @param lb a long buffer containing a little-endian representation
jtulach@1399
   211
     *        of a sequence of bits between its position and limit, to be
jtulach@1399
   212
     *        used as the initial bits of the new bit set
jtulach@1399
   213
     * @since 1.7
jtulach@1399
   214
     */
jtulach@1399
   215
    public static BitSet valueOf(LongBuffer lb) {
jtulach@1399
   216
        lb = lb.slice();
jtulach@1399
   217
        int n;
jtulach@1399
   218
        for (n = lb.remaining(); n > 0 && lb.get(n - 1) == 0; n--)
jtulach@1399
   219
            ;
jtulach@1399
   220
        long[] words = new long[n];
jtulach@1399
   221
        lb.get(words);
jtulach@1399
   222
        return new BitSet(words);
jtulach@1399
   223
    }
jtulach@1399
   224
jtulach@1399
   225
    /**
jtulach@1399
   226
     * Returns a new bit set containing all the bits in the given byte array.
jtulach@1399
   227
     *
jtulach@1399
   228
     * <p>More precisely,
jtulach@1399
   229
     * <br>{@code BitSet.valueOf(bytes).get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)}
jtulach@1399
   230
     * <br>for all {@code n <  8 * bytes.length}.
jtulach@1399
   231
     *
jtulach@1399
   232
     * <p>This method is equivalent to
jtulach@1399
   233
     * {@code BitSet.valueOf(ByteBuffer.wrap(bytes))}.
jtulach@1399
   234
     *
jtulach@1399
   235
     * @param bytes a byte array containing a little-endian
jtulach@1399
   236
     *        representation of a sequence of bits to be used as the
jtulach@1399
   237
     *        initial bits of the new bit set
jtulach@1399
   238
     * @since 1.7
jtulach@1399
   239
     */
jtulach@1399
   240
    public static BitSet valueOf(byte[] bytes) {
jtulach@1399
   241
        return BitSet.valueOf(ByteBuffer.wrap(bytes));
jtulach@1399
   242
    }
jtulach@1399
   243
jtulach@1399
   244
    /**
jtulach@1399
   245
     * Returns a new bit set containing all the bits in the given byte
jtulach@1399
   246
     * buffer between its position and limit.
jtulach@1399
   247
     *
jtulach@1399
   248
     * <p>More precisely,
jtulach@1399
   249
     * <br>{@code BitSet.valueOf(bb).get(n) == ((bb.get(bb.position()+n/8) & (1<<(n%8))) != 0)}
jtulach@1399
   250
     * <br>for all {@code n < 8 * bb.remaining()}.
jtulach@1399
   251
     *
jtulach@1399
   252
     * <p>The byte buffer is not modified by this method, and no
jtulach@1399
   253
     * reference to the buffer is retained by the bit set.
jtulach@1399
   254
     *
jtulach@1399
   255
     * @param bb a byte buffer containing a little-endian representation
jtulach@1399
   256
     *        of a sequence of bits between its position and limit, to be
jtulach@1399
   257
     *        used as the initial bits of the new bit set
jtulach@1399
   258
     * @since 1.7
jtulach@1399
   259
     */
jtulach@1399
   260
    public static BitSet valueOf(ByteBuffer bb) {
jtulach@1399
   261
        bb = bb.slice().order(ByteOrder.LITTLE_ENDIAN);
jtulach@1399
   262
        int n;
jtulach@1399
   263
        for (n = bb.remaining(); n > 0 && bb.get(n - 1) == 0; n--)
jtulach@1399
   264
            ;
jtulach@1399
   265
        long[] words = new long[(n + 7) / 8];
jtulach@1399
   266
        bb.limit(n);
jtulach@1399
   267
        int i = 0;
jtulach@1399
   268
        while (bb.remaining() >= 8)
jtulach@1399
   269
            words[i++] = bb.getLong();
jtulach@1399
   270
        for (int remaining = bb.remaining(), j = 0; j < remaining; j++)
jtulach@1399
   271
            words[i] |= (bb.get() & 0xffL) << (8 * j);
jtulach@1399
   272
        return new BitSet(words);
jtulach@1399
   273
    }
jtulach@1399
   274
jtulach@1399
   275
    /**
jtulach@1399
   276
     * Returns a new byte array containing all the bits in this bit set.
jtulach@1399
   277
     *
jtulach@1399
   278
     * <p>More precisely, if
jtulach@1399
   279
     * <br>{@code byte[] bytes = s.toByteArray();}
jtulach@1399
   280
     * <br>then {@code bytes.length == (s.length()+7)/8} and
jtulach@1399
   281
     * <br>{@code s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)}
jtulach@1399
   282
     * <br>for all {@code n < 8 * bytes.length}.
jtulach@1399
   283
     *
jtulach@1399
   284
     * @return a byte array containing a little-endian representation
jtulach@1399
   285
     *         of all the bits in this bit set
jtulach@1399
   286
     * @since 1.7
jtulach@1399
   287
    */
jtulach@1399
   288
    public byte[] toByteArray() {
jtulach@1399
   289
        int n = wordsInUse;
jtulach@1399
   290
        if (n == 0)
jtulach@1399
   291
            return new byte[0];
jtulach@1399
   292
        int len = 8 * (n-1);
jtulach@1399
   293
        for (long x = words[n - 1]; x != 0; x >>>= 8)
jtulach@1399
   294
            len++;
jtulach@1399
   295
        byte[] bytes = new byte[len];
jtulach@1399
   296
        ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
jtulach@1399
   297
        for (int i = 0; i < n - 1; i++)
jtulach@1399
   298
            bb.putLong(words[i]);
jtulach@1399
   299
        for (long x = words[n - 1]; x != 0; x >>>= 8)
jtulach@1399
   300
            bb.put((byte) (x & 0xff));
jtulach@1399
   301
        return bytes;
jtulach@1399
   302
    }
jtulach@1399
   303
jtulach@1399
   304
    /**
jtulach@1399
   305
     * Returns a new long array containing all the bits in this bit set.
jtulach@1399
   306
     *
jtulach@1399
   307
     * <p>More precisely, if
jtulach@1399
   308
     * <br>{@code long[] longs = s.toLongArray();}
jtulach@1399
   309
     * <br>then {@code longs.length == (s.length()+63)/64} and
jtulach@1399
   310
     * <br>{@code s.get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)}
jtulach@1399
   311
     * <br>for all {@code n < 64 * longs.length}.
jtulach@1399
   312
     *
jtulach@1399
   313
     * @return a long array containing a little-endian representation
jtulach@1399
   314
     *         of all the bits in this bit set
jtulach@1399
   315
     * @since 1.7
jtulach@1399
   316
    */
jtulach@1399
   317
    public long[] toLongArray() {
jtulach@1399
   318
        return Arrays.copyOf(words, wordsInUse);
jtulach@1399
   319
    }
jtulach@1399
   320
jtulach@1399
   321
    /**
jtulach@1399
   322
     * Ensures that the BitSet can hold enough words.
jtulach@1399
   323
     * @param wordsRequired the minimum acceptable number of words.
jtulach@1399
   324
     */
jtulach@1399
   325
    private void ensureCapacity(int wordsRequired) {
jtulach@1399
   326
        if (words.length < wordsRequired) {
jtulach@1399
   327
            // Allocate larger of doubled size or required size
jtulach@1399
   328
            int request = Math.max(2 * words.length, wordsRequired);
jtulach@1399
   329
            words = Arrays.copyOf(words, request);
jtulach@1399
   330
            sizeIsSticky = false;
jtulach@1399
   331
        }
jtulach@1399
   332
    }
jtulach@1399
   333
jtulach@1399
   334
    /**
jtulach@1399
   335
     * Ensures that the BitSet can accommodate a given wordIndex,
jtulach@1399
   336
     * temporarily violating the invariants.  The caller must
jtulach@1399
   337
     * restore the invariants before returning to the user,
jtulach@1399
   338
     * possibly using recalculateWordsInUse().
jtulach@1399
   339
     * @param wordIndex the index to be accommodated.
jtulach@1399
   340
     */
jtulach@1399
   341
    private void expandTo(int wordIndex) {
jtulach@1399
   342
        int wordsRequired = wordIndex+1;
jtulach@1399
   343
        if (wordsInUse < wordsRequired) {
jtulach@1399
   344
            ensureCapacity(wordsRequired);
jtulach@1399
   345
            wordsInUse = wordsRequired;
jtulach@1399
   346
        }
jtulach@1399
   347
    }
jtulach@1399
   348
jtulach@1399
   349
    /**
jtulach@1399
   350
     * Checks that fromIndex ... toIndex is a valid range of bit indices.
jtulach@1399
   351
     */
jtulach@1399
   352
    private static void checkRange(int fromIndex, int toIndex) {
jtulach@1399
   353
        if (fromIndex < 0)
jtulach@1399
   354
            throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
jtulach@1399
   355
        if (toIndex < 0)
jtulach@1399
   356
            throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex);
jtulach@1399
   357
        if (fromIndex > toIndex)
jtulach@1399
   358
            throw new IndexOutOfBoundsException("fromIndex: " + fromIndex +
jtulach@1399
   359
                                                " > toIndex: " + toIndex);
jtulach@1399
   360
    }
jtulach@1399
   361
jtulach@1399
   362
    /**
jtulach@1399
   363
     * Sets the bit at the specified index to the complement of its
jtulach@1399
   364
     * current value.
jtulach@1399
   365
     *
jtulach@1399
   366
     * @param  bitIndex the index of the bit to flip
jtulach@1399
   367
     * @throws IndexOutOfBoundsException if the specified index is negative
jtulach@1399
   368
     * @since  1.4
jtulach@1399
   369
     */
jtulach@1399
   370
    public void flip(int bitIndex) {
jtulach@1399
   371
        if (bitIndex < 0)
jtulach@1399
   372
            throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
jtulach@1399
   373
jtulach@1399
   374
        int wordIndex = wordIndex(bitIndex);
jtulach@1399
   375
        expandTo(wordIndex);
jtulach@1399
   376
jtulach@1399
   377
        words[wordIndex] ^= (1L << bitIndex);
jtulach@1399
   378
jtulach@1399
   379
        recalculateWordsInUse();
jtulach@1399
   380
        checkInvariants();
jtulach@1399
   381
    }
jtulach@1399
   382
jtulach@1399
   383
    /**
jtulach@1399
   384
     * Sets each bit from the specified {@code fromIndex} (inclusive) to the
jtulach@1399
   385
     * specified {@code toIndex} (exclusive) to the complement of its current
jtulach@1399
   386
     * value.
jtulach@1399
   387
     *
jtulach@1399
   388
     * @param  fromIndex index of the first bit to flip
jtulach@1399
   389
     * @param  toIndex index after the last bit to flip
jtulach@1399
   390
     * @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
jtulach@1399
   391
     *         or {@code toIndex} is negative, or {@code fromIndex} is
jtulach@1399
   392
     *         larger than {@code toIndex}
jtulach@1399
   393
     * @since  1.4
jtulach@1399
   394
     */
jtulach@1399
   395
    public void flip(int fromIndex, int toIndex) {
jtulach@1399
   396
        checkRange(fromIndex, toIndex);
jtulach@1399
   397
jtulach@1399
   398
        if (fromIndex == toIndex)
jtulach@1399
   399
            return;
jtulach@1399
   400
jtulach@1399
   401
        int startWordIndex = wordIndex(fromIndex);
jtulach@1399
   402
        int endWordIndex   = wordIndex(toIndex - 1);
jtulach@1399
   403
        expandTo(endWordIndex);
jtulach@1399
   404
jtulach@1399
   405
        long firstWordMask = WORD_MASK << fromIndex;
jtulach@1399
   406
        long lastWordMask  = WORD_MASK >>> -toIndex;
jtulach@1399
   407
        if (startWordIndex == endWordIndex) {
jtulach@1399
   408
            // Case 1: One word
jtulach@1399
   409
            words[startWordIndex] ^= (firstWordMask & lastWordMask);
jtulach@1399
   410
        } else {
jtulach@1399
   411
            // Case 2: Multiple words
jtulach@1399
   412
            // Handle first word
jtulach@1399
   413
            words[startWordIndex] ^= firstWordMask;
jtulach@1399
   414
jtulach@1399
   415
            // Handle intermediate words, if any
jtulach@1399
   416
            for (int i = startWordIndex+1; i < endWordIndex; i++)
jtulach@1399
   417
                words[i] ^= WORD_MASK;
jtulach@1399
   418
jtulach@1399
   419
            // Handle last word
jtulach@1399
   420
            words[endWordIndex] ^= lastWordMask;
jtulach@1399
   421
        }
jtulach@1399
   422
jtulach@1399
   423
        recalculateWordsInUse();
jtulach@1399
   424
        checkInvariants();
jtulach@1399
   425
    }
jtulach@1399
   426
jtulach@1399
   427
    /**
jtulach@1399
   428
     * Sets the bit at the specified index to {@code true}.
jtulach@1399
   429
     *
jtulach@1399
   430
     * @param  bitIndex a bit index
jtulach@1399
   431
     * @throws IndexOutOfBoundsException if the specified index is negative
jtulach@1399
   432
     * @since  JDK1.0
jtulach@1399
   433
     */
jtulach@1399
   434
    public void set(int bitIndex) {
jtulach@1399
   435
        if (bitIndex < 0)
jtulach@1399
   436
            throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
jtulach@1399
   437
jtulach@1399
   438
        int wordIndex = wordIndex(bitIndex);
jtulach@1399
   439
        expandTo(wordIndex);
jtulach@1399
   440
jtulach@1399
   441
        words[wordIndex] |= (1L << bitIndex); // Restores invariants
jtulach@1399
   442
jtulach@1399
   443
        checkInvariants();
jtulach@1399
   444
    }
jtulach@1399
   445
jtulach@1399
   446
    /**
jtulach@1399
   447
     * Sets the bit at the specified index to the specified value.
jtulach@1399
   448
     *
jtulach@1399
   449
     * @param  bitIndex a bit index
jtulach@1399
   450
     * @param  value a boolean value to set
jtulach@1399
   451
     * @throws IndexOutOfBoundsException if the specified index is negative
jtulach@1399
   452
     * @since  1.4
jtulach@1399
   453
     */
jtulach@1399
   454
    public void set(int bitIndex, boolean value) {
jtulach@1399
   455
        if (value)
jtulach@1399
   456
            set(bitIndex);
jtulach@1399
   457
        else
jtulach@1399
   458
            clear(bitIndex);
jtulach@1399
   459
    }
jtulach@1399
   460
jtulach@1399
   461
    /**
jtulach@1399
   462
     * Sets the bits from the specified {@code fromIndex} (inclusive) to the
jtulach@1399
   463
     * specified {@code toIndex} (exclusive) to {@code true}.
jtulach@1399
   464
     *
jtulach@1399
   465
     * @param  fromIndex index of the first bit to be set
jtulach@1399
   466
     * @param  toIndex index after the last bit to be set
jtulach@1399
   467
     * @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
jtulach@1399
   468
     *         or {@code toIndex} is negative, or {@code fromIndex} is
jtulach@1399
   469
     *         larger than {@code toIndex}
jtulach@1399
   470
     * @since  1.4
jtulach@1399
   471
     */
jtulach@1399
   472
    public void set(int fromIndex, int toIndex) {
jtulach@1399
   473
        checkRange(fromIndex, toIndex);
jtulach@1399
   474
jtulach@1399
   475
        if (fromIndex == toIndex)
jtulach@1399
   476
            return;
jtulach@1399
   477
jtulach@1399
   478
        // Increase capacity if necessary
jtulach@1399
   479
        int startWordIndex = wordIndex(fromIndex);
jtulach@1399
   480
        int endWordIndex   = wordIndex(toIndex - 1);
jtulach@1399
   481
        expandTo(endWordIndex);
jtulach@1399
   482
jtulach@1399
   483
        long firstWordMask = WORD_MASK << fromIndex;
jtulach@1399
   484
        long lastWordMask  = WORD_MASK >>> -toIndex;
jtulach@1399
   485
        if (startWordIndex == endWordIndex) {
jtulach@1399
   486
            // Case 1: One word
jtulach@1399
   487
            words[startWordIndex] |= (firstWordMask & lastWordMask);
jtulach@1399
   488
        } else {
jtulach@1399
   489
            // Case 2: Multiple words
jtulach@1399
   490
            // Handle first word
jtulach@1399
   491
            words[startWordIndex] |= firstWordMask;
jtulach@1399
   492
jtulach@1399
   493
            // Handle intermediate words, if any
jtulach@1399
   494
            for (int i = startWordIndex+1; i < endWordIndex; i++)
jtulach@1399
   495
                words[i] = WORD_MASK;
jtulach@1399
   496
jtulach@1399
   497
            // Handle last word (restores invariants)
jtulach@1399
   498
            words[endWordIndex] |= lastWordMask;
jtulach@1399
   499
        }
jtulach@1399
   500
jtulach@1399
   501
        checkInvariants();
jtulach@1399
   502
    }
jtulach@1399
   503
jtulach@1399
   504
    /**
jtulach@1399
   505
     * Sets the bits from the specified {@code fromIndex} (inclusive) to the
jtulach@1399
   506
     * specified {@code toIndex} (exclusive) to the specified value.
jtulach@1399
   507
     *
jtulach@1399
   508
     * @param  fromIndex index of the first bit to be set
jtulach@1399
   509
     * @param  toIndex index after the last bit to be set
jtulach@1399
   510
     * @param  value value to set the selected bits to
jtulach@1399
   511
     * @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
jtulach@1399
   512
     *         or {@code toIndex} is negative, or {@code fromIndex} is
jtulach@1399
   513
     *         larger than {@code toIndex}
jtulach@1399
   514
     * @since  1.4
jtulach@1399
   515
     */
jtulach@1399
   516
    public void set(int fromIndex, int toIndex, boolean value) {
jtulach@1399
   517
        if (value)
jtulach@1399
   518
            set(fromIndex, toIndex);
jtulach@1399
   519
        else
jtulach@1399
   520
            clear(fromIndex, toIndex);
jtulach@1399
   521
    }
jtulach@1399
   522
jtulach@1399
   523
    /**
jtulach@1399
   524
     * Sets the bit specified by the index to {@code false}.
jtulach@1399
   525
     *
jtulach@1399
   526
     * @param  bitIndex the index of the bit to be cleared
jtulach@1399
   527
     * @throws IndexOutOfBoundsException if the specified index is negative
jtulach@1399
   528
     * @since  JDK1.0
jtulach@1399
   529
     */
jtulach@1399
   530
    public void clear(int bitIndex) {
jtulach@1399
   531
        if (bitIndex < 0)
jtulach@1399
   532
            throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
jtulach@1399
   533
jtulach@1399
   534
        int wordIndex = wordIndex(bitIndex);
jtulach@1399
   535
        if (wordIndex >= wordsInUse)
jtulach@1399
   536
            return;
jtulach@1399
   537
jtulach@1399
   538
        words[wordIndex] &= ~(1L << bitIndex);
jtulach@1399
   539
jtulach@1399
   540
        recalculateWordsInUse();
jtulach@1399
   541
        checkInvariants();
jtulach@1399
   542
    }
jtulach@1399
   543
jtulach@1399
   544
    /**
jtulach@1399
   545
     * Sets the bits from the specified {@code fromIndex} (inclusive) to the
jtulach@1399
   546
     * specified {@code toIndex} (exclusive) to {@code false}.
jtulach@1399
   547
     *
jtulach@1399
   548
     * @param  fromIndex index of the first bit to be cleared
jtulach@1399
   549
     * @param  toIndex index after the last bit to be cleared
jtulach@1399
   550
     * @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
jtulach@1399
   551
     *         or {@code toIndex} is negative, or {@code fromIndex} is
jtulach@1399
   552
     *         larger than {@code toIndex}
jtulach@1399
   553
     * @since  1.4
jtulach@1399
   554
     */
jtulach@1399
   555
    public void clear(int fromIndex, int toIndex) {
jtulach@1399
   556
        checkRange(fromIndex, toIndex);
jtulach@1399
   557
jtulach@1399
   558
        if (fromIndex == toIndex)
jtulach@1399
   559
            return;
jtulach@1399
   560
jtulach@1399
   561
        int startWordIndex = wordIndex(fromIndex);
jtulach@1399
   562
        if (startWordIndex >= wordsInUse)
jtulach@1399
   563
            return;
jtulach@1399
   564
jtulach@1399
   565
        int endWordIndex = wordIndex(toIndex - 1);
jtulach@1399
   566
        if (endWordIndex >= wordsInUse) {
jtulach@1399
   567
            toIndex = length();
jtulach@1399
   568
            endWordIndex = wordsInUse - 1;
jtulach@1399
   569
        }
jtulach@1399
   570
jtulach@1399
   571
        long firstWordMask = WORD_MASK << fromIndex;
jtulach@1399
   572
        long lastWordMask  = WORD_MASK >>> -toIndex;
jtulach@1399
   573
        if (startWordIndex == endWordIndex) {
jtulach@1399
   574
            // Case 1: One word
jtulach@1399
   575
            words[startWordIndex] &= ~(firstWordMask & lastWordMask);
jtulach@1399
   576
        } else {
jtulach@1399
   577
            // Case 2: Multiple words
jtulach@1399
   578
            // Handle first word
jtulach@1399
   579
            words[startWordIndex] &= ~firstWordMask;
jtulach@1399
   580
jtulach@1399
   581
            // Handle intermediate words, if any
jtulach@1399
   582
            for (int i = startWordIndex+1; i < endWordIndex; i++)
jtulach@1399
   583
                words[i] = 0;
jtulach@1399
   584
jtulach@1399
   585
            // Handle last word
jtulach@1399
   586
            words[endWordIndex] &= ~lastWordMask;
jtulach@1399
   587
        }
jtulach@1399
   588
jtulach@1399
   589
        recalculateWordsInUse();
jtulach@1399
   590
        checkInvariants();
jtulach@1399
   591
    }
jtulach@1399
   592
jtulach@1399
   593
    /**
jtulach@1399
   594
     * Sets all of the bits in this BitSet to {@code false}.
jtulach@1399
   595
     *
jtulach@1399
   596
     * @since 1.4
jtulach@1399
   597
     */
jtulach@1399
   598
    public void clear() {
jtulach@1399
   599
        while (wordsInUse > 0)
jtulach@1399
   600
            words[--wordsInUse] = 0;
jtulach@1399
   601
    }
jtulach@1399
   602
jtulach@1399
   603
    /**
jtulach@1399
   604
     * Returns the value of the bit with the specified index. The value
jtulach@1399
   605
     * is {@code true} if the bit with the index {@code bitIndex}
jtulach@1399
   606
     * is currently set in this {@code BitSet}; otherwise, the result
jtulach@1399
   607
     * is {@code false}.
jtulach@1399
   608
     *
jtulach@1399
   609
     * @param  bitIndex   the bit index
jtulach@1399
   610
     * @return the value of the bit with the specified index
jtulach@1399
   611
     * @throws IndexOutOfBoundsException if the specified index is negative
jtulach@1399
   612
     */
jtulach@1399
   613
    public boolean get(int bitIndex) {
jtulach@1399
   614
        if (bitIndex < 0)
jtulach@1399
   615
            throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
jtulach@1399
   616
jtulach@1399
   617
        checkInvariants();
jtulach@1399
   618
jtulach@1399
   619
        int wordIndex = wordIndex(bitIndex);
jtulach@1399
   620
        return (wordIndex < wordsInUse)
jtulach@1399
   621
            && ((words[wordIndex] & (1L << bitIndex)) != 0);
jtulach@1399
   622
    }
jtulach@1399
   623
jtulach@1399
   624
    /**
jtulach@1399
   625
     * Returns a new {@code BitSet} composed of bits from this {@code BitSet}
jtulach@1399
   626
     * from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive).
jtulach@1399
   627
     *
jtulach@1399
   628
     * @param  fromIndex index of the first bit to include
jtulach@1399
   629
     * @param  toIndex index after the last bit to include
jtulach@1399
   630
     * @return a new {@code BitSet} from a range of this {@code BitSet}
jtulach@1399
   631
     * @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
jtulach@1399
   632
     *         or {@code toIndex} is negative, or {@code fromIndex} is
jtulach@1399
   633
     *         larger than {@code toIndex}
jtulach@1399
   634
     * @since  1.4
jtulach@1399
   635
     */
jtulach@1399
   636
    public BitSet get(int fromIndex, int toIndex) {
jtulach@1399
   637
        checkRange(fromIndex, toIndex);
jtulach@1399
   638
jtulach@1399
   639
        checkInvariants();
jtulach@1399
   640
jtulach@1399
   641
        int len = length();
jtulach@1399
   642
jtulach@1399
   643
        // If no set bits in range return empty bitset
jtulach@1399
   644
        if (len <= fromIndex || fromIndex == toIndex)
jtulach@1399
   645
            return new BitSet(0);
jtulach@1399
   646
jtulach@1399
   647
        // An optimization
jtulach@1399
   648
        if (toIndex > len)
jtulach@1399
   649
            toIndex = len;
jtulach@1399
   650
jtulach@1399
   651
        BitSet result = new BitSet(toIndex - fromIndex);
jtulach@1399
   652
        int targetWords = wordIndex(toIndex - fromIndex - 1) + 1;
jtulach@1399
   653
        int sourceIndex = wordIndex(fromIndex);
jtulach@1399
   654
        boolean wordAligned = ((fromIndex & BIT_INDEX_MASK) == 0);
jtulach@1399
   655
jtulach@1399
   656
        // Process all words but the last word
jtulach@1399
   657
        for (int i = 0; i < targetWords - 1; i++, sourceIndex++)
jtulach@1399
   658
            result.words[i] = wordAligned ? words[sourceIndex] :
jtulach@1399
   659
                (words[sourceIndex] >>> fromIndex) |
jtulach@1399
   660
                (words[sourceIndex+1] << -fromIndex);
jtulach@1399
   661
jtulach@1399
   662
        // Process the last word
jtulach@1399
   663
        long lastWordMask = WORD_MASK >>> -toIndex;
jtulach@1399
   664
        result.words[targetWords - 1] =
jtulach@1399
   665
            ((toIndex-1) & BIT_INDEX_MASK) < (fromIndex & BIT_INDEX_MASK)
jtulach@1399
   666
            ? /* straddles source words */
jtulach@1399
   667
            ((words[sourceIndex] >>> fromIndex) |
jtulach@1399
   668
             (words[sourceIndex+1] & lastWordMask) << -fromIndex)
jtulach@1399
   669
            :
jtulach@1399
   670
            ((words[sourceIndex] & lastWordMask) >>> fromIndex);
jtulach@1399
   671
jtulach@1399
   672
        // Set wordsInUse correctly
jtulach@1399
   673
        result.wordsInUse = targetWords;
jtulach@1399
   674
        result.recalculateWordsInUse();
jtulach@1399
   675
        result.checkInvariants();
jtulach@1399
   676
jtulach@1399
   677
        return result;
jtulach@1399
   678
    }
jtulach@1399
   679
jtulach@1399
   680
    /**
jtulach@1399
   681
     * Returns the index of the first bit that is set to {@code true}
jtulach@1399
   682
     * that occurs on or after the specified starting index. If no such
jtulach@1399
   683
     * bit exists then {@code -1} is returned.
jtulach@1399
   684
     *
jtulach@1399
   685
     * <p>To iterate over the {@code true} bits in a {@code BitSet},
jtulach@1399
   686
     * use the following loop:
jtulach@1399
   687
     *
jtulach@1399
   688
     *  <pre> {@code
jtulach@1399
   689
     * for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
jtulach@1399
   690
     *     // operate on index i here
jtulach@1399
   691
     * }}</pre>
jtulach@1399
   692
     *
jtulach@1399
   693
     * @param  fromIndex the index to start checking from (inclusive)
jtulach@1399
   694
     * @return the index of the next set bit, or {@code -1} if there
jtulach@1399
   695
     *         is no such bit
jtulach@1399
   696
     * @throws IndexOutOfBoundsException if the specified index is negative
jtulach@1399
   697
     * @since  1.4
jtulach@1399
   698
     */
jtulach@1399
   699
    public int nextSetBit(int fromIndex) {
jtulach@1399
   700
        if (fromIndex < 0)
jtulach@1399
   701
            throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
jtulach@1399
   702
jtulach@1399
   703
        checkInvariants();
jtulach@1399
   704
jtulach@1399
   705
        int u = wordIndex(fromIndex);
jtulach@1399
   706
        if (u >= wordsInUse)
jtulach@1399
   707
            return -1;
jtulach@1399
   708
jtulach@1399
   709
        long word = words[u] & (WORD_MASK << fromIndex);
jtulach@1399
   710
jtulach@1399
   711
        while (true) {
jtulach@1399
   712
            if (word != 0)
jtulach@1399
   713
                return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);
jtulach@1399
   714
            if (++u == wordsInUse)
jtulach@1399
   715
                return -1;
jtulach@1399
   716
            word = words[u];
jtulach@1399
   717
        }
jtulach@1399
   718
    }
jtulach@1399
   719
jtulach@1399
   720
    /**
jtulach@1399
   721
     * Returns the index of the first bit that is set to {@code false}
jtulach@1399
   722
     * that occurs on or after the specified starting index.
jtulach@1399
   723
     *
jtulach@1399
   724
     * @param  fromIndex the index to start checking from (inclusive)
jtulach@1399
   725
     * @return the index of the next clear bit
jtulach@1399
   726
     * @throws IndexOutOfBoundsException if the specified index is negative
jtulach@1399
   727
     * @since  1.4
jtulach@1399
   728
     */
jtulach@1399
   729
    public int nextClearBit(int fromIndex) {
jtulach@1399
   730
        // Neither spec nor implementation handle bitsets of maximal length.
jtulach@1399
   731
        // See 4816253.
jtulach@1399
   732
        if (fromIndex < 0)
jtulach@1399
   733
            throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
jtulach@1399
   734
jtulach@1399
   735
        checkInvariants();
jtulach@1399
   736
jtulach@1399
   737
        int u = wordIndex(fromIndex);
jtulach@1399
   738
        if (u >= wordsInUse)
jtulach@1399
   739
            return fromIndex;
jtulach@1399
   740
jtulach@1399
   741
        long word = ~words[u] & (WORD_MASK << fromIndex);
jtulach@1399
   742
jtulach@1399
   743
        while (true) {
jtulach@1399
   744
            if (word != 0)
jtulach@1399
   745
                return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);
jtulach@1399
   746
            if (++u == wordsInUse)
jtulach@1399
   747
                return wordsInUse * BITS_PER_WORD;
jtulach@1399
   748
            word = ~words[u];
jtulach@1399
   749
        }
jtulach@1399
   750
    }
jtulach@1399
   751
jtulach@1399
   752
    /**
jtulach@1399
   753
     * Returns the index of the nearest bit that is set to {@code true}
jtulach@1399
   754
     * that occurs on or before the specified starting index.
jtulach@1399
   755
     * If no such bit exists, or if {@code -1} is given as the
jtulach@1399
   756
     * starting index, then {@code -1} is returned.
jtulach@1399
   757
     *
jtulach@1399
   758
     * <p>To iterate over the {@code true} bits in a {@code BitSet},
jtulach@1399
   759
     * use the following loop:
jtulach@1399
   760
     *
jtulach@1399
   761
     *  <pre> {@code
jtulach@1399
   762
     * for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) {
jtulach@1399
   763
     *     // operate on index i here
jtulach@1399
   764
     * }}</pre>
jtulach@1399
   765
     *
jtulach@1399
   766
     * @param  fromIndex the index to start checking from (inclusive)
jtulach@1399
   767
     * @return the index of the previous set bit, or {@code -1} if there
jtulach@1399
   768
     *         is no such bit
jtulach@1399
   769
     * @throws IndexOutOfBoundsException if the specified index is less
jtulach@1399
   770
     *         than {@code -1}
jtulach@1399
   771
     * @since  1.7
jtulach@1399
   772
     */
jtulach@1399
   773
    public int previousSetBit(int fromIndex) {
jtulach@1399
   774
        if (fromIndex < 0) {
jtulach@1399
   775
            if (fromIndex == -1)
jtulach@1399
   776
                return -1;
jtulach@1399
   777
            throw new IndexOutOfBoundsException(
jtulach@1399
   778
                "fromIndex < -1: " + fromIndex);
jtulach@1399
   779
        }
jtulach@1399
   780
jtulach@1399
   781
        checkInvariants();
jtulach@1399
   782
jtulach@1399
   783
        int u = wordIndex(fromIndex);
jtulach@1399
   784
        if (u >= wordsInUse)
jtulach@1399
   785
            return length() - 1;
jtulach@1399
   786
jtulach@1399
   787
        long word = words[u] & (WORD_MASK >>> -(fromIndex+1));
jtulach@1399
   788
jtulach@1399
   789
        while (true) {
jtulach@1399
   790
            if (word != 0)
jtulach@1399
   791
                return (u+1) * BITS_PER_WORD - 1 - Long.numberOfLeadingZeros(word);
jtulach@1399
   792
            if (u-- == 0)
jtulach@1399
   793
                return -1;
jtulach@1399
   794
            word = words[u];
jtulach@1399
   795
        }
jtulach@1399
   796
    }
jtulach@1399
   797
jtulach@1399
   798
    /**
jtulach@1399
   799
     * Returns the index of the nearest bit that is set to {@code false}
jtulach@1399
   800
     * that occurs on or before the specified starting index.
jtulach@1399
   801
     * If no such bit exists, or if {@code -1} is given as the
jtulach@1399
   802
     * starting index, then {@code -1} is returned.
jtulach@1399
   803
     *
jtulach@1399
   804
     * @param  fromIndex the index to start checking from (inclusive)
jtulach@1399
   805
     * @return the index of the previous clear bit, or {@code -1} if there
jtulach@1399
   806
     *         is no such bit
jtulach@1399
   807
     * @throws IndexOutOfBoundsException if the specified index is less
jtulach@1399
   808
     *         than {@code -1}
jtulach@1399
   809
     * @since  1.7
jtulach@1399
   810
     */
jtulach@1399
   811
    public int previousClearBit(int fromIndex) {
jtulach@1399
   812
        if (fromIndex < 0) {
jtulach@1399
   813
            if (fromIndex == -1)
jtulach@1399
   814
                return -1;
jtulach@1399
   815
            throw new IndexOutOfBoundsException(
jtulach@1399
   816
                "fromIndex < -1: " + fromIndex);
jtulach@1399
   817
        }
jtulach@1399
   818
jtulach@1399
   819
        checkInvariants();
jtulach@1399
   820
jtulach@1399
   821
        int u = wordIndex(fromIndex);
jtulach@1399
   822
        if (u >= wordsInUse)
jtulach@1399
   823
            return fromIndex;
jtulach@1399
   824
jtulach@1399
   825
        long word = ~words[u] & (WORD_MASK >>> -(fromIndex+1));
jtulach@1399
   826
jtulach@1399
   827
        while (true) {
jtulach@1399
   828
            if (word != 0)
jtulach@1399
   829
                return (u+1) * BITS_PER_WORD -1 - Long.numberOfLeadingZeros(word);
jtulach@1399
   830
            if (u-- == 0)
jtulach@1399
   831
                return -1;
jtulach@1399
   832
            word = ~words[u];
jtulach@1399
   833
        }
jtulach@1399
   834
    }
jtulach@1399
   835
jtulach@1399
   836
    /**
jtulach@1399
   837
     * Returns the "logical size" of this {@code BitSet}: the index of
jtulach@1399
   838
     * the highest set bit in the {@code BitSet} plus one. Returns zero
jtulach@1399
   839
     * if the {@code BitSet} contains no set bits.
jtulach@1399
   840
     *
jtulach@1399
   841
     * @return the logical size of this {@code BitSet}
jtulach@1399
   842
     * @since  1.2
jtulach@1399
   843
     */
jtulach@1399
   844
    public int length() {
jtulach@1399
   845
        if (wordsInUse == 0)
jtulach@1399
   846
            return 0;
jtulach@1399
   847
jtulach@1399
   848
        return BITS_PER_WORD * (wordsInUse - 1) +
jtulach@1399
   849
            (BITS_PER_WORD - Long.numberOfLeadingZeros(words[wordsInUse - 1]));
jtulach@1399
   850
    }
jtulach@1399
   851
jtulach@1399
   852
    /**
jtulach@1399
   853
     * Returns true if this {@code BitSet} contains no bits that are set
jtulach@1399
   854
     * to {@code true}.
jtulach@1399
   855
     *
jtulach@1399
   856
     * @return boolean indicating whether this {@code BitSet} is empty
jtulach@1399
   857
     * @since  1.4
jtulach@1399
   858
     */
jtulach@1399
   859
    public boolean isEmpty() {
jtulach@1399
   860
        return wordsInUse == 0;
jtulach@1399
   861
    }
jtulach@1399
   862
jtulach@1399
   863
    /**
jtulach@1399
   864
     * Returns true if the specified {@code BitSet} has any bits set to
jtulach@1399
   865
     * {@code true} that are also set to {@code true} in this {@code BitSet}.
jtulach@1399
   866
     *
jtulach@1399
   867
     * @param  set {@code BitSet} to intersect with
jtulach@1399
   868
     * @return boolean indicating whether this {@code BitSet} intersects
jtulach@1399
   869
     *         the specified {@code BitSet}
jtulach@1399
   870
     * @since  1.4
jtulach@1399
   871
     */
jtulach@1399
   872
    public boolean intersects(BitSet set) {
jtulach@1399
   873
        for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--)
jtulach@1399
   874
            if ((words[i] & set.words[i]) != 0)
jtulach@1399
   875
                return true;
jtulach@1399
   876
        return false;
jtulach@1399
   877
    }
jtulach@1399
   878
jtulach@1399
   879
    /**
jtulach@1399
   880
     * Returns the number of bits set to {@code true} in this {@code BitSet}.
jtulach@1399
   881
     *
jtulach@1399
   882
     * @return the number of bits set to {@code true} in this {@code BitSet}
jtulach@1399
   883
     * @since  1.4
jtulach@1399
   884
     */
jtulach@1399
   885
    public int cardinality() {
jtulach@1399
   886
        int sum = 0;
jtulach@1399
   887
        for (int i = 0; i < wordsInUse; i++)
jtulach@1399
   888
            sum += Long.bitCount(words[i]);
jtulach@1399
   889
        return sum;
jtulach@1399
   890
    }
jtulach@1399
   891
jtulach@1399
   892
    /**
jtulach@1399
   893
     * Performs a logical <b>AND</b> of this target bit set with the
jtulach@1399
   894
     * argument bit set. This bit set is modified so that each bit in it
jtulach@1399
   895
     * has the value {@code true} if and only if it both initially
jtulach@1399
   896
     * had the value {@code true} and the corresponding bit in the
jtulach@1399
   897
     * bit set argument also had the value {@code true}.
jtulach@1399
   898
     *
jtulach@1399
   899
     * @param set a bit set
jtulach@1399
   900
     */
jtulach@1399
   901
    public void and(BitSet set) {
jtulach@1399
   902
        if (this == set)
jtulach@1399
   903
            return;
jtulach@1399
   904
jtulach@1399
   905
        while (wordsInUse > set.wordsInUse)
jtulach@1399
   906
            words[--wordsInUse] = 0;
jtulach@1399
   907
jtulach@1399
   908
        // Perform logical AND on words in common
jtulach@1399
   909
        for (int i = 0; i < wordsInUse; i++)
jtulach@1399
   910
            words[i] &= set.words[i];
jtulach@1399
   911
jtulach@1399
   912
        recalculateWordsInUse();
jtulach@1399
   913
        checkInvariants();
jtulach@1399
   914
    }
jtulach@1399
   915
jtulach@1399
   916
    /**
jtulach@1399
   917
     * Performs a logical <b>OR</b> of this bit set with the bit set
jtulach@1399
   918
     * argument. This bit set is modified so that a bit in it has the
jtulach@1399
   919
     * value {@code true} if and only if it either already had the
jtulach@1399
   920
     * value {@code true} or the corresponding bit in the bit set
jtulach@1399
   921
     * argument has the value {@code true}.
jtulach@1399
   922
     *
jtulach@1399
   923
     * @param set a bit set
jtulach@1399
   924
     */
jtulach@1399
   925
    public void or(BitSet set) {
jtulach@1399
   926
        if (this == set)
jtulach@1399
   927
            return;
jtulach@1399
   928
jtulach@1399
   929
        int wordsInCommon = Math.min(wordsInUse, set.wordsInUse);
jtulach@1399
   930
jtulach@1399
   931
        if (wordsInUse < set.wordsInUse) {
jtulach@1399
   932
            ensureCapacity(set.wordsInUse);
jtulach@1399
   933
            wordsInUse = set.wordsInUse;
jtulach@1399
   934
        }
jtulach@1399
   935
jtulach@1399
   936
        // Perform logical OR on words in common
jtulach@1399
   937
        for (int i = 0; i < wordsInCommon; i++)
jtulach@1399
   938
            words[i] |= set.words[i];
jtulach@1399
   939
jtulach@1399
   940
        // Copy any remaining words
jtulach@1399
   941
        if (wordsInCommon < set.wordsInUse)
jtulach@1399
   942
            System.arraycopy(set.words, wordsInCommon,
jtulach@1399
   943
                             words, wordsInCommon,
jtulach@1399
   944
                             wordsInUse - wordsInCommon);
jtulach@1399
   945
jtulach@1399
   946
        // recalculateWordsInUse() is unnecessary
jtulach@1399
   947
        checkInvariants();
jtulach@1399
   948
    }
jtulach@1399
   949
jtulach@1399
   950
    /**
jtulach@1399
   951
     * Performs a logical <b>XOR</b> of this bit set with the bit set
jtulach@1399
   952
     * argument. This bit set is modified so that a bit in it has the
jtulach@1399
   953
     * value {@code true} if and only if one of the following
jtulach@1399
   954
     * statements holds:
jtulach@1399
   955
     * <ul>
jtulach@1399
   956
     * <li>The bit initially has the value {@code true}, and the
jtulach@1399
   957
     *     corresponding bit in the argument has the value {@code false}.
jtulach@1399
   958
     * <li>The bit initially has the value {@code false}, and the
jtulach@1399
   959
     *     corresponding bit in the argument has the value {@code true}.
jtulach@1399
   960
     * </ul>
jtulach@1399
   961
     *
jtulach@1399
   962
     * @param  set a bit set
jtulach@1399
   963
     */
jtulach@1399
   964
    public void xor(BitSet set) {
jtulach@1399
   965
        int wordsInCommon = Math.min(wordsInUse, set.wordsInUse);
jtulach@1399
   966
jtulach@1399
   967
        if (wordsInUse < set.wordsInUse) {
jtulach@1399
   968
            ensureCapacity(set.wordsInUse);
jtulach@1399
   969
            wordsInUse = set.wordsInUse;
jtulach@1399
   970
        }
jtulach@1399
   971
jtulach@1399
   972
        // Perform logical XOR on words in common
jtulach@1399
   973
        for (int i = 0; i < wordsInCommon; i++)
jtulach@1399
   974
            words[i] ^= set.words[i];
jtulach@1399
   975
jtulach@1399
   976
        // Copy any remaining words
jtulach@1399
   977
        if (wordsInCommon < set.wordsInUse)
jtulach@1399
   978
            System.arraycopy(set.words, wordsInCommon,
jtulach@1399
   979
                             words, wordsInCommon,
jtulach@1399
   980
                             set.wordsInUse - wordsInCommon);
jtulach@1399
   981
jtulach@1399
   982
        recalculateWordsInUse();
jtulach@1399
   983
        checkInvariants();
jtulach@1399
   984
    }
jtulach@1399
   985
jtulach@1399
   986
    /**
jtulach@1399
   987
     * Clears all of the bits in this {@code BitSet} whose corresponding
jtulach@1399
   988
     * bit is set in the specified {@code BitSet}.
jtulach@1399
   989
     *
jtulach@1399
   990
     * @param  set the {@code BitSet} with which to mask this
jtulach@1399
   991
     *         {@code BitSet}
jtulach@1399
   992
     * @since  1.2
jtulach@1399
   993
     */
jtulach@1399
   994
    public void andNot(BitSet set) {
jtulach@1399
   995
        // Perform logical (a & !b) on words in common
jtulach@1399
   996
        for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--)
jtulach@1399
   997
            words[i] &= ~set.words[i];
jtulach@1399
   998
jtulach@1399
   999
        recalculateWordsInUse();
jtulach@1399
  1000
        checkInvariants();
jtulach@1399
  1001
    }
jtulach@1399
  1002
jtulach@1399
  1003
    /**
jtulach@1399
  1004
     * Returns the hash code value for this bit set. The hash code depends
jtulach@1399
  1005
     * only on which bits are set within this {@code BitSet}.
jtulach@1399
  1006
     *
jtulach@1399
  1007
     * <p>The hash code is defined to be the result of the following
jtulach@1399
  1008
     * calculation:
jtulach@1399
  1009
     *  <pre> {@code
jtulach@1399
  1010
     * public int hashCode() {
jtulach@1399
  1011
     *     long h = 1234;
jtulach@1399
  1012
     *     long[] words = toLongArray();
jtulach@1399
  1013
     *     for (int i = words.length; --i >= 0; )
jtulach@1399
  1014
     *         h ^= words[i] * (i + 1);
jtulach@1399
  1015
     *     return (int)((h >> 32) ^ h);
jtulach@1399
  1016
     * }}</pre>
jtulach@1399
  1017
     * Note that the hash code changes if the set of bits is altered.
jtulach@1399
  1018
     *
jtulach@1399
  1019
     * @return the hash code value for this bit set
jtulach@1399
  1020
     */
jtulach@1399
  1021
    public int hashCode() {
jtulach@1399
  1022
        long h = 1234;
jtulach@1399
  1023
        for (int i = wordsInUse; --i >= 0; )
jtulach@1399
  1024
            h ^= words[i] * (i + 1);
jtulach@1399
  1025
jtulach@1399
  1026
        return (int)((h >> 32) ^ h);
jtulach@1399
  1027
    }
jtulach@1399
  1028
jtulach@1399
  1029
    /**
jtulach@1399
  1030
     * Returns the number of bits of space actually in use by this
jtulach@1399
  1031
     * {@code BitSet} to represent bit values.
jtulach@1399
  1032
     * The maximum element in the set is the size - 1st element.
jtulach@1399
  1033
     *
jtulach@1399
  1034
     * @return the number of bits currently in this bit set
jtulach@1399
  1035
     */
jtulach@1399
  1036
    public int size() {
jtulach@1399
  1037
        return words.length * BITS_PER_WORD;
jtulach@1399
  1038
    }
jtulach@1399
  1039
jtulach@1399
  1040
    /**
jtulach@1399
  1041
     * Compares this object against the specified object.
jtulach@1399
  1042
     * The result is {@code true} if and only if the argument is
jtulach@1399
  1043
     * not {@code null} and is a {@code Bitset} object that has
jtulach@1399
  1044
     * exactly the same set of bits set to {@code true} as this bit
jtulach@1399
  1045
     * set. That is, for every nonnegative {@code int} index {@code k},
jtulach@1399
  1046
     * <pre>((BitSet)obj).get(k) == this.get(k)</pre>
jtulach@1399
  1047
     * must be true. The current sizes of the two bit sets are not compared.
jtulach@1399
  1048
     *
jtulach@1399
  1049
     * @param  obj the object to compare with
jtulach@1399
  1050
     * @return {@code true} if the objects are the same;
jtulach@1399
  1051
     *         {@code false} otherwise
jtulach@1399
  1052
     * @see    #size()
jtulach@1399
  1053
     */
jtulach@1399
  1054
    public boolean equals(Object obj) {
jtulach@1399
  1055
        if (!(obj instanceof BitSet))
jtulach@1399
  1056
            return false;
jtulach@1399
  1057
        if (this == obj)
jtulach@1399
  1058
            return true;
jtulach@1399
  1059
jtulach@1399
  1060
        BitSet set = (BitSet) obj;
jtulach@1399
  1061
jtulach@1399
  1062
        checkInvariants();
jtulach@1399
  1063
        set.checkInvariants();
jtulach@1399
  1064
jtulach@1399
  1065
        if (wordsInUse != set.wordsInUse)
jtulach@1399
  1066
            return false;
jtulach@1399
  1067
jtulach@1399
  1068
        // Check words in use by both BitSets
jtulach@1399
  1069
        for (int i = 0; i < wordsInUse; i++)
jtulach@1399
  1070
            if (words[i] != set.words[i])
jtulach@1399
  1071
                return false;
jtulach@1399
  1072
jtulach@1399
  1073
        return true;
jtulach@1399
  1074
    }
jtulach@1399
  1075
jtulach@1399
  1076
    /**
jtulach@1399
  1077
     * Cloning this {@code BitSet} produces a new {@code BitSet}
jtulach@1399
  1078
     * that is equal to it.
jtulach@1399
  1079
     * The clone of the bit set is another bit set that has exactly the
jtulach@1399
  1080
     * same bits set to {@code true} as this bit set.
jtulach@1399
  1081
     *
jtulach@1399
  1082
     * @return a clone of this bit set
jtulach@1399
  1083
     * @see    #size()
jtulach@1399
  1084
     */
jtulach@1399
  1085
    public Object clone() {
jtulach@1399
  1086
        if (! sizeIsSticky)
jtulach@1399
  1087
            trimToSize();
jtulach@1399
  1088
jtulach@1399
  1089
        try {
jtulach@1399
  1090
            BitSet result = (BitSet) super.clone();
jtulach@1399
  1091
            result.words = words.clone();
jtulach@1399
  1092
            result.checkInvariants();
jtulach@1399
  1093
            return result;
jtulach@1399
  1094
        } catch (CloneNotSupportedException e) {
jtulach@1399
  1095
            throw new InternalError();
jtulach@1399
  1096
        }
jtulach@1399
  1097
    }
jtulach@1399
  1098
jtulach@1399
  1099
    /**
jtulach@1399
  1100
     * Attempts to reduce internal storage used for the bits in this bit set.
jtulach@1399
  1101
     * Calling this method may, but is not required to, affect the value
jtulach@1399
  1102
     * returned by a subsequent call to the {@link #size()} method.
jtulach@1399
  1103
     */
jtulach@1399
  1104
    private void trimToSize() {
jtulach@1399
  1105
        if (wordsInUse != words.length) {
jtulach@1399
  1106
            words = Arrays.copyOf(words, wordsInUse);
jtulach@1399
  1107
            checkInvariants();
jtulach@1399
  1108
        }
jtulach@1399
  1109
    }
jtulach@1399
  1110
jtulach@1399
  1111
    /**
jtulach@1399
  1112
     * Save the state of the {@code BitSet} instance to a stream (i.e.,
jtulach@1399
  1113
     * serialize it).
jtulach@1399
  1114
     */
jtulach@1399
  1115
    private void writeObject(ObjectOutputStream s)
jtulach@1399
  1116
        throws IOException {
jtulach@1399
  1117
jtulach@1399
  1118
        checkInvariants();
jtulach@1399
  1119
jtulach@1399
  1120
        if (! sizeIsSticky)
jtulach@1399
  1121
            trimToSize();
jtulach@1399
  1122
jtulach@1399
  1123
        ObjectOutputStream.PutField fields = s.putFields();
jtulach@1399
  1124
        fields.put("bits", words);
jtulach@1399
  1125
        s.writeFields();
jtulach@1399
  1126
    }
jtulach@1399
  1127
jtulach@1399
  1128
    /**
jtulach@1399
  1129
     * Reconstitute the {@code BitSet} instance from a stream (i.e.,
jtulach@1399
  1130
     * deserialize it).
jtulach@1399
  1131
     */
jtulach@1399
  1132
    private void readObject(ObjectInputStream s)
jtulach@1399
  1133
        throws IOException, ClassNotFoundException {
jtulach@1399
  1134
jtulach@1399
  1135
        ObjectInputStream.GetField fields = s.readFields();
jtulach@1399
  1136
        words = (long[]) fields.get("bits", null);
jtulach@1399
  1137
jtulach@1399
  1138
        // Assume maximum length then find real length
jtulach@1399
  1139
        // because recalculateWordsInUse assumes maintenance
jtulach@1399
  1140
        // or reduction in logical size
jtulach@1399
  1141
        wordsInUse = words.length;
jtulach@1399
  1142
        recalculateWordsInUse();
jtulach@1399
  1143
        sizeIsSticky = (words.length > 0 && words[words.length-1] == 0L); // heuristic
jtulach@1399
  1144
        checkInvariants();
jtulach@1399
  1145
    }
jtulach@1399
  1146
jtulach@1399
  1147
    /**
jtulach@1399
  1148
     * Returns a string representation of this bit set. For every index
jtulach@1399
  1149
     * for which this {@code BitSet} contains a bit in the set
jtulach@1399
  1150
     * state, the decimal representation of that index is included in
jtulach@1399
  1151
     * the result. Such indices are listed in order from lowest to
jtulach@1399
  1152
     * highest, separated by ",&nbsp;" (a comma and a space) and
jtulach@1399
  1153
     * surrounded by braces, resulting in the usual mathematical
jtulach@1399
  1154
     * notation for a set of integers.
jtulach@1399
  1155
     *
jtulach@1399
  1156
     * <p>Example:
jtulach@1399
  1157
     * <pre>
jtulach@1399
  1158
     * BitSet drPepper = new BitSet();</pre>
jtulach@1399
  1159
     * Now {@code drPepper.toString()} returns "{@code {}}".<p>
jtulach@1399
  1160
     * <pre>
jtulach@1399
  1161
     * drPepper.set(2);</pre>
jtulach@1399
  1162
     * Now {@code drPepper.toString()} returns "{@code {2}}".<p>
jtulach@1399
  1163
     * <pre>
jtulach@1399
  1164
     * drPepper.set(4);
jtulach@1399
  1165
     * drPepper.set(10);</pre>
jtulach@1399
  1166
     * Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}".
jtulach@1399
  1167
     *
jtulach@1399
  1168
     * @return a string representation of this bit set
jtulach@1399
  1169
     */
jtulach@1399
  1170
    public String toString() {
jtulach@1399
  1171
        checkInvariants();
jtulach@1399
  1172
jtulach@1399
  1173
        int numBits = (wordsInUse > 128) ?
jtulach@1399
  1174
            cardinality() : wordsInUse * BITS_PER_WORD;
jtulach@1399
  1175
        StringBuilder b = new StringBuilder(6*numBits + 2);
jtulach@1399
  1176
        b.append('{');
jtulach@1399
  1177
jtulach@1399
  1178
        int i = nextSetBit(0);
jtulach@1399
  1179
        if (i != -1) {
jtulach@1399
  1180
            b.append(i);
jtulach@1399
  1181
            for (i = nextSetBit(i+1); i >= 0; i = nextSetBit(i+1)) {
jtulach@1399
  1182
                int endOfRun = nextClearBit(i);
jtulach@1399
  1183
                do { b.append(", ").append(i); }
jtulach@1399
  1184
                while (++i < endOfRun);
jtulach@1399
  1185
            }
jtulach@1399
  1186
        }
jtulach@1399
  1187
jtulach@1399
  1188
        b.append('}');
jtulach@1399
  1189
        return b.toString();
jtulach@1399
  1190
    }
jtulach@1399
  1191
}