1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.atlassian.fugue;
18
19 import static io.atlassian.fugue.Functions.countingPredicate;
20 import static io.atlassian.fugue.Iterators.emptyIterator;
21 import static io.atlassian.fugue.Iterators.peekingIterator;
22 import static io.atlassian.fugue.Option.none;
23 import static io.atlassian.fugue.Option.some;
24 import static io.atlassian.fugue.Pair.leftValue;
25 import static io.atlassian.fugue.Pair.pair;
26 import static io.atlassian.fugue.Pair.rightValue;
27 import static io.atlassian.fugue.Suppliers.ofInstance;
28 import static java.util.Arrays.asList;
29 import static java.util.Collections.unmodifiableCollection;
30 import static java.util.Objects.requireNonNull;
31
32 import java.io.Serializable;
33 import java.lang.ref.Reference;
34 import java.lang.ref.WeakReference;
35 import java.util.Arrays;
36 import java.util.Collection;
37 import java.util.Comparator;
38 import java.util.Iterator;
39 import java.util.LinkedList;
40 import java.util.List;
41 import java.util.NoSuchElementException;
42 import java.util.Queue;
43 import java.util.TreeSet;
44 import java.util.concurrent.CancellationException;
45 import java.util.concurrent.ExecutionException;
46 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
47 import java.util.function.BiFunction;
48 import java.util.function.Function;
49 import java.util.function.Predicate;
50 import java.util.function.Supplier;
51 import java.util.stream.Collector;
52 import java.util.stream.StreamSupport;
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
487 @Override public boolean hasNext() {
488 return step > 0 ? i <= end : i >= end;
489 }
490
491 @Override public Integer next() {
492 try {
493 return i;
494 } finally {
495 i += step;
496 }
497 }
498 };
499 }
500
501 static abstract class IterableToString<A> implements Iterable<A> {
502 @Override public final String toString() {
503 return makeString(this, "[", ", ", "]");
504 }
505 }
506
507
508
509
510 static final class Take<A> extends IterableToString<A> {
511 private final Iterable<A> as;
512 private final Predicate<A> p;
513
514 private Take(final Iterable<A> as, final Predicate<A> p) {
515 this.p = requireNonNull(p);
516 this.as = requireNonNull(as);
517 }
518
519 @Override public Iterator<A> iterator() {
520 return new Iter<>(as.iterator(), p);
521 }
522
523 static final class Iter<A> extends Iterators.Abstract<A> {
524 private final Iterator<A> ias;
525 private final Predicate<A> p;
526
527 Iter(final Iterator<A> ias, final Predicate<A> p) {
528 this.ias = ias;
529 this.p = p;
530 }
531
532 @Override protected A computeNext() {
533 if (ias.hasNext()) {
534 final A a = ias.next();
535 return p.test(a) ? a : endOfData();
536 }
537 return endOfData();
538 }
539 }
540 }
541
542
543
544
545 static final class Drop<A> extends IterableToString<A> {
546 private final Iterable<A> as;
547 private final Predicate<A> p;
548
549 private Drop(final Iterable<A> as, final Predicate<A> p) {
550 this.p = requireNonNull(p);
551 this.as = requireNonNull(as);
552 }
553
554 @Override public Iterator<A> iterator() {
555 return new Iter<>(as.iterator(), p);
556 }
557
558 static final class Iter<A> extends Iterators.Abstract<A> {
559 private final Iterators.Peeking<A> as;
560
561 Iter(final Iterator<A> as, final Predicate<A> p) {
562 this.as = peekingIterator(as);
563 while (this.as.hasNext() && p.test(this.as.peek())) {
564 this.as.next();
565 }
566 }
567
568 @Override protected A computeNext() {
569 return as.hasNext() ? as.next() : endOfData();
570 }
571 }
572 }
573
574
575
576
577 static class CollectingIterable<A, B> extends IterableToString<B> {
578 private final Iterable<? extends A> delegate;
579 private final Function<? super A, Option<B>> partial;
580
581 CollectingIterable(final Iterable<? extends A> delegate, final Function<? super A, Option<B>> partial) {
582 this.delegate = requireNonNull(delegate);
583 this.partial = requireNonNull(partial);
584 }
585
586 @Override public Iterator<B> iterator() {
587 return new Iter();
588 }
589
590 final class Iter extends Iterators.Abstract<B> {
591 private final Iterator<? extends A> it = delegate.iterator();
592
593 @Override protected B computeNext() {
594 while (it.hasNext()) {
595 final Option<B> result = partial.apply(it.next());
596 if (result.isDefined())
597 return result.get();
598 }
599 return endOfData();
600 }
601 }
602 }
603
604
605
606
607 static class Zipper<A, B, C> extends IterableToString<C> {
608 private final Iterable<A> as;
609 private final Iterable<B> bs;
610 private final BiFunction<A, B, C> f;
611
612 Zipper(final Iterable<A> as, final Iterable<B> bs, final BiFunction<A, B, C> f) {
613 this.as = requireNonNull(as, "as must not be null.");
614 this.bs = requireNonNull(bs, "bs must not be null.");
615 this.f = requireNonNull(f, "f must not be null.");
616 }
617
618 @Override public Iterator<C> iterator() {
619 return new Iter();
620 }
621
622 class Iter implements Iterator<C> {
623 private final Iterator<A> a = requireNonNull(as.iterator(), "as iterator must not be null.");
624 private final Iterator<B> b = requireNonNull(bs.iterator(), "bs iterator must not be null.");
625
626 @Override public boolean hasNext() {
627 return a.hasNext() && b.hasNext();
628 }
629
630 @Override public C next() {
631 return f.apply(a.next(), b.next());
632 }
633
634 @Override public void remove() {
635 throw new UnsupportedOperationException();
636 }
637 }
638 }
639
640
641
642
643
644
645
646
647
648
649 public static <A> Iterable<A> intersperse(final Iterable<? extends A> as, final A a) {
650 return intersperse(as, ofInstance(a));
651 }
652
653
654
655
656
657
658
659
660
661
662
663 public static <A> Iterable<A> intersperse(final Iterable<? extends A> as, final Supplier<A> a) {
664 return new Intersperse<>(as, a);
665 }
666
667 static final class Intersperse<A> implements Iterable<A> {
668 private final Iterable<? extends A> as;
669 private final Supplier<A> a;
670
671 Intersperse(final Iterable<? extends A> as, final Supplier<A> a) {
672 this.as = as;
673 this.a = a;
674 }
675
676 @Override public Iterator<A> iterator() {
677 return new Iterators.Abstract<A>() {
678 private final Iterator<? extends A> it = as.iterator();
679 private boolean inter = false;
680
681 @Override protected A computeNext() {
682 if (!it.hasNext()) {
683 return endOfData();
684 }
685 try {
686 return inter ? a.get() : it.next();
687 } finally {
688 inter = !inter;
689 }
690 }
691 };
692 }
693 }
694
695
696
697
698
699
700
701
702
703
704
705 public static <A> int size(final Iterable<A> as) {
706 if (as instanceof Collection) {
707 return ((Collection<?>) as).size();
708 } else {
709 final Iterator<A> iterator = as.iterator();
710 int count = 0;
711 while (iterator.hasNext()) {
712 iterator.next();
713 count++;
714 }
715 return count;
716 }
717 }
718
719
720
721
722
723
724
725
726
727
728
729
730
731 @Deprecated public static <A, B> Iterable<B> transform(final Iterable<A> as, final Function<? super A, ? extends B> f) {
732 return map(as, f);
733 }
734
735
736
737
738
739
740
741
742
743
744
745
746
747 public static <A, B> Iterable<B> map(final Iterable<A> as, final Function<? super A, ? extends B> f) {
748 return new Mapped<>(as, f);
749 }
750
751 static final class Mapped<A, B> implements Iterable<B> {
752 private final Iterable<? extends A> as;
753 private final Function<? super A, ? extends B> f;
754
755 Mapped(final Iterable<? extends A> as, final Function<? super A, ? extends B> f) {
756 this.as = as;
757 this.f = f;
758 }
759
760 @Override public Iterator<B> iterator() {
761 return new Iterators.Abstract<B>() {
762 private final Iterator<? extends A> it = as.iterator();
763
764 @Override protected B computeNext() {
765 if (!it.hasNext()) {
766 return endOfData();
767 }
768 return f.apply(it.next());
769 }
770 };
771 }
772 }
773
774
775
776
777
778
779
780
781
782
783
784
785 public static <A> Iterable<A> filter(final Iterable<A> as, final Predicate<? super A> p) {
786 return new Filter<>(as, p);
787 }
788
789 static final class Filter<A> implements Iterable<A> {
790 private final Iterable<? extends A> as;
791 private final Predicate<? super A> p;
792
793 Filter(final Iterable<? extends A> as, final Predicate<? super A> p) {
794 this.as = as;
795 this.p = p;
796 }
797
798 @Override public Iterator<A> iterator() {
799 return new Iterators.Abstract<A>() {
800 private final Iterator<? extends A> it = as.iterator();
801
802 @Override protected A computeNext() {
803 if (!it.hasNext()) {
804 return endOfData();
805 }
806 while (it.hasNext()) {
807 final A a = it.next();
808 if (p.test(a)) {
809 return a;
810 }
811 }
812 return endOfData();
813 }
814 };
815 }
816 }
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831 public static <A> Iterable<A> join(final Iterable<? extends Iterable<? extends A>> ias) {
832 return new Join<>(ias);
833 }
834
835 static final class Join<A> extends IterableToString<A> {
836 private final Iterable<? extends Iterable<? extends A>> ias;
837
838 public Join(final Iterable<? extends Iterable<? extends A>> ias) {
839 this.ias = ias;
840 }
841
842 @Override public Iterator<A> iterator() {
843 return new Iter<>(ias);
844 }
845
846 static class Iter<A> extends Iterators.Abstract<A> {
847 final Queue<Iterator<? extends A>> qas = new LinkedList<>();
848
849 public Iter(final Iterable<? extends Iterable<? extends A>> ias) {
850 for (final Iterable<? extends A> a : ias) {
851 qas.add(requireNonNull(a.iterator()));
852 }
853 }
854
855 @Override protected A computeNext() {
856 while (!qas.isEmpty() && !qas.peek().hasNext()) {
857 qas.remove();
858 }
859 if (qas.isEmpty()) {
860 return endOfData();
861 }
862 return qas.peek().next();
863 }
864 }
865 }
866
867
868
869
870
871
872
873
874
875
876
877 @SafeVarargs public static <A> Iterable<A> concat(final Iterable<? extends A>... as) {
878 return as.length > 0 ? join(Arrays.asList(as)) : emptyIterable();
879 }
880
881
882
883
884
885
886
887
888
889
890
891 public static <A> boolean any(final Iterable<? extends A> as, final Predicate<? super A> p) {
892 return !isEmpty().test(filter(as, p));
893 }
894
895
896
897
898
899
900
901
902
903
904
905 public static <A> boolean all(final Iterable<? extends A> as, final Predicate<? super A> p) {
906 return isEmpty().test(filter(as, p.negate()));
907 }
908
909
910
911
912
913
914
915
916
917
918
919
920 public static <A> Iterable<A> iterate(final Function<? super A, ? extends A> f, final A start) {
921 return new IteratingIterable<>(f, start);
922 }
923
924
925
926
927 static final class IteratingIterable<A> implements Iterable<A> {
928 private final Function<? super A, ? extends A> f;
929 private final A start;
930
931 private IteratingIterable(final Function<? super A, ? extends A> f, final A start) {
932 this.f = requireNonNull(f, "f");
933 this.start = start;
934 }
935
936 @Override public Iterator<A> iterator() {
937 return new Iter<>(f, start);
938 }
939
940 static final class Iter<A> extends Iterators.Unmodifiable<A> {
941 private final Function<? super A, ? extends A> f;
942 private A current;
943
944 Iter(final Function<? super A, ? extends A> f, final A start) {
945 this.f = f;
946 this.current = start;
947 }
948
949 @Override public boolean hasNext() {
950 return true;
951 }
952
953 @Override public A next() {
954 final A value = current;
955 current = f.apply(current);
956 return value;
957 }
958 }
959 }
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976 public static <A, B> Iterable<A> unfold(final Function<? super B, Option<Pair<A, B>>> f, final B seed) {
977 return new UnfoldingIterable<>(f, seed);
978 }
979
980
981
982
983 static final class UnfoldingIterable<A, B> extends IterableToString<A> {
984 private final Function<? super B, Option<Pair<A, B>>> f;
985 private final B seed;
986
987 private UnfoldingIterable(final Function<? super B, Option<Pair<A, B>>> f, final B seed) {
988 this.f = requireNonNull(f, "f");
989 this.seed = seed;
990 }
991
992 @Override public Iterator<A> iterator() {
993 return new Iter<>(f, seed);
994 }
995
996 static final class Iter<A, B> extends Iterators.Abstract<A> {
997 private final Function<? super B, Option<Pair<A, B>>> f;
998 private B current;
999
1000 Iter(final Function<? super B, Option<Pair<A, B>>> f, final B seed) {
1001 this.f = f;
1002 this.current = seed;
1003 }
1004
1005 @Override protected A computeNext() {
1006 final Option<Pair<A, B>> option = f.apply(current);
1007 if (option.isDefined()) {
1008 final Pair<A, B> pair = option.get();
1009 current = pair.right();
1010 return pair.left();
1011 } else {
1012 return endOfData();
1013 }
1014 }
1015 }
1016 }
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028 public static <A extends Comparable<A>> Iterable<A> mergeSorted(final Iterable<? extends Iterable<A>> xss) {
1029 return mergeSorted(xss, Comparator.<A> naturalOrder());
1030 }
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043 public static <A> Iterable<A> mergeSorted(final Iterable<? extends Iterable<A>> xss, final Comparator<A> ordering) {
1044 return new MergeSortedIterable<>(xss, ordering);
1045 }
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056 @SuppressWarnings("unchecked") public static <A> boolean addAll(final Collection<A> collectionToModify, final Iterable<? extends A> elementsToAdd) {
1057 if (elementsToAdd instanceof Collection) {
1058 return collectionToModify.addAll((Collection<? extends A>) elementsToAdd);
1059 }
1060 return Iterators.addAll(collectionToModify, requireNonNull(elementsToAdd).iterator());
1061 }
1062
1063
1064
1065
1066 static final class MergeSortedIterable<A> extends IterableToString<A> {
1067 private final Iterable<? extends Iterable<A>> xss;
1068 private final Comparator<A> comparator;
1069
1070 MergeSortedIterable(final Iterable<? extends Iterable<A>> xss, final Comparator<A> comparator) {
1071 this.xss = requireNonNull(xss, "xss");
1072 this.comparator = requireNonNull(comparator, "comparator");
1073 }
1074
1075 @Override public Iterator<A> iterator() {
1076 return new Iter<>(xss, comparator);
1077 }
1078
1079 private static final class Iter<A> extends Iterators.Abstract<A> {
1080 private final TreeSet<Iterators.Peeking<A>> xss;
1081
1082 private Iter(final Iterable<? extends Iterable<A>> xss, final Comparator<A> c) {
1083 this.xss = new TreeSet<>(peekingIteratorComparator(c));
1084 addAll(this.xss, map(filter(xss, isEmpty().negate()), i -> peekingIterator(i.iterator())));
1085 }
1086
1087 @Override protected A computeNext() {
1088 final Option<Iterators.Peeking<A>> currFirstOption = first(xss);
1089 if (!currFirstOption.isDefined()) {
1090 return endOfData();
1091 }
1092 final Iterators.Peeking<A> currFirst = currFirstOption.get();
1093
1094
1095
1096
1097 xss.remove(currFirst);
1098
1099 final A next = currFirst.next();
1100 if (currFirst.hasNext()) {
1101 xss.add(currFirst);
1102 }
1103 return next;
1104 }
1105
1106 private Comparator<? super Iterators.Peeking<A>> peekingIteratorComparator(final Comparator<A> comparator) {
1107 return (lhs, rhs) -> (lhs == rhs) ? 0 : comparator.compare(lhs.peek(), rhs.peek());
1108 }
1109 }
1110 }
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122 @SafeVarargs public static <A> Iterable<A> cycle(final A... as) {
1123 if (as.length > 0) {
1124 return new Cycle<>(Arrays.asList(as));
1125 } else {
1126 return emptyIterable();
1127 }
1128 }
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140 public static <A> Iterable<A> cycle(final Iterable<? extends A> as) {
1141 return new Cycle<>(as);
1142 }
1143
1144 static final class Cycle<A> implements Iterable<A> {
1145 final Iterable<? extends A> as;
1146
1147 Cycle(final Iterable<? extends A> as) {
1148 this.as = requireNonNull(as);
1149 }
1150
1151 @Override public Iterator<A> iterator() {
1152 return new Iter<>(as);
1153 }
1154
1155 static final class Iter<A> extends Iterators.Abstract<A> {
1156 Iterable<? extends A> as;
1157 Iterator<? extends A> ias;
1158
1159 Iter(final Iterable<? extends A> as) {
1160 this.as = as;
1161 this.ias = as.iterator();
1162 }
1163
1164 @Override protected A computeNext() {
1165 if (!ias.hasNext() && !(ias = as.iterator()).hasNext()) {
1166 return endOfData();
1167 }
1168 return ias.next();
1169 }
1170 }
1171
1172 @Override public String toString() {
1173 return makeString(as, "[", ", ", "...]", 100);
1174 }
1175 }
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194 public static <A> String makeString(final Iterable<? extends A> as, final String start, final String sep, final String end, final int maxLength) {
1195 final StringBuilder b = new StringBuilder();
1196 b.append(start);
1197 final Iterator<? extends A> ias = requireNonNull(as).iterator();
1198
1199 if (ias.hasNext()) {
1200 b.append(String.valueOf(ias.next()));
1201 }
1202 while (ias.hasNext()) {
1203 if (b.length() >= maxLength) {
1204 break;
1205 }
1206
1207 b.append(sep);
1208 final String value = String.valueOf(ias.next());
1209 b.append(value);
1210 }
1211 if (ias.hasNext()) {
1212 b.append("...");
1213 }
1214 b.append(end);
1215 return b.toString();
1216 }
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236 public static <A> String makeString(final Iterable<? extends A> as, final String start, final String sep, final String end) {
1237 return makeString(as, start, sep, end, 100);
1238 }
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248 public static <A> Iterable<A> memoize(final Iterable<A> xs) {
1249 return new Memoizer<>(xs);
1250 }
1251
1252
1253
1254
1255 static final class Memoizer<A> extends IterableToString<A> {
1256 private final Node<A> head;
1257
1258 Memoizer(final Iterable<A> delegate) {
1259 head = nextNode(delegate.iterator());
1260 }
1261
1262 @Override public Iterator<A> iterator() {
1263 return new Iter<>(head);
1264 }
1265
1266 private static <A> Node<A> nextNode(final Iterator<A> delegate) {
1267 return delegate.hasNext() ? new Lazy<>(delegate) : new End<>();
1268 }
1269
1270
1271
1272
1273 interface Node<A> {
1274 boolean isEnd();
1275
1276 A value();
1277
1278
1279
1280
1281
1282
1283
1284 Node<A> next() throws NoSuchElementException;
1285 }
1286
1287
1288
1289
1290 static class Lazy<A> extends LazyReference<Node<A>> implements Node<A> {
1291 private final Iterator<A> delegate;
1292 private final A value;
1293
1294 Lazy(final Iterator<A> delegate) {
1295 this.delegate = delegate;
1296 this.value = delegate.next();
1297 }
1298
1299 @Override protected Node<A> create() throws Exception {
1300 return nextNode(delegate);
1301 }
1302
1303 @Override public Node<A> next() throws NoSuchElementException {
1304 return get();
1305 }
1306
1307 @Override public boolean isEnd() {
1308 return false;
1309 }
1310
1311 @Override public A value() {
1312 return value;
1313 }
1314 }
1315
1316 static class End<A> implements Node<A> {
1317 @Override public boolean isEnd() {
1318 return true;
1319 }
1320
1321
1322 @Override public Node<A> next() {
1323 throw new NoSuchElementException();
1324 }
1325
1326 @Override public A value() {
1327 throw new NoSuchElementException();
1328 }
1329
1330 }
1331
1332 static class Iter<A> extends Iterators.Abstract<A> {
1333 Node<A> node;
1334
1335 Iter(final Node<A> node) {
1336 this.node = node;
1337 }
1338
1339 @Override protected A computeNext() {
1340 if (node.isEnd()) {
1341 return endOfData();
1342 }
1343 try {
1344 return node.value();
1345 } finally {
1346 node = node.next();
1347 }
1348 }
1349 }
1350 }
1351
1352
1353
1354
1355
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 static abstract class LazyReference<T> extends WeakReference<T> implements Supplier<T> {
1410
1411 private final Sync sync = new Sync();
1412
1413 public LazyReference() {
1414 super(null);
1415 }
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426 protected abstract T create() throws Exception;
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439 @Override public final T get() {
1440 boolean interrupted = false;
1441 try {
1442 while (true) {
1443 try {
1444 return getInterruptibly();
1445 } catch (final InterruptedException ignore) {
1446
1447 interrupted = true;
1448 }
1449 }
1450 } finally {
1451 if (interrupted) {
1452 Thread.currentThread().interrupt();
1453 }
1454 }
1455 }
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473 public final T getInterruptibly() throws InterruptedException {
1474 if (!sync.isDone()) {
1475 sync.run();
1476 }
1477
1478 try {
1479 return sync.get();
1480 } catch (final ExecutionException e) {
1481 throw new InitializationException(e);
1482 }
1483 }
1484
1485
1486
1487
1488
1489
1490 public final boolean isInitialized() {
1491 return sync.isDone();
1492 }
1493
1494
1495
1496
1497
1498 public final void cancel() {
1499 sync.cancel(true);
1500 }
1501
1502
1503
1504
1505
1506 public static class InitializationException extends RuntimeException {
1507 private static final long serialVersionUID = 3638376010285456759L;
1508
1509 InitializationException(final ExecutionException e) {
1510 super((e.getCause() != null) ? e.getCause() : e);
1511 }
1512 }
1513
1514 static final class State {
1515 static final int INIT = 0;
1516 static final int RUNNING = 1;
1517 static final int RAN = 2;
1518 static final int CANCELLED = 4;
1519 }
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529 private final class Sync extends AbstractQueuedSynchronizer {
1530
1531 static final int IGNORED = 0;
1532
1533
1534
1535
1536
1537 private static final long serialVersionUID = -1645412544240373524L;
1538
1539
1540 private T result;
1541
1542 private Throwable exception;
1543
1544
1545
1546
1547
1548
1549 private volatile Thread runner;
1550
1551 private boolean ranOrCancelled(final int state) {
1552 return (state & (State.RAN | State.CANCELLED)) != State.INIT;
1553 }
1554
1555
1556
1557
1558 @Override protected int tryAcquireShared(final int ignore) {
1559 return isDone() ? 1 : -1;
1560 }
1561
1562
1563
1564
1565
1566 @Override protected boolean tryReleaseShared(final int ignore) {
1567 runner = null;
1568 return true;
1569 }
1570
1571 boolean isDone() {
1572 return ranOrCancelled(getState()) && (runner == null);
1573 }
1574
1575 T get() throws InterruptedException, ExecutionException {
1576 acquireSharedInterruptibly(IGNORED);
1577 if (getState() == State.CANCELLED) {
1578 throw new CancellationException();
1579 }
1580 if (exception != null) {
1581 throw new ExecutionException(exception);
1582 }
1583 return result;
1584 }
1585
1586 void set(final T v) {
1587 for (;;) {
1588 final int s = getState();
1589 if (s == State.RAN) {
1590 return;
1591 }
1592 if (s == State.CANCELLED) {
1593
1594
1595
1596 releaseShared(IGNORED);
1597 return;
1598 }
1599 if (compareAndSetState(s, State.RAN)) {
1600 result = v;
1601 releaseShared(IGNORED);
1602 return;
1603 }
1604 }
1605 }
1606
1607 void setException(final Throwable t) {
1608 for (;;) {
1609 final int s = getState();
1610 if (s == State.RAN) {
1611 return;
1612 }
1613 if (s == State.CANCELLED) {
1614
1615
1616
1617 releaseShared(0);
1618 return;
1619 }
1620 if (compareAndSetState(s, State.RAN)) {
1621 exception = t;
1622 result = null;
1623 releaseShared(0);
1624 return;
1625 }
1626 }
1627 }
1628
1629 void cancel(final boolean mayInterruptIfRunning) {
1630 for (;;) {
1631 final int s = getState();
1632 if (ranOrCancelled(s)) {
1633 return;
1634 }
1635 if (compareAndSetState(s, State.CANCELLED)) {
1636 break;
1637 }
1638 }
1639 if (mayInterruptIfRunning) {
1640 final Thread r = runner;
1641 if (r != null) {
1642 r.interrupt();
1643 }
1644 }
1645 releaseShared(IGNORED);
1646 }
1647
1648 void run() {
1649 if ((getState() != State.INIT) || !compareAndSetState(State.INIT, State.RUNNING)) {
1650 if (runner == Thread.currentThread()) {
1651 throw new IllegalMonitorStateException("Not reentrant!");
1652 }
1653 return;
1654 }
1655 try {
1656 runner = Thread.currentThread();
1657 set(create());
1658 } catch (final Throwable ex) {
1659 setException(ex);
1660 }
1661 }
1662 }
1663 }
1664 }