• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

amaembo / streamex / #667

02 Sep 2023 01:21PM UTC coverage: 99.462% (-0.2%) from 99.619%
#667

push

amaembo
One more test for Limiter

5733 of 5764 relevant lines covered (99.46%)

0.99 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

99.0
/src/main/java/one/util/streamex/Internals.java
1
/*
2
 * Copyright 2015, 2019 StreamEx contributors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
package one.util.streamex;
17

18
import java.math.BigDecimal;
19
import java.math.BigInteger;
20
import java.math.MathContext;
21
import java.nio.ByteOrder;
22
import java.util.AbstractCollection;
23
import java.util.AbstractMap;
24
import java.util.AbstractSet;
25
import java.util.Arrays;
26
import java.util.BitSet;
27
import java.util.EnumSet;
28
import java.util.Iterator;
29
import java.util.Map;
30
import java.util.Map.Entry;
31
import java.util.Objects;
32
import java.util.Optional;
33
import java.util.OptionalDouble;
34
import java.util.OptionalInt;
35
import java.util.OptionalLong;
36
import java.util.Set;
37
import java.util.Spliterator;
38
import java.util.function.BiConsumer;
39
import java.util.function.BinaryOperator;
40
import java.util.function.Consumer;
41
import java.util.function.Function;
42
import java.util.function.ObjDoubleConsumer;
43
import java.util.function.ObjIntConsumer;
44
import java.util.function.ObjLongConsumer;
45
import java.util.function.Predicate;
46
import java.util.function.Supplier;
47
import java.util.stream.Collector;
48
import java.util.stream.Collector.Characteristics;
49

50
/* package */interface Internals {
51
    int INITIAL_SIZE = 128;
52
    Function<int[], Integer> UNBOX_INT = box -> box[0];
1✔
53
    Function<long[], Long> UNBOX_LONG = box -> box[0];
1✔
54
    Function<double[], Double> UNBOX_DOUBLE = box -> box[0];
1✔
55
    Object NONE = new Object();
1✔
56
    Set<Characteristics> NO_CHARACTERISTICS = EnumSet.noneOf(Characteristics.class);
1✔
57
    Set<Characteristics> UNORDERED_CHARACTERISTICS = EnumSet.of(Characteristics.UNORDERED);
1✔
58
    Set<Characteristics> UNORDERED_ID_CHARACTERISTICS = EnumSet.of(Characteristics.UNORDERED,
1✔
59
        Characteristics.IDENTITY_FINISH);
60
    Set<Characteristics> ID_CHARACTERISTICS = EnumSet.of(Characteristics.IDENTITY_FINISH);
1✔
61
    boolean IMMUTABLE_TO_LIST = isImmutableToSetToList();
1✔
62

63
    static boolean isImmutableToSetToList() {
64
        try {
65
            return Boolean.parseBoolean(System.getProperty("streamex.default.immutable", "false"));
1✔
66
        } catch (SecurityException e) {
×
67
            return false;
×
68
        }
69
    }
70

71
    static void checkNonNegative(String name, int value) {
72
        if (value < 0) {
1✔
73
            throw new IllegalArgumentException(name + " must be non-negative: " + value);
1✔
74
        }
75
    }
1✔
76

77
    final class ByteBuffer {
78
        int size = 0;
1✔
79
        byte[] data;
80

81
        ByteBuffer() {
1✔
82
            data = new byte[INITIAL_SIZE];
1✔
83
        }
1✔
84

85
        ByteBuffer(int size) {
1✔
86
            data = new byte[size];
1✔
87
        }
1✔
88

89
        void add(int n) {
90
            if (data.length == size) {
1✔
91
                data = Arrays.copyOf(data, data.length * 2);
1✔
92
            }
93
            data[size++] = (byte) n;
1✔
94
        }
1✔
95

96
        void addUnsafe(int n) {
97
            data[size++] = (byte) n;
1✔
98
        }
1✔
99

100
        void addAll(ByteBuffer buf) {
101
            if (data.length < buf.size + size) {
1✔
102
                data = Arrays.copyOf(data, buf.size + size);
1✔
103
            }
104
            System.arraycopy(buf.data, 0, data, size, buf.size);
1✔
105
            size += buf.size;
1✔
106
        }
1✔
107

108
        byte[] toArray() {
109
            return data.length == size ? data : Arrays.copyOfRange(data, 0, size);
1✔
110
        }
111
    }
112

113
    final class CharBuffer {
114
        int size = 0;
1✔
115
        char[] data;
116

117
        CharBuffer() {
1✔
118
            data = new char[INITIAL_SIZE];
1✔
119
        }
1✔
120

121
        CharBuffer(int size) {
1✔
122
            data = new char[size];
1✔
123
        }
1✔
124

125
        void add(int n) {
126
            if (data.length == size) {
1✔
127
                data = Arrays.copyOf(data, data.length * 2);
1✔
128
            }
129
            data[size++] = (char) n;
1✔
130
        }
1✔
131

132
        void addUnsafe(int n) {
133
            data[size++] = (char) n;
1✔
134
        }
1✔
135

136
        void addAll(CharBuffer buf) {
137
            if (data.length < buf.size + size) {
1✔
138
                data = Arrays.copyOf(data, buf.size + size);
1✔
139
            }
140
            System.arraycopy(buf.data, 0, data, size, buf.size);
1✔
141
            size += buf.size;
1✔
142
        }
1✔
143

144
        char[] toArray() {
145
            return data.length == size ? data : Arrays.copyOfRange(data, 0, size);
1✔
146
        }
147
    }
148

149
    final class ShortBuffer {
150
        int size = 0;
1✔
151
        short[] data;
152

153
        ShortBuffer() {
1✔
154
            data = new short[INITIAL_SIZE];
1✔
155
        }
1✔
156

157
        ShortBuffer(int size) {
1✔
158
            data = new short[size];
1✔
159
        }
1✔
160

161
        void add(int n) {
162
            if (data.length == size) {
1✔
163
                data = Arrays.copyOf(data, data.length * 2);
1✔
164
            }
165
            data[size++] = (short) n;
1✔
166
        }
1✔
167

168
        void addUnsafe(int n) {
169
            data[size++] = (short) n;
1✔
170
        }
1✔
171

172
        void addAll(ShortBuffer buf) {
173
            if (data.length < buf.size + size) {
1✔
174
                data = Arrays.copyOf(data, buf.size + size);
1✔
175
            }
176
            System.arraycopy(buf.data, 0, data, size, buf.size);
1✔
177
            size += buf.size;
1✔
178
        }
1✔
179

180
        short[] toArray() {
181
            return data.length == size ? data : Arrays.copyOfRange(data, 0, size);
1✔
182
        }
183
    }
184

185
    final class FloatBuffer {
186
        int size = 0;
1✔
187
        float[] data;
188

189
        FloatBuffer() {
1✔
190
            data = new float[INITIAL_SIZE];
1✔
191
        }
1✔
192

193
        FloatBuffer(int size) {
1✔
194
            data = new float[size];
1✔
195
        }
1✔
196

197
        void add(double n) {
198
            if (data.length == size) {
1✔
199
                data = Arrays.copyOf(data, data.length * 2);
1✔
200
            }
201
            data[size++] = (float) n;
1✔
202
        }
1✔
203

204
        void addUnsafe(double n) {
205
            data[size++] = (float) n;
1✔
206
        }
1✔
207

208
        void addAll(FloatBuffer buf) {
209
            if (data.length < buf.size + size) {
1✔
210
                data = Arrays.copyOf(data, buf.size + size);
1✔
211
            }
212
            System.arraycopy(buf.data, 0, data, size, buf.size);
1✔
213
            size += buf.size;
1✔
214
        }
1✔
215

216
        float[] toArray() {
217
            return data.length == size ? data : Arrays.copyOfRange(data, 0, size);
1✔
218
        }
219
    }
220

221
    final class IntBuffer {
222
        int size = 0;
1✔
223
        int[] data;
224

225
        IntBuffer() {
1✔
226
            data = new int[INITIAL_SIZE];
1✔
227
        }
1✔
228

229
        IntBuffer(int size) {
1✔
230
            data = new int[size];
1✔
231
        }
1✔
232

233
        void add(int n) {
234
            if (data.length == size) {
1✔
235
                data = Arrays.copyOf(data, data.length * 2);
1✔
236
            }
237
            data[size++] = n;
1✔
238
        }
1✔
239

240
        void addAll(IntBuffer buf) {
241
            if (data.length < buf.size + size) {
1✔
242
                data = Arrays.copyOf(data, buf.size + size);
1✔
243
            }
244
            System.arraycopy(buf.data, 0, data, size, buf.size);
1✔
245
            size += buf.size;
1✔
246
        }
1✔
247

248
        int[] toArray() {
249
            return data.length == size ? data : Arrays.copyOfRange(data, 0, size);
1✔
250
        }
251
    }
252

253
    final class LongBuffer {
254
        int size = 0;
1✔
255
        long[] data;
256

257
        LongBuffer() {
1✔
258
            data = new long[INITIAL_SIZE];
1✔
259
        }
1✔
260

261
        LongBuffer(int size) {
1✔
262
            data = new long[size];
1✔
263
        }
1✔
264

265
        void add(long n) {
266
            if (data.length == size) {
1✔
267
                data = Arrays.copyOf(data, data.length * 2);
1✔
268
            }
269
            data[size++] = n;
1✔
270
        }
1✔
271

272
        void addAll(LongBuffer buf) {
273
            if (data.length < buf.size + size) {
1✔
274
                data = Arrays.copyOf(data, buf.size + size);
1✔
275
            }
276
            System.arraycopy(buf.data, 0, data, size, buf.size);
1✔
277
            size += buf.size;
1✔
278
        }
1✔
279

280
        long[] toArray() {
281
            return data.length == size ? data : Arrays.copyOfRange(data, 0, size);
1✔
282
        }
283
    }
284

285
    final class DoubleBuffer {
286
        int size = 0;
1✔
287
        double[] data;
288

289
        DoubleBuffer() {
1✔
290
            data = new double[INITIAL_SIZE];
1✔
291
        }
1✔
292

293
        DoubleBuffer(int size) {
1✔
294
            data = new double[size];
1✔
295
        }
1✔
296

297
        void add(double n) {
298
            if (data.length == size) {
1✔
299
                data = Arrays.copyOf(data, data.length * 2);
1✔
300
            }
301
            data[size++] = n;
1✔
302
        }
1✔
303

304
        void addAll(DoubleBuffer buf) {
305
            if (data.length < buf.size + size) {
1✔
306
                data = Arrays.copyOf(data, buf.size + size);
1✔
307
            }
308
            System.arraycopy(buf.data, 0, data, size, buf.size);
1✔
309
            size += buf.size;
1✔
310
        }
1✔
311

312
        double[] toArray() {
313
            return data.length == size ? data : Arrays.copyOfRange(data, 0, size);
1✔
314
        }
315
    }
316

317
    final class BooleanMap<T> extends AbstractMap<Boolean, T> {
318
        T trueValue, falseValue;
319

320
        BooleanMap(T trueValue, T falseValue) {
1✔
321
            this.trueValue = trueValue;
1✔
322
            this.falseValue = falseValue;
1✔
323
        }
1✔
324

325
        @Override
326
        public boolean containsKey(Object key) {
327
            return key instanceof Boolean;
1✔
328
        }
329

330
        @Override
331
        public T get(Object key) {
332
            if (Boolean.TRUE.equals(key))
1✔
333
                return trueValue;
1✔
334
            if (Boolean.FALSE.equals(key))
1✔
335
                return falseValue;
1✔
336
            return null;
1✔
337
        }
338

339
        @Override
340
        public Set<Map.Entry<Boolean, T>> entrySet() {
341
            return new AbstractSet<Map.Entry<Boolean, T>>() {
1✔
342
                @Override
343
                public Iterator<Map.Entry<Boolean, T>> iterator() {
344
                    return Arrays.<Map.Entry<Boolean, T>>asList(new SimpleEntry<>(Boolean.TRUE, trueValue),
1✔
345
                        new SimpleEntry<>(Boolean.FALSE, falseValue)).iterator();
1✔
346
                }
347

348
                @Override
349
                public int size() {
350
                    return 2;
1✔
351
                }
352
            };
353
        }
354

355
        @Override
356
        public int size() {
357
            return 2;
1✔
358
        }
359

360
        @SuppressWarnings({ "unchecked", "rawtypes" })
361
        static <A, R> PartialCollector<BooleanMap<A>, Map<Boolean, R>> partialCollector(Collector<?, A, R> downstream) {
362
            Supplier<A> downstreamSupplier = downstream.supplier();
1✔
363
            Supplier<BooleanMap<A>> supplier = () -> new BooleanMap<>(downstreamSupplier.get(), downstreamSupplier
1✔
364
                    .get());
1✔
365
            BinaryOperator<A> downstreamCombiner = downstream.combiner();
1✔
366
            BiConsumer<BooleanMap<A>, BooleanMap<A>> merger = (left, right) -> {
1✔
367
                left.trueValue = downstreamCombiner.apply(left.trueValue, right.trueValue);
1✔
368
                left.falseValue = downstreamCombiner.apply(left.falseValue, right.falseValue);
1✔
369
            };
1✔
370
            if (downstream.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)) {
1✔
371
                return (PartialCollector) new PartialCollector<>(supplier, merger, Function.identity(),
1✔
372
                        ID_CHARACTERISTICS);
373
            }
374
            Function<A, R> downstreamFinisher = downstream.finisher();
1✔
375
            return new PartialCollector<>(supplier, merger, par -> new BooleanMap<>(downstreamFinisher
1✔
376
                    .apply(par.trueValue), downstreamFinisher.apply(par.falseValue)), NO_CHARACTERISTICS);
1✔
377
        }
378
    }
