1 /*
2  * Copyright (c) 2012, 2021, 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         if (linkedOrConsumed)
334             throw new IllegalStateException(MSG_STREAM_LINKED);
335         Objects.requireNonNull(closeHandler);
336         Runnable existingHandler = sourceStage.sourceCloseAction;
337         sourceStage.sourceCloseAction =
338                 (existingHandler == null)
339                 ? closeHandler
340                 : Streams.composeWithExceptions(existingHandler, closeHandler);
341         return (S) this;
342     }
343 
344     // Primitive specialization use co-variant overrides, hence is not final
345     @Override
346     @SuppressWarnings("unchecked")
spliterator()347     public Spliterator<E_OUT> spliterator() {
348         if (linkedOrConsumed)
349             throw new IllegalStateException(MSG_STREAM_LINKED);
350         linkedOrConsumed = true;
351 
352         if (this == sourceStage) {
353             if (sourceStage.sourceSpliterator != null) {
354                 @SuppressWarnings("unchecked")
355                 Spliterator<E_OUT> s = (Spliterator<E_OUT>) sourceStage.sourceSpliterator;
356                 sourceStage.sourceSpliterator = null;
357                 return s;
358             }
359             else if (sourceStage.sourceSupplier != null) {
360                 @SuppressWarnings("unchecked")
361                 Supplier<Spliterator<E_OUT>> s = (Supplier<Spliterator<E_OUT>>) sourceStage.sourceSupplier;
362                 sourceStage.sourceSupplier = null;
363                 return lazySpliterator(s);
364             }
365             else {
366                 throw new IllegalStateException(MSG_CONSUMED);
367             }
368         }
369         else {
370             return wrap(this, () -> sourceSpliterator(0), isParallel());
371         }
372     }
373 
374     @Override
isParallel()375     public final boolean isParallel() {
376         return sourceStage.parallel;
377     }
378 
379 
380     /**
381      * Returns the composition of stream flags of the stream source and all
382      * intermediate operations.
383      *
384      * @return the composition of stream flags of the stream source and all
385      *         intermediate operations
386      * @see StreamOpFlag
387      */
388     // Android-changed: Made public for CTS tests only.
getStreamFlags()389     public final int getStreamFlags() {
390         return StreamOpFlag.toStreamFlags(combinedFlags);
391     }
392 
393     /**
394      * Get the source spliterator for this pipeline stage.  For a sequential or
395      * stateless parallel pipeline, this is the source spliterator.  For a
396      * stateful parallel pipeline, this is a spliterator describing the results
397      * of all computations up to and including the most recent stateful
398      * operation.
399      */
400     @SuppressWarnings("unchecked")
sourceSpliterator(int terminalFlags)401     private Spliterator<?> sourceSpliterator(int terminalFlags) {
402         // Get the source spliterator of the pipeline
403         Spliterator<?> spliterator = null;
404         if (sourceStage.sourceSpliterator != null) {
405             spliterator = sourceStage.sourceSpliterator;
406             sourceStage.sourceSpliterator = null;
407         }
408         else if (sourceStage.sourceSupplier != null) {
409             spliterator = (Spliterator<?>) sourceStage.sourceSupplier.get();
410             sourceStage.sourceSupplier = null;
411         }
412         else {
413             throw new IllegalStateException(MSG_CONSUMED);
414         }
415 
416         if (isParallel() && sourceStage.sourceAnyStateful) {
417             // Adapt the source spliterator, evaluating each stateful op
418             // in the pipeline up to and including this pipeline stage.
419             // The depth and flags of each pipeline stage are adjusted accordingly.
420             int depth = 1;
421             for (@SuppressWarnings("rawtypes") AbstractPipeline u = sourceStage, p = sourceStage.nextStage, e = this;
422                  u != e;
423                  u = p, p = p.nextStage) {
424 
425                 int thisOpFlags = p.sourceOrOpFlags;
426                 if (p.opIsStateful()) {
427                     depth = 0;
428 
429                     if (StreamOpFlag.SHORT_CIRCUIT.isKnown(thisOpFlags)) {
430                         // Clear the short circuit flag for next pipeline stage
431                         // This stage encapsulates short-circuiting, the next
432                         // stage may not have any short-circuit operations, and
433                         // if so spliterator.forEachRemaining should be used
434                         // for traversal
435                         thisOpFlags = thisOpFlags & ~StreamOpFlag.IS_SHORT_CIRCUIT;
436                     }
437 
438                     spliterator = p.opEvaluateParallelLazy(u, spliterator);
439 
440                     // Inject or clear SIZED on the source pipeline stage
441                     // based on the stage's spliterator
442                     thisOpFlags = spliterator.hasCharacteristics(Spliterator.SIZED)
443                             ? (thisOpFlags & ~StreamOpFlag.NOT_SIZED) | StreamOpFlag.IS_SIZED
444                             : (thisOpFlags & ~StreamOpFlag.IS_SIZED) | StreamOpFlag.NOT_SIZED;
445                 }
446                 p.depth = depth++;
447                 p.combinedFlags = StreamOpFlag.combineOpFlags(thisOpFlags, u.combinedFlags);
448             }
449         }
450 
451         if (terminalFlags != 0)  {
452             // Apply flags from the terminal operation to last pipeline stage
453             combinedFlags = StreamOpFlag.combineOpFlags(terminalFlags, combinedFlags);
454         }
455 
456         return spliterator;
457     }
458 
459     // PipelineHelper
460 
461     @Override
getSourceShape()462     final StreamShape getSourceShape() {
463         @SuppressWarnings("rawtypes")
464         AbstractPipeline p = AbstractPipeline.this;
465         while (p.depth > 0) {
466             p = p.previousStage;
467         }
468         return p.getOutputShape();
469     }
470 
471     @Override
exactOutputSizeIfKnown(Spliterator<P_IN> spliterator)472     final <P_IN> long exactOutputSizeIfKnown(Spliterator<P_IN> spliterator) {
473         int flags = getStreamAndOpFlags();
474         long size = StreamOpFlag.SIZED.isKnown(flags) ? spliterator.getExactSizeIfKnown() : -1;
475         // Currently, we have no stateless SIZE_ADJUSTING intermediate operations,
476         // so we can simply ignore SIZE_ADJUSTING in parallel streams, since adjustments
477         // are already accounted in the input spliterator.
478         //
479         // If we ever have a stateless SIZE_ADJUSTING intermediate operation,
480         // we would need step back until depth == 0, then call exactOutputSize() for
481         // the subsequent stages.
482         if (size != -1 && StreamOpFlag.SIZE_ADJUSTING.isKnown(flags) && !isParallel()) {
483             // Skip the source stage as it's never SIZE_ADJUSTING
484             for (AbstractPipeline<?, ?, ?> stage = sourceStage.nextStage; stage != null; stage = stage.nextStage) {
485                 size = stage.exactOutputSize(size);
486             }
487         }
488         return size;
489     }
490 
491     /**
492      * Returns the exact output size of the pipeline given the exact size reported by the previous stage.
493      *
494      * @param previousSize the exact size reported by the previous stage
495      * @return the output size of this stage
496      */
exactOutputSize(long previousSize)497     long exactOutputSize(long previousSize) {
498         return previousSize;
499     }
500 
501     @Override
wrapAndCopyInto(S sink, Spliterator<P_IN> spliterator)502     final <P_IN, S extends Sink<E_OUT>> S wrapAndCopyInto(S sink, Spliterator<P_IN> spliterator) {
503         copyInto(wrapSink(Objects.requireNonNull(sink)), spliterator);
504         return sink;
505     }
506 
507     @Override
copyInto(Sink<P_IN> wrappedSink, Spliterator<P_IN> spliterator)508     final <P_IN> void copyInto(Sink<P_IN> wrappedSink, Spliterator<P_IN> spliterator) {
509         Objects.requireNonNull(wrappedSink);
510 
511         if (!StreamOpFlag.SHORT_CIRCUIT.isKnown(getStreamAndOpFlags())) {
512             wrappedSink.begin(spliterator.getExactSizeIfKnown());
513             spliterator.forEachRemaining(wrappedSink);
514             wrappedSink.end();
515         }
516         else {
517             copyIntoWithCancel(wrappedSink, spliterator);
518         }
519     }
520 
521     @Override
522     @SuppressWarnings("unchecked")
copyIntoWithCancel(Sink<P_IN> wrappedSink, Spliterator<P_IN> spliterator)523     final <P_IN> boolean copyIntoWithCancel(Sink<P_IN> wrappedSink, Spliterator<P_IN> spliterator) {
524         @SuppressWarnings({"rawtypes","unchecked"})
525         AbstractPipeline p = AbstractPipeline.this;
526         while (p.depth > 0) {
527             p = p.previousStage;
528         }
529 
530         wrappedSink.begin(spliterator.getExactSizeIfKnown());
531         boolean cancelled = p.forEachWithCancel(spliterator, wrappedSink);
532         wrappedSink.end();
533         return cancelled;
534     }
535 
536     @Override
537     // Android-changed: Made public for CTS tests only.
getStreamAndOpFlags()538     public final int getStreamAndOpFlags() {
539         return combinedFlags;
540     }
541 
isOrdered()542     final boolean isOrdered() {
543         return StreamOpFlag.ORDERED.isKnown(combinedFlags);
544     }
545 
546     @Override
547     @SuppressWarnings("unchecked")
548     // Android-changed: Made public for CTS tests only.
wrapSink(Sink<E_OUT> sink)549     public final <P_IN> Sink<P_IN> wrapSink(Sink<E_OUT> sink) {
550         Objects.requireNonNull(sink);
551 
552         for ( @SuppressWarnings("rawtypes") AbstractPipeline p=AbstractPipeline.this; p.depth > 0; p=p.previousStage) {
553             sink = p.opWrapSink(p.previousStage.combinedFlags, sink);
554         }
555         return (Sink<P_IN>) sink;
556     }
557 
558     @Override
559     @SuppressWarnings("unchecked")
wrapSpliterator(Spliterator<P_IN> sourceSpliterator)560     final <P_IN> Spliterator<E_OUT> wrapSpliterator(Spliterator<P_IN> sourceSpliterator) {
561         if (depth == 0) {
562             return (Spliterator<E_OUT>) sourceSpliterator;
563         }
564         else {
565             return wrap(this, () -> sourceSpliterator, isParallel());
566         }
567     }
568 
569     @Override
570     @SuppressWarnings("unchecked")
571     // Android-changed: Made public for CTS tests only.
evaluate(Spliterator<P_IN> spliterator, boolean flatten, IntFunction<E_OUT[]> generator)572     public final <P_IN> Node<E_OUT> evaluate(Spliterator<P_IN> spliterator,
573                                       boolean flatten,
574                                       IntFunction<E_OUT[]> generator) {
575         if (isParallel()) {
576             // @@@ Optimize if op of this pipeline stage is a stateful op
577             return evaluateToNode(this, spliterator, flatten, generator);
578         }
579         else {
580             Node.Builder<E_OUT> nb = makeNodeBuilder(
581                     exactOutputSizeIfKnown(spliterator), generator);
582             return wrapAndCopyInto(nb, spliterator).build();
583         }
584     }
585 
586 
587     // Shape-specific abstract methods, implemented by XxxPipeline classes
588 
589     /**
590      * Get the output shape of the pipeline.  If the pipeline is the head,
591      * then it's output shape corresponds to the shape of the source.
592      * Otherwise, it's output shape corresponds to the output shape of the
593      * associated operation.
594      *
595      * @return the output shape
596      */
597     // Android-changed: Made public for CTS tests only.
getOutputShape()598     public abstract StreamShape getOutputShape();
599 
600     /**
601      * Collect elements output from a pipeline into a Node that holds elements
602      * of this shape.
603      *
604      * @param helper the pipeline helper describing the pipeline stages
605      * @param spliterator the source spliterator
606      * @param flattenTree true if the returned node should be flattened
607      * @param generator the array generator
608      * @return a Node holding the output of the pipeline
609      */
610     // Android-changed: Made public for CTS tests only.
evaluateToNode(PipelineHelper<E_OUT> helper, Spliterator<P_IN> spliterator, boolean flattenTree, IntFunction<E_OUT[]> generator)611     public abstract <P_IN> Node<E_OUT> evaluateToNode(PipelineHelper<E_OUT> helper,
612                                                       Spliterator<P_IN> spliterator,
613                                                       boolean flattenTree,
614                                                       IntFunction<E_OUT[]> generator);
615 
616     /**
617      * Create a spliterator that wraps a source spliterator, compatible with
618      * this stream shape, and operations associated with a {@link
619      * PipelineHelper}.
620      *
621      * @param ph the pipeline helper describing the pipeline stages
622      * @param supplier the supplier of a spliterator
623      * @return a wrapping spliterator compatible with this shape
624      */
625     // Android-changed: Made public for CTS tests only.
wrap(PipelineHelper<E_OUT> ph, Supplier<Spliterator<P_IN>> supplier, boolean isParallel)626     public abstract <P_IN> Spliterator<E_OUT> wrap(PipelineHelper<E_OUT> ph,
627                                                    Supplier<Spliterator<P_IN>> supplier,
628                                                    boolean isParallel);
629 
630     /**
631      * Create a lazy spliterator that wraps and obtains the supplied the
632      * spliterator when a method is invoked on the lazy spliterator.
633      * @param supplier the supplier of a spliterator
634      */
635     // Android-changed: Made public for CTS tests only.
lazySpliterator(Supplier<? extends Spliterator<E_OUT>> supplier)636     public abstract Spliterator<E_OUT> lazySpliterator(Supplier<? extends Spliterator<E_OUT>> supplier);
637 
638     /**
639      * Traverse the elements of a spliterator compatible with this stream shape,
640      * pushing those elements into a sink.   If the sink requests cancellation,
641      * no further elements will be pulled or pushed.
642      *
643      * @param spliterator the spliterator to pull elements from
644      * @param sink the sink to push elements to
645      * @return true if the cancellation was requested
646      */
647     // Android-changed: Made public for CTS tests only.
forEachWithCancel(Spliterator<E_OUT> spliterator, Sink<E_OUT> sink)648     public abstract boolean forEachWithCancel(Spliterator<E_OUT> spliterator, Sink<E_OUT> sink);
649 
650     /**
651      * Make a node builder compatible with this stream shape.
652      *
653      * @param exactSizeIfKnown if {@literal >=0}, then a node builder will be
654      * created that has a fixed capacity of at most sizeIfKnown elements. If
655      * {@literal < 0}, then the node builder has an unfixed capacity. A fixed
656      * capacity node builder will throw exceptions if an element is added after
657      * builder has reached capacity, or is built before the builder has reached
658      * capacity.
659      *
660      * @param generator the array generator to be used to create instances of a
661      * T[] array. For implementations supporting primitive nodes, this parameter
662      * may be ignored.
663      * @return a node builder
664      */
665     @Override
666     // Android-changed: Made public for CTS tests only.
makeNodeBuilder(long exactSizeIfKnown, IntFunction<E_OUT[]> generator)667     public abstract Node.Builder<E_OUT> makeNodeBuilder(long exactSizeIfKnown,
668                                                         IntFunction<E_OUT[]> generator);
669 
670 
671     // Op-specific abstract methods, implemented by the operation class
672 
673     /**
674      * Returns whether this operation is stateful or not.  If it is stateful,
675      * then the method
676      * {@link #opEvaluateParallel(PipelineHelper, java.util.Spliterator, java.util.function.IntFunction)}
677      * must be overridden.
678      *
679      * @return {@code true} if this operation is stateful
680      */
681     // Android-changed: Made public for CTS tests only.
opIsStateful()682     public abstract boolean opIsStateful();
683 
684     /**
685      * Accepts a {@code Sink} which will receive the results of this operation,
686      * and return a {@code Sink} which accepts elements of the input type of
687      * this operation and which performs the operation, passing the results to
688      * the provided {@code Sink}.
689      *
690      * @apiNote
691      * The implementation may use the {@code flags} parameter to optimize the
692      * sink wrapping.  For example, if the input is already {@code DISTINCT},
693      * the implementation for the {@code Stream#distinct()} method could just
694      * return the sink it was passed.
695      *
696      * @param flags The combined stream and operation flags up to, but not
697      *        including, this operation
698      * @param sink sink to which elements should be sent after processing
699      * @return a sink which accepts elements, perform the operation upon
700      *         each element, and passes the results (if any) to the provided
701      *         {@code Sink}.
702      */
703     // Android-changed: Made public for CTS tests only.
opWrapSink(int flags, Sink<E_OUT> sink)704     public abstract Sink<E_IN> opWrapSink(int flags, Sink<E_OUT> sink);
705 
706     /**
707      * Performs a parallel evaluation of the operation using the specified
708      * {@code PipelineHelper} which describes the upstream intermediate
709      * operations.  Only called on stateful operations.  If {@link
710      * #opIsStateful()} returns true then implementations must override the
711      * default implementation.
712      *
713      * @implSpec The default implementation always throw
714      * {@code UnsupportedOperationException}.
715      *
716      * @param helper the pipeline helper describing the pipeline stages
717      * @param spliterator the source {@code Spliterator}
718      * @param generator the array generator
719      * @return a {@code Node} describing the result of the evaluation
720      */
721     // Android-changed: Made public for CTS tests only.
opEvaluateParallel(PipelineHelper<E_OUT> helper, Spliterator<P_IN> spliterator, IntFunction<E_OUT[]> generator)722     public <P_IN> Node<E_OUT> opEvaluateParallel(PipelineHelper<E_OUT> helper,
723                                           Spliterator<P_IN> spliterator,
724                                           IntFunction<E_OUT[]> generator) {
725         throw new UnsupportedOperationException("Parallel evaluation is not supported");
726     }
727 
728     /**
729      * Returns a {@code Spliterator} describing a parallel evaluation of the
730      * operation, using the specified {@code PipelineHelper} which describes the
731      * upstream intermediate operations.  Only called on stateful operations.
732      * It is not necessary (though acceptable) to do a full computation of the
733      * result here; it is preferable, if possible, to describe the result via a
734      * lazily evaluated spliterator.
735      *
736      * @implSpec The default implementation behaves as if:
737      * <pre>{@code
738      *     return evaluateParallel(helper, i -> (E_OUT[]) new
739      * Object[i]).spliterator();
740      * }</pre>
741      * and is suitable for implementations that cannot do better than a full
742      * synchronous evaluation.
743      *
744      * @param helper the pipeline helper
745      * @param spliterator the source {@code Spliterator}
746      * @return a {@code Spliterator} describing the result of the evaluation
747      */
748     @SuppressWarnings("unchecked")
749     // Android-changed: Made public for CTS tests only.
opEvaluateParallelLazy(PipelineHelper<E_OUT> helper, Spliterator<P_IN> spliterator)750     public <P_IN> Spliterator<E_OUT> opEvaluateParallelLazy(PipelineHelper<E_OUT> helper,
751                                                      Spliterator<P_IN> spliterator) {
752         return opEvaluateParallel(helper, spliterator, i -> (E_OUT[]) new Object[i]).spliterator();
753     }
754 }
755