undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,43 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4201163
* @summary test the BitSet.and() method
*/
import java.util.BitSet;
public final class And {
public static void main(String[] args) throws Exception {
BitSet a = new BitSet();
BitSet b = new BitSet();
a.set(0);
a.set(70);
b.set(40);
a.and(b);
if (a.length() != 0)
throw new RuntimeException("Incorrect length after and().");
}
}

View file

@ -0,0 +1,986 @@
/*
* Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4098239 4107540 4080736 4261102 4274710 4305272
* 4979017 4979028 4979031 5030267 6222207 8040806
* @summary Test the operation of the methods of BitSet class
* @author Mike McCloskey, Martin Buchholz
* @run main/othervm BSMethods
* @key randomness
*/
import java.util.*;
/**
* This is a simple test class created to run tests on the BitSet class.
*
*/
public class BSMethods {
private static Random generator = new Random();
private static boolean failure = false;
private static void fail(String diagnostic) {
new Error(diagnostic).printStackTrace();
failure = true;
}
private static void check(boolean condition) {
check(condition, "something's fishy");
}
private static void check(boolean condition, String diagnostic) {
if (! condition)
fail(diagnostic);
}
private static void checkEmpty(BitSet s) {
check(s.isEmpty(), "isEmpty");
check(s.length() == 0, "length");
check(s.cardinality() == 0, "cardinality");
check(s.equals(new BitSet()) , "equals");
check(s.equals(new BitSet(0)) , "equals");
check(s.equals(new BitSet(127)), "equals");
check(s.equals(new BitSet(128)), "equals");
check(s.nextSetBit(0) == -1, "nextSetBit");
check(s.nextSetBit(127) == -1, "nextSetBit");
check(s.nextSetBit(128) == -1, "nextSetBit");
check(s.nextClearBit(0) == 0, "nextClearBit");
check(s.nextClearBit(127) == 127, "nextClearBit");
check(s.nextClearBit(128) == 128, "nextClearBit");
check(s.toString().equals("{}"), "toString");
check(! s.get(0), "get");
}
private static BitSet makeSet(int... elts) {
BitSet s = new BitSet();
for (int elt : elts)
s.set(elt);
return s;
}
private static void checkEquality(BitSet s, BitSet t) {
checkSanity(s, t);
check(s.equals(t), "equals");
check(s.toString().equals(t.toString()), "equal strings");
check(s.length() == t.length(), "equal lengths");
check(s.cardinality() == t.cardinality(), "equal cardinalities");
}
private static void checkSanity(BitSet... sets) {
for (BitSet s : sets) {
int len = s.length();
int cardinality1 = s.cardinality();
int cardinality2 = 0;
for (int i = s.nextSetBit(0); i >= 0; i = s.nextSetBit(i+1)) {
check(s.get(i));
cardinality2++;
}
check(s.nextSetBit(len) == -1, "last set bit");
check(s.nextClearBit(len) == len, "last set bit");
check(s.isEmpty() == (len == 0), "emptiness");
check(cardinality1 == cardinality2, "cardinalities");
check(len <= s.size(), "length <= size");
check(len >= 0, "length >= 0");
check(cardinality1 >= 0, "cardinality >= 0");
}
}
public static void main(String[] args) {
//testFlipTime();
// These are the single bit versions
testSetGetClearFlip();
// Test the ranged versions
testClear();
testFlip();
testSet();
testGet();
// BitSet interaction calls
testAndNot();
testAnd();
testOr();
testXor();
// Miscellaneous calls
testLength();
testEquals();
testNextSetBit();
testNextClearBit();
testIntersects();
testCardinality();
testEmpty();
testEmpty2();
testToString();
testLogicalIdentities();
if (failure)
throw new RuntimeException("One or more BitSet failures.");
}
private static void report(String testName, int failCount) {
System.err.println(testName+": " +
(failCount==0 ? "Passed":"Failed("+failCount+")"));
if (failCount > 0)
failure = true;
}
private static void testFlipTime() {
// Make a fairly random bitset
BitSet b1 = new BitSet();
b1.set(1000);
long startTime = System.currentTimeMillis();
for(int x=0; x<100000; x++) {
b1.flip(100, 900);
}
long endTime = System.currentTimeMillis();
long total = endTime - startTime;
System.out.println("Multiple word flip Time "+total);
startTime = System.currentTimeMillis();
for(int x=0; x<100000; x++) {
b1.flip(2, 44);
}
endTime = System.currentTimeMillis();
total = endTime - startTime;
System.out.println("Single word flip Time "+total);
}
private static void testNextSetBit() {
int failCount = 0;
for (int i=0; i<100; i++) {
int numberOfSetBits = generator.nextInt(100) + 1;
BitSet testSet = new BitSet();
int[] history = new int[numberOfSetBits];
// Set some random bits and remember them
int nextBitToSet = 0;
for (int x=0; x<numberOfSetBits; x++) {
nextBitToSet += generator.nextInt(30)+1;
history[x] = nextBitToSet;
testSet.set(nextBitToSet);
}
// Verify their retrieval using nextSetBit()
int historyIndex = 0;
for(int x=testSet.nextSetBit(0); x>=0; x=testSet.nextSetBit(x+1)) {
if (x != history[historyIndex++])
failCount++;
}
checkSanity(testSet);
}
report("NextSetBit ", failCount);
}
private static void testNextClearBit() {
int failCount = 0;
for (int i=0; i<1000; i++) {
BitSet b = new BitSet(256);
int[] history = new int[10];
// Set all the bits
for (int x=0; x<256; x++)
b.set(x);
// Clear some random bits and remember them
int nextBitToClear = 0;
for (int x=0; x<10; x++) {
nextBitToClear += generator.nextInt(24)+1;
history[x] = nextBitToClear;
b.clear(nextBitToClear);
}
// Verify their retrieval using nextClearBit()
int historyIndex = 0;
for(int x=b.nextClearBit(0); x<256; x=b.nextClearBit(x+1)) {
if (x != history[historyIndex++])
failCount++;
}
checkSanity(b);
}
// regression test for 4350178
BitSet bs = new BitSet();
if (bs.nextClearBit(0) != 0)
failCount++;
for (int i = 0; i < 64; i++) {
bs.set(i);
if (bs.nextClearBit(0) != i+1)
failCount++;
}
checkSanity(bs);
report("NextClearBit ", failCount);
}
private static void testSetGetClearFlip() {
int failCount = 0;
for (int i=0; i<100; i++) {
BitSet testSet = new BitSet();
HashSet<Integer> history = new HashSet<Integer>();
// Set a random number of bits in random places
// up to a random maximum
int nextBitToSet = 0;
int numberOfSetBits = generator.nextInt(100) + 1;
int highestPossibleSetBit = generator.nextInt(1000) + 1;
for (int x=0; x<numberOfSetBits; x++) {
nextBitToSet = generator.nextInt(highestPossibleSetBit);
history.add(new Integer(nextBitToSet));
testSet.set(nextBitToSet);
}
// Make sure each bit is set appropriately
for (int x=0; x<highestPossibleSetBit; x++) {
if (testSet.get(x) != history.contains(new Integer(x)))
failCount++;
}
// Clear the bits
Iterator<Integer> setBitIterator = history.iterator();
while (setBitIterator.hasNext()) {
Integer setBit = setBitIterator.next();
testSet.clear(setBit.intValue());
}
// Verify they were cleared
for (int x=0; x<highestPossibleSetBit; x++)
if (testSet.get(x))
failCount++;
if(testSet.length() != 0)
failCount++;
// Set them with set(int, boolean)
setBitIterator = history.iterator();
while (setBitIterator.hasNext()) {
Integer setBit = setBitIterator.next();
testSet.set(setBit.intValue(), true);
}
// Make sure each bit is set appropriately
for (int x=0; x<highestPossibleSetBit; x++) {
if (testSet.get(x) != history.contains(new Integer(x)))
failCount++;
}
// Clear them with set(int, boolean)
setBitIterator = history.iterator();
while (setBitIterator.hasNext()) {
Integer setBit = (Integer)setBitIterator.next();
testSet.set(setBit.intValue(), false);
}
// Verify they were cleared
for (int x=0; x<highestPossibleSetBit; x++)
if (testSet.get(x))
failCount++;
if(testSet.length() != 0)
failCount++;
// Flip them on
setBitIterator = history.iterator();
while (setBitIterator.hasNext()) {
Integer setBit = (Integer)setBitIterator.next();
testSet.flip(setBit.intValue());
}
// Verify they were flipped
for (int x=0; x<highestPossibleSetBit; x++) {
if (testSet.get(x) != history.contains(new Integer(x)))
failCount++;
}
// Flip them off
setBitIterator = history.iterator();
while (setBitIterator.hasNext()) {
Integer setBit = (Integer)setBitIterator.next();
testSet.flip(setBit.intValue());
}
// Verify they were flipped
for (int x=0; x<highestPossibleSetBit; x++)
if (testSet.get(x))
failCount++;
if(testSet.length() != 0)
failCount++;
checkSanity(testSet);
}
report("SetGetClearFlip ", failCount);
}
private static void testAndNot() {
int failCount = 0;
for (int i=0; i<100; i++) {
BitSet b1 = new BitSet(256);
BitSet b2 = new BitSet(256);
// Set some random bits in first set and remember them
int nextBitToSet = 0;
for (int x=0; x<10; x++)
b1.set(generator.nextInt(255));
// Set some random bits in second set and remember them
for (int x=10; x<20; x++)
b2.set(generator.nextInt(255));
// andNot the sets together
BitSet b3 = (BitSet)b1.clone();
b3.andNot(b2);
// Examine each bit of b3 for errors
for(int x=0; x<256; x++) {
boolean bit1 = b1.get(x);
boolean bit2 = b2.get(x);
boolean bit3 = b3.get(x);
if (!(bit3 == (bit1 & (!bit2))))
failCount++;
}
checkSanity(b1, b2, b3);
}
report("AndNot ", failCount);
}
private static void testAnd() {
int failCount = 0;
for (int i=0; i<100; i++) {
BitSet b1 = new BitSet(256);
BitSet b2 = new BitSet(256);
// Set some random bits in first set and remember them
int nextBitToSet = 0;
for (int x=0; x<10; x++)
b1.set(generator.nextInt(255));
// Set more random bits in second set and remember them
for (int x=10; x<20; x++)
b2.set(generator.nextInt(255));
// And the sets together
BitSet b3 = (BitSet)b1.clone();
b3.and(b2);
// Examine each bit of b3 for errors
for(int x=0; x<256; x++) {
boolean bit1 = b1.get(x);
boolean bit2 = b2.get(x);
boolean bit3 = b3.get(x);
if (!(bit3 == (bit1 & bit2)))
failCount++;
}
checkSanity(b1, b2, b3);
}
// `and' that happens to clear the last word
BitSet b4 = makeSet(2, 127);
b4.and(makeSet(2, 64));
checkSanity(b4);
if (!(b4.equals(makeSet(2))))
failCount++;
report("And ", failCount);
}
private static void testOr() {
int failCount = 0;
for (int i=0; i<100; i++) {
BitSet b1 = new BitSet(256);
BitSet b2 = new BitSet(256);
int[] history = new int[20];
// Set some random bits in first set and remember them
int nextBitToSet = 0;
for (int x=0; x<10; x++) {
nextBitToSet = generator.nextInt(255);
history[x] = nextBitToSet;
b1.set(nextBitToSet);
}
// Set more random bits in second set and remember them
for (int x=10; x<20; x++) {
nextBitToSet = generator.nextInt(255);
history[x] = nextBitToSet;
b2.set(nextBitToSet);
}
// Or the sets together
BitSet b3 = (BitSet)b1.clone();
b3.or(b2);
// Verify the set bits of b3 from the history
int historyIndex = 0;
for(int x=0; x<20; x++) {
if (!b3.get(history[x]))
failCount++;
}
// Examine each bit of b3 for errors
for(int x=0; x<256; x++) {
boolean bit1 = b1.get(x);
boolean bit2 = b2.get(x);
boolean bit3 = b3.get(x);
if (!(bit3 == (bit1 | bit2)))
failCount++;
}
checkSanity(b1, b2, b3);
}
report("Or ", failCount);
}
private static void testXor() {
int failCount = 0;
for (int i=0; i<100; i++) {
BitSet b1 = new BitSet(256);
BitSet b2 = new BitSet(256);
// Set some random bits in first set and remember them
int nextBitToSet = 0;
for (int x=0; x<10; x++)
b1.set(generator.nextInt(255));
// Set more random bits in second set and remember them
for (int x=10; x<20; x++)
b2.set(generator.nextInt(255));
// Xor the sets together
BitSet b3 = (BitSet)b1.clone();
b3.xor(b2);
// Examine each bit of b3 for errors
for(int x=0; x<256; x++) {
boolean bit1 = b1.get(x);
boolean bit2 = b2.get(x);
boolean bit3 = b3.get(x);
if (!(bit3 == (bit1 ^ bit2)))
failCount++;
}
checkSanity(b1, b2, b3);
b3.xor(b3); checkEmpty(b3);
}
// xor that happens to clear the last word
BitSet b4 = makeSet(2, 64, 127);
b4.xor(makeSet(64, 127));
checkSanity(b4);
if (!(b4.equals(makeSet(2))))
failCount++;
report("Xor ", failCount);
}
private static void testEquals() {
int failCount = 0;
for (int i=0; i<100; i++) {
// Create BitSets of different sizes
BitSet b1 = new BitSet(generator.nextInt(1000)+1);
BitSet b2 = new BitSet(generator.nextInt(1000)+1);
// Set some random bits
int nextBitToSet = 0;
for (int x=0; x<10; x++) {
nextBitToSet += generator.nextInt(50)+1;
b1.set(nextBitToSet);
b2.set(nextBitToSet);
}
// Verify their equality despite different storage sizes
if (!b1.equals(b2))
failCount++;
checkEquality(b1,b2);
}
report("Equals ", failCount);
}
private static void testLength() {
int failCount = 0;
// Test length after set
for (int i=0; i<100; i++) {
BitSet b1 = new BitSet(256);
int highestSetBit = 0;
for(int x=0; x<100; x++) {
int nextBitToSet = generator.nextInt(255);
if (nextBitToSet > highestSetBit)
highestSetBit = nextBitToSet;
b1.set(nextBitToSet);
if (b1.length() != highestSetBit + 1)
failCount++;
}
checkSanity(b1);
}
// Test length after flip
for (int i=0; i<100; i++) {
BitSet b1 = new BitSet(256);
for(int x=0; x<100; x++) {
// Flip a random range twice
int rangeStart = generator.nextInt(100);
int rangeEnd = rangeStart + generator.nextInt(100);
b1.flip(rangeStart);
b1.flip(rangeStart);
if (b1.length() != 0)
failCount++;
b1.flip(rangeStart, rangeEnd);
b1.flip(rangeStart, rangeEnd);
if (b1.length() != 0)
failCount++;
}
checkSanity(b1);
}
// Test length after or
for (int i=0; i<100; i++) {
BitSet b1 = new BitSet(256);
BitSet b2 = new BitSet(256);
int bit1 = generator.nextInt(100);
int bit2 = generator.nextInt(100);
int highestSetBit = (bit1 > bit2) ? bit1 : bit2;
b1.set(bit1);
b2.set(bit2);
b1.or(b2);
if (b1.length() != highestSetBit + 1)
failCount++;
checkSanity(b1, b2);
}
report("Length ", failCount);
}
private static void testClear() {
int failCount = 0;
for (int i=0; i<1000; i++) {
BitSet b1 = new BitSet();
// Make a fairly random bitset
int numberOfSetBits = generator.nextInt(100) + 1;
int highestPossibleSetBit = generator.nextInt(1000) + 1;
for (int x=0; x<numberOfSetBits; x++)
b1.set(generator.nextInt(highestPossibleSetBit));
BitSet b2 = (BitSet)b1.clone();
// Clear out a random range
int rangeStart = generator.nextInt(100);
int rangeEnd = rangeStart + generator.nextInt(100);
// Use the clear(int, int) call on b1
b1.clear(rangeStart, rangeEnd);
// Use a loop on b2
for (int x=rangeStart; x<rangeEnd; x++)
b2.clear(x);
// Verify their equality
if (!b1.equals(b2)) {
System.out.println("rangeStart = " + rangeStart);
System.out.println("rangeEnd = " + rangeEnd);
System.out.println("b1 = " + b1);
System.out.println("b2 = " + b2);
failCount++;
}
checkEquality(b1,b2);
}
report("Clear ", failCount);
}
private static void testSet() {
int failCount = 0;
// Test set(int, int)
for (int i=0; i<1000; i++) {
BitSet b1 = new BitSet();
// Make a fairly random bitset
int numberOfSetBits = generator.nextInt(100) + 1;
int highestPossibleSetBit = generator.nextInt(1000) + 1;
for (int x=0; x<numberOfSetBits; x++)
b1.set(generator.nextInt(highestPossibleSetBit));
BitSet b2 = (BitSet)b1.clone();
// Set a random range
int rangeStart = generator.nextInt(100);
int rangeEnd = rangeStart + generator.nextInt(100);
// Use the set(int, int) call on b1
b1.set(rangeStart, rangeEnd);
// Use a loop on b2
for (int x=rangeStart; x<rangeEnd; x++)
b2.set(x);
// Verify their equality
if (!b1.equals(b2)) {
System.out.println("Set 1");
System.out.println("rangeStart = " + rangeStart);
System.out.println("rangeEnd = " + rangeEnd);
System.out.println("b1 = " + b1);
System.out.println("b2 = " + b2);
failCount++;
}
checkEquality(b1,b2);
}
// Test set(int, int, boolean)
for (int i=0; i<100; i++) {
BitSet b1 = new BitSet();
// Make a fairly random bitset
int numberOfSetBits = generator.nextInt(100) + 1;
int highestPossibleSetBit = generator.nextInt(1000) + 1;
for (int x=0; x<numberOfSetBits; x++)
b1.set(generator.nextInt(highestPossibleSetBit));
BitSet b2 = (BitSet)b1.clone();
boolean setOrClear = generator.nextBoolean();
// Set a random range
int rangeStart = generator.nextInt(100);
int rangeEnd = rangeStart + generator.nextInt(100);
// Use the set(int, int, boolean) call on b1
b1.set(rangeStart, rangeEnd, setOrClear);
// Use a loop on b2
for (int x=rangeStart; x<rangeEnd; x++)
b2.set(x, setOrClear);
// Verify their equality
if (!b1.equals(b2)) {
System.out.println("Set 2");
System.out.println("b1 = " + b1);
System.out.println("b2 = " + b2);
failCount++;
}
checkEquality(b1,b2);
}
report("Set ", failCount);
}
private static void testFlip() {
int failCount = 0;
for (int i=0; i<1000; i++) {
BitSet b1 = new BitSet();
// Make a fairly random bitset
int numberOfSetBits = generator.nextInt(100) + 1;
int highestPossibleSetBit = generator.nextInt(1000) + 1;
for (int x=0; x<numberOfSetBits; x++)
b1.set(generator.nextInt(highestPossibleSetBit));
BitSet b2 = (BitSet)b1.clone();
// Flip a random range
int rangeStart = generator.nextInt(100);
int rangeEnd = rangeStart + generator.nextInt(100);
// Use the flip(int, int) call on b1
b1.flip(rangeStart, rangeEnd);
// Use a loop on b2
for (int x=rangeStart; x<rangeEnd; x++)
b2.flip(x);
// Verify their equality
if (!b1.equals(b2))
failCount++;
checkEquality(b1,b2);
}
report("Flip ", failCount);
}
private static void testGet() {
int failCount = 0;
for (int i=0; i<1000; i++) {
BitSet b1 = new BitSet();
// Make a fairly random bitset
int numberOfSetBits = generator.nextInt(100) + 1;
int highestPossibleSetBit = generator.nextInt(1000) + 1;
for (int x=0; x<numberOfSetBits; x++)
b1.set(generator.nextInt(highestPossibleSetBit));
// Get a new set from a random range
int rangeStart = generator.nextInt(100);
int rangeEnd = rangeStart + generator.nextInt(100);
BitSet b2 = b1.get(rangeStart, rangeEnd);
BitSet b3 = new BitSet();
for(int x=rangeStart; x<rangeEnd; x++)
b3.set(x-rangeStart, b1.get(x));
// Verify their equality
if (!b2.equals(b3)) {
System.out.println("start="+rangeStart);
System.out.println("end="+rangeEnd);
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
failCount++;
}
checkEquality(b2,b3);
}
report("Get ", failCount);
}
private static void testIntersects() {
int failCount = 0;
for (int i=0; i<100; i++) {
BitSet b1 = new BitSet(256);
BitSet b2 = new BitSet(256);
// Set some random bits in first set
int nextBitToSet = 0;
for (int x=0; x<30; x++) {
nextBitToSet = generator.nextInt(255);
b1.set(nextBitToSet);
}
// Set more random bits in second set
for (int x=0; x<30; x++) {
nextBitToSet = generator.nextInt(255);
b2.set(nextBitToSet);
}
// Make sure they intersect
nextBitToSet = generator.nextInt(255);
b1.set(nextBitToSet);
b2.set(nextBitToSet);
if (!b1.intersects(b2))
failCount++;
// Remove the common set bits
b1.andNot(b2);
// Make sure they don't intersect
if (b1.intersects(b2))
failCount++;
checkSanity(b1, b2);
}
report("Intersects ", failCount);
}
private static void testCardinality() {
int failCount = 0;
for (int i=0; i<100; i++) {
BitSet b1 = new BitSet(256);
// Set a random number of increasing bits
int nextBitToSet = 0;
int iterations = generator.nextInt(20)+1;
for (int x=0; x<iterations; x++) {
nextBitToSet += generator.nextInt(20)+1;
b1.set(nextBitToSet);
}
if (b1.cardinality() != iterations) {
System.out.println("Iterations is "+iterations);
System.out.println("Cardinality is "+b1.cardinality());
failCount++;
}
checkSanity(b1);
}
report("Cardinality ", failCount);
}
private static void testEmpty() {
int failCount = 0;
BitSet b1 = new BitSet();
if (!b1.isEmpty())
failCount++;
int nextBitToSet = 0;
int numberOfSetBits = generator.nextInt(100) + 1;
int highestPossibleSetBit = generator.nextInt(1000) + 1;
for (int x=0; x<numberOfSetBits; x++) {
nextBitToSet = generator.nextInt(highestPossibleSetBit);
b1.set(nextBitToSet);
if (b1.isEmpty())
failCount++;
b1.clear(nextBitToSet);
if (!b1.isEmpty())
failCount++;
}
report("Empty ", failCount);
}
private static void testEmpty2() {
{BitSet t = new BitSet(); t.set(100); t.clear(3,600); checkEmpty(t);}
checkEmpty(new BitSet(0));
checkEmpty(new BitSet(342));
BitSet s = new BitSet(0);
checkEmpty(s);
s.clear(92); checkEmpty(s);
s.clear(127,127); checkEmpty(s);
s.set(127,127); checkEmpty(s);
s.set(128,128); checkEmpty(s);
BitSet empty = new BitSet();
{BitSet t = new BitSet(); t.and (empty); checkEmpty(t);}
{BitSet t = new BitSet(); t.or (empty); checkEmpty(t);}
{BitSet t = new BitSet(); t.xor (empty); checkEmpty(t);}
{BitSet t = new BitSet(); t.andNot(empty); checkEmpty(t);}
{BitSet t = new BitSet(); t.and (t); checkEmpty(t);}
{BitSet t = new BitSet(); t.or (t); checkEmpty(t);}
{BitSet t = new BitSet(); t.xor (t); checkEmpty(t);}
{BitSet t = new BitSet(); t.andNot(t); checkEmpty(t);}
{BitSet t = new BitSet(); t.and(makeSet(1)); checkEmpty(t);}
{BitSet t = new BitSet(); t.and(makeSet(127)); checkEmpty(t);}
{BitSet t = new BitSet(); t.and(makeSet(128)); checkEmpty(t);}
{BitSet t = new BitSet(); t.flip(7);t.flip(7); checkEmpty(t);}
{BitSet t = new BitSet(); checkEmpty(t.get(200,300));}
{BitSet t = makeSet(2,5); check(t.get(2,6).equals(makeSet(0,3)),"");}
}
private static void testToString() {
check(new BitSet().toString().equals("{}"));
check(makeSet(2,3,42,43,234).toString().equals("{2, 3, 42, 43, 234}"));
final long MB = 1024*1024;
if (Runtime.getRuntime().maxMemory() >= 512*MB) {
// only run it if we have enough memory
try {
check(makeSet(Integer.MAX_VALUE-1).toString().equals(
"{" + (Integer.MAX_VALUE-1) + "}"));
check(makeSet(Integer.MAX_VALUE).toString().equals(
"{" + Integer.MAX_VALUE + "}"));
check(makeSet(0, 1, Integer.MAX_VALUE-1, Integer.MAX_VALUE).toString().equals(
"{0, 1, " + (Integer.MAX_VALUE-1) + ", " + Integer.MAX_VALUE + "}"));
} catch (IndexOutOfBoundsException exc) {
fail("toString() with indices near MAX_VALUE");
}
}
}
private static void testLogicalIdentities() {
int failCount = 0;
// Verify that (!b1)|(!b2) == !(b1&b2)
for (int i=0; i<50; i++) {
// Construct two fairly random bitsets
BitSet b1 = new BitSet();
BitSet b2 = new BitSet();
int numberOfSetBits = generator.nextInt(100) + 1;
int highestPossibleSetBit = generator.nextInt(1000) + 1;
for (int x=0; x<numberOfSetBits; x++) {
b1.set(generator.nextInt(highestPossibleSetBit));
b2.set(generator.nextInt(highestPossibleSetBit));
}
BitSet b3 = (BitSet) b1.clone();
BitSet b4 = (BitSet) b2.clone();
for (int x=0; x<highestPossibleSetBit; x++) {
b1.flip(x);
b2.flip(x);
}
b1.or(b2);
b3.and(b4);
for (int x=0; x<highestPossibleSetBit; x++)
b3.flip(x);
if (!b1.equals(b3))
failCount++;
checkSanity(b1, b2, b3, b4);
}
// Verify that (b1&(!b2)|(b2&(!b1) == b1^b2
for (int i=0; i<50; i++) {
// Construct two fairly random bitsets
BitSet b1 = new BitSet();
BitSet b2 = new BitSet();
int numberOfSetBits = generator.nextInt(100) + 1;
int highestPossibleSetBit = generator.nextInt(1000) + 1;
for (int x=0; x<numberOfSetBits; x++) {
b1.set(generator.nextInt(highestPossibleSetBit));
b2.set(generator.nextInt(highestPossibleSetBit));
}
BitSet b3 = (BitSet) b1.clone();
BitSet b4 = (BitSet) b2.clone();
BitSet b5 = (BitSet) b1.clone();
BitSet b6 = (BitSet) b2.clone();
for (int x=0; x<highestPossibleSetBit; x++)
b2.flip(x);
b1.and(b2);
for (int x=0; x<highestPossibleSetBit; x++)
b3.flip(x);
b3.and(b4);
b1.or(b3);
b5.xor(b6);
if (!b1.equals(b5))
failCount++;
checkSanity(b1, b2, b3, b4, b5, b6);
}
report("Logical Identities ", failCount);
}
}