379

380
    abstract class BaseCollector<T, A, R> implements MergingCollector<T, A, R> {
381
        final Supplier<A> supplier;
382
        final BiConsumer<A, A> merger;
383
        final Function<A, R> finisher;
384
        final Set<Characteristics> characteristics;
385

386
        BaseCollector(Supplier<A> supplier, BiConsumer<A, A> merger, Function<A, R> finisher,
387
                Set<Characteristics> characteristics) {
1✔
388
            this.supplier = supplier;
1✔
389
            this.merger = merger;
1✔
390
            this.finisher = finisher;
1✔
391
            this.characteristics = characteristics;
1✔
392
        }
1✔
393

394
        @Override
395
        public Set<Characteristics> characteristics() {
396
            return characteristics;
1✔
397
        }
398

399
        @Override
400
        public Supplier<A> supplier() {
401
            return supplier;
1✔
402
        }
403

404
        @Override
405
        public Function<A, R> finisher() {
406
            return finisher;
1✔
407
        }
408

409
        @Override
410
        public BiConsumer<A, A> merger() {
411
            return merger;
1✔
412
        }
413
    }
414

415
    final class PartialCollector<A, R> extends BaseCollector<Object, A, R> {
416
        PartialCollector(Supplier<A> supplier, BiConsumer<A, A> merger, Function<A, R> finisher,
417
                Set<Characteristics> characteristics) {
418
            super(supplier, merger, finisher, characteristics);
1✔
419
        }
1✔
420

421
        @Override
422
        public BiConsumer<A, Object> accumulator() {
423
            throw new UnsupportedOperationException();
1✔
424
        }
425

426
        IntCollector<A, R> asInt(ObjIntConsumer<A> intAccumulator) {
427
            return new IntCollectorImpl<>(supplier, intAccumulator, merger, finisher, characteristics);
1✔
428
        }
429

430
        LongCollector<A, R> asLong(ObjLongConsumer<A> longAccumulator) {
431
            return new LongCollectorImpl<>(supplier, longAccumulator, merger, finisher, characteristics);
1✔
432
        }
433

434
        DoubleCollector<A, R> asDouble(ObjDoubleConsumer<A> doubleAccumulator) {
435
            return new DoubleCollectorImpl<>(supplier, doubleAccumulator, merger, finisher, characteristics);
1✔
436
        }
437

438
        <T> Collector<T, A, R> asRef(BiConsumer<A, T> accumulator) {
439
            return Collector.of(supplier, accumulator, combiner(), finisher, characteristics
1✔
440
                    .toArray(new Characteristics[0]));
1✔
441
        }
442

443
        <T> Collector<T, A, R> asCancellable(BiConsumer<A, T> accumulator, Predicate<A> finished) {
444
            return new CancellableCollectorImpl<>(supplier, accumulator, combiner(), finisher, finished,
1✔
445
                    characteristics);
446
        }
447

448
        static PartialCollector<int[], Integer> intSum() {
449
            return new PartialCollector<>(() -> new int[1], (box1, box2) -> box1[0] += box2[0], UNBOX_INT,
1✔
450
                    UNORDERED_CHARACTERISTICS);
451
        }
452

453
        static PartialCollector<long[], Long> longSum() {
454
            return new PartialCollector<>(() -> new long[1], (box1, box2) -> box1[0] += box2[0], UNBOX_LONG,
1✔
455
                    UNORDERED_CHARACTERISTICS);
456
        }
457

458
        static PartialCollector<ObjIntBox<BitSet>, boolean[]> booleanArray() {
459
            return new PartialCollector<>(() -> new ObjIntBox<>(new BitSet(), 0), (box1, box2) -> {
1✔
460
                box2.a.stream().forEach(i -> box1.a.set(i + box1.b));
1✔
461
                box1.b = StrictMath.addExact(box1.b, box2.b);
1✔
462
            }, box -> {
1✔
463
                boolean[] res = new boolean[box.b];
1✔
464
                box.a.stream().forEach(i -> res[i] = true);
1✔
465
                return res;
1✔
466
            }, NO_CHARACTERISTICS);
467
        }
468

469
        @SuppressWarnings("unchecked")
470
        static <K, D, A, M extends Map<K, D>> PartialCollector<Map<K, A>, M> grouping(Supplier<M> mapFactory,
471
                Collector<?, A, D> downstream) {
472
            BinaryOperator<A> downstreamMerger = downstream.combiner();
1✔
473
            BiConsumer<Map<K, A>, Map<K, A>> merger = (map1, map2) -> {
1✔
474
                for (Map.Entry<K, A> e : map2.entrySet())
1✔
475
                    map1.merge(e.getKey(), e.getValue(), downstreamMerger);
1✔
476
            };
1✔
477

478
            if (downstream.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)) {
1✔
479
                return (PartialCollector<Map<K, A>, M>) new PartialCollector<>((Supplier<Map<K, A>>) mapFactory,
1✔
480
                        merger, Function.identity(), ID_CHARACTERISTICS);
1✔
481
            }
482
            Function<A, D> downstreamFinisher = downstream.finisher();
1✔
483
            return new PartialCollector<>((Supplier<Map<K, A>>) mapFactory, merger, map -> {
1✔
484
                map.replaceAll((k, v) -> ((Function<A, A>) downstreamFinisher).apply(v));
1✔
485
                return (M) map;
1✔
486
            }, NO_CHARACTERISTICS);
487
        }
