forked from openjdk/jdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImmutableCollections.java
1595 lines (1398 loc) · 50.8 KB
/
ImmutableCollections.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
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) 2016, 2024, 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;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import jdk.internal.access.JavaUtilCollectionAccess;
import jdk.internal.access.SharedSecrets;
import jdk.internal.misc.CDS;
import jdk.internal.vm.annotation.Stable;
/**
* Container class for immutable collections. Not part of the public API.
* Mainly for namespace management and shared infrastructure.
*
* Serial warnings are suppressed throughout because all implementation
* classes use a serial proxy and thus have no need to declare serialVersionUID.
*/
@SuppressWarnings("serial")
class ImmutableCollections {
/**
* A "salt" value used for randomizing iteration order. This is initialized once
* and stays constant for the lifetime of the JVM. It need not be truly random, but
* it needs to vary sufficiently from one run to the next so that iteration order
* will vary between JVM runs.
*/
private static final long SALT32L;
/**
* For set and map iteration, we will iterate in "reverse" stochastically,
* decided at bootstrap time.
*/
private static final boolean REVERSE;
static {
// to generate a reasonably random and well-mixed SALT, use an arbitrary
// value (a slice of pi), multiply with a random seed, then pick
// the mid 32-bits from the product. By picking a SALT value in the
// [0 ... 0xFFFF_FFFFL == 2^32-1] range, we ensure that for any positive
// int N, (SALT32L * N) >> 32 is a number in the [0 ... N-1] range. This
// property will be used to avoid more expensive modulo-based
// calculations.
long color = 0x243F_6A88_85A3_08D3L; // slice of pi
// When running with -Xshare:dump, the VM will supply a "random" seed that's
// derived from the JVM build/version, so can we generate the exact same
// CDS archive for the same JDK build. This makes it possible to verify the
// consistency of the JDK build.
long seed = CDS.getRandomSeedForDumping();
if (seed == 0) {
seed = System.nanoTime();
}
SALT32L = (int)((color * seed) >> 16) & 0xFFFF_FFFFL;
// use the lowest bit to determine if we should reverse iteration
REVERSE = (SALT32L & 1) == 0;
}
/**
* Constants following this might be initialized from the CDS archive via
* this array.
*/
private static Object[] archivedObjects;
private static final Object EMPTY;
static final ListN<?> EMPTY_LIST;
static final ListN<?> EMPTY_LIST_NULLS;
static final SetN<?> EMPTY_SET;
static final MapN<?,?> EMPTY_MAP;
static {
CDS.initializeFromArchive(ImmutableCollections.class);
if (archivedObjects == null) {
EMPTY = new Object();
EMPTY_LIST = new ListN<>(new Object[0], false);
EMPTY_LIST_NULLS = new ListN<>(new Object[0], true);
EMPTY_SET = new SetN<>();
EMPTY_MAP = new MapN<>();
archivedObjects =
new Object[] { EMPTY, EMPTY_LIST, EMPTY_LIST_NULLS, EMPTY_SET, EMPTY_MAP };
} else {
EMPTY = archivedObjects[0];
EMPTY_LIST = (ListN)archivedObjects[1];
EMPTY_LIST_NULLS = (ListN)archivedObjects[2];
EMPTY_SET = (SetN)archivedObjects[3];
EMPTY_MAP = (MapN)archivedObjects[4];
}
}
static class Access {
static {
SharedSecrets.setJavaUtilCollectionAccess(new JavaUtilCollectionAccess() {
public <E> List<E> listFromTrustedArray(Object[] array) {
return ImmutableCollections.listFromTrustedArray(array);
}
public <E> List<E> listFromTrustedArrayNullsAllowed(Object[] array) {
return ImmutableCollections.listFromTrustedArrayNullsAllowed(array);
}
});
}
}
/** No instances. */
private ImmutableCollections() { }
/**
* The reciprocal of load factor. Given a number of elements
* to store, multiply by this factor to get the table size.
*/
static final int EXPAND_FACTOR = 2;
static UnsupportedOperationException uoe() { return new UnsupportedOperationException(); }
@jdk.internal.ValueBased
abstract static class AbstractImmutableCollection<E> extends AbstractCollection<E> {
// all mutating methods throw UnsupportedOperationException
@Override public boolean add(E e) { throw uoe(); }
@Override public boolean addAll(Collection<? extends E> c) { throw uoe(); }
@Override public void clear() { throw uoe(); }
@Override public boolean remove(Object o) { throw uoe(); }
@Override public boolean removeAll(Collection<?> c) { throw uoe(); }
@Override public boolean removeIf(Predicate<? super E> filter) { throw uoe(); }
@Override public boolean retainAll(Collection<?> c) { throw uoe(); }
}
// ---------- List Static Factory Methods ----------
/**
* Copies a collection into a new List, unless the arg is already a safe,
* null-prohibiting unmodifiable list, in which case the arg itself is returned.
* Null argument or null elements in the argument will result in NPE.
*
* @param <E> the List's element type
* @param coll the input collection
* @return the new list
*/
@SuppressWarnings("unchecked")
static <E> List<E> listCopy(Collection<? extends E> coll) {
if (coll instanceof List12 || (coll instanceof ListN<?> c && !c.allowNulls)) {
return (List<E>)coll;
} else if (coll.isEmpty()) { // implicit nullcheck of coll
return List.of();
} else {
return (List<E>)List.of(coll.toArray());
}
}
/**
* Creates a new List from an untrusted array, creating a new array for internal
* storage, and checking for and rejecting null elements.
*
* @param <E> the List's element type
* @param input the input array
* @return the new list
*/
@SafeVarargs
static <E> List<E> listFromArray(E... input) {
// copy and check manually to avoid TOCTOU
@SuppressWarnings("unchecked")
E[] tmp = (E[])new Object[input.length]; // implicit nullcheck of input
for (int i = 0; i < input.length; i++) {
tmp[i] = Objects.requireNonNull(input[i]);
}
return new ListN<>(tmp, false);
}
/**
* Creates a new List from a trusted array, checking for and rejecting null
* elements.
*
* <p>A trusted array has no references retained by the caller. It can therefore be
* safely reused as the List's internal storage, avoiding a defensive copy. The array's
* class must be Object[].class. This method is declared with a parameter type of
* Object... instead of E... so that a varargs call doesn't accidentally create an array
* of some class other than Object[].class.
*
* @param <E> the List's element type
* @param input the input array
* @return the new list
*/
@SuppressWarnings("unchecked")
static <E> List<E> listFromTrustedArray(Object... input) {
assert input.getClass() == Object[].class;
for (Object o : input) { // implicit null check of 'input' array
Objects.requireNonNull(o);
}
return switch (input.length) {
case 0 -> (List<E>) ImmutableCollections.EMPTY_LIST;
case 1 -> (List<E>) new List12<>(input[0]);
case 2 -> (List<E>) new List12<>(input[0], input[1]);
default -> (List<E>) new ListN<>(input, false);
};
}
/**
* Creates a new List from a trusted array, allowing null elements.
*
* <p>A trusted array has no references retained by the caller. It can therefore be
* safely reused as the List's internal storage, avoiding a defensive copy. The array's
* class must be Object[].class. This method is declared with a parameter type of
* Object... instead of E... so that a varargs call doesn't accidentally create an array
* of some class other than Object[].class.
*
* <p>Avoids creating a List12 instance, as it cannot accommodate null elements.
*
* @param <E> the List's element type
* @param input the input array
* @return the new list
*/
@SuppressWarnings("unchecked")
static <E> List<E> listFromTrustedArrayNullsAllowed(Object... input) {
assert input.getClass() == Object[].class;
if (input.length == 0) {
return (List<E>) EMPTY_LIST_NULLS;
} else {
return new ListN<>((E[])input, true);
}
}
// ---------- List Implementations ----------
@jdk.internal.ValueBased
abstract static class AbstractImmutableList<E> extends AbstractImmutableCollection<E>
implements List<E>, RandomAccess {
// all mutating methods throw UnsupportedOperationException
@Override public void add(int index, E element) { throw uoe(); }
@Override public boolean addAll(int index, Collection<? extends E> c) { throw uoe(); }
@Override public E remove(int index) { throw uoe(); }
@Override public E removeFirst() { throw uoe(); }
@Override public E removeLast() { throw uoe(); }
@Override public void replaceAll(UnaryOperator<E> operator) { throw uoe(); }
@Override public E set(int index, E element) { throw uoe(); }
@Override public void sort(Comparator<? super E> c) { throw uoe(); }
@Override
public List<E> subList(int fromIndex, int toIndex) {
int size = size();
subListRangeCheck(fromIndex, toIndex, size);
return SubList.fromList(this, fromIndex, toIndex);
}
static void subListRangeCheck(int fromIndex, int toIndex, int size) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > size)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");
}
@Override
public Iterator<E> iterator() {
return new ListItr<E>(this, size());
}
@Override
public ListIterator<E> listIterator() {
return listIterator(0);
}
@Override
public ListIterator<E> listIterator(final int index) {
int size = size();
if (index < 0 || index > size) {
throw outOfBounds(index);
}
return new ListItr<E>(this, size, index);
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof List)) {
return false;
}
Iterator<?> oit = ((List<?>) o).iterator();
for (int i = 0, s = size(); i < s; i++) {
if (!oit.hasNext() || !Objects.equals(get(i), oit.next())) {
return false;
}
}
return !oit.hasNext();
}
@Override
public int hashCode() {
int hash = 1;
for (int i = 0, s = size(); i < s; i++) {
hash = 31 * hash + Objects.hashCode(get(i));
}
return hash;
}
@Override
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
@Override
public List<E> reversed() {
return ReverseOrderListView.of(this, false);
}
IndexOutOfBoundsException outOfBounds(int index) {
return new IndexOutOfBoundsException("Index: " + index + " Size: " + size());
}
}
static final class ListItr<E> implements ListIterator<E> {
@Stable
private final List<E> list;
@Stable
private final int size;
@Stable
private final boolean isListIterator;
private int cursor;
ListItr(List<E> list, int size) {
this.list = list;
this.size = size;
this.cursor = 0;
isListIterator = false;
}
ListItr(List<E> list, int size, int index) {
this.list = list;
this.size = size;
this.cursor = index;
isListIterator = true;
}
public boolean hasNext() {
return cursor != size;
}
public E next() {
try {
int i = cursor;
E next = list.get(i);
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
public void remove() {
throw uoe();
}
public boolean hasPrevious() {
if (!isListIterator) {
throw uoe();
}
return cursor != 0;
}
public E previous() {
if (!isListIterator) {
throw uoe();
}
try {
int i = cursor - 1;
E previous = list.get(i);
cursor = i;
return previous;
} catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
public int nextIndex() {
if (!isListIterator) {
throw uoe();
}
return cursor;
}
public int previousIndex() {
if (!isListIterator) {
throw uoe();
}
return cursor - 1;
}
public void set(E e) {
throw uoe();
}
public void add(E e) {
throw uoe();
}
}
static final class SubList<E> extends AbstractImmutableList<E>
implements RandomAccess {
@Stable
private final AbstractImmutableList<E> root;
@Stable
private final int offset;
@Stable
private final int size;
private SubList(AbstractImmutableList<E> root, int offset, int size) {
assert root instanceof List12 || root instanceof ListN;
this.root = root;
this.offset = offset;
this.size = size;
}
/**
* Constructs a sublist of another SubList.
*/
static <E> SubList<E> fromSubList(SubList<E> parent, int fromIndex, int toIndex) {
return new SubList<>(parent.root, parent.offset + fromIndex, toIndex - fromIndex);
}
/**
* Constructs a sublist of an arbitrary AbstractImmutableList, which is
* not a SubList itself.
*/
static <E> SubList<E> fromList(AbstractImmutableList<E> list, int fromIndex, int toIndex) {
return new SubList<>(list, fromIndex, toIndex - fromIndex);
}
public E get(int index) {
Objects.checkIndex(index, size);
return root.get(offset + index);
}
public int size() {
return size;
}
public Iterator<E> iterator() {
return new ListItr<>(this, size());
}
public ListIterator<E> listIterator(int index) {
rangeCheck(index);
return new ListItr<>(this, size(), index);
}
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return SubList.fromSubList(this, fromIndex, toIndex);
}
private void rangeCheck(int index) {
if (index < 0 || index > size) {
throw outOfBounds(index);
}
}
private boolean allowNulls() {
return root instanceof ListN && ((ListN<?>)root).allowNulls;
}
@Override
public int indexOf(Object o) {
if (!allowNulls() && o == null) {
throw new NullPointerException();
}
for (int i = 0, s = size(); i < s; i++) {
if (Objects.equals(o, get(i))) {
return i;
}
}
return -1;
}
@Override
public int lastIndexOf(Object o) {
if (!allowNulls() && o == null) {
throw new NullPointerException();
}
for (int i = size() - 1; i >= 0; i--) {
if (Objects.equals(o, get(i))) {
return i;
}
}
return -1;
}
@Override
public Object[] toArray() {
Object[] array = new Object[size];
for (int i = 0; i < size; i++) {
array[i] = get(i);
}
return array;
}
@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
T[] array = a.length >= size ? a :
(T[])java.lang.reflect.Array
.newInstance(a.getClass().getComponentType(), size);
for (int i = 0; i < size; i++) {
array[i] = (T)get(i);
}
if (array.length > size) {
array[size] = null; // null-terminate
}
return array;
}
}
@jdk.internal.ValueBased
static final class List12<E> extends AbstractImmutableList<E>
implements Serializable {
@Stable
private final E e0;
@Stable
private final Object e1;
List12(E e0) {
this.e0 = Objects.requireNonNull(e0);
// Use EMPTY as a sentinel for an unused element: not using null
// enables constant folding optimizations over single-element lists
this.e1 = EMPTY;
}
List12(E e0, E e1) {
this.e0 = Objects.requireNonNull(e0);
this.e1 = Objects.requireNonNull(e1);
}
@Override
public int size() {
return e1 != EMPTY ? 2 : 1;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
@SuppressWarnings("unchecked")
public E get(int index) {
if (index == 0) {
return e0;
} else if (index == 1 && e1 != EMPTY) {
return (E)e1;
}
throw outOfBounds(index);
}
@Override
public int indexOf(Object o) {
Objects.requireNonNull(o);
if (o.equals(e0)) {
return 0;
} else if (e1 != EMPTY && o.equals(e1)) {
return 1;
} else {
return -1;
}
}
@Override
public int lastIndexOf(Object o) {
Objects.requireNonNull(o);
if (e1 != EMPTY && o.equals(e1)) {
return 1;
} else if (o.equals(e0)) {
return 0;
} else {
return -1;
}
}
@java.io.Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
throw new InvalidObjectException("not serial proxy");
}
@java.io.Serial
private Object writeReplace() {
if (e1 == EMPTY) {
return new CollSer(CollSer.IMM_LIST, e0);
} else {
return new CollSer(CollSer.IMM_LIST, e0, e1);
}
}
@Override
public Object[] toArray() {
if (e1 == EMPTY) {
return new Object[] { e0 };
} else {
return new Object[] { e0, e1 };
}
}
@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
int size = size();
T[] array = a.length >= size ? a :
(T[])Array.newInstance(a.getClass().getComponentType(), size);
array[0] = (T)e0;
if (size == 2) {
array[1] = (T)e1;
}
if (array.length > size) {
array[size] = null; // null-terminate
}
return array;
}
@Override
@SuppressWarnings("unchecked")
public void forEach(Consumer<? super E> action) {
action.accept(e0); // implicit null check
if (e1 != EMPTY) {
action.accept((E) e1);
}
}
@Override
public Spliterator<E> spliterator() {
if (e1 == EMPTY) {
return Collections.singletonSpliterator(e0);
} else {
return super.spliterator();
}
}
}
@jdk.internal.ValueBased
static final class ListN<E> extends AbstractImmutableList<E>
implements Serializable {
@Stable
private final E[] elements;
@Stable
private final boolean allowNulls;
// caller must ensure that elements has no nulls if allowNulls is false
private ListN(E[] elements, boolean allowNulls) {
this.elements = elements;
this.allowNulls = allowNulls;
}
@Override
public boolean isEmpty() {
return elements.length == 0;
}
@Override
public int size() {
return elements.length;
}
@Override
public E get(int index) {
return elements[index];
}
@java.io.Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
throw new InvalidObjectException("not serial proxy");
}
@java.io.Serial
private Object writeReplace() {
return new CollSer(allowNulls ? CollSer.IMM_LIST_NULLS : CollSer.IMM_LIST, elements);
}
@Override
public Object[] toArray() {
return Arrays.copyOf(elements, elements.length);
}
@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
int size = elements.length;
if (a.length < size) {
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elements, size, a.getClass());
}
System.arraycopy(elements, 0, a, 0, size);
if (a.length > size) {
a[size] = null; // null-terminate
}
return a;
}
@Override
public int indexOf(Object o) {
if (!allowNulls && o == null) {
throw new NullPointerException();
}
Object[] es = elements;
for (int i = 0; i < es.length; i++) {
if (Objects.equals(o, es[i])) {
return i;
}
}
return -1;
}
@Override
public int lastIndexOf(Object o) {
if (!allowNulls && o == null) {
throw new NullPointerException();
}
Object[] es = elements;
for (int i = es.length - 1; i >= 0; i--) {
if (Objects.equals(o, es[i])) {
return i;
}
}
return -1;
}
}
// ---------- Set Implementations ----------
@jdk.internal.ValueBased
abstract static class AbstractImmutableSet<E> extends AbstractImmutableCollection<E>
implements Set<E> {
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof Set)) {
return false;
}
Collection<?> c = (Collection<?>) o;
if (c.size() != size()) {
return false;
}
for (Object e : c) {
if (e == null || !contains(e)) {
return false;
}
}
return true;
}
@Override
public abstract int hashCode();
}
@jdk.internal.ValueBased
static final class Set12<E> extends AbstractImmutableSet<E>
implements Serializable {
@Stable
private final E e0;
@Stable
private final Object e1;
Set12(E e0) {
this.e0 = Objects.requireNonNull(e0);
// Use EMPTY as a sentinel for an unused element: not using null
// enable constant folding optimizations over single-element sets
this.e1 = EMPTY;
}
Set12(E e0, E e1) {
if (e0.equals(Objects.requireNonNull(e1))) { // implicit nullcheck of e0
throw new IllegalArgumentException("duplicate element: " + e0);
}
this.e0 = e0;
this.e1 = e1;
}
@Override
public int size() {
return (e1 == EMPTY) ? 1 : 2;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean contains(Object o) {
return o.equals(e0) || e1.equals(o); // implicit nullcheck of o
}
@Override
public int hashCode() {
return e0.hashCode() + (e1 == EMPTY ? 0 : e1.hashCode());
}
@Override
public Iterator<E> iterator() {
return new Iterator<>() {
private int idx = (e1 == EMPTY) ? 1 : 2;
@Override
public boolean hasNext() {
return idx > 0;
}
@Override
@SuppressWarnings("unchecked")
public E next() {
if (idx == 1) {
idx = 0;
return (REVERSE || e1 == EMPTY) ? e0 : (E)e1;
} else if (idx == 2) {
idx = 1;
return REVERSE ? (E)e1 : e0;
} else {
throw new NoSuchElementException();
}
}
};
}
@java.io.Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
throw new InvalidObjectException("not serial proxy");
}
@java.io.Serial
private Object writeReplace() {
if (e1 == EMPTY) {
return new CollSer(CollSer.IMM_SET, e0);
} else {
return new CollSer(CollSer.IMM_SET, e0, e1);
}
}
@Override
public Object[] toArray() {
if (e1 == EMPTY) {
return new Object[] { e0 };
} else if (REVERSE) {
return new Object[] { e1, e0 };
} else {
return new Object[] { e0, e1 };
}
}
@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
int size = size();
T[] array = a.length >= size ? a :
(T[])Array.newInstance(a.getClass().getComponentType(), size);
if (size == 1) {
array[0] = (T)e0;
} else if (REVERSE) {
array[0] = (T)e1;
array[1] = (T)e0;
} else {
array[0] = (T)e0;
array[1] = (T)e1;
}
if (array.length > size) {
array[size] = null; // null-terminate
}
return array;
}
@Override
@SuppressWarnings("unchecked")
public void forEach(Consumer<? super E> action) {
if (e1 == EMPTY) {
action.accept(e0); // implicit null check
} else {
action.accept(REVERSE ? (E)e1 : e0); // implicit null check
action.accept(REVERSE ? e0 : (E)e1);
}
}
@Override
public Spliterator<E> spliterator() {
if (e1 == EMPTY) {
return Collections.singletonSpliterator(e0);
} else {
return super.spliterator();
}
}
}
/**
* An array-based Set implementation. The element array must be strictly
* larger than the size (the number of contained elements) so that at
* least one null is always present.
* @param <E> the element type
*/
@jdk.internal.ValueBased
static final class SetN<E> extends AbstractImmutableSet<E>
implements Serializable {
@Stable
final E[] elements;
@Stable
final int size;
@SafeVarargs
@SuppressWarnings("unchecked")
SetN(E... input) {
size = input.length; // implicit nullcheck of input
elements = (E[])new Object[EXPAND_FACTOR * input.length];
for (int i = 0; i < input.length; i++) {
E e = input[i];
int idx = probe(e); // implicit nullcheck of e
if (idx >= 0) {
throw new IllegalArgumentException("duplicate element: " + e);
} else {
elements[-(idx + 1)] = e;
}
}
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public boolean contains(Object o) {
Objects.requireNonNull(o);
return size > 0 && probe(o) >= 0;
}
private final class SetNIterator implements Iterator<E> {
private int remaining;
private int idx;
SetNIterator() {
remaining = size;
// pick a starting index in the [0 .. element.length-1] range
// randomly based on SALT32L
idx = (int) ((SALT32L * elements.length) >>> 32);