View file

@ -0,0 +1,45 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8225397
* @summary Integer value miscalculation in toString() method of BitSet
* @run main/othervm -Xms250m HugeToString
*/
import java.util.BitSet;
public final class HugeToString {
public static void main(String[] args) {
BitSet bs = new BitSet(500_000_000);
bs.flip(0, 500_000_000);
try {
bs.toString();
} catch (OutOfMemoryError expected) {
} catch (Throwable t) {
throw new AssertionError("Unexpected exception", t);
}
}
}

View file

@ -0,0 +1,100 @@
/*
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @summary Basic tests of immutable BitSets
* @modules java.base/jdk.internal.util
* @run junit ImmutableBitSet
*/
import jdk.internal.util.ImmutableBitSetPredicate;
import org.junit.jupiter.api.Test;
import java.util.BitSet;
import java.util.Random;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.*;
public class ImmutableBitSet {
@Test
void empty() {
BitSet bs = new BitSet();
IntPredicate ibs = ImmutableBitSetPredicate.of(bs);
test(bs, ibs);
}
@Test
void negativeIndex() {
IntStream.of(0, 127, 128, 129, 143, 4711).forEach(k -> {
BitSet bs = new BitSet(k);
IntPredicate ibs = ImmutableBitSetPredicate.of(bs);
assertFalse(ibs.test(-1));
assertFalse(ibs.test(Integer.MIN_VALUE));
});
}
@Test
void basic() {
IntStream.of(0, 16, 127, 128, 129, 143, 4711).forEach(k -> basic(k));
}
void basic(int length) {
BitSet bs = createReference(length);
IntPredicate ibs = ImmutableBitSetPredicate.of(bs);
test(bs, ibs);
}
@Test
void clearedAtTheTail() {
IntStream.of(0, 16, 127, 128, 129, 143, 4711).forEach(k -> {
for (int i = Long.BYTES - 1; i < Long.BYTES + 2; i++) {
BitSet bs = createReference(k + i);
for (int j = bs.length() - 1; j > Long.BYTES - 1; j--) {
bs.clear(j);
}
IntPredicate ibs = ImmutableBitSetPredicate.of(bs);
test(bs, ibs);
}
});
}
static void test(BitSet expected, IntPredicate actual) {
for (int i = 0; i < expected.length() + 17; i++) {
assertEquals(expected.get(i), actual.test(i), "at index " + i);
}
}
private static BitSet createReference(int length) {
BitSet result = new BitSet(length);
Random random = new Random(length);
for (int i = 0; i < length; i++) {
result.set(i, random.nextBoolean());
}
return result;
}
}