488

489
        static PartialCollector<StringBuilder, String> joining(CharSequence delimiter, CharSequence prefix,
490
                CharSequence suffix, boolean hasPS) {
491
            BiConsumer<StringBuilder, StringBuilder> merger = (sb1, sb2) -> {
1✔
492
                if (sb2.length() > 0) {
1✔
493
                    if (sb1.length() > 0)
1✔
494
                        sb1.append(delimiter);
1✔
495
                    sb1.append(sb2);
1✔
496
                }
497
            };
1✔
498
            Supplier<StringBuilder> supplier = StringBuilder::new;
1✔
499
            if (hasPS)
1✔
500
                return new PartialCollector<>(supplier, merger, sb -> String.valueOf(prefix) + sb + suffix,
1✔
501
                        NO_CHARACTERISTICS);
502
            return new PartialCollector<>(supplier, merger, StringBuilder::toString, NO_CHARACTERISTICS);
1✔
503
        }
504
    }
505

506
    final class CancellableCollectorImpl<T, A, R> extends CancellableCollector<T, A, R> {
507
        private final Supplier<A> supplier;
508
        private final BiConsumer<A, T> accumulator;
509
        private final BinaryOperator<A> combiner;
510
        private final Function<A, R> finisher;
511
        private final Predicate<A> finished;
512
        private final Set<Characteristics> characteristics;
513

514
        CancellableCollectorImpl(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner,
515
                                 Function<A, R> finisher, Predicate<A> finished,
516
                                 Set<java.util.stream.Collector.Characteristics> characteristics) {
1✔
517
            this.supplier = supplier;
1✔
518
            this.accumulator = accumulator;
1✔
519
            this.combiner = combiner;
1✔
520
            this.finisher = finisher;
1✔
521
            this.finished = finished;
1✔
522
            this.characteristics = characteristics;
1✔
523
        }
1✔
524

525
        @Override
526
        public Supplier<A> supplier() {
527
            return supplier;
1✔
528
        }
529

530
        @Override
531
        public BiConsumer<A, T> accumulator() {
532
            return accumulator;
1✔
533
        }
534

535
        @Override
536
        public BinaryOperator<A> combiner() {
537
            return combiner;
1✔
538
        }
539

540
        @Override
541
        public Function<A, R> finisher() {
542
            return finisher;
1✔
543
        }
544

545
        @Override
546
        public Set<Characteristics> characteristics() {
547
            return characteristics;
1✔
548
        }
549

550
        @Override
551
        Predicate<A> finished() {
552
            return finished;
1✔
553
        }
554
    }
