forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStreams.java
929 lines (800 loc) · 33.7 KB
/
Streams.java
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
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util.stream;
import jdk.internal.HotSpotIntrinsicCandidate;
import java.util.Comparator;
import java.util.Objects;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
/**
* Utility methods for operating on and creating streams.
*
* <p>Unless otherwise stated, streams are created as sequential streams. A
* sequential stream can be transformed into a parallel stream by calling the
* {@code parallel()} method on the created stream.
*
* @since 1.8
*/
// 定义了一个Stream构建器和几个专用的Spliterator
final class Streams {
private Streams() {
throw new Error("no instances");
}
/*▼ Stream构建器 ████████████████████████████████████████████████████████████████████████████████┓ */
/*
* Stream构建器的抽象基类,用来构建单元素或多元素的流。
*
* 当元素个数为0个1个时,创建单元素流
* 当元素个数>=2时,创建多元素流
*
* 具体行为参见实现类StreamBuilderImpl
*/
private abstract static class AbstractStreamBuilderImpl<T, S extends Spliterator<T>>
implements Spliterator<T> {
// >= 0 when building, < 0 when built
// -1 == no elements
// -2 == one element, held by first
// -3 == two or more elements, held by buffer
int count;
// Spliterator implementation for 0 or 1 element
// count == -1 for no elements
// count == -2 for one element held by first
@Override
public S trySplit() {
return null;
}
@Override
public long estimateSize() {
return -count - 1;
}
@Override
public int characteristics() {
return Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED | Spliterator.IMMUTABLE;
}
}
/*
* ⑴ ⑵
* 模式一 first = × add t1 first = t1 add t2 first = t1 add t3 first = t1
* StreamBuilderImpl() ---▶ count = 0 -------▷ count = 1 -------▷ count = 2 -------▷ count = 3
* buffer = × buffer = × buffer = t1|t2 buffer = t1|t2|t3
* ▼▼ ▼▼
* ▼▼ ▼▼
* first = × 消费 first = t1 模式二
* count = -1 ◁------- count = -2 ◀--- StreamBuilderImpl(t1)
* ⑵ ⑴
*
* Stream构建器,兼具Spliterator属性,是个多面手
* Stream构建器对象有两种创建模式,参见上图。
*
* Stream构建器可能构建出两种形态的流:
* 第一种:构建器内没有元素或只有一个元素,此时存储元素的容器是first。
* (1) 构建器采用模式一创建。
* 需要通过build()方法将构建器从模式一切换到模式二,而且,将返回以构建器自身做Spliterator的流。
* (2) 构建器采用模式二创建。
* 需要通过Stream.of或Stream.ofNullable方法创建以构建器自身做Spliterator的流。
* 第二种:构建器内存在>=2个元素,此时存储元素的容器是buffer。
* 该构建器必定使用模式一创建。
* 返回的流以SpinedBuffer内部的Spliterator做Spliterator。
*/
static final class StreamBuilderImpl<T>
extends AbstractStreamBuilderImpl<T, Spliterator<T>>
implements Stream.Builder<T> {
// The first element in the stream
// valid if count == 1
T first;
// The first and subsequent elements in the stream
// non-null if count == 2
SpinedBuffer<T> buffer; // 容量可变的缓冲区
/**
* Constructor for building a stream of 0 or more elements.
*/
StreamBuilderImpl() {
}
/**
* Constructor for a singleton stream.
*
* @param t the single element
*/
StreamBuilderImpl(T t) {
first = t;
count = -2;
}
// StreamBuilder implementation
// 使用模式一创建构建器后,可以调用此方法构建一个新的流
@Override
public Stream<T> build() {
int c = count;
if(c >= 0) {
// Switch count to negative value signalling the builder is built
count = -count - 1; // 元素个数为0或1,则完成模式一到模式二的切换
// Use this spliterator if 0 or 1 elements, otherwise use the spliterator of the spined buffer
return (c < 2)
? StreamSupport.stream(this, false) // 只有0或1个元素,创建单元素流,自身做Spliterator
: StreamSupport.stream(buffer.spliterator(), false); // 元素个数>=2时,创建多元素流
}
throw new IllegalStateException();
}
// 使用模式一创建构建器后,可以调用此方法添加元素
@Override
public void accept(T t) {
// 处于模式一的⑴阶段
if(count == 0) {
first = t;
count++;
} else if(count > 0) { // 处于模式一⑵阶段(含)以后
// 如果添加2个以上的元素,需要启用buffer
if(buffer == null) {
buffer = new SpinedBuffer<>();
buffer.accept(first); // 别忘了把第一个元素添加进来
count++;
}
buffer.accept(t);
} else {
throw new IllegalStateException();
}
}
// 使用模式一创建构建器后,可以调用此方法添加元素
public Stream.Builder<T> add(T t) {
accept(t);
return this;
}
// Spliterator implementation for 0 or 1 element
// count == -1 for no elements
// count == -2 for one element held by first
// 使用模式二创建构建器后,可以调用此方法消费元素
@Override
public boolean tryAdvance(Consumer<? super T> action) {
Objects.requireNonNull(action);
if(count == -2) {
action.accept(first);
count = -1;
return true;
} else {
return false;
}
}
// 使用模式二创建构建器后,可以调用此方法消费元素
@Override
public void forEachRemaining(Consumer<? super T> action) {
Objects.requireNonNull(action);
// 行为与tryAdvance一致,因为此时最多只有一个元素可供消费
if(count == -2) {
action.accept(first);
count = -1;
}
}
}
static final class IntStreamBuilderImpl
extends AbstractStreamBuilderImpl<Integer, Spliterator.OfInt>
implements IntStream.Builder, Spliterator.OfInt {
// The first element in the stream
// valid if count == 1
int first;
// The first and subsequent elements in the stream
// non-null if count == 2
SpinedBuffer.OfInt buffer;
/**
* Constructor for building a stream of 0 or more elements.
*/
IntStreamBuilderImpl() {
}
/**
* Constructor for a singleton stream.
*
* @param t the single element
*/
IntStreamBuilderImpl(int t) {
first = t;
count = -2;
}
// StreamBuilder implementation
@Override
public void accept(int t) {
if(count == 0) {
first = t;
count++;
} else if(count > 0) {
if(buffer == null) {
buffer = new SpinedBuffer.OfInt();
buffer.accept(first);
count++;
}
buffer.accept(t);
} else {
throw new IllegalStateException();
}
}
@Override
public IntStream build() {
int c = count;
if(c >= 0) {
// Switch count to negative value signalling the builder is built
count = -count - 1;
// Use this spliterator if 0 or 1 elements, otherwise use
// the spliterator of the spined buffer
return (c < 2) ? StreamSupport.intStream(this, false) : StreamSupport.intStream(buffer.spliterator(), false);
}
throw new IllegalStateException();
}
// Spliterator implementation for 0 or 1 element
// count == -1 for no elements
// count == -2 for one element held by first
@Override
public boolean tryAdvance(IntConsumer action) {
Objects.requireNonNull(action);
if(count == -2) {
action.accept(first);
count = -1;
return true;
} else {
return false;
}
}
@Override
public void forEachRemaining(IntConsumer action) {
Objects.requireNonNull(action);
if(count == -2) {
action.accept(first);
count = -1;
}
}
}
static final class LongStreamBuilderImpl
extends AbstractStreamBuilderImpl<Long, Spliterator.OfLong>
implements LongStream.Builder, Spliterator.OfLong {
// The first element in the stream
// valid if count == 1
long first;
// The first and subsequent elements in the stream
// non-null if count == 2
SpinedBuffer.OfLong buffer;
/**
* Constructor for building a stream of 0 or more elements.
*/
LongStreamBuilderImpl() {
}
/**
* Constructor for a singleton stream.
*
* @param t the single element
*/
LongStreamBuilderImpl(long t) {
first = t;
count = -2;
}
// StreamBuilder implementation
@Override
public void accept(long t) {
if(count == 0) {
first = t;
count++;
} else if(count > 0) {
if(buffer == null) {
buffer = new SpinedBuffer.OfLong();
buffer.accept(first);
count++;
}
buffer.accept(t);
} else {
throw new IllegalStateException();
}
}
@Override
public LongStream build() {
int c = count;
if(c >= 0) {
// Switch count to negative value signalling the builder is built
count = -count - 1;
// Use this spliterator if 0 or 1 elements, otherwise use
// the spliterator of the spined buffer
return (c < 2) ? StreamSupport.longStream(this, false) : StreamSupport.longStream(buffer.spliterator(), false);
}
throw new IllegalStateException();
}
// Spliterator implementation for 0 or 1 element
// count == -1 for no elements
// count == -2 for one element held by first
@Override
public boolean tryAdvance(LongConsumer action) {
Objects.requireNonNull(action);
if(count == -2) {
action.accept(first);
count = -1;
return true;
} else {
return false;
}
}
@Override
public void forEachRemaining(LongConsumer action) {
Objects.requireNonNull(action);
if(count == -2) {
action.accept(first);
count = -1;
}
}
}
static final class DoubleStreamBuilderImpl
extends AbstractStreamBuilderImpl<Double, Spliterator.OfDouble>
implements DoubleStream.Builder, Spliterator.OfDouble {
// The first element in the stream
// valid if count == 1
double first;
// The first and subsequent elements in the stream
// non-null if count == 2
SpinedBuffer.OfDouble buffer;
/**
* Constructor for building a stream of 0 or more elements.
*/
DoubleStreamBuilderImpl() {
}
/**
* Constructor for a singleton stream.
*
* @param t the single element
*/
DoubleStreamBuilderImpl(double t) {
first = t;
count = -2;
}
// StreamBuilder implementation
@Override
public void accept(double t) {
if(count == 0) {
first = t;
count++;
} else if(count > 0) {
if(buffer == null) {
buffer = new SpinedBuffer.OfDouble();
buffer.accept(first);
count++;
}
buffer.accept(t);
} else {
throw new IllegalStateException();
}
}
@Override
public DoubleStream build() {
int c = count;
if(c >= 0) {
// Switch count to negative value signalling the builder is built
count = -count - 1;
// Use this spliterator if 0 or 1 elements, otherwise use
// the spliterator of the spined buffer
return (c < 2) ? StreamSupport.doubleStream(this, false) : StreamSupport.doubleStream(buffer.spliterator(), false);
}
throw new IllegalStateException();
}
// Spliterator implementation for 0 or 1 element
// count == -1 for no elements
// count == -2 for one element held by first
@Override
public boolean tryAdvance(DoubleConsumer action) {
Objects.requireNonNull(action);
if(count == -2) {
action.accept(first);
count = -1;
return true;
} else {
return false;
}
}
@Override
public void forEachRemaining(DoubleConsumer action) {
Objects.requireNonNull(action);
if(count == -2) {
action.accept(first);
count = -1;
}
}
}
/*▲ Stream构建器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 专用Spliterator,参见Stream#concat ████████████████████████████████████████████████████████████████████████████████┓ */
abstract static class ConcatSpliterator<T, T_SPLITR extends Spliterator<T>>
implements Spliterator<T> {
protected final T_SPLITR aSpliterator;
protected final T_SPLITR bSpliterator;
// Never read after splitting
final boolean unsized;
// True when no split has occurred, otherwise false
boolean beforeSplit;
public ConcatSpliterator(T_SPLITR aSpliterator, T_SPLITR bSpliterator) {
this.aSpliterator = aSpliterator;
this.bSpliterator = bSpliterator;
beforeSplit = true;
// The spliterator is known to be unsized before splitting if the
// sum of the estimates overflows.
unsized = aSpliterator.estimateSize() + bSpliterator.estimateSize() < 0;
}
@Override
public T_SPLITR trySplit() {
@SuppressWarnings("unchecked")
T_SPLITR ret = beforeSplit ? aSpliterator : (T_SPLITR) bSpliterator.trySplit();
beforeSplit = false;
return ret;
}
@Override
public boolean tryAdvance(Consumer<? super T> consumer) {
boolean hasNext;
if(beforeSplit) {
hasNext = aSpliterator.tryAdvance(consumer);
if(!hasNext) {
beforeSplit = false;
hasNext = bSpliterator.tryAdvance(consumer);
}
} else
hasNext = bSpliterator.tryAdvance(consumer);
return hasNext;
}
@Override
public void forEachRemaining(Consumer<? super T> consumer) {
if(beforeSplit)
aSpliterator.forEachRemaining(consumer);
bSpliterator.forEachRemaining(consumer);
}
@Override
public long estimateSize() {
if(beforeSplit) {
// If one or both estimates are Long.MAX_VALUE then the sum
// will either be Long.MAX_VALUE or overflow to a negative value
long size = aSpliterator.estimateSize() + bSpliterator.estimateSize();
return (size >= 0) ? size : Long.MAX_VALUE;
} else {
return bSpliterator.estimateSize();
}
}
@Override
public int characteristics() {
if(beforeSplit) {
// Concatenation loses DISTINCT and SORTED characteristics
return aSpliterator.characteristics() & bSpliterator.characteristics() & ~(Spliterator.DISTINCT | Spliterator.SORTED | (unsized ? Spliterator.SIZED | Spliterator.SUBSIZED : 0));
} else {
return bSpliterator.characteristics();
}
}
@Override
public Comparator<? super T> getComparator() {
if(beforeSplit)
throw new IllegalStateException();
return bSpliterator.getComparator();
}
static class OfRef<T> extends ConcatSpliterator<T, Spliterator<T>> {
OfRef(Spliterator<T> aSpliterator, Spliterator<T> bSpliterator) {
super(aSpliterator, bSpliterator);
}
}
private abstract static class OfPrimitive<T, T_CONS, T_SPLITR extends Spliterator.OfPrimitive<T, T_CONS, T_SPLITR>>
extends ConcatSpliterator<T, T_SPLITR>
implements Spliterator.OfPrimitive<T, T_CONS, T_SPLITR> {
private OfPrimitive(T_SPLITR aSpliterator, T_SPLITR bSpliterator) {
super(aSpliterator, bSpliterator);
}
@Override
public boolean tryAdvance(T_CONS action) {
boolean hasNext;
if(beforeSplit) {
hasNext = aSpliterator.tryAdvance(action);
if(!hasNext) {
beforeSplit = false;
hasNext = bSpliterator.tryAdvance(action);
}
} else
hasNext = bSpliterator.tryAdvance(action);
return hasNext;
}
@Override
public void forEachRemaining(T_CONS action) {
if(beforeSplit)
aSpliterator.forEachRemaining(action);
bSpliterator.forEachRemaining(action);
}
}
static class OfInt
extends ConcatSpliterator.OfPrimitive<Integer, IntConsumer, Spliterator.OfInt>
implements Spliterator.OfInt {
OfInt(Spliterator.OfInt aSpliterator, Spliterator.OfInt bSpliterator) {
super(aSpliterator, bSpliterator);
}
}
static class OfLong
extends ConcatSpliterator.OfPrimitive<Long, LongConsumer, Spliterator.OfLong>
implements Spliterator.OfLong {
OfLong(Spliterator.OfLong aSpliterator, Spliterator.OfLong bSpliterator) {
super(aSpliterator, bSpliterator);
}
}
static class OfDouble
extends ConcatSpliterator.OfPrimitive<Double, DoubleConsumer, Spliterator.OfDouble>
implements Spliterator.OfDouble {
OfDouble(Spliterator.OfDouble aSpliterator, Spliterator.OfDouble bSpliterator) {
super(aSpliterator, bSpliterator);
}
}
}
/*▲ 专用Spliterator,参见Stream#concat ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 专用Spliterator,参见IntStream#range ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* An {@code int} range spliterator.
*/
static final class RangeIntSpliterator
implements Spliterator.OfInt {
/**
* The spliterator size below which the spliterator will be split
* at the mid-point to produce balanced splits. Above this size the
* spliterator will be split at a ratio of
* 1:(RIGHT_BALANCED_SPLIT_RATIO - 1)
* to produce right-balanced splits.
*
* <p>Such splitting ensures that for very large ranges that the left
* side of the range will more likely be processed at a lower-depth
* than a balanced tree at the expense of a higher-depth for the right
* side of the range.
*
* <p>This is optimized for cases such as IntStream.range(0, Integer.MAX_VALUE)
* that is likely to be augmented with a limit operation that limits the
* number of elements to a count lower than this threshold.
*/
private static final int BALANCED_SPLIT_THRESHOLD = 1 << 24;
/**
* The split ratio of the left and right split when the spliterator
* size is above BALANCED_SPLIT_THRESHOLD.
*/
private static final int RIGHT_BALANCED_SPLIT_RATIO = 1 << 3;
private final int upTo;
// Can never be greater that upTo, this avoids overflow if upper bound
// is Integer.MAX_VALUE
// All elements are traversed if from == upTo & last == 0
private int from;
// 1 if the range is closed and the last element has not been traversed
// Otherwise, 0 if the range is open, or is a closed range and all
// elements have been traversed
private int last;
RangeIntSpliterator(int from, int upTo, boolean closed) {
this(from, upTo, closed ? 1 : 0);
}
private RangeIntSpliterator(int from, int upTo, int last) {
this.from = from;
this.upTo = upTo;
this.last = last;
}
@Override
public boolean tryAdvance(IntConsumer consumer) {
Objects.requireNonNull(consumer);
final int i = from;
if(i < upTo) {
from++;
consumer.accept(i);
return true;
} else if(last > 0) {
last = 0;
consumer.accept(i);
return true;
}
return false;
}
@Override
@HotSpotIntrinsicCandidate
public void forEachRemaining(IntConsumer consumer) {
Objects.requireNonNull(consumer);
int i = from;
final int hUpTo = upTo;
int hLast = last;
from = upTo;
last = 0;
while(i < hUpTo) {
consumer.accept(i++);
}
if(hLast > 0) {
// Last element of closed range
consumer.accept(i);
}
}
@Override
public long estimateSize() {
// Ensure ranges of size > Integer.MAX_VALUE report the correct size
return ((long) upTo) - from + last;
}
@Override
public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE | Spliterator.NONNULL | Spliterator.DISTINCT | Spliterator.SORTED;
}
@Override
public Comparator<? super Integer> getComparator() {
return null;
}
@Override
public Spliterator.OfInt trySplit() {
long size = estimateSize();
return size <= 1 ? null
// Left split always has a half-open range
: new RangeIntSpliterator(from, from = from + splitPoint(size), 0);
}
private int splitPoint(long size) {
int d = (size < BALANCED_SPLIT_THRESHOLD) ? 2 : RIGHT_BALANCED_SPLIT_RATIO;
// Cast to int is safe since:
// 2 <= size < 2^32
// 2 <= d <= 8
return (int) (size / d);
}
}
/*▲ 专用Spliterator,参见IntStream#range ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 专用Spliterator,参见LongStream#range ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* A {@code long} range spliterator.
*
* This implementation cannot be used for ranges whose size is greater
* than Long.MAX_VALUE
*/
static final class RangeLongSpliterator
implements Spliterator.OfLong {
/**
* The spliterator size below which the spliterator will be split
* at the mid-point to produce balanced splits. Above this size the
* spliterator will be split at a ratio of
* 1:(RIGHT_BALANCED_SPLIT_RATIO - 1)
* to produce right-balanced splits.
*
* <p>Such splitting ensures that for very large ranges that the left
* side of the range will more likely be processed at a lower-depth
* than a balanced tree at the expense of a higher-depth for the right
* side of the range.
*
* <p>This is optimized for cases such as LongStream.range(0, Long.MAX_VALUE)
* that is likely to be augmented with a limit operation that limits the
* number of elements to a count lower than this threshold.
*/
private static final long BALANCED_SPLIT_THRESHOLD = 1 << 24;
/**
* The split ratio of the left and right split when the spliterator
* size is above BALANCED_SPLIT_THRESHOLD.
*/
private static final long RIGHT_BALANCED_SPLIT_RATIO = 1 << 3;
private final long upTo;
// Can never be greater that upTo, this avoids overflow if upper bound
// is Long.MAX_VALUE
// All elements are traversed if from == upTo & last == 0
private long from;
// 1 if the range is closed and the last element has not been traversed
// Otherwise, 0 if the range is open, or is a closed range and all
// elements have been traversed
private int last;
RangeLongSpliterator(long from, long upTo, boolean closed) {
this(from, upTo, closed ? 1 : 0);
}
private RangeLongSpliterator(long from, long upTo, int last) {
assert upTo - from + last > 0;
this.from = from;
this.upTo = upTo;
this.last = last;
}
@Override
public boolean tryAdvance(LongConsumer consumer) {
Objects.requireNonNull(consumer);
final long i = from;
if(i < upTo) {
from++;
consumer.accept(i);
return true;
} else if(last > 0) {
last = 0;
consumer.accept(i);
return true;
}
return false;
}
@Override
public void forEachRemaining(LongConsumer consumer) {
Objects.requireNonNull(consumer);
long i = from;
final long hUpTo = upTo;
int hLast = last;
from = upTo;
last = 0;
while(i < hUpTo) {
consumer.accept(i++);
}
if(hLast > 0) {
// Last element of closed range
consumer.accept(i);
}
}
@Override
public long estimateSize() {
return upTo - from + last;
}
@Override
public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE | Spliterator.NONNULL | Spliterator.DISTINCT | Spliterator.SORTED;
}
@Override
public Comparator<? super Long> getComparator() {
return null;
}
@Override
public Spliterator.OfLong trySplit() {
long size = estimateSize();
return size <= 1 ? null
// Left split always has a half-open range
: new RangeLongSpliterator(from, from = from + splitPoint(size), 0);
}
private long splitPoint(long size) {
long d = (size < BALANCED_SPLIT_THRESHOLD) ? 2 : RIGHT_BALANCED_SPLIT_RATIO;
// 2 <= size <= Long.MAX_VALUE
return size / d;
}
}
/*▲ 专用Spliterator,参见LongStream#range ████████████████████████████████████████████████████████████████████████████████┛ */
/**
* Given two Runnables, return a Runnable that executes both in sequence,
* even if the first throws an exception, and if both throw exceptions, add
* any exceptions thrown by the second as suppressed exceptions of the first.
*/
static Runnable composeWithExceptions(Runnable a, Runnable b) {
return () -> {
try {
a.run();
} catch(Throwable e1) {
try {
b.run();
} catch(Throwable e2) {
try {
e1.addSuppressed(e2);
} catch(Throwable ignore) {
}
}
throw e1;
}
b.run();
};
}
/**
* Given two streams, return a Runnable that
* executes both of their {@link BaseStream#close} methods in sequence,
* even if the first throws an exception, and if both throw exceptions, add
* any exceptions thrown by the second as suppressed exceptions of the first.
*/
static Runnable composedClose(BaseStream<?, ?> a, BaseStream<?, ?> b) {
return () -> {
try {
a.close();
} catch(Throwable e1) {
try {
b.close();
} catch(Throwable e2) {
try {
e1.addSuppressed(e2);
} catch(Throwable ignore) {
}
}
throw e1;
}
b.close();
};
}
}