View file

@ -0,0 +1,156 @@
/*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 5037068
* @summary Test import/export constructors and methods
* @author Martin Buchholz
* @key randomness
*/
import java.nio.*;
import java.util.*;
public class ImportExport {
final Random rnd = new Random();
void equal(byte[] x, byte[] y) {
check(Arrays.equals(x, y));
}
void equal(long[] x, long[] y) {
check(Arrays.equals(x, y));
}
void equal(byte[] bytes, BitSet s) {
equal(s, BitSet.valueOf(bytes));
equal(s, BitSet.valueOf(ByteBuffer.wrap(bytes)));
equal(s, BitSet.valueOf(
ByteBuffer.wrap(
Arrays.copyOf(bytes, bytes.length + 8 + rnd.nextInt(8)))
.order(ByteOrder.LITTLE_ENDIAN)
.asLongBuffer()));
}
void checkEmptyBitSet(BitSet s) {
equal(s.toByteArray(), new byte[0]);
equal(s.toLongArray(), new long[0]);
check(s.isEmpty());
}
void test(String[] args) throws Throwable {
for (int i = 0; i < 17; i++) {
byte[] bytes = new byte[i];
BitSet s = new BitSet();
equal(bytes, s);
equal(BitSet.valueOf(bytes).toByteArray(), new byte[0]);
if (i > 0) {
int k = rnd.nextInt(i);
for (int j = 0; j < 8; j++) {
bytes[k] |= 1 << j;
s.set(8*k+j);
equal(bytes, s);
byte[] expected = new byte[k+1]; expected[k] = bytes[k];
equal(BitSet.valueOf(bytes).toByteArray(), expected);
ByteBuffer bb = ByteBuffer.wrap(bytes);
bb.position(k);
equal(BitSet.valueOf(bb).toByteArray(),
new byte[]{bytes[k]});
}
}
}
for (int i = 0; i < 100; i++) {
byte[] bytes = new byte[rnd.nextInt(17)];
for (int j = 0; j < bytes.length; j++)
bytes[j] = (byte) rnd.nextInt(0x100);
BitSet s = BitSet.valueOf(bytes);
byte[] expected = s.toByteArray();
equal(expected.length, (s.length()+7)/8);
if (bytes.length == 0)
continue;
if (expected.length > 0)
check(expected[expected.length-1] != 0);
if (bytes[bytes.length-1] != 0)
equal(bytes, expected);
int n = rnd.nextInt(8 * bytes.length);
equal(s.get(n), ((bytes[n/8] & (1<<(n%8))) != 0));
}
for (int i = 0; i < 3; i++) {
checkEmptyBitSet(BitSet.valueOf(new byte[i]));
checkEmptyBitSet(BitSet.valueOf(ByteBuffer.wrap(new byte[i])));
checkEmptyBitSet(BitSet.valueOf(new byte[i*64]));
checkEmptyBitSet(BitSet.valueOf(ByteBuffer.wrap(new byte[i*64])));
checkEmptyBitSet(BitSet.valueOf(new long[i]));
checkEmptyBitSet(BitSet.valueOf(LongBuffer.wrap(new long[i])));
}
{
long[] longs = new long[rnd.nextInt(10)];
for (int i = 0; i < longs.length; i++)
longs[i] = rnd.nextLong();
LongBuffer b1 = LongBuffer.wrap(longs);
LongBuffer b2 = LongBuffer.allocate(longs.length + 10);
for (int i = 0; i < b2.limit(); i++)
b2.put(i, rnd.nextLong());
int beg = rnd.nextInt(10);
b2.position(beg);
b2.put(longs);
b2.limit(b2.position());
b2.position(beg);
BitSet s1 = BitSet.valueOf(longs);
BitSet s2 = BitSet.valueOf(b1);
BitSet s3 = BitSet.valueOf(b2);
equal(s1, s2);
equal(s1, s3);
if (longs.length > 0 && longs[longs.length -1] != 0) {
equal(longs, s1.toLongArray());
equal(longs, s2.toLongArray());
equal(longs, s3.toLongArray());
}
for (int i = 0; i < 64 * longs.length; i++) {
equal(s1.get(i), ((longs [i/64] & (1L<<(i%64))) != 0));
equal(s2.get(i), ((b1.get(i/64) & (1L<<(i%64))) != 0));
equal(s3.get(i), ((b2.get(b2.position()+i/64) & (1L<<(i%64))) != 0));
}
}
}
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
new ImportExport().instanceMain(args);}
void instanceMain(String[] args) throws Throwable {
try {test(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
}

View file

@ -0,0 +1,56 @@
/*
* Copyright (c) 1997, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4091185
* @summary Repeatedly OR BitSets; No OutOfMemoryException should result
*/
import java.util.*;
/**
* This is a simple test class that repeatedly ORs two
* BitSets of unequal size together. Previously this
* caused an exponential growth in the memory underlying
* the BitSets quickly using all available memory
*/
public class MemoryLeak {
public static void main(String[] args) {
//create 2 test bitsets
BitSet setOne = new BitSet();
BitSet setTwo = new BitSet();
setOne.set(64);
setTwo.set(129);
//test for bug #4091185
//exponential set growth causing memory depletion
for (int i = 0; i < 50; i++) {
setOne.or(setTwo);
setTwo.or(setOne);
}
}
}

View file

@ -0,0 +1,158 @@
/*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6410729 6586631
* @summary Test previousClearBit, previousSetBit
* @key randomness
*/
import java.util.*;
public class PreviousBits {
void testHashCode(final BitSet s) {
long h = 1234;
long[] words = s.toLongArray();
for (int i = words.length; --i >= 0; )
h ^= words[i] * (i + 1);
equal((int)((h >> 32) ^ h), s.hashCode());
}
void testOutOfBounds(final BitSet s) {
THROWS(IndexOutOfBoundsException.class,
new F(){void f(){ s.previousSetBit(-2);}},
new F(){void f(){ s.previousClearBit(-2);}},
new F(){void f(){ s.previousSetBit(Integer.MIN_VALUE);}},
new F(){void f(){ s.previousClearBit(Integer.MIN_VALUE);}},
new F(){void f(){ s.nextSetBit(-1);}},
new F(){void f(){ s.nextClearBit(-1);}},
new F(){void f(){ s.nextSetBit(Integer.MIN_VALUE);}},
new F(){void f(){ s.nextClearBit(Integer.MIN_VALUE);}});
}
void test(String[] args) throws Throwable {
final BitSet s = new BitSet();
// Test empty bitset
testOutOfBounds(s);
testHashCode(s);
for (int i = -1; i < 93;) {
equal(-1, s.previousSetBit(i));
equal( i, s.previousClearBit(i));
i++;
equal(-1, s.nextSetBit(i));
equal( i, s.nextClearBit(i));
}
// Test "singleton" bitsets
for (int j = 0; j < 161; j++) {
s.clear();
s.set(j);
testOutOfBounds(s);
testHashCode(s);
for (int i = -1; i < j; i++) {
equal(-1, s.previousSetBit(i));
equal( i, s.previousClearBit(i));
if (i >= 0) {
equal(j, s.nextSetBit(i));
equal(i, s.nextClearBit(i));
}
}
equal(j, s.previousSetBit(j));
equal(j-1, s.previousClearBit(j));
equal(j, s.nextSetBit(j));
equal(j+1, s.nextClearBit(j));
for (int i = j+1; i < j+100; i++) {
equal(j, s.previousSetBit(i));
equal(i, s.previousClearBit(i));
equal(-1, s.nextSetBit(i));
equal(i, s.nextClearBit(i));
}
}
// set even bits
s.clear();
for (int i = 0; i <= 128; i+=2)
s.set(i);
testHashCode(s);
for (int i = 1; i <= 128; i++) {
equal(s.previousSetBit(i),
((i & 1) == 0) ? i : i - 1);
equal(s.previousClearBit(i),
((i & 1) == 0) ? i - 1 : i);
}
// set odd bits as well
for (int i = 1; i <= 128; i+=2)
s.set(i);
testHashCode(s);
for (int i = 1; i <= 128; i++) {
equal(s.previousSetBit(i), i);
equal(s.previousClearBit(i), -1);
}
// Test loops documented in javadoc
Random rnd = new Random();
s.clear();
for (int i = 0; i < 10; i++)
s.set(rnd.nextInt(1066));
List<Integer> down = new ArrayList<Integer>();
for (int i = s.length(); (i = s.previousSetBit(i-1)) >= 0; )
down.add(i);
List<Integer> up = new ArrayList<Integer>();
for (int i = s.nextSetBit(0); i >= 0; i = s.nextSetBit(i+1))
up.add(i);
Collections.reverse(up);
equal(up, down);
}
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
new PreviousBits().instanceMain(args);}
void instanceMain(String[] args) throws Throwable {
try {test(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
abstract class F {abstract void f() throws Throwable;}
void THROWS(Class<? extends Throwable> k, F... fs) {
for (F f : fs)
try {f.f(); fail("Expected " + k.getName() + " not thrown");}
catch (Throwable t) {
if (k.isAssignableFrom(t.getClass())) pass();
else unexpected(t);}}
}

View file

@ -0,0 +1,103 @@
/*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6404711
* @summary Check capacity management
* @author Martin Buchholz
*/
import java.io.*;
import java.util.*;
public class StickySize {
static void equalClones(BitSet s, int expectedSize) {
equal(expectedSize, clone(s).size());
equal(expectedSize, serialClone(s).size());
equal(expectedSize, s.size());
equal(clone(s), serialClone(s));
}
private static void realMain(String[] args) {
BitSet s;
s = new BitSet(); // non-sticky
equal(s.size(), 64);
equalClones(s, 0);
s.set(3*64);
s.set(7*64);
equal(s.size(), 8*64);
equalClones(s, 8*64);
s.clear(7*64);
equal(s.size(), 8*64);
equalClones(s, 4*64);
s = new BitSet(8*64); // sticky
equalClones(s, 8*64);
s.set(3*64);
s.set(7*64);
equalClones(s, 8*64);
s.clear(7*64);
equalClones(s, 8*64);
equalClones(clone(s), 8*64);
equalClones(serialClone(s), 8*64);
s.set(17*64); // Expand beyond sticky size
equalClones(s, 18*64);
s.clear(17*64);
equalClones(s, 4*64);
}
static BitSet clone(BitSet s) {
return (BitSet) s.clone();
}
//--------------------- Infrastructure ---------------------------
static volatile int passed = 0, failed = 0;
static void pass() {passed++;}
static void fail() {failed++; Thread.dumpStack();}
static void fail(String msg) {System.out.println(msg); fail();}
static void unexpected(Throwable t) {failed++; t.printStackTrace();}
static void check(boolean cond) {if (cond) pass(); else fail();}
static void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
static byte[] serializedForm(Object obj) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new ObjectOutputStream(baos).writeObject(obj);
return baos.toByteArray();
} catch (IOException e) { throw new RuntimeException(e); }}
static Object readObject(byte[] bytes)
throws IOException, ClassNotFoundException {
InputStream is = new ByteArrayInputStream(bytes);
return new ObjectInputStream(is).readObject();}
@SuppressWarnings("unchecked")
static <T> T serialClone(T obj) {
try { return (T) readObject(serializedForm(obj)); }
catch (Exception e) { throw new RuntimeException(e); }}
}

View file

@ -0,0 +1,241 @@
/*
* Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.List;
import java.util.PrimitiveIterator;
import java.util.Random;
import java.util.Spliterator;
import java.util.SpliteratorOfIntDataBuilder;
import java.util.SpliteratorTestHelper;
import java.util.function.IntConsumer;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.util.stream.Collectors.toList;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;
/**
* @test
* @summary test BitSet stream
* @bug 8012645 8076442
* @requires os.maxMemory >= 2g
* @library /lib/testlibrary/bootlib
* @build java.base/java.util.SpliteratorTestHelper
* java.base/java.util.SpliteratorOfIntDataBuilder
* @run testng/othervm -Xms512m -Xmx1024m BitSetStreamTest
*/
public class BitSetStreamTest extends SpliteratorTestHelper {
static class Fibs implements IntSupplier {
private int n1 = 0;
private int n2 = 1;
static int fibs(int n) {
Fibs f = new Fibs();
while (n-- > 0) f.getAsInt();
return f.getAsInt();
}
public int getAsInt() { int s = n1; n1 = n2; n2 = s + n1; return s; }
}
@Test
public void testFibs() {
Fibs f = new Fibs();
assertEquals(0, f.getAsInt());
assertEquals(1, f.getAsInt());
assertEquals(1, f.getAsInt());
assertEquals(2, f.getAsInt());
assertEquals(3, f.getAsInt());
assertEquals(5, f.getAsInt());
assertEquals(8, f.getAsInt());
assertEquals(13, f.getAsInt());
assertEquals(987, Fibs.fibs(16));
}
@DataProvider(name = "cases")
public static Object[][] produceCases() {
return new Object[][] {
{ "none", IntStream.empty() },
{ "index 0", IntStream.of(0) },
{ "index 255", IntStream.of(255) },
{ "index 0 and 255", IntStream.of(0, 255) },
{ "index Integer.MAX_VALUE", IntStream.of(Integer.MAX_VALUE) },
{ "index Integer.MAX_VALUE - 1", IntStream.of(Integer.MAX_VALUE - 1) },
{ "index 0 and Integer.MAX_VALUE", IntStream.of(0, Integer.MAX_VALUE) },
{ "every bit", IntStream.range(0, 255) },
{ "step 2", IntStream.range(0, 255).map(f -> f * 2) },
{ "step 3", IntStream.range(0, 255).map(f -> f * 3) },
{ "step 5", IntStream.range(0, 255).map(f -> f * 5) },
{ "step 7", IntStream.range(0, 255).map(f -> f * 7) },
{ "1, 10, 100, 1000", IntStream.of(1, 10, 100, 1000) },
{ "25 fibs", IntStream.generate(new Fibs()).limit(25) }
};
}
@Test(dataProvider = "cases")
public void testBitsetStream(String name, IntStream data) {
BitSet bs = data.collect(BitSet::new, BitSet::set, BitSet::or);
assertEquals(bs.cardinality(), bs.stream().count());
int[] indexHolder = new int[] { -1 };
bs.stream().forEach(i -> {
int ei = indexHolder[0];
indexHolder[0] = bs.nextSetBit(ei + 1);
assertEquals(i, indexHolder[0]);
});
PrimitiveIterator.OfInt it = bs.stream().iterator();
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
assertTrue(it.hasNext());
assertEquals(it.nextInt(), i);
if (i == Integer.MAX_VALUE)
break; // or (i + 1) would overflow
}
assertFalse(it.hasNext());
}
static Object[][] spliteratorOfIntDataProvider;
@DataProvider(name = "BitSet.stream.spliterator")
public static Object[][] spliteratorOfIntDataProvider() {
if (spliteratorOfIntDataProvider != null) {
return spliteratorOfIntDataProvider;
}
List<Object[]> data = new ArrayList<>();
Object[][] bitStreamTestcases = new Object[][] {
{ "none", IntStream.empty().toArray() },
{ "index 0", IntStream.of(0).toArray() },
{ "index 255", IntStream.of(255).toArray() },
{ "index 0 and 255", IntStream.of(0, 255).toArray() },
{ "index Integer.MAX_VALUE", IntStream.of(Integer.MAX_VALUE).toArray() },
{ "index Integer.MAX_VALUE - 1", IntStream.of(Integer.MAX_VALUE - 1).toArray() },
{ "index 0 and Integer.MAX_VALUE", IntStream.of(0, Integer.MAX_VALUE).toArray() },
{ "every bit", IntStream.range(0, 255).toArray() },
{ "step 2", IntStream.range(0, 255).map(f -> f * 2).toArray() },
{ "step 3", IntStream.range(0, 255).map(f -> f * 3).toArray() },
{ "step 5", IntStream.range(0, 255).map(f -> f * 5).toArray() },
{ "step 7", IntStream.range(0, 255).map(f -> f * 7).toArray() },
{ "1, 10, 100, 1000", IntStream.of(1, 10, 100, 1000).toArray() },
};
for (Object[] tc : bitStreamTestcases) {
String description = (String)tc[0];
int[] exp = (int[])tc[1];
SpliteratorOfIntDataBuilder db = new SpliteratorOfIntDataBuilder(
data, IntStream.of(exp).boxed().collect(toList()));
db.add("BitSet.stream.spliterator() {" + description + "}", () ->
IntStream.of(exp).collect(BitSet::new, BitSet::set, BitSet::or).
stream().spliterator()
);
}
return spliteratorOfIntDataProvider = data.toArray(new Object[0][]);
}
@Test(dataProvider = "BitSet.stream.spliterator")
public void testIntNullPointerException(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
assertThrows(NullPointerException.class, () -> s.get().forEachRemaining((IntConsumer) null));
assertThrows(NullPointerException.class, () -> s.get().tryAdvance((IntConsumer) null));
}
@Test(dataProvider = "BitSet.stream.spliterator")
public void testIntForEach(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testForEach(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "BitSet.stream.spliterator")
public void testIntTryAdvance(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testTryAdvance(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "BitSet.stream.spliterator")
public void testIntMixedTryAdvanceForEach(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testMixedTryAdvanceForEach(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "BitSet.stream.spliterator")
public void testIntMixedTraverseAndSplit(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testMixedTraverseAndSplit(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "BitSet.stream.spliterator")
public void testIntSplitAfterFullTraversal(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitAfterFullTraversal(s, intBoxingConsumer());
}
@Test(dataProvider = "BitSet.stream.spliterator")
public void testIntSplitOnce(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitOnce(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "BitSet.stream.spliterator")
public void testIntSplitSixDeep(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitSixDeep(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "BitSet.stream.spliterator")
public void testIntSplitUntilNull(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitUntilNull(exp, s, intBoxingConsumer());
}
@Test
public void testRandomStream() {
final int size = 1024 * 1024;
final int[] seeds = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
final byte[] bytes = new byte[size];
for (int seed : seeds) {
final Random random = new Random(seed);
random.nextBytes(bytes);
BitSet bitSet = BitSet.valueOf(bytes);
testBitSetContents(bitSet, bitSet.stream().toArray());
testBitSetContents(bitSet, bitSet.stream().parallel().toArray());
}
}
void testBitSetContents(BitSet bitSet, int[] array) {
int cardinality = bitSet.cardinality();
assertEquals(array.length, cardinality);
int nextSetBit = -1;
for (int i = 0; i < cardinality; i++) {
nextSetBit = bitSet.nextSetBit(nextSetBit + 1);
assertEquals(array[i], nextSetBit);
}
}
}