555

556
    final class IntCollectorImpl<A, R> extends BaseCollector<Integer, A, R> implements IntCollector<A, R> {
557
        private final ObjIntConsumer<A> intAccumulator;
558

559
        IntCollectorImpl(Supplier<A> supplier, ObjIntConsumer<A> intAccumulator, BiConsumer<A, A> merger,
560
                         Function<A, R> finisher, Set<Characteristics> characteristics) {
561
            super(supplier, merger, finisher, characteristics);
1✔
562
            this.intAccumulator = intAccumulator;
1✔
563
        }
1✔
564

565
        @Override
566
        public ObjIntConsumer<A> intAccumulator() {
567
            return intAccumulator;
1✔
568
        }
569
    }
570

571
    final class LongCollectorImpl<A, R> extends BaseCollector<Long, A, R> implements LongCollector<A, R> {
572
        private final ObjLongConsumer<A> longAccumulator;
573

574
        LongCollectorImpl(Supplier<A> supplier, ObjLongConsumer<A> longAccumulator, BiConsumer<A, A> merger,
575
                          Function<A, R> finisher, Set<Characteristics> characteristics) {
576
            super(supplier, merger, finisher, characteristics);
1✔
577
            this.longAccumulator = longAccumulator;
1✔
578
        }
1✔
579

580
        @Override
581
        public ObjLongConsumer<A> longAccumulator() {
582
            return longAccumulator;
1✔
583
        }
584
    }
