1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.atlassian.fugue;
18
19 import java.io.Serializable;
20 import java.lang.ref.Reference;
21 import java.lang.ref.WeakReference;
22 import java.util.Arrays;
23 import java.util.Collection;
24 import java.util.Comparator;
25 import java.util.Iterator;
26 import java.util.LinkedList;
27 import java.util.List;
28 import java.util.NoSuchElementException;
29 import java.util.Queue;
30 import java.util.TreeSet;
31 import java.util.concurrent.CancellationException;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
34 import java.util.function.BiFunction;
35 import java.util.function.Function;
36 import java.util.function.Predicate;
37 import java.util.function.Supplier;
38 import java.util.stream.Collector;
39 import java.util.stream.StreamSupport;
40
41 import static io.atlassian.fugue.Functions.countingPredicate;
42 import static io.atlassian.fugue.Iterators.emptyIterator;
43 import static io.atlassian.fugue.Iterators.peekingIterator;
44 import static io.atlassian.fugue.Option.none;
45 import static io.atlassian.fugue.Option.some;
46 import static io.atlassian.fugue.Pair.leftValue;
47 import static io.atlassian.fugue.Pair.pair;
48 import static io.atlassian.fugue.Pair.rightValue;
49 import static io.atlassian.fugue.Suppliers.ofInstance;
50 import static java.util.Arrays.asList;
51 import static java.util.Collections.unmodifiableCollection;
52 import static java.util.Objects.requireNonNull;
53
54
55
56
57
58
59
60
61
62
63 public class Iterables {
64 private Iterables() {
65 throw new UnsupportedOperationException("This class is not instantiable.");
66 }
67
68 static final Iterable<?> EMPTY = new Iterable<Object>() {
69 @Override public Iterator<Object> iterator() {
70 return emptyIterator();
71 }
72
73 @Override public String toString() {
74 return "[]";
75 }
76 };
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91 public static <T> Iterable<T> emptyIterable() {
92 @SuppressWarnings("unchecked")
93 final Iterable<T> result = (Iterable<T>) EMPTY;
94 return result;
95 }
96
97
98
99
100
101
102
103
104
105 @SafeVarargs public static <A> Iterable<A> iterable(final A... as) {
106 return unmodifiableCollection(asList(as));
107 }
108
109
110
111
112
113
114
115
116
117
118
119
120
121 public static <T> Option<T> findFirst(final Iterable<? extends T> elements, final Predicate<? super T> p) {
122 for (final T t : filter(elements, p)) {
123 return some(t);
124 }
125 return none();
126 }
127
128
129
130
131
132
133
134
135
136
137
138
139
140 public static <A> Function<Iterable<A>, Option<A>> findFirst(final Predicate<? super A> predicate) {
141 return input -> findFirst(input, predicate);
142 }
143
144
145
146
147
148
149
150
151
152
153
154 public static <A> Option<A> first(final Iterable<A> as) {
155 for (final A a : as) {
156 return some(a);
157 }
158 return none();
159 }
160
161
162
163
164
165
166
167
168
169
170 public static <A, B> Iterable<B> ap(final Iterable<A> as, final Iterable<Function<A, B>> fs) {
171 return flatMap(fs, f -> map(as, f));
172 }
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187 public static <A, B> Iterable<B> flatMap(final Iterable<A> collection, final Function<? super A, ? extends Iterable<? extends B>> f) {
188 return join(map(collection, f));
189 }
190
191
192
193
194
195
196
197
198
199
200
201
202 public static <A, B> Iterable<B> revMap(final Iterable<? extends Function<A, B>> fs, final A arg) {
203 return map(fs, Functions.<A, B> apply(arg));
204 }
205
206
207
208
209
210
211
212 public static Predicate<Iterable<?>> isEmpty() {
213 return it -> {
214 if (it instanceof Collection) {
215 return ((Collection<?>) it).isEmpty();
216 }
217 return !it.iterator().hasNext();
218 };
219 }
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236 public static <A, B> Iterable<B> collect(final Iterable<? extends A> from, final Function<? super A, Option<B>> partial) {
237 return new CollectingIterable<>(from, partial);
238 }
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254 public static <T, A, R> R collect(final Iterable<T> elements, final Collector<T, A, R> collector) {
255 requireNonNull(elements, "elements is null.");
256 requireNonNull(collector, "collector is null.");
257 return StreamSupport.stream(elements.spliterator(), false).collect(collector);
258 }
259
260
261
262
263
264
265
266
267
268
269
270 public static <A> Pair<Iterable<A>, Iterable<A>> partition(final Iterable<A> iterable, final Predicate<? super A> p) {
271 return pair(filter(iterable, p), filter(iterable, p.negate()));
272 }
273
274
275
276
277
278
279
280
281
282
283 public static <A> Iterable<A> take(final int n, final Iterable<A> as) {
284 if (n < 0) {
285 throw new IllegalArgumentException("Cannot take a negative number of elements");
286 }
287 if (as instanceof List<?>) {
288 final List<A> list = (List<A>) as;
289 return list.subList(0, n < list.size() ? n : list.size());
290 }
291 return new Take<>(as, countingPredicate(n));
292 }
293
294
295
296
297
298
299
300
301
302
303 public static <A> Iterable<A> drop(final int n, final Iterable<A> as) {
304 if (n < 0) {
305 throw new IllegalArgumentException("Cannot drop a negative number of elements");
306 }
307 if (as instanceof List<?>) {
308 final List<A> list = (List<A>) as;
309 if (n > (list.size() - 1)) {
310 return emptyIterable();
311 }
312 return list.subList(n, list.size());
313 }
314 return new Drop<>(as, countingPredicate(n));
315 }
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331 public static <A> Iterable<A> dropWhile(final Iterable<A> as, final Predicate<A> p) {
332 return new Drop<>(as, p);
333 }
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349 public static <A> Iterable<A> takeWhile(final Iterable<A> as, final Predicate<A> p) {
350 return new Take<>(as, p);
351 }
352
353
354
355
356
357
358
359
360
361
362
363
364
365 public static <A, B> Iterable<Pair<A, B>> zip(final Iterable<A> as, final Iterable<B> bs) {
366 return zipWith(Pair.<A, B> pairs()).apply(as, bs);
367 }
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383 public static <A, B, C> BiFunction<Iterable<A>, Iterable<B>, Iterable<C>> zipWith(final BiFunction<A, B, C> f) {
384 return (as, bs) -> new Zipper<>(as, bs, f);
385 }
386
387
388
389
390
391
392
393
394
395
396 public static <A> Iterable<Pair<A, Integer>> zipWithIndex(final Iterable<A> as) {
397 return zip(as, rangeTo(0, Integer.MAX_VALUE));
398 }
399
400
401
402
403
404
405
406
407
408
409
410
411 public static <A, B> Pair<Iterable<A>, Iterable<B>> unzip(Iterable<Pair<A, B>> pairs) {
412 return pair(map(pairs, leftValue()), map(pairs, rightValue()));
413 }
414
415
416
417
418
419
420
421
422
423
424 public static Iterable<Integer> rangeUntil(final int start, final int end) {
425 return rangeUntil(start, end, (start > end) ? -1 : 1);
426 }
427
428
429
430
431
432
433
434
435
436
437
438
439 public static Iterable<Integer> rangeUntil(final int start, final int end, final int step) {
440 if (step == 0) {
441 throw new IllegalArgumentException("Step must not be zero");
442 }
443 return rangeTo(start, end - (Math.abs(step) / step), step);
444 }
445
446
447
448
449
450
451
452
453
454
455 public static Iterable<Integer> rangeTo(final int start, final int end) {
456 return rangeTo(start, end, (start > end) ? -1 : 1);
457 }
458
459
460
461
462
463
464
465
466
467
468
469
470 public static Iterable<Integer> rangeTo(final int start, final int end, final int step) {
471 if (step == 0) {
472 throw new IllegalArgumentException("Step must not be zero");
473 }
474 if (step > 0) {
475 if (start > end) {
476 throw new IllegalArgumentException(String.format("Start %s must not be greater than end %s with step %s", start, end, step));
477 }
478 } else {
479 if (start < end) {
480 throw new IllegalArgumentException(String.format("Start %s must not be less than end %s with step %s", start, end, step));
481 }
482 }
483
484 return () -> new Iterators.Unmodifiable<Integer>() {
485 private int i = start;
486 private boolean reachedMinOrMax = false;
487
488 @Override public boolean hasNext() {
489 return (step > 0 ? i <= end : i >= end) && !reachedMinOrMax;
490 }
491
492 @Override public Integer next() {
493 if (!hasNext()) {
494 throw new NoSuchElementException();
495 }
496 try {
497 return i;
498 } finally {
499 int attempt = i + step;
500
501 if (((i ^ attempt) & (step ^ attempt)) < 0) {
502 reachedMinOrMax = true;
503 }
504 i = attempt;
505 }
506 }
507 };
508 }
509
510 static abstract class IterableToString<A> implements Iterable<A> {
511 @Override public final String toString() {
512 return makeString(this, "[", ", ", "]");
513 }
514 }
515
516
517
518
519 static final class Take<A> extends IterableToString<A> {
520 private final Iterable<A> as;
521 private final Predicate<A> p;
522
523 private Take(final Iterable<A> as, final Predicate<A> p) {
524 this.p = requireNonNull(p);
525 this.as = requireNonNull(as);
526 }
527
528 @Override public Iterator<A> iterator() {
529 return new Iter<>(as.iterator(), p);
530 }
531
532 static final class Iter<A> extends Iterators.Abstract<A> {
533 private final Iterator<A> ias;
534 private final Predicate<A> p;
535
536 Iter(final Iterator<A> ias, final Predicate<A> p) {
537 this.ias = ias;
538 this.p = p;
539 }
540
541 @Override protected A computeNext() {
542 if (ias.hasNext()) {
543 final A a = ias.next();
544 return p.test(a) ? a : endOfData();
545 }
546 return endOfData();
547 }
548 }
549 }
550
551
552
553
554 static final class Drop<A> extends IterableToString<A> {
555 private final Iterable<A> as;
556 private final Predicate<A> p;
557
558 private Drop(final Iterable<A> as, final Predicate<A> p) {
559 this.p = requireNonNull(p);
560 this.as = requireNonNull(as);
561 }
562
563 @Override public Iterator<A> iterator() {
564 return new Iter<>(as.iterator(), p);
565 }
566
567 static final class Iter<A> extends Iterators.Abstract<A> {
568 private final Iterators.Peeking<A> as;
569
570 Iter(final Iterator<A> as, final Predicate<A> p) {
571 this.as = peekingIterator(as);
572 while (this.as.hasNext() && p.test(this.as.peek())) {
573 this.as.next();
574 }
575 }
576
577 @Override protected A computeNext() {
578 return as.hasNext() ? as.next() : endOfData();
579 }
580 }
581 }
582
583
584
585
586 static class CollectingIterable<A, B> extends IterableToString<B> {
587 private final Iterable<? extends A> delegate;
588 private final Function<? super A, Option<B>> partial;
589
590 CollectingIterable(final Iterable<? extends A> delegate, final Function<? super A, Option<B>> partial) {
591 this.delegate = requireNonNull(delegate);
592 this.partial = requireNonNull(partial);
593 }
594
595 @Override public Iterator<B> iterator() {
596 return new Iter();
597 }
598
599 final class Iter extends Iterators.Abstract<B> {
600 private final Iterator<? extends A> it = delegate.iterator();
601
602 @Override protected B computeNext() {
603 while (it.hasNext()) {
604 final Option<B> result = partial.apply(it.next());
605 if (result.isDefined())
606 return result.get();
607 }
608 return endOfData();
609 }
610 }
611 }
612
613
614
615
616 static class Zipper<A, B, C> extends IterableToString<C> {
617 private final Iterable<A> as;
618 private final Iterable<B> bs;
619 private final BiFunction<A, B, C> f;
620
621 Zipper(final Iterable<A> as, final Iterable<B> bs, final BiFunction<A, B, C> f) {
622 this.as = requireNonNull(as, "as must not be null.");
623 this.bs = requireNonNull(bs, "bs must not be null.");
624 this.f = requireNonNull(f, "f must not be null.");
625 }
626
627 @Override public Iterator<C> iterator() {
628 return new Iter();
629 }
630
631 class Iter implements Iterator<C> {
632 private final Iterator<A> a = requireNonNull(as.iterator(), "as iterator must not be null.");
633 private final Iterator<B> b = requireNonNull(bs.iterator(), "bs iterator must not be null.");
634
635 @Override public boolean hasNext() {
636 return a.hasNext() && b.hasNext();
637 }
638
639 @Override public C next() {
640 return f.apply(a.next(), b.next());
641 }
642
643 @Override public void remove() {
644 throw new UnsupportedOperationException();
645 }
646 }
647 }
648
649
650
651
652
653
654
655
656
657
658 public static <A> Iterable<A> intersperse(final Iterable<? extends A> as, final A a) {
659 return intersperse(as, ofInstance(a));
660 }
661
662
663
664
665
666
667
668
669
670
671
672 public static <A> Iterable<A> intersperse(final Iterable<? extends A> as, final Supplier<A> a) {
673 return new Intersperse<>(as, a);
674 }
675
676 static final class Intersperse<A> implements Iterable<A> {
677 private final Iterable<? extends A> as;
678 private final Supplier<A> a;
679
680 Intersperse(final Iterable<? extends A> as, final Supplier<A> a) {
681 this.as = as;
682 this.a = a;
683 }
684
685 @Override public Iterator<A> iterator() {
686 return new Iterators.Abstract<A>() {
687 private final Iterator<? extends A> it = as.iterator();
688 private boolean inter = false;
689
690 @Override protected A computeNext() {
691 if (!it.hasNext()) {
692 return endOfData();
693 }
694 try {
695 return inter ? a.get() : it.next();
696 } finally {
697 inter = !inter;
698 }
699 }
700 };
701 }
702 }
703
704
705
706
707
708
709
710
711
712
713
714 public static <A> int size(final Iterable<A> as) {
715 if (as instanceof Collection) {
716 return ((Collection<?>) as).size();
717 } else {
718 final Iterator<A> iterator = as.iterator();
719 int count = 0;
720 while (iterator.hasNext()) {
721 iterator.next();
722 count++;
723 }
724 return count;
725 }
726 }
727
728
729
730
731
732
733
734
735
736
737
738
739
740 @Deprecated public static <A, B> Iterable<B> transform(final Iterable<A> as, final Function<? super A, ? extends B> f) {
741 return map(as, f);
742 }
743
744
745
746
747
748
749
750
751
752
753
754
755
756 public static <A, B> Iterable<B> map(final Iterable<A> as, final Function<? super A, ? extends B> f) {
757 return new Mapped<>(as, f);
758 }
759
760 static final class Mapped<A, B> implements Iterable<B> {
761 private final Iterable<? extends A> as;
762 private final Function<? super A, ? extends B> f;
763
764 Mapped(final Iterable<? extends A> as, final Function<? super A, ? extends B> f) {
765 this.as = as;
766 this.f = f;
767 }
768
769 @Override public Iterator<B> iterator() {
770 return new Iterators.Abstract<B>() {
771 private final Iterator<? extends A> it = as.iterator();
772
773 @Override protected B computeNext() {
774 if (!it.hasNext()) {
775 return endOfData();
776 }
777 return f.apply(it.next());
778 }
779 };
780 }
781 }
782
783
784
785
786
787
788
789
790
791
792
793
794 public static <A> Iterable<A> filter(final Iterable<A> as, final Predicate<? super A> p) {
795 return new Filter<>(as, p);
796 }
797
798 static final class Filter<A> implements Iterable<A> {
799 private final Iterable<? extends A> as;
800 private final Predicate<? super A> p;
801
802 Filter(final Iterable<? extends A> as, final Predicate<? super A> p) {
803 this.as = as;
804 this.p = p;
805 }
806
807 @Override public Iterator<A> iterator() {
808 return new Iterators.Abstract<A>() {
809 private final Iterator<? extends A> it = as.iterator();
810
811 @Override protected A computeNext() {
812 if (!it.hasNext()) {
813 return endOfData();
814 }
815 while (it.hasNext()) {
816 final A a = it.next();
817 if (p.test(a)) {
818 return a;
819 }
820 }
821 return endOfData();
822 }
823 };
824 }
825 }
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840 public static <A> Iterable<A> join(final Iterable<? extends Iterable<? extends A>> ias) {
841 return new Join<>(ias);
842 }
843
844 static final class Join<A> extends IterableToString<A> {
845 private final Iterable<? extends Iterable<? extends A>> ias;
846
847 public Join(final Iterable<? extends Iterable<? extends A>> ias) {
848 this.ias = ias;
849 }
850
851 @Override public Iterator<A> iterator() {
852 return new Iter<>(ias);
853 }
854
855 static class Iter<A> extends Iterators.Abstract<A> {
856 final Queue<Iterator<? extends A>> qas = new LinkedList<>();
857
858 public Iter(final Iterable<? extends Iterable<? extends A>> ias) {
859 for (final Iterable<? extends A> a : ias) {
860 qas.add(requireNonNull(a.iterator()));
861 }
862 }
863
864 @Override protected A computeNext() {
865 while (!qas.isEmpty() && !qas.peek().hasNext()) {
866 qas.remove();
867 }
868 if (qas.isEmpty()) {
869 return endOfData();
870 }
871 return qas.peek().next();
872 }
873 }
874 }
875
876
877
878
879
880
881
882
883
884
885
886 @SafeVarargs public static <A> Iterable<A> concat(final Iterable<? extends A>... as) {
887 return as.length > 0 ? join(Arrays.asList(as)) : emptyIterable();
888 }
889
890
891
892
893
894
895
896
897
898
899
900 public static <A> boolean any(final Iterable<? extends A> as, final Predicate<? super A> p) {
901 return !isEmpty().test(filter(as, p));
902 }
903
904
905
906
907
908
909
910
911
912
913
914 public static <A> boolean all(final Iterable<? extends A> as, final Predicate<? super A> p) {
915 return isEmpty().test(filter(as, p.negate()));
916 }
917
918
919
920
921
922
923
924
925
926
927
928
929 public static <A> Iterable<A> iterate(final Function<? super A, ? extends A> f, final A start) {
930 return new IteratingIterable<>(f, start);
931 }
932
933
934
935
936 static final class IteratingIterable<A> implements Iterable<A> {
937 private final Function<? super A, ? extends A> f;
938 private final A start;
939
940 private IteratingIterable(final Function<? super A, ? extends A> f, final A start) {
941 this.f = requireNonNull(f, "f");
942 this.start = start;
943 }
944
945 @Override public Iterator<A> iterator() {
946 return new Iter<>(f, start);
947 }
948
949 static final class Iter<A> extends Iterators.Unmodifiable<A> {
950 private final Function<? super A, ? extends A> f;
951 private A current;
952
953 Iter(final Function<? super A, ? extends A> f, final A start) {
954 this.f = f;
955 this.current = start;
956 }
957
958 @Override public boolean hasNext() {
959 return true;
960 }
961
962 @Override public A next() {
963 final A value = current;
964 current = f.apply(current);
965 return value;
966 }
967 }
968 }
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985 public static <A, B> Iterable<A> unfold(final Function<? super B, Option<Pair<A, B>>> f, final B seed) {
986 return new UnfoldingIterable<>(f, seed);
987 }
988
989
990
991
992 static final class UnfoldingIterable<A, B> extends IterableToString<A> {
993 private final Function<? super B, Option<Pair<A, B>>> f;
994 private final B seed;
995
996 private UnfoldingIterable(final Function<? super B, Option<Pair<A, B>>> f, final B seed) {
997 this.f = requireNonNull(f, "f");
998 this.seed = seed;
999 }
1000
1001 @Override public Iterator<A> iterator() {
1002 return new Iter<>(f, seed);
1003 }
1004
1005 static final class Iter<A, B> extends Iterators.Abstract<A> {
1006 private final Function<? super B, Option<Pair<A, B>>> f;
1007 private B current;
1008
1009 Iter(final Function<? super B, Option<Pair<A, B>>> f, final B seed) {
1010 this.f = f;
1011 this.current = seed;
1012 }
1013
1014 @Override protected A computeNext() {
1015 final Option<Pair<A, B>> option = f.apply(current);
1016 if (option.isDefined()) {
1017 final Pair<A, B> pair = option.get();
1018 current = pair.right();
1019 return pair.left();
1020 } else {
1021 return endOfData();
1022 }
1023 }
1024 }
1025 }
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037 public static <A extends Comparable<A>> Iterable<A> mergeSorted(final Iterable<? extends Iterable<A>> xss) {
1038 return mergeSorted(xss, Comparator.<A> naturalOrder());
1039 }
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052 public static <A> Iterable<A> mergeSorted(final Iterable<? extends Iterable<A>> xss, final Comparator<A> ordering) {
1053 return new MergeSortedIterable<>(xss, ordering);
1054 }
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065 @SuppressWarnings("unchecked") public static <A> boolean addAll(final Collection<A> collectionToModify, final Iterable<? extends A> elementsToAdd) {
1066 if (elementsToAdd instanceof Collection) {
1067 return collectionToModify.addAll((Collection<? extends A>) elementsToAdd);
1068 }
1069 return Iterators.addAll(collectionToModify, requireNonNull(elementsToAdd).iterator());
1070 }
1071
1072
1073
1074
1075 static final class MergeSortedIterable<A> extends IterableToString<A> {
1076 private final Iterable<? extends Iterable<A>> xss;
1077 private final Comparator<A> comparator;
1078
1079 MergeSortedIterable(final Iterable<? extends Iterable<A>> xss, final Comparator<A> comparator) {
1080 this.xss = requireNonNull(xss, "xss");
1081 this.comparator = requireNonNull(comparator, "comparator");
1082 }
1083
1084 @Override public Iterator<A> iterator() {
1085 return new Iter<>(xss, comparator);
1086 }
1087
1088 private static final class Iter<A> extends Iterators.Abstract<A> {
1089 private final TreeSet<Iterators.Peeking<A>> xss;
1090
1091 private Iter(final Iterable<? extends Iterable<A>> xss, final Comparator<A> c) {
1092 this.xss = new TreeSet<>(peekingIteratorComparator(c));
1093 addAll(this.xss, map(filter(xss, isEmpty().negate()), i -> peekingIterator(i.iterator())));
1094 }
1095
1096 @Override protected A computeNext() {
1097 final Option<Iterators.Peeking<A>> currFirstOption = first(xss);
1098 if (!currFirstOption.isDefined()) {
1099 return endOfData();
1100 }
1101 final Iterators.Peeking<A> currFirst = currFirstOption.get();
1102
1103
1104
1105
1106 xss.remove(currFirst);
1107
1108 final A next = currFirst.next();
1109 if (currFirst.hasNext()) {
1110 xss.add(currFirst);
1111 }
1112 return next;
1113 }
1114
1115 private Comparator<? super Iterators.Peeking<A>> peekingIteratorComparator(final Comparator<A> comparator) {
1116 return (lhs, rhs) -> (lhs == rhs) ? 0 : comparator.compare(lhs.peek(), rhs.peek());
1117 }
1118 }
1119 }
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131 @SafeVarargs public static <A> Iterable<A> cycle(final A... as) {
1132 if (as.length > 0) {
1133 return new Cycle<>(Arrays.asList(as));
1134 } else {
1135 return emptyIterable();
1136 }
1137 }
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149 public static <A> Iterable<A> cycle(final Iterable<? extends A> as) {
1150 return new Cycle<>(as);
1151 }
1152
1153 static final class Cycle<A> implements Iterable<A> {
1154 final Iterable<? extends A> as;
1155
1156 Cycle(final Iterable<? extends A> as) {
1157 this.as = requireNonNull(as);
1158 }
1159
1160 @Override public Iterator<A> iterator() {
1161 return new Iter<>(as);
1162 }
1163
1164 static final class Iter<A> extends Iterators.Abstract<A> {
1165 Iterable<? extends A> as;
1166 Iterator<? extends A> ias;
1167
1168 Iter(final Iterable<? extends A> as) {
1169 this.as = as;
1170 this.ias = as.iterator();
1171 }
1172
1173 @Override protected A computeNext() {
1174 if (!ias.hasNext() && !(ias = as.iterator()).hasNext()) {
1175 return endOfData();
1176 }
1177 return ias.next();
1178 }
1179 }
1180
1181 @Override public String toString() {
1182 return makeString(as, "[", ", ", "...]", 100);
1183 }
1184 }
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203 public static <A> String makeString(final Iterable<? extends A> as, final String start, final String sep, final String end, final int maxLength) {
1204 final StringBuilder b = new StringBuilder();
1205 b.append(start);
1206 final Iterator<? extends A> ias = requireNonNull(as).iterator();
1207
1208 if (ias.hasNext()) {
1209 b.append(String.valueOf(ias.next()));
1210 }
1211 while (ias.hasNext()) {
1212 if (b.length() >= maxLength) {
1213 break;
1214 }
1215
1216 b.append(sep);
1217 final String value = String.valueOf(ias.next());
1218 b.append(value);
1219 }
1220 if (ias.hasNext()) {
1221 b.append("...");
1222 }
1223 b.append(end);
1224 return b.toString();
1225 }
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245 public static <A> String makeString(final Iterable<? extends A> as, final String start, final String sep, final String end) {
1246 return makeString(as, start, sep, end, 100);
1247 }
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257 public static <A> Iterable<A> memoize(final Iterable<A> xs) {
1258 return new Memoizer<>(xs);
1259 }
1260
1261
1262
1263
1264 static final class Memoizer<A> extends IterableToString<A> {
1265 private final Node<A> head;
1266
1267 Memoizer(final Iterable<A> delegate) {
1268 head = nextNode(delegate.iterator());
1269 }
1270
1271 @Override public Iterator<A> iterator() {
1272 return new Iter<>(head);
1273 }
1274
1275 private static <A> Node<A> nextNode(final Iterator<A> delegate) {
1276 return delegate.hasNext() ? new Lazy<>(delegate) : new End<>();
1277 }
1278
1279
1280
1281
1282 interface Node<A> {
1283 boolean isEnd();
1284
1285 A value();
1286
1287
1288
1289
1290
1291
1292
1293 Node<A> next() throws NoSuchElementException;
1294 }
1295
1296
1297
1298
1299 static class Lazy<A> extends LazyReference<Node<A>> implements Node<A> {
1300 private final Iterator<A> delegate;
1301 private final A value;
1302
1303 Lazy(final Iterator<A> delegate) {
1304 this.delegate = delegate;
1305 this.value = delegate.next();
1306 }
1307
1308 @Override protected Node<A> create() throws Exception {
1309 return nextNode(delegate);
1310 }
1311
1312 @Override public Node<A> next() throws NoSuchElementException {
1313 return get();
1314 }
1315
1316 @Override public boolean isEnd() {
1317 return false;
1318 }
1319
1320 @Override public A value() {
1321 return value;
1322 }
1323 }
1324
1325 static class End<A> implements Node<A> {
1326 @Override public boolean isEnd() {
1327 return true;
1328 }
1329
1330
1331 @Override public Node<A> next() {
1332 throw new NoSuchElementException();
1333 }
1334
1335 @Override public A value() {
1336 throw new NoSuchElementException();
1337 }
1338
1339 }
1340
1341 static class Iter<A> extends Iterators.Abstract<A> {
1342 Node<A> node;
1343
1344 Iter(final Node<A> node) {
1345 this.node = node;
1346 }
1347
1348 @Override protected A computeNext() {
1349 if (node.isEnd()) {
1350 return endOfData();
1351 }
1352 try {
1353 return node.value();
1354 } finally {
1355 node = node.next();
1356 }
1357 }
1358 }
1359 }
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418 static abstract class LazyReference<T> extends WeakReference<T> implements Supplier<T> {
1419
1420 private final Sync sync = new Sync();
1421
1422 public LazyReference() {
1423 super(null);
1424 }
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435 protected abstract T create() throws Exception;
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448 @Override public final T get() {
1449 boolean interrupted = false;
1450 try {
1451 while (true) {
1452 try {
1453 return getInterruptibly();
1454 } catch (final InterruptedException ignore) {
1455
1456 interrupted = true;
1457 }
1458 }
1459 } finally {
1460 if (interrupted) {
1461 Thread.currentThread().interrupt();
1462 }
1463 }
1464 }
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482 public final T getInterruptibly() throws InterruptedException {
1483 if (!sync.isDone()) {
1484 sync.run();
1485 }
1486
1487 try {
1488 return sync.get();
1489 } catch (final ExecutionException e) {
1490 throw new InitializationException(e);
1491 }
1492 }
1493
1494
1495
1496
1497
1498
1499 public final boolean isInitialized() {
1500 return sync.isDone();
1501 }
1502
1503
1504
1505
1506
1507 public final void cancel() {
1508 sync.cancel(true);
1509 }
1510
1511
1512
1513
1514
1515 public static class InitializationException extends RuntimeException {
1516 private static final long serialVersionUID = 3638376010285456759L;
1517
1518 InitializationException(final ExecutionException e) {
1519 super((e.getCause() != null) ? e.getCause() : e);
1520 }
1521 }
1522
1523 static final class State {
1524 static final int INIT = 0;
1525 static final int RUNNING = 1;
1526 static final int RAN = 2;
1527 static final int CANCELLED = 4;
1528 }
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538 private final class Sync extends AbstractQueuedSynchronizer {
1539
1540 static final int IGNORED = 0;
1541
1542
1543
1544
1545
1546 private static final long serialVersionUID = -1645412544240373524L;
1547
1548
1549 private T result;
1550
1551 private Throwable exception;
1552
1553
1554
1555
1556
1557
1558 private volatile Thread runner;
1559
1560 private boolean ranOrCancelled(final int state) {
1561 return (state & (State.RAN | State.CANCELLED)) != State.INIT;
1562 }
1563
1564
1565
1566
1567 @Override protected int tryAcquireShared(final int ignore) {
1568 return isDone() ? 1 : -1;
1569 }
1570
1571
1572
1573
1574
1575 @Override protected boolean tryReleaseShared(final int ignore) {
1576 runner = null;
1577 return true;
1578 }
1579
1580 boolean isDone() {
1581 return ranOrCancelled(getState()) && (runner == null);
1582 }
1583
1584 T get() throws InterruptedException, ExecutionException {
1585 acquireSharedInterruptibly(IGNORED);
1586 if (getState() == State.CANCELLED) {
1587 throw new CancellationException();
1588 }
1589 if (exception != null) {
1590 throw new ExecutionException(exception);
1591 }
1592 return result;
1593 }
1594
1595 void set(final T v) {
1596 for (;;) {
1597 final int s = getState();
1598 if (s == State.RAN) {
1599 return;
1600 }
1601 if (s == State.CANCELLED) {
1602
1603
1604
1605 releaseShared(IGNORED);
1606 return;
1607 }
1608 if (compareAndSetState(s, State.RAN)) {
1609 result = v;
1610 releaseShared(IGNORED);
1611 return;
1612 }
1613 }
1614 }
1615
1616 void setException(final Throwable t) {
1617 for (;;) {
1618 final int s = getState();
1619 if (s == State.RAN) {
1620 return;
1621 }
1622 if (s == State.CANCELLED) {
1623
1624
1625
1626 releaseShared(0);
1627 return;
1628 }
1629 if (compareAndSetState(s, State.RAN)) {
1630 exception = t;
1631 result = null;
1632 releaseShared(0);
1633 return;
1634 }
1635 }
1636 }
1637
1638 void cancel(final boolean mayInterruptIfRunning) {
1639 for (;;) {
1640 final int s = getState();
1641 if (ranOrCancelled(s)) {
1642 return;
1643 }
1644 if (compareAndSetState(s, State.CANCELLED)) {
1645 break;
1646 }
1647 }
1648 if (mayInterruptIfRunning) {
1649 final Thread r = runner;
1650 if (r != null) {
1651 r.interrupt();
1652 }
1653 }
1654 releaseShared(IGNORED);
1655 }
1656
1657 void run() {
1658 if ((getState() != State.INIT) || !compareAndSetState(State.INIT, State.RUNNING)) {
1659 if (runner == Thread.currentThread()) {
1660 throw new IllegalMonitorStateException("Not reentrant!");
1661 }
1662 return;
1663 }
1664 try {
1665 runner = Thread.currentThread();
1666 set(create());
1667 } catch (final Throwable ex) {
1668 setException(ex);
1669 }
1670 }
1671 }
1672 }
1673 }