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 static java.util.Objects.requireNonNull;
23
24 import java.util.Spliterator;
25 import java.util.function.Consumer;
26 import java.util.function.Function;
27
28 /**
29 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
30 * @version 4.1
31 * @since 4.1
32 */
33 public class GeneratorSpliterator<T> implements Spliterator<T> {
34
35 private final Function<? super T, ? extends Spliterator<T>> _generator;
36
37 private Spliterator<T> _current;
38 private T _element;
39
40 public GeneratorSpliterator(
41 final Function<? super T, ? extends Spliterator<T>> generator
42 ) {
43 _generator = requireNonNull(generator);
44 }
45
46 @Override
47 public boolean tryAdvance(final Consumer<? super T> action) {
48 requireNonNull(action);
49
50 final boolean advance = spliterator().tryAdvance(element -> {
51 action.accept(element);
52 _element = element;
53 });
54
55 if (!advance) {
56 _current = null;
57 }
58
59 return true;
60 }
61
62 @Override
63 public Spliterator<T> trySplit() {
64 return new GeneratorSpliterator<>(_generator);
65 }
66
67 @Override
68 public long estimateSize() {
69 return Long.MAX_VALUE;
70 }
71
72 @Override
73 public int characteristics() {
74 return Spliterator.ORDERED;
75 }
76
77 private Spliterator<T> spliterator() {
78 if (_current == null) {
79 _current = _generator.apply(_element);
80 }
81
82 return _current;
83 }
84
85 }
|