585

586
    final class DoubleCollectorImpl<A, R> extends BaseCollector<Double, A, R> implements DoubleCollector<A, R> {
587
        private final ObjDoubleConsumer<A> doubleAccumulator;
588

589
        DoubleCollectorImpl(Supplier<A> supplier, ObjDoubleConsumer<A> doubleAccumulator,
590
                            BiConsumer<A, A> merger, Function<A, R> finisher, Set<Characteristics> characteristics) {
591
            super(supplier, merger, finisher, characteristics);
1✔
592
            this.doubleAccumulator = doubleAccumulator;
1✔
593
        }
1✔
594

595
        @Override
596
        public ObjDoubleConsumer<A> doubleAccumulator() {
597
            return doubleAccumulator;
1✔
598
        }
599
    }
600

601
    class Box<A> implements Consumer<A> {
602
        A a;
603
        
604
        Box() {
1✔
605
        }
1✔
606
        
607
        Box(A obj) {
1✔
608
            this.a = obj;
1✔
609
        }
1✔
610

611
        @Override
612
        public void accept(A a) {
613
            this.a = a;
1✔
614
        }
1✔
615

616
        static <A, R> PartialCollector<Box<A>, R> partialCollector(Collector<?, A, R> c) {
617
            Supplier<A> supplier = c.supplier();
1✔
618
            BinaryOperator<A> combiner = c.combiner();
1✔
619
            Function<A, R> finisher = c.finisher();
1✔
620
            return new PartialCollector<>(() -> new Box<>(supplier.get()), (box1, box2) -> box1.a = combiner.apply(
1✔
621
                box1.a, box2.a), box -> finisher.apply(box.a), NO_CHARACTERISTICS);
1✔
622
        }
623

624
        static <A> Optional<A> asOptional(Box<A> box) {
625
            return box == null ? Optional.empty() : Optional.of(box.a);
1✔
626
        }
627
    }
