-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamSpliterators.java
More file actions
1543 lines (1294 loc) · 51.1 KB
/
StreamSpliterators.java
File metadata and controls
1543 lines (1294 loc) · 51.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.util.stream;
import java.util.Comparator;
import java.util.Objects;
import java.util.Spliterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.DoubleSupplier;
import java.util.function.IntConsumer;
import java.util.function.IntSupplier;
import java.util.function.LongConsumer;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
/**
* Spliterator implementations for wrapping and delegating spliterators, used
* in the implementation of the {@link Stream#spliterator()} method.
*
* @since 1.8
*/
class StreamSpliterators {
/**
* Abstract wrapping spliterator that binds to the spliterator of a
* pipeline helper on first operation.
*
* <p>This spliterator is not late-binding and will bind to the source
* spliterator when first operated on.
*
* <p>A wrapping spliterator produced from a sequential stream
* cannot be split if there are stateful operations present.
*/
private static abstract class AbstractWrappingSpliterator<P_IN, P_OUT,
T_BUFFER extends AbstractSpinedBuffer>
implements Spliterator<P_OUT> {
// @@@ Detect if stateful operations are present or not
// If not then can split otherwise cannot
/**
* True if this spliterator supports splitting
*/
final boolean isParallel;
final PipelineHelper<P_OUT> ph;
/**
* Supplier for the source spliterator. Client provides either a
* spliterator or a supplier.
*/
private Supplier<Spliterator<P_IN>> spliteratorSupplier;
/**
* Source spliterator. Either provided from client or obtained from
* supplier.
*/
Spliterator<P_IN> spliterator;
/**
* Sink chain for the downstream stages of the pipeline, ultimately
* leading to the buffer. Used during partial traversal.
*/
Sink<P_IN> bufferSink;
/**
* A function that advances one element of the spliterator, pushing
* it to bufferSink. Returns whether any elements were processed.
* Used during partial traversal.
*/
BooleanSupplier pusher;
/** Next element to consume from the buffer, used during partial traversal */
long nextToConsume;
/** Buffer into which elements are pushed. Used during partial traversal. */
T_BUFFER buffer;
/**
* True if full traversal has occurred (with possible cancelation).
* If doing a partial traversal, there may be still elements in buffer.
*/
boolean finished;
/**
* Construct an AbstractWrappingSpliterator from a
* {@code Supplier<Spliterator>}.
*/
AbstractWrappingSpliterator(PipelineHelper<P_OUT> ph,
Supplier<Spliterator<P_IN>> spliteratorSupplier,
boolean parallel) {
this.ph = ph;
this.spliteratorSupplier = spliteratorSupplier;
this.spliterator = null;
this.isParallel = parallel;
}
/**
* Construct an AbstractWrappingSpliterator from a
* {@code Spliterator}.
*/
AbstractWrappingSpliterator(PipelineHelper<P_OUT> ph,
Spliterator<P_IN> spliterator,
boolean parallel) {
this.ph = ph;
this.spliteratorSupplier = null;
this.spliterator = spliterator;
this.isParallel = parallel;
}
/**
* Called before advancing to set up spliterator, if needed.
*/
final void init() {
if (spliterator == null) {
spliterator = spliteratorSupplier.get();
spliteratorSupplier = null;
}
}
/**
* Get an element from the source, pushing it into the sink chain,
* setting up the buffer if needed
* @return whether there are elements to consume from the buffer
*/
final boolean doAdvance() {
if (buffer == null) {
if (finished)
return false;
init();
initPartialTraversalState();
nextToConsume = 0;
bufferSink.begin(spliterator.getExactSizeIfKnown());
return fillBuffer();
}
else {
++nextToConsume;
boolean hasNext = nextToConsume < buffer.count();
if (!hasNext) {
nextToConsume = 0;
buffer.clear();
hasNext = fillBuffer();
}
return hasNext;
}
}
/**
* Invokes the shape-specific constructor with the provided arguments
* and returns the result.
*/
abstract AbstractWrappingSpliterator<P_IN, P_OUT, ?> wrap(Spliterator<P_IN> s);
/**
* Initializes buffer, sink chain, and pusher for a shape-specific
* implementation.
*/
abstract void initPartialTraversalState();
@Override
public Spliterator<P_OUT> trySplit() {
if (isParallel && !finished) {
init();
Spliterator<P_IN> split = spliterator.trySplit();
return (split == null) ? null : wrap(split);
}
else
return null;
}
/**
* If the buffer is empty, push elements into the sink chain until
* the source is empty or cancellation is requested.
* @return whether there are elements to consume from the buffer
*/
private boolean fillBuffer() {
while (buffer.count() == 0) {
if (bufferSink.cancellationRequested() || !pusher.getAsBoolean()) {
if (finished)
return false;
else {
bufferSink.end(); // might trigger more elements
finished = true;
}
}
}
return true;
}
@Override
public final long estimateSize() {
init();
// Use the estimate of the wrapped spliterator
// Note this may not be accurate if there are filter/flatMap
// operations filtering or adding elements to the stream
return spliterator.estimateSize();
}
@Override
public final long getExactSizeIfKnown() {
init();
return StreamOpFlag.SIZED.isKnown(ph.getStreamAndOpFlags())
? spliterator.getExactSizeIfKnown()
: -1;
}
@Override
public final int characteristics() {
init();
// Get the characteristics from the pipeline
int c = StreamOpFlag.toCharacteristics(StreamOpFlag.toStreamFlags(ph.getStreamAndOpFlags()));
// Mask off the size and uniform characteristics and replace with
// those of the spliterator
// Note that a non-uniform spliterator can change from something
// with an exact size to an estimate for a sub-split, for example
// with HashSet where the size is known at the top level spliterator
// but for sub-splits only an estimate is known
if ((c & Spliterator.SIZED) != 0) {
c &= ~(Spliterator.SIZED | Spliterator.SUBSIZED);
c |= (spliterator.characteristics() & (Spliterator.SIZED | Spliterator.SUBSIZED));
}
return c;
}
@Override
public Comparator<? super P_OUT> getComparator() {
if (!hasCharacteristics(SORTED))
throw new IllegalStateException();
return null;
}
@Override
public final String toString() {
return String.format("%s[%s]", getClass().getName(), spliterator);
}
}
static final class WrappingSpliterator<P_IN, P_OUT>
extends AbstractWrappingSpliterator<P_IN, P_OUT, SpinedBuffer<P_OUT>> {
WrappingSpliterator(PipelineHelper<P_OUT> ph,
Supplier<Spliterator<P_IN>> supplier,
boolean parallel) {
super(ph, supplier, parallel);
}
WrappingSpliterator(PipelineHelper<P_OUT> ph,
Spliterator<P_IN> spliterator,
boolean parallel) {
super(ph, spliterator, parallel);
}
@Override
WrappingSpliterator<P_IN, P_OUT> wrap(Spliterator<P_IN> s) {
return new WrappingSpliterator<>(ph, s, isParallel);
}
@Override
void initPartialTraversalState() {
SpinedBuffer<P_OUT> b = new SpinedBuffer<>();
buffer = b;
bufferSink = ph.wrapSink(b::accept);
pusher = () -> spliterator.tryAdvance(bufferSink);
}
@Override
public boolean tryAdvance(Consumer<? super P_OUT> consumer) {
Objects.requireNonNull(consumer);
boolean hasNext = doAdvance();
if (hasNext)
consumer.accept(buffer.get(nextToConsume));
return hasNext;
}
@Override
public void forEachRemaining(Consumer<? super P_OUT> consumer) {
if (buffer == null && !finished) {
Objects.requireNonNull(consumer);
init();
ph.wrapAndCopyInto((Sink<P_OUT>) consumer::accept, spliterator);
finished = true;
}
else {
do { } while (tryAdvance(consumer));
}
}
}
static final class IntWrappingSpliterator<P_IN>
extends AbstractWrappingSpliterator<P_IN, Integer, SpinedBuffer.OfInt>
implements Spliterator.OfInt {
IntWrappingSpliterator(PipelineHelper<Integer> ph,
Supplier<Spliterator<P_IN>> supplier,
boolean parallel) {
super(ph, supplier, parallel);
}
IntWrappingSpliterator(PipelineHelper<Integer> ph,
Spliterator<P_IN> spliterator,
boolean parallel) {
super(ph, spliterator, parallel);
}
@Override
AbstractWrappingSpliterator<P_IN, Integer, ?> wrap(Spliterator<P_IN> s) {
return new IntWrappingSpliterator<>(ph, s, isParallel);
}
@Override
void initPartialTraversalState() {
SpinedBuffer.OfInt b = new SpinedBuffer.OfInt();
buffer = b;
bufferSink = ph.wrapSink((Sink.OfInt) b::accept);
pusher = () -> spliterator.tryAdvance(bufferSink);
}
@Override
public Spliterator.OfInt trySplit() {
return (Spliterator.OfInt) super.trySplit();
}
@Override
public boolean tryAdvance(IntConsumer consumer) {
Objects.requireNonNull(consumer);
boolean hasNext = doAdvance();
if (hasNext)
consumer.accept(buffer.get(nextToConsume));
return hasNext;
}
@Override
public void forEachRemaining(IntConsumer consumer) {
if (buffer == null && !finished) {
Objects.requireNonNull(consumer);
init();
ph.wrapAndCopyInto((Sink.OfInt) consumer::accept, spliterator);
finished = true;
}
else {
do { } while (tryAdvance(consumer));
}
}
}
static final class LongWrappingSpliterator<P_IN>
extends AbstractWrappingSpliterator<P_IN, Long, SpinedBuffer.OfLong>
implements Spliterator.OfLong {
LongWrappingSpliterator(PipelineHelper<Long> ph,
Supplier<Spliterator<P_IN>> supplier,
boolean parallel) {
super(ph, supplier, parallel);
}
LongWrappingSpliterator(PipelineHelper<Long> ph,
Spliterator<P_IN> spliterator,
boolean parallel) {
super(ph, spliterator, parallel);
}
@Override
AbstractWrappingSpliterator<P_IN, Long, ?> wrap(Spliterator<P_IN> s) {
return new LongWrappingSpliterator<>(ph, s, isParallel);
}
@Override
void initPartialTraversalState() {
SpinedBuffer.OfLong b = new SpinedBuffer.OfLong();
buffer = b;
bufferSink = ph.wrapSink((Sink.OfLong) b::accept);
pusher = () -> spliterator.tryAdvance(bufferSink);
}
@Override
public Spliterator.OfLong trySplit() {
return (Spliterator.OfLong) super.trySplit();
}
@Override
public boolean tryAdvance(LongConsumer consumer) {
Objects.requireNonNull(consumer);
boolean hasNext = doAdvance();
if (hasNext)
consumer.accept(buffer.get(nextToConsume));
return hasNext;
}
@Override
public void forEachRemaining(LongConsumer consumer) {
if (buffer == null && !finished) {
Objects.requireNonNull(consumer);
init();
ph.wrapAndCopyInto((Sink.OfLong) consumer::accept, spliterator);
finished = true;
}
else {
do { } while (tryAdvance(consumer));
}
}
}
static final class DoubleWrappingSpliterator<P_IN>
extends AbstractWrappingSpliterator<P_IN, Double, SpinedBuffer.OfDouble>
implements Spliterator.OfDouble {
DoubleWrappingSpliterator(PipelineHelper<Double> ph,
Supplier<Spliterator<P_IN>> supplier,
boolean parallel) {
super(ph, supplier, parallel);
}
DoubleWrappingSpliterator(PipelineHelper<Double> ph,
Spliterator<P_IN> spliterator,
boolean parallel) {
super(ph, spliterator, parallel);
}
@Override
AbstractWrappingSpliterator<P_IN, Double, ?> wrap(Spliterator<P_IN> s) {
return new DoubleWrappingSpliterator<>(ph, s, isParallel);
}
@Override
void initPartialTraversalState() {
SpinedBuffer.OfDouble b = new SpinedBuffer.OfDouble();
buffer = b;
bufferSink = ph.wrapSink((Sink.OfDouble) b::accept);
pusher = () -> spliterator.tryAdvance(bufferSink);
}
@Override
public Spliterator.OfDouble trySplit() {
return (Spliterator.OfDouble) super.trySplit();
}
@Override
public boolean tryAdvance(DoubleConsumer consumer) {
Objects.requireNonNull(consumer);
boolean hasNext = doAdvance();
if (hasNext)
consumer.accept(buffer.get(nextToConsume));
return hasNext;
}
@Override
public void forEachRemaining(DoubleConsumer consumer) {
if (buffer == null && !finished) {
Objects.requireNonNull(consumer);
init();
ph.wrapAndCopyInto((Sink.OfDouble) consumer::accept, spliterator);
finished = true;
}
else {
do { } while (tryAdvance(consumer));
}
}
}
/**
* Spliterator implementation that delegates to an underlying spliterator,
* acquiring the spliterator from a {@code Supplier<Spliterator>} on the
* first call to any spliterator method.
* @param <T>
*/
static class DelegatingSpliterator<T, T_SPLITR extends Spliterator<T>>
implements Spliterator<T> {
private final Supplier<? extends T_SPLITR> supplier;
private T_SPLITR s;
DelegatingSpliterator(Supplier<? extends T_SPLITR> supplier) {
this.supplier = supplier;
}
T_SPLITR get() {
if (s == null) {
s = supplier.get();
}
return s;
}
@Override
public T_SPLITR trySplit() {
return (T_SPLITR) get().trySplit();
}
@Override
public boolean tryAdvance(Consumer<? super T> consumer) {
return get().tryAdvance(consumer);
}
@Override
public void forEachRemaining(Consumer<? super T> consumer) {
get().forEachRemaining(consumer);
}
@Override
public long estimateSize() {
return get().estimateSize();
}
@Override
public int characteristics() {
return get().characteristics();
}
@Override
public Comparator<? super T> getComparator() {
return get().getComparator();
}
@Override
public long getExactSizeIfKnown() {
return get().getExactSizeIfKnown();
}
@Override
public String toString() {
return getClass().getName() + "[" + get() + "]";
}
static class OfPrimitive<T, T_CONS, T_SPLITR extends Spliterator.OfPrimitive<T, T_CONS, T_SPLITR>>
extends DelegatingSpliterator<T, T_SPLITR>
implements Spliterator.OfPrimitive<T, T_CONS, T_SPLITR> {
OfPrimitive(Supplier<? extends T_SPLITR> supplier) {
super(supplier);
}
@Override
public boolean tryAdvance(T_CONS consumer) {
return get().tryAdvance(consumer);
}
@Override
public void forEachRemaining(T_CONS consumer) {
get().forEachRemaining(consumer);
}
}
static final class OfInt
extends OfPrimitive<Integer, IntConsumer, Spliterator.OfInt>
implements Spliterator.OfInt {
OfInt(Supplier<Spliterator.OfInt> supplier) {
super(supplier);
}
}
static final class OfLong
extends OfPrimitive<Long, LongConsumer, Spliterator.OfLong>
implements Spliterator.OfLong {
OfLong(Supplier<Spliterator.OfLong> supplier) {
super(supplier);
}
}
static final class OfDouble
extends OfPrimitive<Double, DoubleConsumer, Spliterator.OfDouble>
implements Spliterator.OfDouble {
OfDouble(Supplier<Spliterator.OfDouble> supplier) {
super(supplier);
}
}
}
/**
* A slice Spliterator from a source Spliterator that reports
* {@code SUBSIZED}.
*
*/
static abstract class SliceSpliterator<T, T_SPLITR extends Spliterator<T>> {
// The start index of the slice
final long sliceOrigin;
// One past the last index of the slice
final long sliceFence;
// The spliterator to slice
T_SPLITR s;
// current (absolute) index, modified on advance/split
long index;
// one past last (absolute) index or sliceFence, which ever is smaller
long fence;
SliceSpliterator(T_SPLITR s, long sliceOrigin, long sliceFence, long origin, long fence) {
assert s.hasCharacteristics(Spliterator.SUBSIZED);
this.s = s;
this.sliceOrigin = sliceOrigin;
this.sliceFence = sliceFence;
this.index = origin;
this.fence = fence;
}
protected abstract T_SPLITR makeSpliterator(T_SPLITR s, long sliceOrigin, long sliceFence, long origin, long fence);
public T_SPLITR trySplit() {
if (sliceOrigin >= fence)
return null;
if (index >= fence)
return null;
// Keep splitting until the left and right splits intersect with the slice
// thereby ensuring the size estimate decreases.
// This also avoids creating empty spliterators which can result in
// existing and additionally created F/J tasks that perform
// redundant work on no elements.
while (true) {
T_SPLITR leftSplit = (T_SPLITR) s.trySplit();
if (leftSplit == null)
return null;
long leftSplitFenceUnbounded = index + leftSplit.estimateSize();
long leftSplitFence = Math.min(leftSplitFenceUnbounded, sliceFence);
if (sliceOrigin >= leftSplitFence) {
// The left split does not intersect with, and is to the left of, the slice
// The right split does intersect
// Discard the left split and split further with the right split
index = leftSplitFence;
}
else if (leftSplitFence >= sliceFence) {
// The right split does not intersect with, and is to the right of, the slice
// The left split does intersect
// Discard the right split and split further with the left split
s = leftSplit;
fence = leftSplitFence;
}
else if (index >= sliceOrigin && leftSplitFenceUnbounded <= sliceFence) {
// The left split is contained within the slice, return the underlying left split
// Right split is contained within or intersects with the slice
index = leftSplitFence;
return leftSplit;
} else {
// The left split intersects with the slice
// Right split is contained within or intersects with the slice
return makeSpliterator(leftSplit, sliceOrigin, sliceFence, index, index = leftSplitFence);
}
}
}
public long estimateSize() {
return (sliceOrigin < fence)
? fence - Math.max(sliceOrigin, index) : 0;
}
public int characteristics() {
return s.characteristics();
}
static final class OfRef<T>
extends SliceSpliterator<T, Spliterator<T>>
implements Spliterator<T> {
OfRef(Spliterator<T> s, long sliceOrigin, long sliceFence) {
this(s, sliceOrigin, sliceFence, 0, Math.min(s.estimateSize(), sliceFence));
}
private OfRef(Spliterator<T> s,
long sliceOrigin, long sliceFence, long origin, long fence) {
super(s, sliceOrigin, sliceFence, origin, fence);
}
@Override
protected Spliterator<T> makeSpliterator(Spliterator<T> s,
long sliceOrigin, long sliceFence,
long origin, long fence) {
return new OfRef<>(s, sliceOrigin, sliceFence, origin, fence);
}
@Override
public boolean tryAdvance(Consumer<? super T> action) {
Objects.requireNonNull(action);
if (sliceOrigin >= fence)
return false;
while (sliceOrigin > index) {
s.tryAdvance(e -> {});
index++;
}
if (index >= fence)
return false;
index++;
return s.tryAdvance(action);
}
@Override
public void forEachRemaining(Consumer<? super T> action) {
Objects.requireNonNull(action);
if (sliceOrigin >= fence)
return;
if (index >= fence)
return;
if (index >= sliceOrigin && (index + s.estimateSize()) <= sliceFence) {
// The spliterator is contained within the slice
s.forEachRemaining(action);
index = fence;
} else {
// The spliterator intersects with the slice
while (sliceOrigin > index) {
s.tryAdvance(e -> {});
index++;
}
// Traverse elements up to the fence
for (;index < fence; index++) {
s.tryAdvance(action);
}
}
}
}
static abstract class OfPrimitive<T,
T_SPLITR extends Spliterator.OfPrimitive<T, T_CONS, T_SPLITR>,
T_CONS>
extends SliceSpliterator<T, T_SPLITR>
implements Spliterator.OfPrimitive<T, T_CONS, T_SPLITR> {
OfPrimitive(T_SPLITR s, long sliceOrigin, long sliceFence) {
this(s, sliceOrigin, sliceFence, 0, Math.min(s.estimateSize(), sliceFence));
}
private OfPrimitive(T_SPLITR s,
long sliceOrigin, long sliceFence, long origin, long fence) {
super(s, sliceOrigin, sliceFence, origin, fence);
}
@Override
public boolean tryAdvance(T_CONS action) {
Objects.requireNonNull(action);
if (sliceOrigin >= fence)
return false;
while (sliceOrigin > index) {
s.tryAdvance(emptyConsumer());
index++;
}
if (index >= fence)
return false;
index++;
return s.tryAdvance(action);
}
@Override
public void forEachRemaining(T_CONS action) {
Objects.requireNonNull(action);
if (sliceOrigin >= fence)
return;
if (index >= fence)
return;
if (index >= sliceOrigin && (index + s.estimateSize()) <= sliceFence) {
// The spliterator is contained within the slice
s.forEachRemaining(action);
index = fence;
} else {
// The spliterator intersects with the slice
while (sliceOrigin > index) {
s.tryAdvance(emptyConsumer());
index++;
}
// Traverse elements up to the fence
for (;index < fence; index++) {
s.tryAdvance(action);
}
}
}
protected abstract T_CONS emptyConsumer();
}
static final class OfInt extends OfPrimitive<Integer, Spliterator.OfInt, IntConsumer>
implements Spliterator.OfInt {
OfInt(Spliterator.OfInt s, long sliceOrigin, long sliceFence) {
super(s, sliceOrigin, sliceFence);
}
OfInt(Spliterator.OfInt s,
long sliceOrigin, long sliceFence, long origin, long fence) {
super(s, sliceOrigin, sliceFence, origin, fence);
}
@Override
protected Spliterator.OfInt makeSpliterator(Spliterator.OfInt s,
long sliceOrigin, long sliceFence,
long origin, long fence) {
return new SliceSpliterator.OfInt(s, sliceOrigin, sliceFence, origin, fence);
}
@Override
protected IntConsumer emptyConsumer() {
return e -> {};
}
}
static final class OfLong extends OfPrimitive<Long, Spliterator.OfLong, LongConsumer>
implements Spliterator.OfLong {
OfLong(Spliterator.OfLong s, long sliceOrigin, long sliceFence) {
super(s, sliceOrigin, sliceFence);
}
OfLong(Spliterator.OfLong s,
long sliceOrigin, long sliceFence, long origin, long fence) {
super(s, sliceOrigin, sliceFence, origin, fence);
}
@Override
protected Spliterator.OfLong makeSpliterator(Spliterator.OfLong s,
long sliceOrigin, long sliceFence,
long origin, long fence) {
return new SliceSpliterator.OfLong(s, sliceOrigin, sliceFence, origin, fence);
}
@Override
protected LongConsumer emptyConsumer() {
return e -> {};
}
}
static final class OfDouble extends OfPrimitive<Double, Spliterator.OfDouble, DoubleConsumer>
implements Spliterator.OfDouble {
OfDouble(Spliterator.OfDouble s, long sliceOrigin, long sliceFence) {
super(s, sliceOrigin, sliceFence);
}
OfDouble(Spliterator.OfDouble s,
long sliceOrigin, long sliceFence, long origin, long fence) {
super(s, sliceOrigin, sliceFence, origin, fence);
}
@Override
protected Spliterator.OfDouble makeSpliterator(Spliterator.OfDouble s,
long sliceOrigin, long sliceFence,
long origin, long fence) {
return new SliceSpliterator.OfDouble(s, sliceOrigin, sliceFence, origin, fence);
}
@Override
protected DoubleConsumer emptyConsumer() {
return e -> {};
}
}
}
/**
* A slice Spliterator that does not preserve order, if any, of a source
* Spliterator.
*
* Note: The source spliterator may report {@code ORDERED} since that
* spliterator be the result of a previous pipeline stage that was
* collected to a {@code Node}. It is the order of the pipeline stage
* that governs whether the this slice spliterator is to be used or not.
*/
static abstract class UnorderedSliceSpliterator<T, T_SPLITR extends Spliterator<T>> {
static final int CHUNK_SIZE = 1 << 7;
// The spliterator to slice
protected final T_SPLITR s;
protected final boolean unlimited;
private final long skipThreshold;
private final AtomicLong permits;
UnorderedSliceSpliterator(T_SPLITR s, long skip, long limit) {
this.s = s;
this.unlimited = limit < 0;
this.skipThreshold = limit >= 0 ? limit : 0;
this.permits = new AtomicLong(limit >= 0 ? skip + limit : skip);
}
UnorderedSliceSpliterator(T_SPLITR s,
UnorderedSliceSpliterator<T, T_SPLITR> parent) {
this.s = s;
this.unlimited = parent.unlimited;
this.permits = parent.permits;
this.skipThreshold = parent.skipThreshold;
}
/**
* Acquire permission to skip or process elements. The caller must
* first acquire the elements, then consult this method for guidance
* as to what to do with the data.
*
* <p>We use an {@code AtomicLong} to atomically maintain a counter,
* which is initialized as skip+limit if we are limiting, or skip only
* if we are not limiting. The user should consult the method
* {@code checkPermits()} before acquiring data elements.
*
* @param numElements the number of elements the caller has in hand
* @return the number of elements that should be processed; any
* remaining elements should be discarded.
*/
protected final long acquirePermits(long numElements) {
long remainingPermits;
long grabbing;
// permits never increase, and don't decrease below zero
assert numElements > 0;
do {
remainingPermits = permits.get();
if (remainingPermits == 0)
return unlimited ? numElements : 0;
grabbing = Math.min(remainingPermits, numElements);
} while (grabbing > 0 &&
!permits.compareAndSet(remainingPermits, remainingPermits - grabbing));
if (unlimited)
return Math.max(numElements - grabbing, 0);
else if (remainingPermits > skipThreshold)
return Math.max(grabbing - (remainingPermits - skipThreshold), 0);
else
return grabbing;
}
enum PermitStatus { NO_MORE, MAYBE_MORE, UNLIMITED }
/** Call to check if permits might be available before acquiring data */
protected final PermitStatus permitStatus() {
if (permits.get() > 0)
return PermitStatus.MAYBE_MORE;
else
return unlimited ? PermitStatus.UNLIMITED : PermitStatus.NO_MORE;
}
public final T_SPLITR trySplit() {
// Stop splitting when there are no more limit permits
if (permits.get() == 0)
return null;
T_SPLITR split = (T_SPLITR) s.trySplit();
return split == null ? null : makeSpliterator(split);
}
protected abstract T_SPLITR makeSpliterator(T_SPLITR s);
public final long estimateSize() {
return s.estimateSize();
}
public final int characteristics() {
return s.characteristics() &
~(Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED);
}
static final class OfRef<T> extends UnorderedSliceSpliterator<T, Spliterator<T>>
implements Spliterator<T>, Consumer<T> {
T tmpSlot;
OfRef(Spliterator<T> s, long skip, long limit) {
super(s, skip, limit);
}
OfRef(Spliterator<T> s, OfRef<T> parent) {
super(s, parent);
}
@Override