1 /*
2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 package java.util.stream;
26 
27 import java.util.Objects;
28 import java.util.Spliterator;
29 import java.util.function.IntFunction;
30 import java.util.function.Supplier;
31 
32 /**
33  * Abstract base class for "pipeline" classes, which are the core
34  * implementations of the Stream interface and its primitive specializations.
35  * Manages construction and evaluation of stream pipelines.
36  *
37  * <p>An {@code AbstractPipeline} represents an initial portion of a stream
38  * pipeline, encapsulating a stream source and zero or more intermediate
39  * operations.  The individual {@code AbstractPipeline} objects are often
40  * referred to as <em>stages</em>, where each stage describes either the stream
41  * source or an intermediate operation.
42  *
43  * <p>A concrete intermediate stage is generally built from an
44  * {@code AbstractPipeline}, a shape-specific pipeline class which extends it
45  * (e.g., {@code IntPipeline}) which is also abstract, and an operation-specific
46  * concrete class which extends that.  {@code AbstractPipeline} contains most of
47  * the mechanics of evaluating the pipeline, and implements methods that will be
48  * used by the operation; the shape-specific classes add helper methods for
49  * dealing with collection of results into the appropriate shape-specific
50  * containers.
51  *
52  * <p>After chaining a new intermediate operation, or executing a terminal
53  * operation, the stream is considered to be consumed, and no more intermediate
54  * or terminal operations are permitted on this stream instance.
55  *
56  * @implNote
57  * <p>For sequential streams, and parallel streams without
58  * <a href="package-summary.html#StreamOps">stateful intermediate
59  * operations</a>, parallel streams, pipeline evaluation is done in a single
60  * pass that "jams" all the operations together.  For parallel streams with
61  * stateful operations, execution is divided into segments, where each
62  * stateful operations marks the end of a segment, and each segment is
63  * evaluated separately and the result used as the input to the next
64  * segment.  In all cases, the source data is not consumed until a terminal
65  * operation begins.
66  *
67  * @param <E_IN>  type of input elements
68  * @param <E_OUT> type of output elements
69  * @param <S> type of the subclass implementing {@code BaseStream}
70  * @since 1.8
71  * @hide Made public for CTS tests only (OpenJDK 8 streams tests).
72  */
73 // Android-changed: Made public for CTS tests only.
74 public abstract class AbstractPipeline<E_IN, E_OUT, S extends BaseStream<E_OUT, S>>
75         extends PipelineHelper<E_OUT> implements BaseStream<E_OUT, S> {
76     private static final String MSG_STREAM_LINKED = "stream has already been operated upon or closed";
77     private static final String MSG_CONSUMED = "source already consumed or closed";
78 
79     /**
80      * Backlink to the head of the pipeline chain (self if this is the source
81      * stage).
82      */
83     @SuppressWarnings("rawtypes")
84     private final AbstractPipeline sourceStage;
85 
86     /**
87      * The "upstream" pipeline, or null if this is the source stage.
88      */
89     @SuppressWarnings("rawtypes")
90     private final AbstractPipeline previousStage;
91 
92     /**
93      * The operation flags for the intermediate operation represented by this
94      * pipeline object.
95      */
96     protected final int sourceOrOpFlags;
97 
98     /**
99      * The next stage in the pipeline, or null if this is the last stage.
100      * Effectively final at the point of linking to the next pipeline.
101      */
102     @SuppressWarnings("rawtypes")
103     private AbstractPipeline nextStage;
104 
105     /**
106      * The number of intermediate operations between this pipeline object
107      * and the stream source if sequential, or the previous stateful if parallel.
108      * Valid at the point of pipeline preparation for evaluation.
109      */
110     private int depth;
111 
112     /**
113      * The combined source and operation flags for the source and all operations
114      * up to and including the operation represented by this pipeline object.
115      * Valid at the point of pipeline preparation for evaluation.
116      */
117     private int combinedFlags;
118 
119     /**
120      * The source spliterator. Only valid for the head pipeline.
121      * Before the pipeline is consumed if non-null then {@code sourceSupplier}
122      * must be null. After the pipeline is consumed if non-null then is set to
123      * null.
124      */
125     private Spliterator<?> sourceSpliterator;
126 
127     /**
128      * The source supplier. Only valid for the head pipeline. Before the
129      * pipeline is consumed if non-null then {@code sourceSpliterator} must be
130      * null. After the pipeline is consumed if non-null then is set to null.
131      */
132     private Supplier<? extends Spliterator<?>> sourceSupplier;
133 
134     /**
135      * True if this pipeline has been linked or consumed
136      */
137     private boolean linkedOrConsumed;
138 
139     /**
140      * True if there are any stateful ops in the pipeline; only valid for the
141      * source stage.
142      */
143     private boolean sourceAnyStateful;
144 
145     private Runnable sourceCloseAction;
146 
147     /**
148      * True if pipeline is parallel, otherwise the pipeline is sequential; only
149      * valid for the source stage.
150      */
151     private boolean parallel;
152 
153     /**
154      * Constructor for the head of a stream pipeline.
155      *
156      * @param source {@code Supplier<Spliterator>} describing the stream source
157      * @param sourceFlags The source flags for the stream source, described in
158      * {@link StreamOpFlag}
159      * @param parallel True if the pipeline is parallel
160      */
AbstractPipeline(Supplier<? extends Spliterator<?>> source, int sourceFlags, boolean parallel)161     AbstractPipeline(Supplier<? extends Spliterator<?>> source,
162                      int sourceFlags, boolean parallel) {
163         this.previousStage = null;
164         this.sourceSupplier = source;
165         this.sourceStage = this;
166         this.sourceOrOpFlags = sourceFlags & StreamOpFlag.STREAM_MASK;
167         // The following is an optimization of:
168         // StreamOpFlag.combineOpFlags(sourceOrOpFlags, StreamOpFlag.INITIAL_OPS_VALUE);
169         this.combinedFlags = (~(sourceOrOpFlags << 1)) & StreamOpFlag.INITIAL_OPS_VALUE;
170         this.depth = 0;
171         this.parallel = parallel;
172     }
173 
174     /**
175      * Constructor for the head of a stream pipeline.
176      *
177      * @param source {@code Spliterator} describing the stream source
178      * @param sourceFlags the source flags for the stream source, described in
179      * {@link StreamOpFlag}
180      * @param parallel {@code true} if the pipeline is parallel
181      */
AbstractPipeline(Spliterator<?> source, int sourceFlags, boolean parallel)182     AbstractPipeline(Spliterator<?> source,
183                      int sourceFlags, boolean parallel) {
184         this.previousStage = null;
185         this.sourceSpliterator = source;
186         this.sourceStage = this;
187         this.sourceOrOpFlags = sourceFlags & StreamOpFlag.STREAM_MASK;
188         // The following is an optimization of:
189         // StreamOpFlag.combineOpFlags(sourceOrOpFlags, StreamOpFlag.INITIAL_OPS_VALUE);
190         this.combinedFlags = (~(sourceOrOpFlags << 1)) & StreamOpFlag.INITIAL_OPS_VALUE;
191         this.depth = 0;
192         this.parallel = parallel;
193     }
194 
195     /**
196      * Constructor for appending an intermediate operation stage onto an
197      * existing pipeline.
198      *
199      * @param previousStage the upstream pipeline stage
200      * @param opFlags the operation flags for the new stage, described in
201      * {@link StreamOpFlag}
202      */
AbstractPipeline(AbstractPipeline<?, E_IN, ?> previousStage, int opFlags)203     AbstractPipeline(AbstractPipeline<?, E_IN, ?> previousStage, int opFlags) {
204         if (previousStage.linkedOrConsumed)
205             throw new IllegalStateException(MSG_STREAM_LINKED);
206         previousStage.linkedOrConsumed = true;
207         previousStage.nextStage = this;
208 
209         this.previousStage = previousStage;
210         this.sourceOrOpFlags = opFlags & StreamOpFlag.OP_MASK;
211         this.combinedFlags = StreamOpFlag.combineOpFlags(opFlags, previousStage.combinedFlags);
212         this.sourceStage = previousStage.sourceStage;
213         if (opIsStateful())
214             sourceStage.sourceAnyStateful = true;
215         this.depth = previousStage.depth + 1;
216     }
217 
218 
219     // Terminal evaluation methods
220 
221     /**
222      * Evaluate the pipeline with a terminal operation to produce a result.
223      *
224      * @param <R> the type of result
225      * @param terminalOp the terminal operation to be applied to the pipeline.
226      * @return the result
227      */
evaluate(TerminalOp<E_OUT, R> terminalOp)228     final <R> R evaluate(TerminalOp<E_OUT, R> terminalOp) {
229         assert getOutputShape() == terminalOp.inputShape();
230         if (linkedOrConsumed)
231             throw new IllegalStateException(MSG_STREAM_LINKED);
232         linkedOrConsumed = true;
233 
234         return isParallel()
235                ? terminalOp.evaluateParallel(this, sourceSpliterator(terminalOp.getOpFlags()))
236                : terminalOp.evaluateSequential(this, sourceSpliterator(terminalOp.getOpFlags()));
237     }
238 
239     /**
240      * Collect the elements output from the pipeline stage.
241      *
242      * @param generator the array generator to be used to create array instances
243      * @return a flat array-backed Node that holds the collected output elements
244      */
245     @SuppressWarnings("unchecked")
246     // Android-changed: Made public for CTS tests only.
evaluateToArrayNode(IntFunction<E_OUT[]> generator)247     public final Node<E_OUT> evaluateToArrayNode(IntFunction<E_OUT[]> generator) {
248         if (linkedOrConsumed)
249             throw new IllegalStateException(MSG_STREAM_LINKED);
250         linkedOrConsumed = true;
251 
252         // If the last intermediate operation is stateful then
253         // evaluate directly to avoid an extra collection step
254         if (isParallel() && previousStage != null && opIsStateful()) {
255             // Set the depth of this, last, pipeline stage to zero to slice the
256             // pipeline such that this operation will not be included in the
257             // upstream slice and upstream operations will not be included
258             // in this slice
259             depth = 0;
260             return opEvaluateParallel(previousStage, previousStage.sourceSpliterator(0), generator);
261         }
262         else {
263             return evaluate(sourceSpliterator(0), true, generator);
264         }
265     }
266 
267     /**
268      * Gets the source stage spliterator if this pipeline stage is the source
269      * stage.  The pipeline is consumed after this method is called and
270      * returns successfully.
271      *
272      * @return the source stage spliterator
273      * @throws IllegalStateException if this pipeline stage is not the source
274      *         stage.
275      */
276     @SuppressWarnings("unchecked")
sourceStageSpliterator()277     final Spliterator<E_OUT> sourceStageSpliterator() {
278         if (this != sourceStage)
279             throw new IllegalStateException();
280 
281         if (linkedOrConsumed)
282             throw new IllegalStateException(MSG_STREAM_LINKED);
283         linkedOrConsumed = true;
284 
285         if (sourceStage.sourceSpliterator != null) {
286             @SuppressWarnings("unchecked")
287             Spliterator<E_OUT> s = sourceStage.sourceSpliterator;
288             sourceStage.sourceSpliterator = null;
289             return s;
290         }
291         else if (sourceStage.sourceSupplier != null) {
292             @SuppressWarnings("unchecked")
293             Spliterator<E_OUT> s = (Spliterator<E_OUT>) sourceStage.sourceSupplier.get();
294             sourceStage.sourceSupplier = null;
295             return s;
296         }
297         else {
298             throw new IllegalStateException(MSG_CONSUMED);
299         }
300     }
301 
302     // BaseStream
303 
304     @Override
305     @SuppressWarnings("unchecked")
sequential()306     public final S sequential() {
307         sourceStage.parallel = false;
308         return (S) this;
309     }
310 
311     @Override
312     @SuppressWarnings("unchecked")
parallel()313     public final S parallel() {
314         sourceStage.parallel = true;
315         return (S) this;
316     }
317 
318     @Override
close()319     public void close() {
320         linkedOrConsumed = true;
321         sourceSupplier = null;
322         sourceSpliterator = null;
323         if (sourceStage.sourceCloseAction != null) {
324             Runnable closeAction = sourceStage.sourceCloseAction;
325             sourceStage.sourceCloseAction = null;
326             closeAction.run();
327         }
328     }
329 
330     @Override
331     @SuppressWarnings("unchecked")
onClose(Runnable closeHandler)332     public S onClose(Runnable closeHandler) {
333         Runnable existingHandler = sourceStage.sourceCloseAction;
334         sourceStage.sourceCloseAction =
335                 (existingHandler == null)
336                 ? closeHandler
337                 : Streams.composeWithExceptions(existingHandler, closeHandler);
338         return (S) this;
339     }
340 
341     // Primitive specialization use co-variant overrides, hence is not final
342     @Override
343     @SuppressWarnings("unchecked")
spliterator()344     public Spliterator<E_OUT> spliterator() {
345         if (linkedOrConsumed)
346             throw new IllegalStateException(MSG_STREAM_LINKED);
347         linkedOrConsumed = true;
348 
349         if (this == sourceStage) {
350             if (sourceStage.sourceSpliterator != null) {
351                 @SuppressWarnings("unchecked")
352                 Spliterator<E_OUT> s = (Spliterator<E_OUT>) sourceStage.sourceSpliterator;
353                 sourceStage.sourceSpliterator = null;
354                 return s;
355             }
356             else if (sourceStage.sourceSupplier != null) {
357                 @SuppressWarnings("unchecked")
358                 Supplier<Spliterator<E_OUT>> s = (Supplier<Spliterator<E_OUT>>) sourceStage.sourceSupplier;
359                 sourceStage.sourceSupplier = null;
360                 return lazySpliterator(s);
361             }
362             else {
363                 throw new IllegalStateException(MSG_CONSUMED);
364             }
365         }
366         else {
367             return wrap(this, () -> sourceSpliterator(0), isParallel());
368         }
369     }
370 
371     @Override
isParallel()372     public final boolean isParallel() {
373         return sourceStage.parallel;
374     }
375 
376 
377     /**
378      * Returns the composition of stream flags of the stream source and all
379      * intermediate operations.
380      *
381      * @return the composition of stream flags of the stream source and all
382      *         intermediate operations
383      * @see StreamOpFlag
384      */
385     // Android-changed: Made public for CTS tests only.
getStreamFlags()386     public final int getStreamFlags() {
387         return StreamOpFlag.toStreamFlags(combinedFlags);
388     }
389 
390     /**
391      * Get the source spliterator for this pipeline stage.  For a sequential or
392      * stateless parallel pipeline, this is the source spliterator.  For a
393      * stateful parallel pipeline, this is a spliterator describing the results
394      * of all computations up to and including the most recent stateful
395      * operation.
396      */
397     @SuppressWarnings("unchecked")
sourceSpliterator(int terminalFlags)398     private Spliterator<?> sourceSpliterator(int terminalFlags) {
399         // Get the source spliterator of the pipeline
400         Spliterator<?> spliterator = null;
401         if (sourceStage.sourceSpliterator != null) {
402             spliterator = sourceStage.sourceSpliterator;
403             sourceStage.sourceSpliterator = null;
404         }
405         else if (sourceStage.sourceSupplier != null) {
406             spliterator = (Spliterator<?>) sourceStage.sourceSupplier.get();
407             sourceStage.sourceSupplier = null;
408         }
409         else {
410             throw new IllegalStateException(MSG_CONSUMED);
411         }
412 
413         if (isParallel() && sourceStage.sourceAnyStateful) {
414             // Adapt the source spliterator, evaluating each stateful op
415             // in the pipeline up to and including this pipeline stage.
416             // The depth and flags of each pipeline stage are adjusted accordingly.
417             int depth = 1;
418             for (@SuppressWarnings("rawtypes") AbstractPipeline u = sourceStage, p = sourceStage.nextStage, e = this;
419                  u != e;
420                  u = p, p = p.nextStage) {
421 
422                 int thisOpFlags = p.sourceOrOpFlags;
423                 if (p.opIsStateful()) {
424                     depth = 0;
425 
426                     if (StreamOpFlag.SHORT_CIRCUIT.isKnown(thisOpFlags)) {
427                         // Clear the short circuit flag for next pipeline stage
428                         // This stage encapsulates short-circuiting, the next
429                         // stage may not have any short-circuit operations, and
430                         // if so spliterator.forEachRemaining should be used
431                         // for traversal
432                         thisOpFlags = thisOpFlags & ~StreamOpFlag.IS_SHORT_CIRCUIT;
433                     }
434 
435                     spliterator = p.opEvaluateParallelLazy(u, spliterator);
436 
437                     // Inject or clear SIZED on the source pipeline stage
438                     // based on the stage's spliterator
439                     thisOpFlags = spliterator.hasCharacteristics(Spliterator.SIZED)
440                             ? (thisOpFlags & ~StreamOpFlag.NOT_SIZED) | StreamOpFlag.IS_SIZED
441                             : (thisOpFlags & ~StreamOpFlag.IS_SIZED) | StreamOpFlag.NOT_SIZED;
442                 }
443                 p.depth = depth++;
444                 p.combinedFlags = StreamOpFlag.combineOpFlags(thisOpFlags, u.combinedFlags);
445             }
446         }
447 
448         if (terminalFlags != 0)  {
449             // Apply flags from the terminal operation to last pipeline stage
450             combinedFlags = StreamOpFlag.combineOpFlags(terminalFlags, combinedFlags);
451         }
452 
453         return spliterator;
454     }
455 
456     // PipelineHelper
457 
458     @Override
getSourceShape()459     final StreamShape getSourceShape() {
460         @SuppressWarnings("rawtypes")
461         AbstractPipeline p = AbstractPipeline.this;
462         while (p.depth > 0) {
463             p = p.previousStage;
464         }
465         return p.getOutputShape();
466     }
467 
468     @Override
exactOutputSizeIfKnown(Spliterator<P_IN> spliterator)469     final <P_IN> long exactOutputSizeIfKnown(Spliterator<P_IN> spliterator) {
470         return StreamOpFlag.SIZED.isKnown(getStreamAndOpFlags()) ? spliterator.getExactSizeIfKnown() : -1;
471     }
472 
473     @Override
wrapAndCopyInto(S sink, Spliterator<P_IN> spliterator)474     final <P_IN, S extends Sink<E_OUT>> S wrapAndCopyInto(S sink, Spliterator<P_IN> spliterator) {
475         copyInto(wrapSink(Objects.requireNonNull(sink)), spliterator);
476         return sink;
477     }
478 
479     @Override
copyInto(Sink<P_IN> wrappedSink, Spliterator<P_IN> spliterator)480     final <P_IN> void copyInto(Sink<P_IN> wrappedSink, Spliterator<P_IN> spliterator) {
481         Objects.requireNonNull(wrappedSink);
482 
483         if (!StreamOpFlag.SHORT_CIRCUIT.isKnown(getStreamAndOpFlags())) {
484             wrappedSink.begin(spliterator.getExactSizeIfKnown());
485             spliterator.forEachRemaining(wrappedSink);
486             wrappedSink.end();
487         }
488         else {
489             copyIntoWithCancel(wrappedSink, spliterator);
490         }
491     }
492 
493     @Override
494     @SuppressWarnings("unchecked")
copyIntoWithCancel(Sink<P_IN> wrappedSink, Spliterator<P_IN> spliterator)495     final <P_IN> void copyIntoWithCancel(Sink<P_IN> wrappedSink, Spliterator<P_IN> spliterator) {
496         @SuppressWarnings({"rawtypes","unchecked"})
497         AbstractPipeline p = AbstractPipeline.this;
498         while (p.depth > 0) {
499             p = p.previousStage;
500         }
501         wrappedSink.begin(spliterator.getExactSizeIfKnown());
502         p.forEachWithCancel(spliterator, wrappedSink);
503         wrappedSink.end();
504     }
505 
506     @Override
507     // Android-changed: Made public for CTS tests only.
getStreamAndOpFlags()508     public final int getStreamAndOpFlags() {
509         return combinedFlags;
510     }
511 
isOrdered()512     final boolean isOrdered() {
513         return StreamOpFlag.ORDERED.isKnown(combinedFlags);
514     }
515 
516     @Override
517     @SuppressWarnings("unchecked")
518     // Android-changed: Made public for CTS tests only.
wrapSink(Sink<E_OUT> sink)519     public final <P_IN> Sink<P_IN> wrapSink(Sink<E_OUT> sink) {
520         Objects.requireNonNull(sink);
521 
522         for ( @SuppressWarnings("rawtypes") AbstractPipeline p=AbstractPipeline.this; p.depth > 0; p=p.previousStage) {
523             sink = p.opWrapSink(p.previousStage.combinedFlags, sink);
524         }
525         return (Sink<P_IN>) sink;
526     }
527 
528     @Override
529     @SuppressWarnings("unchecked")
wrapSpliterator(Spliterator<P_IN> sourceSpliterator)530     final <P_IN> Spliterator<E_OUT> wrapSpliterator(Spliterator<P_IN> sourceSpliterator) {
531         if (depth == 0) {
532             return (Spliterator<E_OUT>) sourceSpliterator;
533         }
534         else {
535             return wrap(this, () -> sourceSpliterator, isParallel());
536         }
537     }
538 
539     @Override
540     @SuppressWarnings("unchecked")
541     // Android-changed: Made public for CTS tests only.
evaluate(Spliterator<P_IN> spliterator, boolean flatten, IntFunction<E_OUT[]> generator)542     public final <P_IN> Node<E_OUT> evaluate(Spliterator<P_IN> spliterator,
543                                       boolean flatten,
544                                       IntFunction<E_OUT[]> generator) {
545         if (isParallel()) {
546             // @@@ Optimize if op of this pipeline stage is a stateful op
547             return evaluateToNode(this, spliterator, flatten, generator);
548         }
549         else {
550             Node.Builder<E_OUT> nb = makeNodeBuilder(
551                     exactOutputSizeIfKnown(spliterator), generator);
552             return wrapAndCopyInto(nb, spliterator).build();
553         }
554     }
555 
556 
557     // Shape-specific abstract methods, implemented by XxxPipeline classes
558 
559     /**
560      * Get the output shape of the pipeline.  If the pipeline is the head,
561      * then it's output shape corresponds to the shape of the source.
562      * Otherwise, it's output shape corresponds to the output shape of the
563      * associated operation.
564      *
565      * @return the output shape
566      */
567     // Android-changed: Made public for CTS tests only.
getOutputShape()568     public abstract StreamShape getOutputShape();
569 
570     /**
571      * Collect elements output from a pipeline into a Node that holds elements
572      * of this shape.
573      *
574      * @param helper the pipeline helper describing the pipeline stages
575      * @param spliterator the source spliterator
576      * @param flattenTree true if the returned node should be flattened
577      * @param generator the array generator
578      * @return a Node holding the output of the pipeline
579      */
580     // Android-changed: Made public for CTS tests only.
evaluateToNode(PipelineHelper<E_OUT> helper, Spliterator<P_IN> spliterator, boolean flattenTree, IntFunction<E_OUT[]> generator)581     public abstract <P_IN> Node<E_OUT> evaluateToNode(PipelineHelper<E_OUT> helper,
582                                                       Spliterator<P_IN> spliterator,
583                                                       boolean flattenTree,
584                                                       IntFunction<E_OUT[]> generator);
585 
586     /**
587      * Create a spliterator that wraps a source spliterator, compatible with
588      * this stream shape, and operations associated with a {@link
589      * PipelineHelper}.
590      *
591      * @param ph the pipeline helper describing the pipeline stages
592      * @param supplier the supplier of a spliterator
593      * @return a wrapping spliterator compatible with this shape
594      */
595     // Android-changed: Made public for CTS tests only.
wrap(PipelineHelper<E_OUT> ph, Supplier<Spliterator<P_IN>> supplier, boolean isParallel)596     public abstract <P_IN> Spliterator<E_OUT> wrap(PipelineHelper<E_OUT> ph,
597                                                    Supplier<Spliterator<P_IN>> supplier,
598                                                    boolean isParallel);
599 
600     /**
601      * Create a lazy spliterator that wraps and obtains the supplied the
602      * spliterator when a method is invoked on the lazy spliterator.
603      * @param supplier the supplier of a spliterator
604      */
605     // Android-changed: Made public for CTS tests only.
lazySpliterator(Supplier<? extends Spliterator<E_OUT>> supplier)606     public abstract Spliterator<E_OUT> lazySpliterator(Supplier<? extends Spliterator<E_OUT>> supplier);
607 
608     /**
609      * Traverse the elements of a spliterator compatible with this stream shape,
610      * pushing those elements into a sink.   If the sink requests cancellation,
611      * no further elements will be pulled or pushed.
612      *
613      * @param spliterator the spliterator to pull elements from
614      * @param sink the sink to push elements to
615      */
616     // Android-changed: Made public for CTS tests only.
forEachWithCancel(Spliterator<E_OUT> spliterator, Sink<E_OUT> sink)617     public abstract void forEachWithCancel(Spliterator<E_OUT> spliterator, Sink<E_OUT> sink);
618 
619     /**
620      * Make a node builder compatible with this stream shape.
621      *
622      * @param exactSizeIfKnown if {@literal >=0}, then a node builder will be
623      * created that has a fixed capacity of at most sizeIfKnown elements. If
624      * {@literal < 0}, then the node builder has an unfixed capacity. A fixed
625      * capacity node builder will throw exceptions if an element is added after
626      * builder has reached capacity, or is built before the builder has reached
627      * capacity.
628      *
629      * @param generator the array generator to be used to create instances of a
630      * T[] array. For implementations supporting primitive nodes, this parameter
631      * may be ignored.
632      * @return a node builder
633      */
634     @Override
635     // Android-changed: Made public for CTS tests only.
makeNodeBuilder(long exactSizeIfKnown, IntFunction<E_OUT[]> generator)636     public abstract Node.Builder<E_OUT> makeNodeBuilder(long exactSizeIfKnown,
637                                                         IntFunction<E_OUT[]> generator);
638 
639 
640     // Op-specific abstract methods, implemented by the operation class
641 
642     /**
643      * Returns whether this operation is stateful or not.  If it is stateful,
644      * then the method
645      * {@link #opEvaluateParallel(PipelineHelper, java.util.Spliterator, java.util.function.IntFunction)}
646      * must be overridden.
647      *
648      * @return {@code true} if this operation is stateful
649      */
650     // Android-changed: Made public for CTS tests only.
opIsStateful()651     public abstract boolean opIsStateful();
652 
653     /**
654      * Accepts a {@code Sink} which will receive the results of this operation,
655      * and return a {@code Sink} which accepts elements of the input type of
656      * this operation and which performs the operation, passing the results to
657      * the provided {@code Sink}.
658      *
659      * @apiNote
660      * The implementation may use the {@code flags} parameter to optimize the
661      * sink wrapping.  For example, if the input is already {@code DISTINCT},
662      * the implementation for the {@code Stream#distinct()} method could just
663      * return the sink it was passed.
664      *
665      * @param flags The combined stream and operation flags up to, but not
666      *        including, this operation
667      * @param sink sink to which elements should be sent after processing
668      * @return a sink which accepts elements, perform the operation upon
669      *         each element, and passes the results (if any) to the provided
670      *         {@code Sink}.
671      */
672     // Android-changed: Made public for CTS tests only.
opWrapSink(int flags, Sink<E_OUT> sink)673     public abstract Sink<E_IN> opWrapSink(int flags, Sink<E_OUT> sink);
674 
675     /**
676      * Performs a parallel evaluation of the operation using the specified
677      * {@code PipelineHelper} which describes the upstream intermediate
678      * operations.  Only called on stateful operations.  If {@link
679      * #opIsStateful()} returns true then implementations must override the
680      * default implementation.
681      *
682      * @implSpec The default implementation always throw
683      * {@code UnsupportedOperationException}.
684      *
685      * @param helper the pipeline helper describing the pipeline stages
686      * @param spliterator the source {@code Spliterator}
687      * @param generator the array generator
688      * @return a {@code Node} describing the result of the evaluation
689      */
690     // Android-changed: Made public for CTS tests only.
opEvaluateParallel(PipelineHelper<E_OUT> helper, Spliterator<P_IN> spliterator, IntFunction<E_OUT[]> generator)691     public <P_IN> Node<E_OUT> opEvaluateParallel(PipelineHelper<E_OUT> helper,
692                                           Spliterator<P_IN> spliterator,
693                                           IntFunction<E_OUT[]> generator) {
694         throw new UnsupportedOperationException("Parallel evaluation is not supported");
695     }
696 
697     /**
698      * Returns a {@code Spliterator} describing a parallel evaluation of the
699      * operation, using the specified {@code PipelineHelper} which describes the
700      * upstream intermediate operations.  Only called on stateful operations.
701      * It is not necessary (though acceptable) to do a full computation of the
702      * result here; it is preferable, if possible, to describe the result via a
703      * lazily evaluated spliterator.
704      *
705      * @implSpec The default implementation behaves as if:
706      * <pre>{@code
707      *     return evaluateParallel(helper, i -> (E_OUT[]) new
708      * Object[i]).spliterator();
709      * }</pre>
710      * and is suitable for implementations that cannot do better than a full
711      * synchronous evaluation.
712      *
713      * @param helper the pipeline helper
714      * @param spliterator the source {@code Spliterator}
715      * @return a {@code Spliterator} describing the result of the evaluation
716      */
717     @SuppressWarnings("unchecked")
718     // Android-changed: Made public for CTS tests only.
opEvaluateParallelLazy(PipelineHelper<E_OUT> helper, Spliterator<P_IN> spliterator)719     public <P_IN> Spliterator<E_OUT> opEvaluateParallelLazy(PipelineHelper<E_OUT> helper,
720                                                      Spliterator<P_IN> spliterator) {
721         return opEvaluateParallel(helper, spliterator, i -> (E_OUT[]) new Object[i]).spliterator();
722     }
723 }
724