628

629
    /**
630
     * A box of two elements with special equality semantics: only the second element matters for equality.
631
     * 
632
     * @param <A> type of the first element
633
     * @param <B> type of the second element
634
     */
635
    final class PairBox<A, B> extends Box<A> {
636
        B b;
637

638
        PairBox(A a, B b) {
639
            super(a);
1✔
640
            this.b = b;
1✔
641
        }
1✔
642

643
        static <T> PairBox<T, T> single(T a) {
644
            return new PairBox<>(a, a);
1✔
645
        }
646

647
        @Override
648
        public int hashCode() {
649
            return Objects.hashCode(b);
1✔
650
        }
651

652
        @Override
653
        public boolean equals(Object obj) {
654
            return obj != null && obj.getClass() == PairBox.class && Objects.equals(b, ((PairBox<?, ?>) obj).b);
1✔
655
        }
656
    }
657

658
    final class ObjIntBox<A> extends Box<A> implements Entry<Integer, A> {
659
        int b;
660

661
        ObjIntBox(A a, int b) {
662
            super(a);
1✔
663
            this.b = b;
1✔
664
        }
1✔
665

666
        @Override
667
        public Integer getKey() {
668
            return b;
1✔
669
        }
670

671
        @Override
672
        public A getValue() {
673
            return a;
1✔
674
        }
675

676
        @Override
677
        public A setValue(A value) {
678
            throw new UnsupportedOperationException();
1✔
679
        }
680

681
        @Override
682
        public int hashCode() {
683
            return Integer.hashCode(b) ^ (a == null ? 0 : a.hashCode());
1✔
684
        }
685

686
        @Override
687
        public boolean equals(Object o) {
688
            if (!(o instanceof Map.Entry))
1✔
689
                return false;
1✔
690
            Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
1✔
691
            return getKey().equals(e.getKey()) && Objects.equals(a, e.getValue());
1✔
692
        }
693

694
        @Override
695
        public String toString() {
696
            return b + "=" + a;
1✔
697
        }
698
    }
699

700
    final class ObjLongBox<A> extends Box<A> implements Entry<A, Long> {
701
        long b;
702

703
        ObjLongBox(A a, long b) {
704
            super(a);
1✔
705
            this.b = b;
1✔
706
        }
1✔
707

708
        @Override
709
        public A getKey() {
710
            return a;
1✔
711
        }
712

713
        @Override
714
        public Long getValue() {
715
            return b;
1✔
716
        }
717

718
        @Override
719
        public Long setValue(Long value) {
720
            throw new UnsupportedOperationException();
1✔
721
        }
722

723
        @Override
724
        public int hashCode() {
725
            return Long.hashCode(b) ^ (a == null ? 0 : a.hashCode());
1✔
726
        }
727

728
        @Override
729
        public boolean equals(Object o) {
730
            if (!(o instanceof Map.Entry))
1✔
731
                return false;
1✔
732
            Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
1✔
733
            return getValue().equals(e.getValue()) && Objects.equals(a, e.getKey());
1✔
734
        }
735

736
        @Override
737
        public String toString() {
738
            return a + "=" + b;
1✔
739
        }
740
    }
741

742
    final class ObjDoubleBox<A> extends Box<A> {
743
        double b;
744

745
        ObjDoubleBox(A a, double b) {
746
            super(a);
1✔
747
            this.b = b;
1✔
748
        }
1✔
749
    }
750

