CyclicSpliterator.java
01 /*
02  * Java Genetic Algorithm Library (jenetics-7.1.1).
03  * Copyright (c) 2007-2022 Franz Wilhelmstötter
04  *
05  * Licensed under the Apache License, Version 2.0 (the "License");
06  * you may not use this file except in compliance with the License.
07  * You may obtain a copy of the License at
08  *
09  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * Author:
18  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
19  */
20 package io.jenetics.ext.internal.util;
21 
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.Objects;
25 import java.util.Spliterator;
26 import java.util.function.Consumer;
27 import java.util.function.Supplier;
28 
29 /**
30  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
31  @version 4.1
32  @since 4.1
33  */
34 public class CyclicSpliterator<T> implements Spliterator<T> {
35 
36     private final List<Supplier<Spliterator<T>>> _spliterators;
37 
38     private ConcatSpliterator<T> _concat = null;
39 
40     public CyclicSpliterator(final List<Supplier<Spliterator<T>>> spliterators) {
41         spliterators.forEach(Objects::requireNonNull);
42         _spliterators = new ArrayList<>(spliterators);
43     }
44 
45     @Override
46     public boolean tryAdvance(final Consumer<? super T> action) {
47         boolean advance = true;
48         if (_spliterators.isEmpty()) {
49             advance = false;
50         else {
51             if (!spliterator().tryAdvance(action)) {
52                 _concat = null;
53             }
54         }
55 
56         return advance;
57     }
58 
59     @Override
60     public Spliterator<T> trySplit() {
61         return new CyclicSpliterator<>(_spliterators);
62     }
63 
64     @Override
65     public long estimateSize() {
66         return Long.MAX_VALUE;
67     }
68 
69     @Override
70     public int characteristics() {
71         return Spliterator.ORDERED;
72     }
73 
74     private ConcatSpliterator<T> spliterator() {
75         if (_concat == null) {
76             _concat = new ConcatSpliterator<>(
77                 _spliterators.stream()
78                     .map(Supplier::get)
79                     .toList()
80             );
81         }
82 
83         return _concat;
84     }
85 
86 }