提交 49886064 编写于 作者: B briangoetz
上级 412ce557
......@@ -517,6 +517,7 @@ jdk_other: $(call TestDirs, \
javax/xml/soap \
javax/xml/ws com/sun/internal/ws com/sun/org/glassfish \
jdk/asm \
jdk/lambda \
com/sun/org/apache/xerces \
com/sun/corba \
com/sun/tracing \
......
/*
* Copyright (c) 2012, 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.concurrent.atomic.AtomicReference;
import java.util.function.UnaryOperator;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
/*
* @test
* @summary Test Map default methods
* @run testng AtomicReferenceTest
* @author Jim Gish <jim.gish@oracle.com>
*/
public class AtomicReferenceTest {
/**
* Test of updateAndGet method, of class AtomicReference.
*/
@Test
public void testUpdateAndGet() {
AtomicReference<Integer> instance = new AtomicReference<>(3);
assertEquals((int) instance.get(), 3);
assertEquals((int) instance.updateAndGet(x -> x + 2), 5);
assertEquals((int) instance.get(), 5);
}
/**
* Test of getAndUpdate method, of class AtomicReference.
*/
@Test
public void testGetAndUpdate() {
AtomicReference<Integer> instance = new AtomicReference<>(3);
assertEquals((int) instance.get(), 3);
assertEquals((int) instance.getAndUpdate(x -> x + 3), 3);
assertEquals((int) instance.get(), 6);
}
}
# This file identifies root(s) of the test-ng hierarchy.
bootclasspath.dirs = .
/*
* Copyright (c) 2012, 2013, 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.
*/
package java.util.stream;
import org.testng.Assert;
import java.util.Spliterator;
import java.util.function.IntFunction;
/** Test helper class for java.util.stream test framework */
public final class CollectorOps {
private CollectorOps() { }
public static <E_IN> StatefulTestOp<E_IN> collector() {
return new StatefulCollector<>(0, StreamShape.REFERENCE);
}
/* Utility classes for collecting output of intermediate pipeline stages */
public static class StatefulCollector<E_IN> implements StatefulTestOp<E_IN> {
private final int opFlags;
private final StreamShape inputShape;
public StatefulCollector(int opFlags, StreamShape inputShape) {
this.opFlags = opFlags;
this.inputShape = inputShape;
}
@Override
public StreamShape inputShape() {
return inputShape;
}
@Override
public StreamShape outputShape() {
return inputShape;
}
@Override
public int opGetFlags() {
return opFlags;
}
@Override
public Sink<E_IN> opWrapSink(int flags, boolean parallel, Sink<E_IN> sink) {
return sink;
}
@Override
public <P_IN> Node<E_IN> opEvaluateParallel(PipelineHelper<E_IN> helper,
Spliterator<P_IN> spliterator,
IntFunction<E_IN[]> generator) {
return helper.evaluate(spliterator, false, generator);
}
}
public static class TestParallelSizedOp<T> extends StatefulCollector<T> {
public TestParallelSizedOp() {
this(StreamShape.REFERENCE);
}
protected TestParallelSizedOp(StreamShape shape) {
super(0, shape);
}
@Override
public <P_IN> Node<T> opEvaluateParallel(PipelineHelper<T> helper,
Spliterator<P_IN> spliterator,
IntFunction<T[]> generator) {
int flags = helper.getStreamAndOpFlags();
Assert.assertTrue(StreamOpFlag.SIZED.isKnown(flags));
return super.opEvaluateParallel(helper, spliterator, generator);
}
public static class OfInt extends TestParallelSizedOp<Integer> {
public OfInt() {
super(StreamShape.INT_VALUE);
}
}
public static class OfLong extends TestParallelSizedOp<Long> {
public OfLong() {
super(StreamShape.LONG_VALUE);
}
}
public static class OfDouble extends TestParallelSizedOp<Double> {
public OfDouble() {
super(StreamShape.DOUBLE_VALUE);
}
}
}
}
/*
* Copyright (c) 2013, 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.
*/
package java.util.stream;
import org.testng.annotations.DataProvider;
import java.util.*;
import java.util.Spliterators;
import java.util.function.Supplier;
/** TestNG DataProvider for double-valued streams */
public class DoubleStreamTestDataProvider {
private static final double[] to0 = new double[0];
private static final double[] to1 = new double[1];
private static final double[] to10 = new double[10];
private static final double[] to100 = new double[100];
private static final double[] to1000 = new double[1000];
private static final double[] reversed = new double[100];
private static final double[] ones = new double[100];
private static final double[] twice = new double[200];
private static final double[] pseudoRandom;
private static final Object[][] testData;
private static final Object[][] spliteratorTestData;
static {
double[][] arrays = {to0, to1, to10, to100, to1000};
for (double[] arr : arrays) {
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
}
for (int i = 0; i < reversed.length; i++) {
reversed[i] = reversed.length - i;
}
for (int i = 0; i < ones.length; i++) {
ones[i] = 1;
}
System.arraycopy(to100, 0, twice, 0, to100.length);
System.arraycopy(to100, 0, twice, to100.length, to100.length);
pseudoRandom = new double[LambdaTestHelpers.LONG_STRING.length()];
for (int i = 0; i < LambdaTestHelpers.LONG_STRING.length(); i++) {
pseudoRandom[i] = (double) LambdaTestHelpers.LONG_STRING.charAt(i);
}
}
static final Object[][] arrays = {
{"empty", to0},
{"0..1", to1},
{"0..10", to10},
{"0..100", to100},
{"0..1000", to1000},
{"100x[1]", ones},
{"2x[0..100]", twice},
{"reverse 0..100", reversed},
{"pseudorandom", pseudoRandom}
};
static {
{
List<Object[]> list = new ArrayList<>();
for (Object[] data : arrays) {
final Object name = data[0];
final double[] doubles = (double[]) data[1];
list.add(new Object[]{"array:" + name,
TestData.Factory.ofArray("array:" + name, doubles)});
SpinedBuffer.OfDouble isl = new SpinedBuffer.OfDouble();
for (double i : doubles) {
isl.accept(i);
}
list.add(new Object[]{"SpinedList:" + name,
TestData.Factory.ofSpinedBuffer("SpinedList:" + name, isl)});
list.add(streamDataDescr("Primitives.range(0,l): " + doubles.length,
() -> DoubleStream.range(0, doubles.length)));
list.add(streamDataDescr("Primitives.range(0,l,2): " + doubles.length,
() -> DoubleStream.range(0, doubles.length, 2)));
list.add(streamDataDescr("Primitives.range(0,l,3): " + doubles.length,
() -> DoubleStream.range(0, doubles.length, 3)));
list.add(streamDataDescr("Primitives.range(0,l,7): " + doubles.length,
() -> DoubleStream.range(0, doubles.length, 7)));
}
testData = list.toArray(new Object[0][]);
}
{
List<Object[]> spliterators = new ArrayList<>();
for (Object[] data : arrays) {
final Object name = data[0];
final double[] doubles = (double[]) data[1];
SpinedBuffer.OfDouble isl = new SpinedBuffer.OfDouble();
for (double i : doubles) {
isl.accept(i);
}
spliterators.add(splitDescr("Arrays.s(array):" + name,
() -> Arrays.spliterator(doubles)));
spliterators.add(splitDescr("Arrays.s(array,o,l):" + name,
() -> Arrays.spliterator(doubles, 0, doubles.length / 2)));
spliterators.add(splitDescr("SpinedBuffer.s():" + name,
() -> isl.spliterator()));
spliterators.add(splitDescr("Primitives.s(SpinedBuffer.iterator(), size):" + name,
() -> Spliterators.spliterator(isl.iterator(), doubles.length, 0)));
spliterators.add(splitDescr("Primitives.s(SpinedBuffer.iterator()):" + name,
() -> Spliterators.spliteratorUnknownSize(isl.iterator(), 0)));
spliterators.add(splitDescr("Primitives.range(0,l):" + name,
() -> DoubleStream.range(0, doubles.length).spliterator()));
spliterators.add(splitDescr("Primitives.range(0,l,2):" + name,
() -> DoubleStream.range(0, doubles.length, 2).spliterator()));
spliterators.add(splitDescr("Primitives.range(0,l,3):" + name,
() -> DoubleStream.range(0, doubles.length, 3).spliterator()));
spliterators.add(splitDescr("Primitives.range(0,l,7):" + name,
() -> DoubleStream.range(0, doubles.length, 7).spliterator()));
// Need more!
}
spliteratorTestData = spliterators.toArray(new Object[0][]);
}
}
static <T> Object[] streamDataDescr(String description, Supplier<DoubleStream> s) {
return new Object[] { description, TestData.Factory.ofDoubleSupplier(description, s) };
}
static <T> Object[] splitDescr(String description, Supplier<Spliterator.OfDouble> s) {
return new Object[] { description, s };
}
// Return an array of ( String name, DoubleStreamTestData )
@DataProvider(name = "DoubleStreamTestData")
public static Object[][] makeDoubleStreamTestData() {
return testData;
}
// returns an array of (String name, Supplier<PrimitiveSpliterator<Double>>)
@DataProvider(name = "DoubleSpliterator")
public static Object[][] spliteratorProvider() {
return spliteratorTestData;
}
}
/*
* Copyright (c) 2013, 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.
*/
package java.util.stream;
import java.util.PrimitiveIterator;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.Function;
/**
* Test scenarios for double streams.
*
* Each scenario is provided with a data source, a function that maps a fresh
* stream (as provided by the data source) to a new stream, and a sink to
* receive results. Each scenario describes a different way of computing the
* stream contents. The test driver will ensure that all scenarios produce
* the same output (modulo allowable differences in ordering).
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public enum DoubleStreamTestScenario implements OpTestCase.BaseStreamTestScenario {
STREAM_FOR_EACH(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
DoubleStream s = m.apply(data.stream());
if (s.isParallel()) {
s = s.sequential();
}
s.forEach(b);
}
},
STREAM_TO_ARRAY(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
for (double t : m.apply(data.stream()).toArray()) {
b.accept(t);
}
}
},
STREAM_ITERATOR(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
for (PrimitiveIterator.OfDouble seqIter = m.apply(data.stream()).iterator(); seqIter.hasNext(); )
b.accept(seqIter.nextDouble());
}
},
// Wrap as stream, and spliterate then iterate in pull mode
STREAM_SPLITERATOR(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
for (Spliterator.OfDouble spl = m.apply(data.stream()).spliterator(); spl.tryAdvance(b); ) {
}
}
},
// Wrap as stream, spliterate, then split a few times mixing advances with forEach
STREAM_SPLITERATOR_WITH_MIXED_TRAVERSE_AND_SPLIT(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
SpliteratorTestHelper.mixedTraverseAndSplit(b, m.apply(data.stream()).spliterator());
}
},
// Wrap as stream, and spliterate then iterate in pull mode
STREAM_SPLITERATOR_FOREACH(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
m.apply(data.stream()).spliterator().forEachRemaining(b);
}
},
PAR_STREAM_SEQUENTIAL_FOR_EACH(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
m.apply(data.parallelStream()).sequential().forEach(b);
}
},
// Wrap as parallel stream + forEachOrdered
PAR_STREAM_FOR_EACH_ORDERED(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
// @@@ Want to explicitly select ordered equalator
m.apply(data.parallelStream()).forEachOrdered(b);
}
},
// Wrap as stream, and spliterate then iterate sequentially
PAR_STREAM_SPLITERATOR(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
for (Spliterator.OfDouble spl = m.apply(data.parallelStream()).spliterator(); spl.tryAdvance(b); ) {
}
}
},
// Wrap as stream, and spliterate then iterate sequentially
PAR_STREAM_SPLITERATOR_FOREACH(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
m.apply(data.parallelStream()).spliterator().forEachRemaining(b);
}
},
PAR_STREAM_TO_ARRAY(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
for (double t : m.apply(data.parallelStream()).toArray())
b.accept(t);
}
},
// Wrap as parallel stream, get the spliterator, wrap as a stream + toArray
PAR_STREAM_SPLITERATOR_STREAM_TO_ARRAY(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
DoubleStream s = m.apply(data.parallelStream());
Spliterator.OfDouble sp = s.spliterator();
DoubleStream ss = StreamSupport.doubleParallelStream(() -> sp,
StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s))
| (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED));
for (double t : ss.toArray())
b.accept(t);
}
},
PAR_STREAM_TO_ARRAY_CLEAR_SIZED(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m) {
S_IN pipe1 = (S_IN) OpTestCase.chain(data.parallelStream(),
new FlagDeclaringOp(StreamOpFlag.NOT_SIZED, data.getShape()));
DoubleStream pipe2 = m.apply(pipe1);
for (double t : pipe2.toArray())
b.accept(t);
}
},;
private boolean isParallel;
DoubleStreamTestScenario(boolean isParallel) {
this.isParallel = isParallel;
}
public StreamShape getShape() {
return StreamShape.DOUBLE_VALUE;
}
public boolean isParallel() {
return isParallel;
}
public <T, U, S_IN extends BaseStream<T, S_IN>, S_OUT extends BaseStream<U, S_OUT>>
void run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, S_OUT> m) {
_run(data, (DoubleConsumer) b, (Function<S_IN, DoubleStream>) m);
}
abstract <T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, DoubleConsumer b, Function<S_IN, DoubleStream> m);
}
/*
* Copyright (c) 2012, 2013, 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.
*/
package java.util.stream;
/**
* An operation that injects or clears flags but otherwise performs no operation on elements.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class FlagDeclaringOp<T> implements StatelessTestOp<T, T> {
private final int flags;
private final StreamShape shape;
public FlagDeclaringOp(int flags) {
this(flags, StreamShape.REFERENCE);
}
public FlagDeclaringOp(int flags, StreamShape shape) {
this.flags = flags;
this.shape = shape;
}
@Override
public StreamShape outputShape() {
return shape;
}
@Override
public StreamShape inputShape() {
return shape;
}
@Override
public int opGetFlags() {
return flags;
}
@Override
public Sink<T> opWrapSink(int flags, boolean parallel, Sink sink) {
return sink;
}
}
/*
* Copyright (c) 2012, 2013, 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.
*/
package java.util.stream;
import org.testng.annotations.DataProvider;
import java.util.*;
import java.util.Spliterators;
import java.util.function.Supplier;
/** TestNG DataProvider for int-valued streams */
public class IntStreamTestDataProvider {
private static final int[] to0 = new int[0];
private static final int[] to1 = new int[1];
private static final int[] to10 = new int[10];
private static final int[] to100 = new int[100];
private static final int[] to1000 = new int[1000];
private static final int[] reversed = new int[100];
private static final int[] ones = new int[100];
private static final int[] twice = new int[200];
private static final int[] pseudoRandom;
private static final Object[][] testData;
private static final Object[][] spliteratorTestData;
static {
int[][] arrays = {to0, to1, to10, to100, to1000};
for (int[] arr : arrays) {
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
}
for (int i = 0; i < reversed.length; i++) {
reversed[i] = reversed.length - i;
}
for (int i = 0; i < ones.length; i++) {
ones[i] = 1;
}
System.arraycopy(to100, 0, twice, 0, to100.length);
System.arraycopy(to100, 0, twice, to100.length, to100.length);
pseudoRandom = new int[LambdaTestHelpers.LONG_STRING.length()];
for (int i = 0; i < LambdaTestHelpers.LONG_STRING.length(); i++) {
pseudoRandom[i] = (int) LambdaTestHelpers.LONG_STRING.charAt(i);
}
}
static final Object[][] arrays = {
{"empty", to0},
{"0..1", to1},
{"0..10", to10},
{"0..100", to100},
{"0..1000", to1000},
{"100x[1]", ones},
{"2x[0..100]", twice},
{"reverse 0..100", reversed},
{"pseudorandom", pseudoRandom}
};
static {
{
List<Object[]> list = new ArrayList<>();
for (Object[] data : arrays) {
final Object name = data[0];
final int[] ints = (int[]) data[1];
list.add(new Object[]{"array:" +
name, TestData.Factory.ofArray("array:" + name, ints)});
SpinedBuffer.OfInt isl = new SpinedBuffer.OfInt();
for (int i : ints) {
isl.accept(i);
}
list.add(new Object[]{"SpinedList:" + name,
TestData.Factory.ofSpinedBuffer("SpinedList:" + name, isl)});
list.add(streamDataDescr("IntStream.intRange(0,l): " + ints.length,
() -> IntStream.range(0, ints.length)));
list.add(streamDataDescr("IntStream.intRange(0,l,2): " + ints.length,
() -> IntStream.range(0, ints.length, 2)));
list.add(streamDataDescr("IntStream.intRange(0,l,3): " + ints.length,
() -> IntStream.range(0, ints.length, 3)));
list.add(streamDataDescr("IntStream.intRange(0,l,7): " + ints.length,
() -> IntStream.range(0, ints.length, 7)));
}
testData = list.toArray(new Object[0][]);
}
{
List<Object[]> spliterators = new ArrayList<>();
for (Object[] data : arrays) {
final Object name = data[0];
final int[] ints = (int[]) data[1];
SpinedBuffer.OfInt isl = new SpinedBuffer.OfInt();
for (int i : ints) {
isl.accept(i);
}
spliterators.add(splitDescr("Arrays.s(array):" + name,
() -> Arrays.spliterator(ints)));
spliterators.add(splitDescr("Arrays.s(array,o,l):" + name,
() -> Arrays.spliterator(ints, 0, ints.length / 2)));
spliterators.add(splitDescr("SpinedBuffer.s():" + name,
() -> isl.spliterator()));
spliterators.add(splitDescr("Primitives.s(SpinedBuffer.iterator(), size):" + name,
() -> Spliterators.spliterator(isl.iterator(), ints.length, 0)));
spliterators.add(splitDescr("Primitives.s(SpinedBuffer.iterator()):" + name,
() -> Spliterators.spliteratorUnknownSize(isl.iterator(), 0)));
spliterators.add(splitDescr("IntStream.intRange(0,l):" + name,
() -> IntStream.range(0, ints.length).spliterator()));
spliterators.add(splitDescr("IntStream.intRange(0,l,2):" + name,
() -> IntStream.range(0, ints.length, 2).spliterator()));
spliterators.add(splitDescr("IntStream.intRange(0,l,3):" + name,
() -> IntStream.range(0, ints.length, 3).spliterator()));
spliterators.add(splitDescr("IntStream.intRange(0,l,7):" + name,
() -> IntStream.range(0, ints.length, 7).spliterator()));
// Need more!
}
spliteratorTestData = spliterators.toArray(new Object[0][]);
}
}
static <T> Object[] streamDataDescr(String description, Supplier<IntStream> s) {
return new Object[] { description, TestData.Factory.ofIntSupplier(description, s) };
}
static <T> Object[] splitDescr(String description, Supplier<Spliterator.OfInt> s) {
return new Object[] { description, s };
}
// Return an array of ( String name, IntStreamTestData )
@DataProvider(name = "IntStreamTestData")
public static Object[][] makeIntStreamTestData() {
return testData;
}
// returns an array of (String name, Supplier<PrimitiveSpliterator<Integer>>)
@DataProvider(name = "IntSpliterator")
public static Object[][] spliteratorProvider() {
return spliteratorTestData;
}
}
/*
* Copyright (c) 2012, 2013, 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.
*/
package java.util.stream;
import java.util.PrimitiveIterator;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntConsumer;
/**
* Test scenarios for int streams.
*
* Each scenario is provided with a data source, a function that maps a fresh
* stream (as provided by the data source) to a new stream, and a sink to
* receive results. Each scenario describes a different way of computing the
* stream contents. The test driver will ensure that all scenarios produce
* the same output (modulo allowable differences in ordering).
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public enum IntStreamTestScenario implements OpTestCase.BaseStreamTestScenario {
STREAM_FOR_EACH(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
IntStream s = m.apply(data.stream());
if (s.isParallel()) {
s = s.sequential();
}
s.forEach(b);
}
},
STREAM_TO_ARRAY(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
for (int t : m.apply(data.stream()).toArray()) {
b.accept(t);
}
}
},
STREAM_ITERATOR(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
for (PrimitiveIterator.OfInt seqIter = m.apply(data.stream()).iterator(); seqIter.hasNext(); )
b.accept(seqIter.nextInt());
}
},
// Wrap as stream, and spliterate then iterate in pull mode
STREAM_SPLITERATOR(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
for (Spliterator.OfInt spl = m.apply(data.stream()).spliterator(); spl.tryAdvance(b); ) {
}
}
},
// Wrap as stream, spliterate, then split a few times mixing advances with forEach
STREAM_SPLITERATOR_WITH_MIXED_TRAVERSE_AND_SPLIT(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
SpliteratorTestHelper.mixedTraverseAndSplit(b, m.apply(data.stream()).spliterator());
}
},
// Wrap as stream, and spliterate then iterate in pull mode
STREAM_SPLITERATOR_FOREACH(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
m.apply(data.stream()).spliterator().forEachRemaining(b);
}
},
PAR_STREAM_SEQUENTIAL_FOR_EACH(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
m.apply(data.parallelStream()).sequential().forEach(b);
}
},
// Wrap as parallel stream + forEachOrdered
PAR_STREAM_FOR_EACH_ORDERED(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
// @@@ Want to explicitly select ordered equalator
m.apply(data.parallelStream()).forEachOrdered(b);
}
},
// Wrap as stream, and spliterate then iterate sequentially
PAR_STREAM_SPLITERATOR(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
for (Spliterator.OfInt spl = m.apply(data.parallelStream()).spliterator(); spl.tryAdvance(b); ) {
}
}
},
// Wrap as stream, and spliterate then iterate sequentially
PAR_STREAM_SPLITERATOR_FOREACH(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
m.apply(data.parallelStream()).spliterator().forEachRemaining(b);
}
},
PAR_STREAM_TO_ARRAY(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
for (int t : m.apply(data.parallelStream()).toArray())
b.accept(t);
}
},
// Wrap as parallel stream, get the spliterator, wrap as a stream + toArray
PAR_STREAM_SPLITERATOR_STREAM_TO_ARRAY(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
IntStream s = m.apply(data.parallelStream());
Spliterator.OfInt sp = s.spliterator();
IntStream ss = StreamSupport.intParallelStream(() -> sp,
StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s))
| (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED));
for (int t : ss.toArray())
b.accept(t);
}
},
PAR_STREAM_TO_ARRAY_CLEAR_SIZED(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m) {
S_IN pipe1 = (S_IN) OpTestCase.chain(data.parallelStream(),
new FlagDeclaringOp(StreamOpFlag.NOT_SIZED, data.getShape()));
IntStream pipe2 = m.apply(pipe1);
for (int t : pipe2.toArray())
b.accept(t);
}
},;
private boolean isParallel;
IntStreamTestScenario(boolean isParallel) {
this.isParallel = isParallel;
}
public StreamShape getShape() {
return StreamShape.INT_VALUE;
}
public boolean isParallel() {
return isParallel;
}
public <T, U, S_IN extends BaseStream<T, S_IN>, S_OUT extends BaseStream<U, S_OUT>>
void run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, S_OUT> m) {
_run(data, (IntConsumer) b, (Function<S_IN, IntStream>) m);
}
abstract <T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, IntConsumer b, Function<S_IN, IntStream> m);
}
/*
* Copyright (c) 2012, 2013, 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.
*/
package java.util.stream;
/**
* A base type for test operations
*/
interface IntermediateTestOp<E_IN, E_OUT> {
@SuppressWarnings({"rawtypes", "unchecked"})
public static<T> AbstractPipeline chain(AbstractPipeline upstream,
IntermediateTestOp<?, T> op) {
if (op instanceof StatelessTestOp)
return StatelessTestOp.chain(upstream, (StatelessTestOp) op);
if (op instanceof StatefulTestOp)
return StatefulTestOp.chain(upstream, (StatefulTestOp) op);
throw new IllegalStateException("Unknown test op type: " + op.getClass().getName());
}
}
/*
* Copyright (c) 1997, 2010, 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.
*/
package java.util.stream;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiPredicate;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.DoubleBinaryOperator;
import java.util.function.DoubleConsumer;
import java.util.function.DoublePredicate;
import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import java.util.function.IntConsumer;
import java.util.function.IntFunction;
import java.util.function.IntPredicate;
import java.util.function.IntUnaryOperator;
import java.util.function.LongBinaryOperator;
import java.util.function.LongConsumer;
import java.util.function.LongPredicate;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
/**
* LambdaTestHelpers -- assertion methods and useful objects for lambda test cases
*/
public class LambdaTestHelpers {
public static final String LONG_STRING = "When in the Course of human events it becomes necessary for one people to dissolve the political bands which have connected them with another and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.";
@SuppressWarnings("rawtypes")
public static final Consumer bEmpty = x -> { };
@SuppressWarnings("rawtypes")
public static final IntConsumer bIntEmpty = x -> { };
@SuppressWarnings("rawtypes")
public static final BiConsumer bBiEmpty = (x,y) -> { };
@SuppressWarnings("rawtypes")
public static final Consumer bHashCode = x -> { Objects.hashCode(x); };
@SuppressWarnings("rawtypes")
public static final BiConsumer bBiHashCode = (x,y) -> { Objects.hash(x, y); };
public static final Function<Integer, Integer> mZero = x -> 0;
public static final Function<Integer, Integer> mId = x -> x;
public static final Function<Integer, Integer> mDoubler = x -> x * 2;
public static final Function<Integer, Stream<Integer>> mfId = e -> Collections.singletonList(e).stream();
public static final Function<Integer, Stream<Integer>> mfNull = e -> Collections.<Integer>emptyList().stream();
public static final Function<Integer, Stream<Integer>> mfLt = e -> {
List<Integer> l = new ArrayList<>();
for (int i=0; i<e; i++)
l.add(i);
return l.stream();
};
public static final ToIntFunction<Integer> imDoubler = x -> x * 2;
public static final ToLongFunction<Long> lmDoubler = x -> x * 2;
public static final ToDoubleFunction<Double> dmDoubler = x -> x * 2;
public static final Predicate<Integer> pFalse = x -> false;
public static final Predicate<Integer> pTrue = x -> true;
public static final Predicate<Integer> pEven = x -> 0 == x % 2;
public static final Predicate<Integer> pOdd = x -> 1 == x % 2;
public static final IntPredicate ipFalse = x -> false;
public static final IntPredicate ipTrue = x -> true;
public static final IntPredicate ipEven = x -> 0 == x % 2;
public static final IntPredicate ipOdd = x -> 1 == x % 2;
public static final LongPredicate lpFalse = x -> false;
public static final LongPredicate lpTrue = x -> true;
public static final LongPredicate lpEven = x -> 0 == x % 2;
public static final LongPredicate lpOdd = x -> 1 == x % 2;
public static final DoublePredicate dpFalse = x -> false;
public static final DoublePredicate dpTrue = x -> true;
public static final DoublePredicate dpEven = x -> 0 == ((long) x) % 2;
public static final DoublePredicate dpOdd = x -> 1 == ((long) x) % 2;
public static final BinaryOperator<Integer> rPlus = (x, y) -> x+y;
public static final BinaryOperator<Integer> rMax = (x, y) -> Math.max(x, y);
public static final BinaryOperator<Integer> rMin = (x, y) -> Math.min(x,y);
public static final IntBinaryOperator irPlus = (x, y) -> x+y;
public static final IntBinaryOperator irMax = (x, y) -> Math.max(x, y);
public static final IntBinaryOperator irMin = (x, y) -> Math.min(x,y);
public static final IntUnaryOperator irDoubler = x -> x * 2;
public static final LongBinaryOperator lrPlus = (x, y) -> x+y;
public static final DoubleBinaryOperator drPlus = (x, y) -> x+y;
public static final Comparator<Integer> cInteger = (a, b) -> Integer.compare(a, b);
public static final BiPredicate<?, ?> bipFalse = (x, y) -> false;
public static final BiPredicate<?, ?> bipTrue = (x, y) -> true;
public static final BiPredicate<Integer, Integer> bipBothEven = (x, y) -> 0 == (x % 2 + y % 2);
public static final BiPredicate<Integer, Integer> bipBothOdd = (x, y) -> 2 == (x % 2 + y % 2);
public static final BiPredicate<?, ?> bipSameString = (x, y) -> String.valueOf(x).equals(String.valueOf(y));
public static final IntFunction<Integer[]> integerArrayGenerator = s -> new Integer[s];
public static final IntFunction<Object[]> objectArrayGenerator = s -> new Object[s];
public static final Function<String, Stream<Character>> flattenChars = string -> {
List<Character> l = new ArrayList<>();
for (int i=0; i<string.length(); i++)
l.add(string.charAt(i));
return l.stream();
};
public static final Function<String, IntStream> flattenInt
= string -> IntStream.range(0, string.length()).map(string::charAt);
public static <T, R> Function<T, R> forPredicate(Predicate<? super T> predicate, R forTrue, R forFalse) {
Objects.requireNonNull(predicate);
return t -> predicate.test(t) ? forTrue : forFalse;
}
public static <T> Function<T, T> identity() {
return t -> t;
}
public static<V, T, R> Function<V, R> compose(Function<? super T, ? extends R> after, Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> after.apply(before.apply(v));
}
public static List<Integer> empty() {
ArrayList<Integer> list = new ArrayList<>();
list.add(null);
return list;
}
public static List<Integer> countTo(int n) {
return range(1, n);
}
public static List<Integer> range(int l, int u) {
ArrayList<Integer> list = new ArrayList<>(u - l + 1);
for (int i=l; i<=u; i++) {
list.add(i);
}
return list;
}
public static List<Integer> repeat(int value, int n) {
ArrayList<Integer> list = new ArrayList<>(n);
for (int i=1; i<=n; i++) {
list.add(value);
}
return list;
}
public static List<Double> asDoubles(List<Integer> integers) {
ArrayList<Double> list = new ArrayList<>();
for (Integer i : integers) {
list.add((double) i);
}
return list;
}
public static List<Long> asLongs(List<Integer> integers) {
ArrayList<Long> list = new ArrayList<>();
for (Integer i : integers) {
list.add((long) i);
}
return list;
}
public static void assertCountSum(Stream<? super Integer> it, int count, int sum) {
assertCountSum(it.iterator(), count, sum);
}
public static void assertCountSum(Iterable<? super Integer> it, int count, int sum) {
assertCountSum(it.iterator(), count, sum);
}
public static void assertCountSum(Iterator<? super Integer> it, int count, int sum) {
int c = 0;
int s = 0;
while (it.hasNext()) {
int i = (Integer) it.next();
c++;
s += i;
}
assertEquals(c, count);
assertEquals(s, sum);
}
public static void assertConcat(Iterator<Character> it, String result) {
StringBuilder sb = new StringBuilder();
while (it.hasNext()) {
sb.append(it.next());
}
assertEquals(result, sb.toString());
}
public static<T extends Comparable<? super T>> void assertSorted(Iterator<T> i) {
i = toBoxedList(i).iterator();
if (!i.hasNext())
return;
T last = i.next();
while (i.hasNext()) {
T t = i.next();
assertTrue(last.compareTo(t) <= 0);
assertTrue(t.compareTo(last) >= 0);
last = t;
}
}
public static<T> void assertSorted(Iterator<T> i, Comparator<? super T> comp) {
if (i instanceof PrimitiveIterator.OfInt
|| i instanceof PrimitiveIterator.OfDouble
|| i instanceof PrimitiveIterator.OfLong) {
i = toBoxedList(i).iterator();
}
if (!i.hasNext())
return;
T last = i.next();
while (i.hasNext()) {
T t = i.next();
assertTrue(comp.compare(last, t) <= 0);
assertTrue(comp.compare(t, last) >= 0);
last = t;
}
}
public static<T extends Comparable<? super T>> void assertSorted(Iterable<T> iter) {
assertSorted(iter.iterator());
}
public static<T> void assertSorted(Iterable<T> iter, Comparator<? super T> comp) {
assertSorted(iter.iterator(), comp);
}
public static <T> void assertUnique(Iterable<T> iter) {
assertUnique(iter.iterator());
}
public static<T> void assertUnique(Iterator<T> iter) {
if (!iter.hasNext()) {
return;
}
if (iter instanceof PrimitiveIterator.OfInt
|| iter instanceof PrimitiveIterator.OfDouble
|| iter instanceof PrimitiveIterator.OfLong) {
iter = toBoxedList(iter).iterator();
}
Set<T> uniq = new HashSet<>();
while(iter.hasNext()) {
T each = iter.next();
assertTrue(!uniq.contains(each));
uniq.add(each);
}
}
public static<T> void assertContents(Iterable<T> actual, Iterable<T> expected) {
if (actual instanceof Collection && expected instanceof Collection) {
assertEquals(actual, expected);
} else {
assertContents(actual.iterator(), expected.iterator());
}
}
public static<T> void assertContents(Iterator<T> actual, Iterator<T> expected) {
assertEquals(toBoxedList(actual), toBoxedList(expected));
}
@SafeVarargs
@SuppressWarnings("varargs")
public static<T> void assertContents(Iterator<T> actual, T... expected) {
assertContents(actual, Arrays.asList(expected).iterator());
}
/**
* The all consuming consumer (rampant capitalist) that can accepting a reference or any primitive value.
*/
private static interface OmnivorousConsumer<T>
extends Consumer<T>, IntConsumer, LongConsumer, DoubleConsumer { }
@SuppressWarnings({"rawtypes", "unchecked"})
public static<T> Consumer<T> toBoxingConsumer(Consumer<? super T> c) {
return (Consumer<T>) new OmnivorousConsumer() {
@Override
public void accept(Object t) {
c.accept((T) t);
}
@Override
public void accept(int t) {
accept((Object) t);
}
@Override
public void accept(long t) {
accept((Object) t);
}
@Override
public void accept(double t) {
accept((Object) t);
}
};
}
/**
* Convert an iterator to a list using forEach with an implementation of
* {@link java.util.stream.LambdaTestHelpers.OmnivorousConsumer}.
*
* This ensures equality comparisons for test results do not trip
* the boxing trip-wires.
*/
private static<T> List<T> toBoxedList(Iterator<T> it) {
List<T> l = new ArrayList<>();
it.forEachRemaining(toBoxingConsumer(l::add));
return l;
}
/**
* Convert a spliterator to a list using forEach with an implementation of
* {@link java.util.stream.LambdaTestHelpers.OmnivorousConsumer}.
*
* This ensures equality comparisons for test results do not trip
* the boxing trip-wires.
*/
public static<T> List<T> toBoxedList(Spliterator<T> sp) {
List<T> l = new ArrayList<>();
sp.forEachRemaining(toBoxingConsumer(l::add));
return l;
}
/**
* Convert an iterator to a multi-set, represented as a Map, using forEach with an implementation of
* {@link java.util.stream.LambdaTestHelpers.OmnivorousConsumer}.
*
* This ensures equality comparisons for test results do not trip
* the boxing trip-wires.
*/
@SuppressWarnings("unchecked")
private static<T> Map<T, Integer> toBoxedMultiset(Iterator<T> it) {
Map<Object, Integer> result = new HashMap<>();
it.forEachRemaining(new OmnivorousConsumer<T>() {
@Override
public void accept(T t) {
add(t);
}
@Override
public void accept(int value) {
add(value);
}
@Override
public void accept(long value) {
add(value);
}
@Override
public void accept(double value) {
add(value);
}
void add(Object o) {
if (result.containsKey(o))
result.put(o, result.get(o) + 1);
else
result.put(o, 1);
}
});
return (Map<T, Integer>) result;
}
@SuppressWarnings("unchecked")
public static void assertContentsEqual(Object a, Object b) {
if (a instanceof Iterable && b instanceof Iterable)
assertContents((Iterable) a, (Iterable) b);
else
assertEquals(a, b);
}
public static<T> void assertContentsUnordered(Iterable<T> actual, Iterable<T> expected) {
assertContentsUnordered(actual.iterator(), expected.iterator());
}
public static<T> void assertContentsUnordered(Iterator<T> actual, Iterator<T> expected) {
assertEquals(toBoxedMultiset(actual), toBoxedMultiset(expected));
}
public static void launderAssertion(Runnable r, Supplier<String> additionalInfo) {
try {
r.run();
}
catch (AssertionError ae) {
AssertionError cloned = new AssertionError(ae.getMessage() + String.format("%n%s", additionalInfo.get()));
cloned.setStackTrace(ae.getStackTrace());
if (ae.getCause() != null)
cloned.initCause(ae.getCause());
throw cloned;
}
}
public static <T, S extends BaseStream<T, S>>
List<Function<S, S>> permuteStreamFunctions(List<Function<S, S>> opFunctions) {
List<List<Function<S, S>>> opFunctionPermutations = perm(opFunctions);
List<Function<S, S>> appliedFunctions = new ArrayList<>();
for (List<Function<S, S>> fs : opFunctionPermutations) {
Function<S, S> applied = s -> {
for (Function<S, S> f : fs) {
s = f.apply(s);
}
return s;
};
appliedFunctions.add(applied);
}
return appliedFunctions;
}
private static <T> List<T> sub(List<T> l, int index) {
List<T> subL = new ArrayList<>(l);
subL.remove(index);
return subL;
}
public static <T> List<List<T>> perm(List<T> l) {
List<List<T>> result = new ArrayList<>();
for (int i = 0; i < l.size(); i++) {
for (List<T> perm : perm(sub(l, i))) {
perm.add(0, l.get(i));
result.add(perm);
}
}
result.add(new ArrayList<T>());
return result;
}
public static String flagsToString(int flags) {
StringJoiner sj = new StringJoiner(", ", "StreamOpFlag[", "]");
if (StreamOpFlag.DISTINCT.isKnown(flags)) sj.add("IS_DISTINCT");
if (StreamOpFlag.ORDERED.isKnown(flags)) sj.add("IS_ORDERED");
if (StreamOpFlag.SIZED.isKnown(flags)) sj.add("IS_SIZED");
if (StreamOpFlag.SORTED.isKnown(flags)) sj.add("IS_SORTED");
if (StreamOpFlag.SHORT_CIRCUIT.isKnown(flags)) sj.add("IS_SHORT_CIRCUIT");
return sj.toString();
}
}
/*
* Copyright (c) 2013, 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.
*/
package java.util.stream;
import org.testng.annotations.DataProvider;
import java.util.*;
import java.util.Spliterators;
import java.util.function.Supplier;
/** TestNG DataProvider for long-valued streams */
public class LongStreamTestDataProvider {
private static final long[] to0 = new long[0];
private static final long[] to1 = new long[1];
private static final long[] to10 = new long[10];
private static final long[] to100 = new long[100];
private static final long[] to1000 = new long[1000];
private static final long[] reversed = new long[100];
private static final long[] ones = new long[100];
private static final long[] twice = new long[200];
private static final long[] pseudoRandom;
private static final Object[][] testData;
private static final Object[][] spliteratorTestData;
static {
long[][] arrays = {to0, to1, to10, to100, to1000};
for (long[] arr : arrays) {
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
}
for (int i = 0; i < reversed.length; i++) {
reversed[i] = reversed.length - i;
}
for (int i = 0; i < ones.length; i++) {
ones[i] = 1;
}
System.arraycopy(to100, 0, twice, 0, to100.length);
System.arraycopy(to100, 0, twice, to100.length, to100.length);
pseudoRandom = new long[LambdaTestHelpers.LONG_STRING.length()];
for (int i = 0; i < LambdaTestHelpers.LONG_STRING.length(); i++) {
pseudoRandom[i] = (long) LambdaTestHelpers.LONG_STRING.charAt(i);
}
}
static final Object[][] arrays = {
{"empty", to0},
{"0..1", to1},
{"0..10", to10},
{"0..100", to100},
{"0..1000", to1000},
{"100x[1]", ones},
{"2x[0..100]", twice},
{"reverse 0..100", reversed},
{"pseudorandom", pseudoRandom}
};
static {
{
List<Object[]> list = new ArrayList<>();
for (Object[] data : arrays) {
final Object name = data[0];
final long[] longs = (long[]) data[1];
list.add(new Object[]{"array:" + name,
TestData.Factory.ofArray("array:" + name, longs)});
SpinedBuffer.OfLong isl = new SpinedBuffer.OfLong();
for (long i : longs) {
isl.accept(i);
}
list.add(new Object[]{"SpinedList:" + name,
TestData.Factory.ofSpinedBuffer("SpinedList:" + name, isl)});
list.add(streamDataDescr("LongStream.longRange(0,l): " + longs.length,
() -> LongStream.range(0, longs.length)));
list.add(streamDataDescr("LongStream.longRange(0,l,2): " + longs.length,
() -> LongStream.range(0, longs.length, 2)));
list.add(streamDataDescr("LongStream.longRange(0,l,3): " + longs.length,
() -> LongStream.range(0, longs.length, 3)));
list.add(streamDataDescr("LongStream.longRange(0,l,7): " + longs.length,
() -> LongStream.range(0, longs.length, 7)));
}
testData = list.toArray(new Object[0][]);
}
{
List<Object[]> spliterators = new ArrayList<>();
for (Object[] data : arrays) {
final Object name = data[0];
final long[] longs = (long[]) data[1];
SpinedBuffer.OfLong isl = new SpinedBuffer.OfLong();
for (long i : longs) {
isl.accept(i);
}
spliterators.add(splitDescr("Arrays.s(array):" + name,
() -> Arrays.spliterator(longs)));
spliterators.add(splitDescr("Arrays.s(array,o,l):" + name,
() -> Arrays.spliterator(longs, 0, longs.length / 2)));
spliterators.add(splitDescr("SpinedBuffer.s():" + name,
() -> isl.spliterator()));
spliterators.add(splitDescr("Primitives.s(SpinedBuffer.iterator(), size):" + name,
() -> Spliterators.spliterator(isl.iterator(), longs.length, 0)));
spliterators.add(splitDescr("Primitives.s(SpinedBuffer.iterator()):" + name,
() -> Spliterators.spliteratorUnknownSize(isl.iterator(), 0)));
spliterators.add(splitDescr("LongStream.longRange(0,l):" + name,
() -> LongStream.range(0, longs.length).spliterator()));
spliterators.add(splitDescr("LongStream.longRange(0,l,2):" + name,
() -> LongStream.range(0, longs.length, 2).spliterator()));
spliterators.add(splitDescr("LongStream.longRange(0,l,3):" + name,
() -> LongStream.range(0, longs.length, 3).spliterator()));
spliterators.add(splitDescr("LongStream.longRange(0,l,7):" + name,
() -> LongStream.range(0, longs.length, 7).spliterator()));
// Need more!
}
spliteratorTestData = spliterators.toArray(new Object[0][]);
}
}
static <T> Object[] streamDataDescr(String description, Supplier<LongStream> s) {
return new Object[] { description, TestData.Factory.ofLongSupplier(description, s) };
}
static <T> Object[] splitDescr(String description, Supplier<Spliterator.OfLong> s) {
return new Object[] { description, s };
}
// Return an array of ( String name, LongStreamTestData )
@DataProvider(name = "LongStreamTestData")
public static Object[][] makeLongStreamTestData() {
return testData;
}
// returns an array of (String name, Supplier<PrimitiveSpliterator<Long>>)
@DataProvider(name = "LongSpliterator")
public static Object[][] spliteratorProvider() {
return spliteratorTestData;
}
}
/*
* Copyright (c) 2013, 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.
*/
package java.util.stream;
import java.util.PrimitiveIterator;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.LongConsumer;
/**
* Test scenarios for long streams.
*
* Each scenario is provided with a data source, a function that maps a fresh
* stream (as provided by the data source) to a new stream, and a sink to
* receive results. Each scenario describes a different way of computing the
* stream contents. The test driver will ensure that all scenarios produce
* the same output (modulo allowable differences in ordering).
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public enum LongStreamTestScenario implements OpTestCase.BaseStreamTestScenario {
STREAM_FOR_EACH(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
LongStream s = m.apply(data.stream());
if (s.isParallel()) {
s = s.sequential();
}
s.forEach(b);
}
},
STREAM_TO_ARRAY(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
for (long t : m.apply(data.stream()).toArray()) {
b.accept(t);
}
}
},
STREAM_ITERATOR(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
for (PrimitiveIterator.OfLong seqIter = m.apply(data.stream()).iterator(); seqIter.hasNext(); )
b.accept(seqIter.nextLong());
}
},
// Wrap as stream, and spliterate then iterate in pull mode
STREAM_SPLITERATOR(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
for (Spliterator.OfLong spl = m.apply(data.stream()).spliterator(); spl.tryAdvance(b); ) {
}
}
},
// Wrap as stream, spliterate, then split a few times mixing advances with forEach
STREAM_SPLITERATOR_WITH_MIXED_TRAVERSE_AND_SPLIT(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
SpliteratorTestHelper.mixedTraverseAndSplit(b, m.apply(data.stream()).spliterator());
}
},
// Wrap as stream, and spliterate then iterate in pull mode
STREAM_SPLITERATOR_FOREACH(false) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
m.apply(data.stream()).spliterator().forEachRemaining(b);
}
},
PAR_STREAM_SEQUENTIAL_FOR_EACH(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
m.apply(data.parallelStream()).sequential().forEach(b);
}
},
// Wrap as parallel stream + forEachOrdered
PAR_STREAM_FOR_EACH_ORDERED(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
// @@@ Want to explicitly select ordered equalator
m.apply(data.parallelStream()).forEachOrdered(b);
}
},
// Wrap as stream, and spliterate then iterate sequentially
PAR_STREAM_SPLITERATOR(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
for (Spliterator.OfLong spl = m.apply(data.parallelStream()).spliterator(); spl.tryAdvance(b); ) {
}
}
},
// Wrap as stream, and spliterate then iterate sequentially
PAR_STREAM_SPLITERATOR_FOREACH(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
m.apply(data.parallelStream()).spliterator().forEachRemaining(b);
}
},
PAR_STREAM_TO_ARRAY(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
for (long t : m.apply(data.parallelStream()).toArray())
b.accept(t);
}
},
// Wrap as parallel stream, get the spliterator, wrap as a stream + toArray
PAR_STREAM_SPLITERATOR_STREAM_TO_ARRAY(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
LongStream s = m.apply(data.parallelStream());
Spliterator.OfLong sp = s.spliterator();
LongStream ss = StreamSupport.longParallelStream(() -> sp,
StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s))
| (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED));
for (long t : ss.toArray())
b.accept(t);
}
},
PAR_STREAM_TO_ARRAY_CLEAR_SIZED(true) {
<T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m) {
S_IN pipe1 = (S_IN) OpTestCase.chain(data.parallelStream(),
new FlagDeclaringOp(StreamOpFlag.NOT_SIZED, data.getShape()));
LongStream pipe2 = m.apply(pipe1);
for (long t : pipe2.toArray())
b.accept(t);
}
},;
private boolean isParallel;
LongStreamTestScenario(boolean isParallel) {
this.isParallel = isParallel;
}
public StreamShape getShape() {
return StreamShape.LONG_VALUE;
}
public boolean isParallel() {
return isParallel;
}
public <T, U, S_IN extends BaseStream<T, S_IN>, S_OUT extends BaseStream<U, S_OUT>>
void run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, S_OUT> m) {
_run(data, (LongConsumer) b, (Function<S_IN, LongStream>) m);
}
abstract <T, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, LongConsumer b, Function<S_IN, LongStream> m);
}
/*
* Copyright (c) 2012, 2013, 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.
*/
package java.util.stream;
import java.util.Spliterator;
import java.util.function.IntFunction;
/**
* The base type for a stateful test operation.
*/
interface StatefulTestOp<E> extends IntermediateTestOp<E, E> {
@SuppressWarnings({"rawtypes", "unchecked"})
public static<T> AbstractPipeline chain(AbstractPipeline upstream,
StatefulTestOp op) {
switch (op.outputShape()) {
case REFERENCE:
return new ReferencePipeline.StatefulOp<Object, T>(upstream, op.inputShape(), op.opGetFlags()) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return op.opWrapSink(flags, isParallel(), sink);
}
@Override
<P_IN> Spliterator<T> opEvaluateParallelLazy(PipelineHelper<T> helper,
Spliterator<P_IN> spliterator) {
return op.opEvaluateParallelLazy(helper, spliterator);
}
@Override
<P_IN> Node<T> opEvaluateParallel(PipelineHelper<T> helper,
Spliterator<P_IN> spliterator,
IntFunction<T[]> generator) {
return op.opEvaluateParallel(helper, spliterator, generator);
}
};
case INT_VALUE:
return new IntPipeline.StatefulOp<Object>(upstream, op.inputShape(), op.opGetFlags()) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return op.opWrapSink(flags, isParallel(), sink);
}
@Override
<P_IN> Spliterator<Integer> opEvaluateParallelLazy(PipelineHelper<Integer> helper,
Spliterator<P_IN> spliterator) {
return op.opEvaluateParallelLazy(helper, spliterator);
}
@Override
<P_IN> Node<Integer> opEvaluateParallel(PipelineHelper<Integer> helper,
Spliterator<P_IN> spliterator,
IntFunction<Integer[]> generator) {
return (Node<Integer>) op.opEvaluateParallel(helper, spliterator, generator);
}
};
case LONG_VALUE:
return new LongPipeline.StatefulOp<Object>(upstream, op.inputShape(), op.opGetFlags()) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return op.opWrapSink(flags, isParallel(), sink);
}
@Override
<P_IN> Spliterator<Long> opEvaluateParallelLazy(PipelineHelper<Long> helper,
Spliterator<P_IN> spliterator) {
return op.opEvaluateParallelLazy(helper, spliterator);
}
@Override
<P_IN> Node<Long> opEvaluateParallel(PipelineHelper<Long> helper,
Spliterator<P_IN> spliterator,
IntFunction<Long[]> generator) {
return (Node<Long>) op.opEvaluateParallel(helper, spliterator, generator);
}
};
case DOUBLE_VALUE:
return new DoublePipeline.StatefulOp<Object>(upstream, op.inputShape(), op.opGetFlags()) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return op.opWrapSink(flags, isParallel(), sink);
}
@Override
<P_IN> Spliterator<Double> opEvaluateParallelLazy(PipelineHelper<Double> helper,
Spliterator<P_IN> spliterator) {
return op.opEvaluateParallelLazy(helper, spliterator);
}
@Override
<P_IN> Node<Double> opEvaluateParallel(PipelineHelper<Double> helper,
Spliterator<P_IN> spliterator,
IntFunction<Double[]> generator) {
return (Node<Double>) op.opEvaluateParallel(helper, spliterator, generator);
}
};
default: throw new IllegalStateException(op.outputShape().toString());
}
}
default StreamShape inputShape() { return StreamShape.REFERENCE; }
default StreamShape outputShape() { return StreamShape.REFERENCE; }
default int opGetFlags() { return 0; }
Sink<E> opWrapSink(int flags, boolean parallel, Sink<E> sink);
@SuppressWarnings("unchecked")
default <P_IN> Spliterator<E> opEvaluateParallelLazy(PipelineHelper<E> helper,
Spliterator<P_IN> spliterator) {
return opEvaluateParallel(helper, spliterator, i -> (E[]) new Object[i]).spliterator();
}
<P_IN> Node<E> opEvaluateParallel(PipelineHelper<E> helper,
Spliterator<P_IN> spliterator,
IntFunction<E[]> generator);
}
/*
* Copyright (c) 2013, 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.
*/
package java.util.stream;
/**
* The base type of a stateless test operation
*/
interface StatelessTestOp<E_IN, E_OUT> extends IntermediateTestOp<E_IN, E_OUT> {
@SuppressWarnings({"rawtypes", "unchecked"})
public static<T> AbstractPipeline chain(AbstractPipeline upstream,
StatelessTestOp<?, T> op) {
int flags = op.opGetFlags();
switch (op.outputShape()) {
case REFERENCE:
return new ReferencePipeline.StatelessOp<Object, T>(upstream, op.inputShape(), flags) {
public Sink opWrapSink(int flags, Sink<T> sink) {
return op.opWrapSink(flags, isParallel(), sink);
}
};
case INT_VALUE:
return new IntPipeline.StatelessOp<Object>(upstream, op.inputShape(), flags) {
public Sink opWrapSink(int flags, Sink sink) {
return op.opWrapSink(flags, isParallel(), sink);
}
};
case LONG_VALUE:
return new LongPipeline.StatelessOp<Object>(upstream, op.inputShape(), flags) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return op.opWrapSink(flags, isParallel(), sink);
}
};
case DOUBLE_VALUE:
return new DoublePipeline.StatelessOp<Object>(upstream, op.inputShape(), flags) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return op.opWrapSink(flags, isParallel(), sink);
}
};
default: throw new IllegalStateException(op.outputShape().toString());
}
}
default StreamShape inputShape() { return StreamShape.REFERENCE; }
default StreamShape outputShape() { return StreamShape.REFERENCE; }
default int opGetFlags() { return 0; }
Sink<E_IN> opWrapSink(int flags, boolean parallel, Sink<E_OUT> sink);
}
/*
* Copyright (c) 2012, 2013, 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.
*/
package java.util.stream;
import java.util.EnumSet;
public class StreamOpFlagTestHelper {
/** EnumSet containing stream flags */
private static final EnumSet<StreamOpFlag> allStreamFlags;
static {
allStreamFlags = EnumSet.allOf(StreamOpFlag.class);
for (StreamOpFlag f : EnumSet.allOf(StreamOpFlag.class))
if (!f.isStreamFlag())
allStreamFlags.remove(f);
}
static EnumSet<StreamOpFlag> allStreamFlags() {
// EnumSet is mutable
return allStreamFlags.clone();
}
public static boolean isStreamOrdered(Stream<?> s) {
return StreamOpFlag.ORDERED.isKnown(OpTestCase.getStreamFlags(s));
}
}
/*
* Copyright (c) 2012, 2013, 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.
*/
package java.util.stream;
import org.testng.annotations.DataProvider;
import java.util.*;
import java.util.Spliterators;
import java.util.function.Supplier;
/**
* StreamTestDataProvider
*
* @author Brian Goetz
*/
/** TestNG DataProvider for ref-valued streams */
public class StreamTestDataProvider {
private static final Integer[] to0 = new Integer[0];
private static final Integer[] to1 = new Integer[1];
private static final Integer[] to10 = new Integer[10];
private static final Integer[] to100 = new Integer[100];
private static final Integer[] to1000 = new Integer[1000];
private static final Integer[] reversed = new Integer[100];
private static final Integer[] ones = new Integer[100];
private static final Integer[] twice = new Integer[200];
private static final Integer[] pseudoRandom;
private static final Object[][] testData;
private static final Object[][] withNullTestData;
private static final Object[][] spliteratorTestData;
static {
Integer[][] arrays = {to0, to1, to10, to100, to1000};
for (Integer[] arr : arrays) {
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
}
for (int i = 0; i < reversed.length; i++) {
reversed[i] = reversed.length - i;
}
for (int i = 0; i < ones.length; i++) {
ones[i] = 1;
}
System.arraycopy(to100, 0, twice, 0, to100.length);
System.arraycopy(to100, 0, twice, to100.length, to100.length);
pseudoRandom = new Integer[LambdaTestHelpers.LONG_STRING.length()];
for (int i = 0; i < LambdaTestHelpers.LONG_STRING.length(); i++) {
pseudoRandom[i] = (int) LambdaTestHelpers.LONG_STRING.charAt(i);
}
}
static final Object[][] arrays = {
{"empty", to0},
{"0..1", to1},
{"0..10", to10},
{"0..100", to100},
{"0..1000", to1000},
{"100x[1]", ones},
{"2x[0..100]", twice},
{"reverse 0..100", reversed},
{"pseudorandom", pseudoRandom}
};
static {
{
List<Object[]> list = new ArrayList<>();
for (Object[] data : arrays) {
final Object name = data[0];
final Integer[] ints = (Integer[])data[1];
final List<Integer> intsAsList = Arrays.asList(ints);
list.add(arrayDataDescr("array:" + name, ints));
list.add(collectionDataDescr("ArrayList.asList:" + name, intsAsList));
list.add(collectionDataDescr("ArrayList:" + name, new ArrayList<>(intsAsList)));
list.add(streamDataDescr("DelegatingStream(ArrayList):" + name,
() -> new ArrayList<>(intsAsList).stream()));
List<Integer> aList = new ArrayList<>(intsAsList);
list.add(collectionDataDescr("ArrayList.Sublist:" + name,
(ints.length) <= 1 ? aList.subList(0, 0) : aList.subList(1, ints.length / 2)));
list.add(collectionDataDescr("LinkedList:" + name, new LinkedList<>(intsAsList)));
list.add(collectionDataDescr("HashSet:" + name, new HashSet<>(intsAsList)));
list.add(collectionDataDescr("LinkedHashSet:" + name, new LinkedHashSet<>(intsAsList)));
list.add(collectionDataDescr("TreeSet:" + name, new TreeSet<>(intsAsList)));
SpinedBuffer<Integer> spinedBuffer = new SpinedBuffer<>();
intsAsList.forEach(spinedBuffer);
list.add(sbDataDescr("SpinedBuffer:" + name, spinedBuffer));
// @@@ Add more
}
testData = list.toArray(new Object[0][]);
}
// Simple combination of numbers and null values, probably excessive but may catch
// errors for initialization/termination/sequence
// @@@ This is separate from the other data for now until nulls are consitently supported by
// all operations
{
List<Object[]> list = new ArrayList<>();
int size = 5;
for (int i = 0; i < (1 << size) - 2; i++) {
Integer[] content = new Integer[size];
for (int e = 0; e < size; e++) {
content[e] = (i & (1 << e)) > 0 ? e + 1 : null;
}
// ORDERED
list.add(arrayDataDescr("array:" + i, content));
// not ORDERED, DISTINCT
list.add(collectionDataDescr("HashSet:" + i, new HashSet<>(Arrays.asList(content))));
}
withNullTestData = list.toArray(new Object[0][]);
}
{
List<Object[]> spliterators = new ArrayList<>();
for (Object[] data : arrays) {
final Object name = data[0];
final Integer[] ints = (Integer[])data[1];
spliterators.add(splitDescr("Arrays.s(array):" + name,
() -> Arrays.spliterator(ints)));
spliterators.add(splitDescr("arrays.s(array,o,l):" + name,
() -> Arrays.spliterator(ints, 0, ints.length/2)));
spliterators.add(splitDescr("SpinedBuffer.s():" + name,
() -> {
SpinedBuffer<Integer> sb = new SpinedBuffer<>();
for (Integer i : ints)
sb.accept(i);
return sb.spliterator();
}));
spliterators.add(splitDescr("Iterators.s(Arrays.s(array).iterator(), size):" + name,
() -> Spliterators.spliterator(Arrays.asList(ints).iterator(), ints.length, 0)));
spliterators.add(splitDescr("Iterators.s(Arrays.s(array).iterator()):" + name,
() -> Spliterators.spliteratorUnknownSize(Arrays.asList(ints).iterator(), 0)));
// @@@ Add map and collection spliterators when spliterator() is exposed on Collection or Iterable
}
spliteratorTestData = spliterators.toArray(new Object[0][]);
}
}
static <T> Object[] arrayDataDescr(String description, T[] data) {
return new Object[] { description, TestData.Factory.ofArray(description, data)};
}
static <T> Object[] streamDataDescr(String description, Supplier<Stream<T>> supplier) {
return new Object[] { description, TestData.Factory.ofSupplier(description, supplier)};
}
static <T> Object[] collectionDataDescr(String description, Collection<T> data) {
return new Object[] { description, TestData.Factory.ofCollection(description, data)};
}
static <T> Object[] sbDataDescr(String description, SpinedBuffer<T> data) {
return new Object[] { description, TestData.Factory.ofSpinedBuffer(description, data)};
}
static <T> Object[] splitDescr(String description, Supplier<Spliterator<T>> ss) {
return new Object[] { description, ss };
}
// Return an array of ( String name, StreamTestData<Integer> )
@DataProvider(name = "StreamTestData<Integer>")
public static Object[][] makeStreamTestData() {
return testData;
}
@DataProvider(name = "withNull:StreamTestData<Integer>")
public static Object[][] makeStreamWithNullTestData() {
return withNullTestData;
}
// returns an array of (String name, Supplier<Spliterator<Integer>>)
@DataProvider(name = "Spliterator<Integer>")
public static Object[][] spliteratorProvider() {
return spliteratorTestData;
}
}
/*
* Copyright (c) 2012, 2013, 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.
*/
package java.util.stream;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* Test scenarios for reference streams.
*
* Each scenario is provided with a data source, a function that maps a fresh
* stream (as provided by the data source) to a new stream, and a sink to
* receive results. Each scenario describes a different way of computing the
* stream contents. The test driver will ensure that all scenarios produce
* the same output (modulo allowable differences in ordering).
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public enum StreamTestScenario implements OpTestCase.BaseStreamTestScenario {
STREAM_FOR_EACH(false) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
Stream<U> s = m.apply(data.stream());
if (s.isParallel()) {
s = s.sequential();
}
s.forEach(b);
}
},
// Collec to list
STREAM_COLLECT(false) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
for (U t : m.apply(data.stream()).collect(Collectors.toList())) {
b.accept(t);
}
}
},
// To array
STREAM_TO_ARRAY(false) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
for (Object t : m.apply(data.stream()).toArray()) {
b.accept((U) t);
}
}
},
// Wrap as stream, and iterate in pull mode
STREAM_ITERATOR(false) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
for (Iterator<U> seqIter = m.apply(data.stream()).iterator(); seqIter.hasNext(); )
b.accept(seqIter.next());
}
},
// Wrap as stream, and spliterate then iterate in pull mode
STREAM_SPLITERATOR(false) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
for (Spliterator<U> spl = m.apply(data.stream()).spliterator(); spl.tryAdvance(b); ) { }
}
},
// Wrap as stream, spliterate, then split a few times mixing advances with forEach
STREAM_SPLITERATOR_WITH_MIXED_TRAVERSE_AND_SPLIT(false) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
SpliteratorTestHelper.mixedTraverseAndSplit(b, m.apply(data.stream()).spliterator());
}
},
// Wrap as stream, and spliterate then iterate in pull mode
STREAM_SPLITERATOR_FOREACH(false) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
m.apply(data.stream()).spliterator().forEachRemaining(b);
}
},
// Wrap as parallel stream + sequential
PAR_STREAM_SEQUENTIAL_FOR_EACH(true) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
m.apply(data.parallelStream()).sequential().forEach(b);
}
},
// Wrap as parallel stream + forEachOrdered
PAR_STREAM_FOR_EACH_ORDERED(true) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
// @@@ Want to explicitly select ordered equalator
m.apply(data.parallelStream()).forEachOrdered(b);
}
},
// Wrap as stream, and spliterate then iterate sequentially
PAR_STREAM_SPLITERATOR(true) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
for (Spliterator<U> spl = m.apply(data.parallelStream()).spliterator(); spl.tryAdvance(b); ) { }
}
},
// Wrap as stream, and spliterate then iterate sequentially
PAR_STREAM_SPLITERATOR_FOREACH(true) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
m.apply(data.parallelStream()).spliterator().forEachRemaining(b);
}
},
// Wrap as parallel stream + toArray
PAR_STREAM_TO_ARRAY(true) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
for (Object t : m.apply(data.parallelStream()).toArray())
b.accept((U) t);
}
},
// Wrap as parallel stream, get the spliterator, wrap as a stream + toArray
PAR_STREAM_SPLITERATOR_STREAM_TO_ARRAY(true) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
Stream<U> s = m.apply(data.parallelStream());
Spliterator<U> sp = s.spliterator();
Stream<U> ss = StreamSupport.parallelStream(() -> sp,
StreamOpFlag.toCharacteristics(OpTestCase.getStreamFlags(s))
| (sp.getExactSizeIfKnown() < 0 ? 0 : Spliterator.SIZED));
for (Object t : ss.toArray())
b.accept((U) t);
}
},
// Wrap as parallel stream + toArray and clear SIZED flag
PAR_STREAM_TO_ARRAY_CLEAR_SIZED(true) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
S_IN pipe1 = (S_IN) OpTestCase.chain(data.parallelStream(),
new FlagDeclaringOp(StreamOpFlag.NOT_SIZED, data.getShape()));
Stream<U> pipe2 = m.apply(pipe1);
for (Object t : pipe2.toArray())
b.accept((U) t);
}
},
// Wrap as parallel + collect
PAR_STREAM_COLLECT(true) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
for (U u : m.apply(data.parallelStream()).collect(Collectors.toList()))
b.accept(u);
}
},
// Wrap sequential as parallel, + collect
STREAM_TO_PAR_STREAM_COLLECT(true) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
for (U u : m.apply(data.stream().parallel()).collect(Collectors.toList()))
b.accept(u);
}
},
// Wrap parallel as sequential,, + collect
PAR_STREAM_TO_STREAM_COLLECT(true) {
<T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m) {
for (U u : m.apply(data.parallelStream().sequential()).collect(Collectors.toList()))
b.accept(u);
}
},
;
private boolean isParallel;
StreamTestScenario(boolean isParallel) {
this.isParallel = isParallel;
}
public StreamShape getShape() {
return StreamShape.REFERENCE;
}
public boolean isParallel() {
return isParallel;
}
public <T, U, S_IN extends BaseStream<T, S_IN>, S_OUT extends BaseStream<U, S_OUT>>
void run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, S_OUT> m) {
_run(data, b, (Function<S_IN, Stream<U>>) m);
}
abstract <T, U, S_IN extends BaseStream<T, S_IN>>
void _run(TestData<T, S_IN> data, Consumer<U> b, Function<S_IN, Stream<U>> m);
}
/*
* Copyright (c) 2012, 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.
*/
package java.util.stream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.PrimitiveIterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.DoubleConsumer;
import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;
/** Describes a test data set for use in stream tests */
public interface TestData<T, S extends BaseStream<T, S>>
extends Iterable<T> {
default int size() {
throw new UnsupportedOperationException();
}
@Override
default Iterator<T> iterator() {
return Spliterators.iteratorFromSpliterator(spliterator());
}
Spliterator<T> spliterator();
default boolean isOrdered() {
return spliterator().hasCharacteristics(Spliterator.ORDERED);
}
StreamShape getShape();
default <A extends Collection<? super T>> A into(A target) {
spliterator().forEachRemaining(target::add);
return target;
}
S stream();
S parallelStream();
public interface OfRef<T> extends TestData<T, Stream<T>> { }
public interface OfInt extends TestData<Integer, IntStream> { }
public interface OfLong extends TestData<Long, LongStream> { }
public interface OfDouble extends TestData<Double, DoubleStream> { }
// @@@ Temporary garbage class to avoid triggering bugs with lambdas in static methods in interfaces
public static class Factory {
public static <T> OfRef<T> ofArray(String name, T[] array) {
return new AbstractTestData.RefTestData<>(name, array, Arrays::stream, a -> Arrays.stream(a).parallel(),
Arrays::spliterator, a -> a.length);
}
public static <T> OfRef<T> ofCollection(String name, Collection<T> collection) {
return new AbstractTestData.RefTestData<>(name, collection, Collection::stream, Collection::parallelStream,
Collection::spliterator, Collection::size);
}
public static <T> OfRef<T> ofSpinedBuffer(String name, SpinedBuffer<T> buffer) {
return new AbstractTestData.RefTestData<>(name, buffer,
b -> StreamSupport.stream(b.spliterator()),
b -> StreamSupport.parallelStream(b.spliterator()),
SpinedBuffer::spliterator,
b -> (int) b.count());
}
public static <T> OfRef<T> ofSupplier(String name, Supplier<Stream<T>> supplier) {
return new AbstractTestData.RefTestData<>(name, supplier,
Supplier::get,
s -> s.get().parallel(),
s -> s.get().spliterator(),
s -> (int) s.get().spliterator().getExactSizeIfKnown());
}
public static <T> OfRef<T> ofRefNode(String name, Node<T> node) {
return new AbstractTestData.RefTestData<>(name, node,
n -> StreamSupport.stream(n::spliterator, Spliterator.SIZED | Spliterator.ORDERED),
n -> StreamSupport.parallelStream(n::spliterator, Spliterator.SIZED | Spliterator.ORDERED),
Node::spliterator,
n -> (int) n.count());
}
// int factories
public static <T> OfInt ofArray(String name, int[] array) {
return new AbstractTestData.IntTestData<>(name, array, Arrays::stream, a -> Arrays.stream(a).parallel(),
Arrays::spliterator, a -> a.length);
}
public static OfInt ofSpinedBuffer(String name, SpinedBuffer.OfInt buffer) {
return new AbstractTestData.IntTestData<>(name, buffer,
b -> StreamSupport.intStream(b.spliterator()),
b -> StreamSupport.intParallelStream(b.spliterator()),
SpinedBuffer.OfInt::spliterator,
b -> (int) b.count());
}
public static OfInt ofIntSupplier(String name, Supplier<IntStream> supplier) {
return new AbstractTestData.IntTestData<>(name, supplier,
Supplier::get,
s -> s.get().parallel(),
s -> s.get().spliterator(),
s -> (int) s.get().spliterator().getExactSizeIfKnown());
}
public static OfInt ofNode(String name, Node.OfInt node) {
int characteristics = Spliterator.SIZED | Spliterator.ORDERED;
return new AbstractTestData.IntTestData<>(name, node,
n -> StreamSupport.intStream(n::spliterator, characteristics),
n -> StreamSupport.intParallelStream(n::spliterator, characteristics),
Node.OfInt::spliterator,
n -> (int) n.count());
}
// long factories
public static <T> OfLong ofArray(String name, long[] array) {
return new AbstractTestData.LongTestData<>(name, array, Arrays::stream, a -> Arrays.stream(a).parallel(),
Arrays::spliterator, a -> a.length);
}
public static OfLong ofSpinedBuffer(String name, SpinedBuffer.OfLong buffer) {
return new AbstractTestData.LongTestData<>(name, buffer,
b -> StreamSupport.longStream(b.spliterator()),
b -> StreamSupport.longParallelStream(b.spliterator()),
SpinedBuffer.OfLong::spliterator,
b -> (int) b.count());
}
public static OfLong ofLongSupplier(String name, Supplier<LongStream> supplier) {
return new AbstractTestData.LongTestData<>(name, supplier,
Supplier::get,
s -> s.get().parallel(),
s -> s.get().spliterator(),
s -> (int) s.get().spliterator().getExactSizeIfKnown());
}
public static OfLong ofNode(String name, Node.OfLong node) {
int characteristics = Spliterator.SIZED | Spliterator.ORDERED;
return new AbstractTestData.LongTestData<>(name, node,
n -> StreamSupport.longStream(n::spliterator, characteristics),
n -> StreamSupport.longParallelStream(n::spliterator, characteristics),
Node.OfLong::spliterator,
n -> (int) n.count());
}
// double factories
public static <T> OfDouble ofArray(String name, double[] array) {
return new AbstractTestData.DoubleTestData<>(name, array, Arrays::stream, a -> Arrays.stream(a).parallel(),
Arrays::spliterator, a -> a.length);
}
public static OfDouble ofSpinedBuffer(String name, SpinedBuffer.OfDouble buffer) {
return new AbstractTestData.DoubleTestData<>(name, buffer,
b -> StreamSupport.doubleStream(b.spliterator()),
b -> StreamSupport.doubleParallelStream(b.spliterator()),
SpinedBuffer.OfDouble::spliterator,
b -> (int) b.count());
}
public static OfDouble ofDoubleSupplier(String name, Supplier<DoubleStream> supplier) {
return new AbstractTestData.DoubleTestData<>(name, supplier,
Supplier::get,
s -> s.get().parallel(),
s -> s.get().spliterator(),
s -> (int) s.get().spliterator().getExactSizeIfKnown());
}
public static OfDouble ofNode(String name, Node.OfDouble node) {
int characteristics = Spliterator.SIZED | Spliterator.ORDERED;
return new AbstractTestData.DoubleTestData<>(name, node,
n -> StreamSupport.doubleStream(n::spliterator, characteristics),
n -> StreamSupport.doubleParallelStream(n::spliterator, characteristics),
Node.OfDouble::spliterator,
n -> (int) n.count());
}
}
abstract class AbstractTestData<T, S extends BaseStream<T, S>,
T_STATE,
T_SPLITR extends Spliterator<T>>
implements TestData<T, S> {
private final String name;
private final StreamShape shape;
protected final T_STATE state;
private final ToIntFunction<T_STATE> sizeFn;
private final Function<T_STATE, S> streamFn;
private final Function<T_STATE, S> parStreamFn;
private final Function<T_STATE, T_SPLITR> splitrFn;
AbstractTestData(String name,
StreamShape shape,
T_STATE state,
Function<T_STATE, S> streamFn,
Function<T_STATE, S> parStreamFn,
Function<T_STATE, T_SPLITR> splitrFn,
ToIntFunction<T_STATE> sizeFn) {
this.name = name;
this.shape = shape;
this.state = state;
this.streamFn = streamFn;
this.parStreamFn = parStreamFn;
this.splitrFn = splitrFn;
this.sizeFn = sizeFn;
}
@Override
public StreamShape getShape() {
return shape;
}
@Override
public String toString() {
return getClass().getSimpleName() + "[" + name + "]";
}
@Override
public int size() {
return sizeFn.applyAsInt(state);
}
@Override
public T_SPLITR spliterator() {
return splitrFn.apply(state);
}
@Override
public S stream() {
return streamFn.apply(state);
}
@Override
public S parallelStream() {
return parStreamFn.apply(state);
}
public static class RefTestData<T, I>
extends AbstractTestData<T, Stream<T>, I, Spliterator<T>>
implements TestData.OfRef<T> {
protected RefTestData(String name,
I state,
Function<I, Stream<T>> streamFn,
Function<I, Stream<T>> parStreamFn,
Function<I, Spliterator<T>> splitrFn,
ToIntFunction<I> sizeFn) {
super(name, StreamShape.REFERENCE, state, streamFn, parStreamFn, splitrFn, sizeFn);
}
}
static class IntTestData<I>
extends AbstractTestData<Integer, IntStream, I, Spliterator.OfInt>
implements TestData.OfInt {
protected IntTestData(String name,
I state,
Function<I, IntStream> streamFn,
Function<I, IntStream> parStreamFn,
Function<I, Spliterator.OfInt> splitrFn,
ToIntFunction<I> sizeFn) {
super(name, StreamShape.INT_VALUE, state, streamFn, parStreamFn, splitrFn, sizeFn);
}
@Override
public PrimitiveIterator.OfInt iterator() {
return Spliterators.iteratorFromSpliterator(spliterator());
}
@Override
public <A extends Collection<? super Integer>> A into(A target) {
spliterator().forEachRemaining((IntConsumer) target::add);
return target;
}
}
static class LongTestData<I>
extends AbstractTestData<Long, LongStream, I, Spliterator.OfLong>
implements TestData.OfLong {
protected LongTestData(String name,
I state,
Function<I, LongStream> streamFn,
Function<I, LongStream> parStreamFn,
Function<I, Spliterator.OfLong> splitrFn,
ToIntFunction<I> sizeFn) {
super(name, StreamShape.LONG_VALUE, state, streamFn, parStreamFn, splitrFn, sizeFn);
}
@Override
public PrimitiveIterator.OfLong iterator() {
return Spliterators.iteratorFromSpliterator(spliterator());
}
@Override
public <A extends Collection<? super Long>> A into(A target) {
spliterator().forEachRemaining((LongConsumer) target::add);
return target;
}
}
static class DoubleTestData<I>
extends AbstractTestData<Double, DoubleStream, I, Spliterator.OfDouble>
implements OfDouble {
protected DoubleTestData(String name,
I state,
Function<I, DoubleStream> streamFn,
Function<I, DoubleStream> parStreamFn,
Function<I, Spliterator.OfDouble> splitrFn,
ToIntFunction<I> sizeFn) {
super(name, StreamShape.DOUBLE_VALUE, state, streamFn, parStreamFn, splitrFn, sizeFn);
}
@Override
public PrimitiveIterator.OfDouble iterator() {
return Spliterators.iteratorFromSpliterator(spliterator());
}
@Override
public <A extends Collection<? super Double>> A into(A target) {
spliterator().forEachRemaining((DoubleConsumer) target::add);
return target;
}
}
}
}
/*
* Copyright (c) 2012, 2013, 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.
*/
package java.util.stream;
import org.testng.Assert;
import java.util.EnumSet;
class TestFlagExpectedOp<T> extends FlagDeclaringOp<T> {
static class Builder<T> {
final int flags;
StreamShape shape = StreamShape.REFERENCE;
EnumSet<StreamOpFlag> known = EnumSet.noneOf(StreamOpFlag.class);
EnumSet<StreamOpFlag> preserve = EnumSet.noneOf(StreamOpFlag.class);
EnumSet<StreamOpFlag> notKnown = EnumSet.noneOf(StreamOpFlag.class);
Builder(int flags) {
this.flags = flags;
}
Builder<T> known(EnumSet<StreamOpFlag> known) {
this.known = known;
return this;
}
Builder<T> preserve(EnumSet<StreamOpFlag> preserve) {
this.preserve = preserve;
return this;
}
Builder<T> notKnown(EnumSet<StreamOpFlag> notKnown) {
this.notKnown = notKnown;
return this;
}
Builder<T> shape(StreamShape shape) {
this.shape = shape;
return this;
}
TestFlagExpectedOp<T> build() {
return new TestFlagExpectedOp<>(flags, known, preserve, notKnown, shape);
}
}
final EnumSet<StreamOpFlag> known;
final EnumSet<StreamOpFlag> preserve;
final EnumSet<StreamOpFlag> notKnown;
final StreamShape shape;
TestFlagExpectedOp(int flags,
EnumSet<StreamOpFlag> known,
EnumSet<StreamOpFlag> preserve,
EnumSet<StreamOpFlag> notKnown) {
this(flags, known, preserve, notKnown, StreamShape.REFERENCE);
}
TestFlagExpectedOp(int flags,
EnumSet<StreamOpFlag> known,
EnumSet<StreamOpFlag> preserve,
EnumSet<StreamOpFlag> notKnown,
StreamShape shape) {
super(flags);
this.known = known;
this.preserve = preserve;
this.notKnown = notKnown;
this.shape = shape;
}
@Override
public StreamShape outputShape() {
return shape;
}
@Override
public StreamShape inputShape() {
return shape;
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public Sink<T> opWrapSink(int flags, boolean parallel, Sink upstream) {
assertFlags(flags);
return upstream;
}
private void assertFlags(int flags) {
for (StreamOpFlag f : known) {
Assert.assertTrue(f.isKnown(flags),
String.format("Flag %s is not known, but should be known.", f.toString()));
}
for (StreamOpFlag f : preserve) {
Assert.assertTrue(f.isPreserved(flags),
String.format("Flag %s is not preserved, but should be preserved.", f.toString()));
}
for (StreamOpFlag f : notKnown) {
Assert.assertFalse(f.isKnown(flags),
String.format("Flag %s is known, but should be not known.", f.toString()));
}
}
}
# This file identifies root(s) of the test-ng hierarchy.
TestNG.dirs = .
bootclasspath.dirs = .
lib.dirs = /java/util/stream/bootlib
/*
* Copyright (c) 2013, 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.
*/
package java.util.stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PrimitiveIterator;
import java.util.Spliterators;
import java.util.function.Function;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Test
public class DoubleNodeTest extends OpTestCase {
@DataProvider(name = "nodes")
public Object[][] createSizes() {
List<Object[]> params = new ArrayList<>();
for (int size : Arrays.asList(0, 1, 4, 15, 16, 17, 127, 128, 129, 1000)) {
double[] array = new double[size];
for (int i = 0; i < array.length; i++) {
array[i] = i;
}
List<Node<Double>> nodes = new ArrayList<>();
nodes.add(Nodes.node(array));
nodes.add(degenerateTree(Spliterators.iteratorFromSpliterator(Arrays.spliterator(array))));
nodes.add(tree(toList(array), l -> Nodes.node(toDoubleArray(l))));
nodes.add(fill(array, Nodes.doubleBuilder(array.length)));
nodes.add(fill(array, Nodes.doubleBuilder()));
for (Node<Double> node : nodes) {
params.add(new Object[]{array, node});
}
}
return params.toArray(new Object[0][]);
}
private static void assertEqualsListDoubleArray(List<Double> list, double[] array) {
assertEquals(list.size(), array.length);
for (int i = 0; i < array.length; i++)
assertEquals(array[i], list.get(i));
}
private List<Double> toList(double[] a) {
List<Double> l = new ArrayList<>();
for (double i : a) {
l.add(i);
}
return l;
}
private double[] toDoubleArray(List<Double> l) {
double[] a = new double[l.size()];
int i = 0;
for (Double e : l) {
a[i++] = e;
}
return a;
}
private Node.OfDouble fill(double[] array, Node.Builder.OfDouble nb) {
nb.begin(array.length);
for (double i : array)
nb.accept(i);
nb.end();
return nb.build();
}
private Node.OfDouble degenerateTree(PrimitiveIterator.OfDouble it) {
if (!it.hasNext()) {
return Nodes.node(new double[0]);
}
double i = it.nextDouble();
if (it.hasNext()) {
return new Nodes.DoubleConcNode(Nodes.node(new double[] {i}), degenerateTree(it));
}
else {
return Nodes.node(new double[] {i});
}
}
private Node.OfDouble tree(List<Double> l, Function<List<Double>, Node.OfDouble> m) {
if (l.size() < 3) {
return m.apply(l);
}
else {
return new Nodes.DoubleConcNode(
tree(l.subList(0, l.size() / 2), m),
tree(l.subList(l.size() / 2, l.size()), m));
}
}
@Test(dataProvider = "nodes")
public void testAsArray(double[] array, Node.OfDouble n) {
assertEquals(n.asDoubleArray(), array);
}
@Test(dataProvider = "nodes")
public void testFlattenAsArray(double[] array, Node.OfDouble n) {
assertEquals(Nodes.flattenDouble(n).asDoubleArray(), array);
}
@Test(dataProvider = "nodes")
public void testCopyTo(double[] array, Node.OfDouble n) {
double[] copy = new double[(int) n.count()];
n.copyInto(copy, 0);
assertEquals(copy, array);
}
@Test(dataProvider = "nodes", groups = { "serialization-hostile" })
public void testForEach(double[] array, Node.OfDouble n) {
List<Double> l = new ArrayList<>((int) n.count());
n.forEach((double e) -> {
l.add(e);
});
assertEqualsListDoubleArray(l, array);
}
@Test(dataProvider = "nodes")
public void testStreams(double[] array, Node.OfDouble n) {
TestData.OfDouble data = TestData.Factory.ofNode("Node", n);
exerciseOps(data, s -> s);
exerciseTerminalOps(data, s -> s.toArray());
}
@Test(dataProvider = "nodes", groups={ "serialization-hostile" })
// throws SOE on serialization of DoubleConcNode[size=1000]
public void testSpliterator(double[] array, Node.OfDouble n) {
SpliteratorTestHelper.testDoubleSpliterator(n::spliterator);
}
}
/*
* Copyright (c) 2012, 2013, 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.
*/
package java.util.stream;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.function.Supplier;
import static java.util.stream.LambdaTestHelpers.countTo;
@Test
public class FlagOpTest extends OpTestCase {
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
public void testFlagsPassThrough(String name, TestData<Integer, Stream<Integer>> data) {
@SuppressWarnings({"unchecked", "rawtypes"})
TestFlagPassThroughOp<Integer>[] ops = new TestFlagPassThroughOp[3];
ops[0] = new TestFlagPassThroughOp<>();
ops[1] = new TestFlagPassThroughOp<>();
ops[2] = new TestFlagPassThroughOp<>();
ops[0].set(null, ops[1]);
ops[1].set(ops[0], ops[2]);
ops[2].set(ops[1], null);
withData(data).ops(ops).exercise();
}
static class TestFlagPassThroughOp<T> extends FlagDeclaringOp<T> {
TestFlagPassThroughOp<T> upstream;
TestFlagPassThroughOp<T> downstream;
TestFlagPassThroughOp() {
super(0);
}
void set(TestFlagPassThroughOp<T> upstream, TestFlagPassThroughOp<T> downstream) {
this.upstream = upstream;
this.downstream = downstream;
}
int wrapFlags;
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public Sink<T> opWrapSink(int flags, boolean parallel, Sink sink) {
this.wrapFlags = flags;
if (downstream != null) {
assertTrue(flags == downstream.wrapFlags);
}
return sink;
}
}
public void testFlagsClearAllSet() {
int clearAllFlags = 0;
for (StreamOpFlag f : EnumSet.allOf(StreamOpFlag.class)) {
if (f.isStreamFlag()) {
clearAllFlags |= f.clear();
}
}
EnumSet<StreamOpFlag> known = EnumSet.noneOf(StreamOpFlag.class);
EnumSet<StreamOpFlag> notKnown = StreamOpFlagTestHelper.allStreamFlags();
List<FlagDeclaringOp<Integer>> ops = new ArrayList<>();
ops.add(new FlagDeclaringOp<>(clearAllFlags));
for (StreamOpFlag f : StreamOpFlagTestHelper.allStreamFlags()) {
if (f.canSet(StreamOpFlag.Type.OP)) {
ops.add(new TestFlagExpectedOp<>(f.set(),
known.clone(),
EnumSet.noneOf(StreamOpFlag.class),
notKnown.clone()));
known.add(f);
notKnown.remove(f);
}
}
ops.add(new TestFlagExpectedOp<>(0,
known.clone(),
EnumSet.noneOf(StreamOpFlag.class),
notKnown.clone()));
TestData<Integer, Stream<Integer>> data = TestData.Factory.ofArray("Array", countTo(10).toArray(new Integer[0]));
@SuppressWarnings("rawtypes")
FlagDeclaringOp[] opsArray = ops.toArray(new FlagDeclaringOp[ops.size()]);
withData(data).ops(opsArray).
without(StreamTestScenario.PAR_STREAM_TO_ARRAY_CLEAR_SIZED).
exercise();
}
public void testFlagsSetAllClear() {
EnumSet<StreamOpFlag> known = StreamOpFlagTestHelper.allStreamFlags();
int setAllFlags = 0;
for (StreamOpFlag f : EnumSet.allOf(StreamOpFlag.class)) {
if (f.isStreamFlag()) {
if (f.canSet(StreamOpFlag.Type.OP)) {
setAllFlags |= f.set();
} else {
known.remove(f);
}
}
}
EnumSet<StreamOpFlag> notKnown = EnumSet.noneOf(StreamOpFlag.class);
List<FlagDeclaringOp<Integer>> ops = new ArrayList<>();
ops.add(new FlagDeclaringOp<>(setAllFlags));
for (StreamOpFlag f : StreamOpFlagTestHelper.allStreamFlags()) {
ops.add(new TestFlagExpectedOp<>(f.clear(),
known.clone(),
EnumSet.noneOf(StreamOpFlag.class),
notKnown.clone()));
known.remove(f);
notKnown.add(f);
}
ops.add(new TestFlagExpectedOp<>(0,
known.clone(),
EnumSet.noneOf(StreamOpFlag.class),
notKnown.clone()));
TestData<Integer, Stream<Integer>> data = TestData.Factory.ofArray("Array", countTo(10).toArray(new Integer[0]));
@SuppressWarnings("rawtypes")
FlagDeclaringOp[] opsArray = ops.toArray(new FlagDeclaringOp[ops.size()]);
withData(data).ops(opsArray).
without(StreamTestScenario.PAR_STREAM_TO_ARRAY_CLEAR_SIZED).
exercise();
}
public void testFlagsParallelCollect() {
testFlagsSetSequence(CollectorOps::collector);
}
private void testFlagsSetSequence(Supplier<StatefulTestOp<Integer>> cf) {
EnumSet<StreamOpFlag> known = EnumSet.of(StreamOpFlag.ORDERED, StreamOpFlag.SIZED);
EnumSet<StreamOpFlag> preserve = EnumSet.of(StreamOpFlag.DISTINCT, StreamOpFlag.SORTED);
List<IntermediateTestOp<Integer, Integer>> ops = new ArrayList<>();
for (StreamOpFlag f : EnumSet.of(StreamOpFlag.DISTINCT, StreamOpFlag.SORTED)) {
ops.add(cf.get());
ops.add(new TestFlagExpectedOp<>(f.set(),
known.clone(),
preserve.clone(),
EnumSet.noneOf(StreamOpFlag.class)));
known.add(f);
preserve.remove(f);
}
ops.add(cf.get());
ops.add(new TestFlagExpectedOp<>(0,
known.clone(),
preserve.clone(),
EnumSet.noneOf(StreamOpFlag.class)));
TestData<Integer, Stream<Integer>> data = TestData.Factory.ofArray("Array", countTo(10).toArray(new Integer[0]));
@SuppressWarnings("rawtypes")
IntermediateTestOp[] opsArray = ops.toArray(new IntermediateTestOp[ops.size()]);
withData(data).ops(opsArray).
without(StreamTestScenario.PAR_STREAM_TO_ARRAY_CLEAR_SIZED).
exercise();
}
public void testFlagsClearParallelCollect() {
testFlagsClearSequence(CollectorOps::collector);
}
protected void testFlagsClearSequence(Supplier<StatefulTestOp<Integer>> cf) {
EnumSet<StreamOpFlag> known = EnumSet.of(StreamOpFlag.ORDERED, StreamOpFlag.SIZED);
EnumSet<StreamOpFlag> preserve = EnumSet.of(StreamOpFlag.DISTINCT, StreamOpFlag.SORTED);
EnumSet<StreamOpFlag> notKnown = EnumSet.noneOf(StreamOpFlag.class);
List<IntermediateTestOp<Integer, Integer>> ops = new ArrayList<>();
for (StreamOpFlag f : EnumSet.of(StreamOpFlag.ORDERED, StreamOpFlag.DISTINCT, StreamOpFlag.SORTED)) {
ops.add(cf.get());
ops.add(new TestFlagExpectedOp<>(f.clear(),
known.clone(),
preserve.clone(),
notKnown.clone()));
known.remove(f);
preserve.remove(f);
notKnown.add(f);
}
ops.add(cf.get());
ops.add(new TestFlagExpectedOp<>(0,
known.clone(),
preserve.clone(),
notKnown.clone()));
TestData<Integer, Stream<Integer>> data = TestData.Factory.ofArray("Array", countTo(10).toArray(new Integer[0]));
@SuppressWarnings("rawtypes")
IntermediateTestOp[] opsArray = ops.toArray(new IntermediateTestOp[ops.size()]);
withData(data).ops(opsArray).
without(StreamTestScenario.PAR_STREAM_TO_ARRAY_CLEAR_SIZED).
exercise();
}
public void testFlagsSizedOrderedParallelCollect() {
EnumSet<StreamOpFlag> parKnown = EnumSet.of(StreamOpFlag.SIZED);
EnumSet<StreamOpFlag> serKnown = parKnown.clone();
List<IntermediateTestOp<Integer, Integer>> ops = new ArrayList<>();
for (StreamOpFlag f : parKnown) {
ops.add(CollectorOps.collector());
ops.add(new ParSerTestFlagExpectedOp<>(f.clear(),
parKnown,
serKnown));
serKnown.remove(f);
}
ops.add(CollectorOps.collector());
ops.add(new ParSerTestFlagExpectedOp<>(0,
parKnown,
EnumSet.noneOf(StreamOpFlag.class)));
TestData<Integer, Stream<Integer>> data = TestData.Factory.ofArray("Array", countTo(10).toArray(new Integer[0]));
@SuppressWarnings("rawtypes")
IntermediateTestOp[] opsArray = ops.toArray(new IntermediateTestOp[ops.size()]);
withData(data).ops(opsArray).exercise();
}
static class ParSerTestFlagExpectedOp<T> extends FlagDeclaringOp<T> {
final EnumSet<StreamOpFlag> parKnown;
final EnumSet<StreamOpFlag> serKnown;
ParSerTestFlagExpectedOp(int flags, EnumSet<StreamOpFlag> known, EnumSet<StreamOpFlag> serKnown) {
super(flags);
this.parKnown = known;
this.serKnown = serKnown;
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public Sink<T> opWrapSink(int flags, boolean parallel, Sink upstream) {
assertFlags(flags, parallel);
return upstream;
}
protected void assertFlags(int flags, boolean parallel) {
if (parallel) {
for (StreamOpFlag f : parKnown) {
Assert.assertTrue(f.isKnown(flags), String.format("Flag %s is not known, but should be known.", f.toString()));
}
} else {
for (StreamOpFlag f : serKnown) {
Assert.assertTrue(f.isKnown(flags), String.format("Flag %s is not known, but should be known.", f.toString()));
}
}
}
}
}
/*
* Copyright (c) 2012, 2013, 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.
*/
package java.util.stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PrimitiveIterator;
import java.util.Spliterators;
import java.util.function.Function;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Test
public class IntNodeTest extends OpTestCase {
@DataProvider(name = "nodes")
public Object[][] createSizes() {
List<Object[]> params = new ArrayList<>();
for (int size : Arrays.asList(0, 1, 4, 15, 16, 17, 127, 128, 129, 1000)) {
int[] array = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = i;
}
List<Node<Integer>> nodes = new ArrayList<>();
nodes.add(Nodes.node(array));
nodes.add(degenerateTree(Spliterators.iteratorFromSpliterator(Arrays.spliterator(array))));
nodes.add(tree(toList(array), l -> Nodes.node(toIntArray(l))));
nodes.add(fill(array, Nodes.intBuilder(array.length)));
nodes.add(fill(array, Nodes.intBuilder()));
for (Node<Integer> node : nodes) {
params.add(new Object[]{array, node});
}
}
return params.toArray(new Object[0][]);
}
private static void assertEqualsListIntArray(List<Integer> list, int[] array) {
assertEquals(list.size(), array.length);
for (int i = 0; i < array.length; i++)
assertEquals(array[i], (int) list.get(i));
}
private List<Integer> toList(int[] a) {
List<Integer> l = new ArrayList<>();
for (int i : a) {
l.add(i);
}
return l;
}
private int[] toIntArray(List<Integer> l) {
int[] a = new int[l.size()];
int i = 0;
for (Integer e : l) {
a[i++] = e;
}
return a;
}
private Node.OfInt fill(int[] array, Node.Builder.OfInt nb) {
nb.begin(array.length);
for (int i : array)
nb.accept(i);
nb.end();
return nb.build();
}
private Node.OfInt degenerateTree(PrimitiveIterator.OfInt it) {
if (!it.hasNext()) {
return Nodes.node(new int[0]);
}
int i = it.nextInt();
if (it.hasNext()) {
return new Nodes.IntConcNode(Nodes.node(new int[] {i}), degenerateTree(it));
}
else {
return Nodes.node(new int[] {i});
}
}
private Node.OfInt tree(List<Integer> l, Function<List<Integer>, Node.OfInt> m) {
if (l.size() < 3) {
return m.apply(l);
}
else {
return new Nodes.IntConcNode(
tree(l.subList(0, l.size() / 2), m),
tree(l.subList(l.size() / 2, l.size()), m));
}
}
@Test(dataProvider = "nodes")
public void testAsArray(int[] array, Node.OfInt n) {
assertEquals(n.asIntArray(), array);
}
@Test(dataProvider = "nodes")
public void testFlattenAsArray(int[] array, Node.OfInt n) {
assertEquals(Nodes.flattenInt(n).asIntArray(), array);
}
@Test(dataProvider = "nodes")
public void testCopyTo(int[] array, Node.OfInt n) {
int[] copy = new int[(int) n.count()];
n.copyInto(copy, 0);
assertEquals(copy, array);
}
@Test(dataProvider = "nodes", groups = { "serialization-hostile" })
public void testForEach(int[] array, Node.OfInt n) {
List<Integer> l = new ArrayList<>((int) n.count());
n.forEach((int e) -> {
l.add(e);
});
assertEqualsListIntArray(l, array);
}
@Test(dataProvider = "nodes")
public void testStreams(int[] array, Node.OfInt n) {
TestData.OfInt data = TestData.Factory.ofNode("Node", n);
exerciseOps(data, s -> s);
exerciseTerminalOps(data, s -> s.toArray());
}
@Test(dataProvider = "nodes")
public void testSpliterator(int[] array, Node.OfInt n) {
SpliteratorTestHelper.testIntSpliterator(n::spliterator);
}
}
/*
* Copyright (c) 2012, 2013, 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.
*/
package java.util.stream;
import org.testng.annotations.Test;
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.StreamOpFlag;
import java.util.stream.Streams;
import static java.util.stream.StreamOpFlag.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
/**
* StreamFlagsTest
*
* @author Brian Goetz
*/
@Test
public class StreamFlagsTest {
Stream<String> arrayList = new ArrayList<String>().stream();
Stream<String> linkedList = new LinkedList<String>().stream();
Stream<String> hashSet = new HashSet<String>().stream();
Stream<String> treeSet = new TreeSet<String>().stream();
Stream<String> linkedHashSet = new LinkedHashSet<String>().stream();
Stream<String> repeat = Stream.generate(() -> "");
Stream<?>[] streams = { arrayList, linkedList, hashSet, treeSet, linkedHashSet, repeat };
private void assertFlags(int value, EnumSet<StreamOpFlag> setFlags, EnumSet<StreamOpFlag> clearFlags) {
for (StreamOpFlag flag : setFlags)
assertTrue(flag.isKnown(value));
for (StreamOpFlag flag : clearFlags)
assertTrue(!flag.isKnown(value));
}
public void testBaseStreams() {
Stream<String> arrayList = new ArrayList<String>().stream();
Stream<String> linkedList = new LinkedList<String>().stream();
Stream<String> hashSet = new HashSet<String>().stream();
Stream<String> treeSet = new TreeSet<String>().stream();
Stream<String> linkedHashSet = new LinkedHashSet<String>().stream();
Stream<String> repeat = Stream.generate(() -> "");
assertFlags(OpTestCase.getStreamFlags(arrayList),
EnumSet.of(ORDERED, SIZED),
EnumSet.of(DISTINCT, SORTED, SHORT_CIRCUIT));
assertFlags(OpTestCase.getStreamFlags(linkedList),
EnumSet.of(ORDERED, SIZED),
EnumSet.of(DISTINCT, SORTED, SHORT_CIRCUIT));
assertFlags(OpTestCase.getStreamFlags(hashSet),
EnumSet.of(SIZED, DISTINCT),
EnumSet.of(ORDERED, SORTED, SHORT_CIRCUIT));
assertFlags(OpTestCase.getStreamFlags(treeSet),
EnumSet.of(ORDERED, SIZED, DISTINCT, SORTED),
EnumSet.of(SHORT_CIRCUIT));
assertFlags(OpTestCase.getStreamFlags(linkedHashSet),
EnumSet.of(ORDERED, DISTINCT, SIZED),
EnumSet.of(SORTED, SHORT_CIRCUIT));
assertFlags(OpTestCase.getStreamFlags(repeat),
EnumSet.of(ORDERED),
EnumSet.of(SIZED, DISTINCT, SORTED, SHORT_CIRCUIT));
}
public void testFilter() {
for (Stream<?> s : streams) {
int baseFlags = OpTestCase.getStreamFlags(s);
int filteredFlags = OpTestCase.getStreamFlags(s.filter((Object e) -> true));
int expectedFlags = baseFlags & ~SIZED.set();
assertEquals(filteredFlags, expectedFlags);
}
}
}
# This file identifies root(s) of the test-ng hierarchy.
TestNG.dirs = .
lib.dirs = /java/util/stream/bootlib
# Tests that must run in othervm mode
othervm.dirs= /java/util/stream
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册