751
    final class PrimitiveBox {
1✔
752
        int i;
753
        double d;
754
        long l;
755
        boolean b;
756

757
        OptionalInt asInt() {
758
            return b ? OptionalInt.of(i) : OptionalInt.empty();
1✔
759
        }
760

761
        OptionalLong asLong() {
762
            return b ? OptionalLong.of(l) : OptionalLong.empty();
1✔
763
        }
764

765
        OptionalDouble asDouble() {
766
            return b ? OptionalDouble.of(d) : OptionalDouble.empty();
1✔
767
        }
768

769
        static final BiConsumer<PrimitiveBox, PrimitiveBox> MAX_LONG = (box1, box2) -> {
1✔
770
            if (box2.b && (!box1.b || box1.l < box2.l)) {
1✔
771
                box1.from(box2);
1✔
772
            }
773
        };
1✔
774

775
        static final BiConsumer<PrimitiveBox, PrimitiveBox> MIN_LONG = (box1, box2) -> {
1✔
776
            if (box2.b && (!box1.b || box1.l > box2.l)) {
1✔
777
                box1.from(box2);
1✔
778
            }
779
        };
1✔
780

781
        static final BiConsumer<PrimitiveBox, PrimitiveBox> MAX_INT = (box1, box2) -> {
1✔
782
            if (box2.b && (!box1.b || box1.i < box2.i)) {
1✔
783
                box1.from(box2);
1✔
784
            }
785
        };
1✔
786

787
        static final BiConsumer<PrimitiveBox, PrimitiveBox> MIN_INT = (box1, box2) -> {
1✔
788
            if (box2.b && (!box1.b || box1.i > box2.i)) {
1✔
789
                box1.from(box2);
1✔
790
            }
791
        };
1✔
792

793
        static final BiConsumer<PrimitiveBox, PrimitiveBox> MAX_DOUBLE = (box1, box2) -> {
1✔
794
            if (box2.b && (!box1.b || Double.compare(box1.d, box2.d) < 0)) {
1✔
795
                box1.from(box2);
1✔
796
            }
797
        };
1✔
798

799
        static final BiConsumer<PrimitiveBox, PrimitiveBox> MIN_DOUBLE = (box1, box2) -> {
1✔
800
            if (box2.b && (!box1.b || Double.compare(box1.d, box2.d) > 0)) {
1✔
801
                box1.from(box2);
1✔
802
            }
803
        };
1✔
804

805
        public void from(PrimitiveBox box) {
806
            b = box.b;
1✔
807
            i = box.i;
1✔
808
            d = box.d;
1✔
809
            l = box.l;
1✔
810
        }
1✔
811
    }
812

813
    final class AverageLong {
1✔
814
        long hi, lo, cnt;
815

816
        public void accept(long val) {
817
            cnt++;
1✔
818
            int cmp = Long.compareUnsigned(lo, lo += val);
1✔
819
            if (val > 0) {
1✔
820
                if (cmp > 0)
1✔
821
                    hi++;
1✔
822
            } else if (cmp < 0)
1✔
823
                hi--;
1✔
824
        }
1✔
825

826
        public AverageLong combine(AverageLong other) {
827
            cnt += other.cnt;
1✔
828
            hi += other.hi;
1✔
829
            if (Long.compareUnsigned(lo, lo += other.lo) > 0) {
1✔
830
                hi++;
1✔
831
            }
832
            return this;
1✔
833
        }
834

835
        public OptionalDouble result() {
836
            if (cnt == 0)
1✔
837
                return OptionalDouble.empty();
1✔
838
            return OptionalDouble.of(((double) (hi + (lo < 0 ? 1 : 0)) / cnt) * 0x1.0p64 + ((double) lo) / cnt);
1✔
839
        }
840
    }
841

842
    @SuppressWarnings("serial")
843
    class CancelException extends Error {
844
        CancelException() {
845
            // Calling this constructor makes the Exception construction much
846
            // faster (like 0.3us vs 1.7us)
847
            super(null, null, false, false);
1✔
848
        }
1✔
849
    }
850

851
    class ArrayCollection extends AbstractCollection<Object> {
852
        private final Object[] arr;
853

854
        ArrayCollection(Object[] arr) {
1✔
855
            this.arr = arr;
1✔
856
        }
1✔
857

858
        @Override
859
        public Iterator<Object> iterator() {
860
            return Arrays.asList(arr).iterator();
1✔
861
        }
862

863
        @Override
864
        public int size() {
865
            return arr.length;
1✔
866
        }
867

868
        @Override
869
        public Object[] toArray() {
870
            // intentional contract violation here:
871
            // this way new ArrayList(new ArrayCollection(arr)) will not copy
872
            // array at all
873
            return arr;
1✔
874
        }
875
    }
876

877
    /**
878
     * A spliterator which may perform tail-stream optimization
879
     *
880
     * @param <T> the type of elements returned by this spliterator
881
     */
882
    interface TailSpliterator<T> extends Spliterator<T> {
883
        /**
884
         * Either advances by one element feeding it to consumer and returns
885
         * this or returns tail spliterator (this spliterator becomes invalid
886
         * and tail must be used instead) or returns null if traversal finished.
887
         * 
888
         * @param action to feed the next element into
889
         * @return tail spliterator, this or null
890
         */
891
        Spliterator<T> tryAdvanceOrTail(Consumer<? super T> action);
892

893
        /**
894
         * Traverses this spliterator and returns null if traversal is completed
895
         * or tail spliterator if it must be used for further traversal.
896
         * 
897
         * @param action to feed the elements into
898
         * @return tail spliterator or null (never returns this)
899
         */
900
        Spliterator<T> forEachOrTail(Consumer<? super T> action);
901

902
        static <T> Spliterator<T> tryAdvanceWithTail(Spliterator<T> target, Consumer<? super T> action) {
903
            while (true) {
904
                if (target instanceof TailSpliterator) {
1✔
905
                    Spliterator<T> spltr = ((TailSpliterator<T>) target).tryAdvanceOrTail(action);
1✔
906
                    if (spltr == null || spltr == target)
1✔
907
                        return spltr;
1✔
908
                    target = spltr;
1✔
909
                } else {
1✔
910
                    return target.tryAdvance(action) ? target : null;
1✔
911
                }
912
            }
913
        }
914

915
        static <T> void forEachWithTail(Spliterator<T> target, Consumer<? super T> action) {
916
            while (true) {
917
                if (target instanceof TailSpliterator) {
1✔
918
                    Spliterator<T> spltr = ((TailSpliterator<T>) target).forEachOrTail(action);
1✔
919
                    if (spltr == null)
1✔
920
                        break;
1✔
921
                    target = spltr;
1✔
922
                } else {
1✔
923
                    target.forEachRemaining(action);
1✔
924
                    break;
1✔
925
                }
926
            }
927
        }
1✔
928
    }
929

930
    abstract class CloneableSpliterator<T, S extends CloneableSpliterator<T, ?>> implements Spliterator<T>,
1✔
931
            Cloneable {
932
        @SuppressWarnings("unchecked")
933
        S doClone() {
934
            try {
935
                return (S) this.clone();
1✔
936
            } catch (CloneNotSupportedException e) {
×
937
                throw new InternalError();
×
938
            }
939
        }
940
    }
941

942
    static ObjIntConsumer<StringBuilder> joinAccumulatorInt(CharSequence delimiter) {
943
        return (sb, i) -> (sb.length() > 0 ? sb.append(delimiter) : sb).append(i);
1✔
944
    }
945

946
    static ObjLongConsumer<StringBuilder> joinAccumulatorLong(CharSequence delimiter) {
947
        return (sb, i) -> (sb.length() > 0 ? sb.append(delimiter) : sb).append(i);
1✔
948
    }
949

950
    static ObjDoubleConsumer<StringBuilder> joinAccumulatorDouble(CharSequence delimiter) {
951
        return (sb, i) -> (sb.length() > 0 ? sb.append(delimiter) : sb).append(i);
1✔
952
    }
953

954
    static <T> BinaryOperator<T> selectFirst() {
955
        return (u, v) -> u;
1✔
956
    }
957

958
    static <T> Predicate<T> alwaysTrue() {
959
        return t -> true;
1✔
960
    }
961
    
962
    static int checkLength(int a, int b) {
963
        if (a != b)
1✔
964
            throw new IllegalArgumentException("Length differs: " + a + " != " + b);
1✔
965
        return a;
1✔
966
    }
967

968
    static void rangeCheck(int arrayLength, int startInclusive, int endExclusive) {
969
        if (startInclusive > endExclusive) {
1✔
970
            throw new ArrayIndexOutOfBoundsException("startInclusive(" + startInclusive + ") > endExclusive("
1✔
971
                + endExclusive + ")");
972
        }
973
        if (startInclusive < 0) {
1✔
974
            throw new ArrayIndexOutOfBoundsException(startInclusive);
1✔
975
        }
976
        if (endExclusive > arrayLength) {
1✔
977
            throw new ArrayIndexOutOfBoundsException(endExclusive);
1✔
978
        }
979
    }
1✔
980

981
    @SuppressWarnings("unchecked")
982
    static <A> Predicate<A> finished(Collector<?, A, ?> collector) {
983
        if (collector instanceof CancellableCollector)
1✔
984
            return ((CancellableCollector<?, A, ?>) collector).finished();
1✔
985
        return null;
1✔
986
    }
987

988
    @SuppressWarnings("unchecked")
989
    static <T> T none() {
990
        return (T) NONE;
1✔
991
    }
992

993
    static <T> int drainTo(T[] array, Spliterator<T> spliterator) {
994
        Box<T> box = new Box<>();
1✔
995
        int index = 0;
1✔
996
        while (index < array.length && spliterator.tryAdvance(box)) {
1✔
997
            array[index++] = box.a;
1✔
998
        }
999
        return index;
1✔
1000
    }
1001

1002
    static int intSize(Spliterator<?> spliterator) {
1003
        long size = spliterator.getExactSizeIfKnown();
1✔
1004
        if (size < -1) {
1✔
1005
            throw new IllegalArgumentException("Spliterator violates its contract: getExactSizeIfKnown() = " + size);
1✔
1006
        }
1007
        if (size > Integer.MAX_VALUE) {
1✔
1008
            throw new OutOfMemoryError("Stream size exceeds Integer.MAX_VALUE: " + size);
1✔
1009
        }
1010
        return (int) size;
1✔
1011
    }
1012
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc