01 /*
02 * Java Genetic Algorithm Library (jenetics-3.5.0).
03 * Copyright (c) 2007-2016 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@gmx.at)
19 */
20 package org.jenetics.util;
21
22 import static java.util.Objects.requireNonNull;
23
24 import java.util.Spliterator;
25 import java.util.function.Consumer;
26
27 /**
28 * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
29 * @since 3.0
30 * @version 3.4
31 */
32 final class SeqSpliterator<T> implements Spliterator<T> {
33
34 private final Seq<T> _seq;
35 private final int _fence;
36 private int _index;
37
38 public SeqSpliterator(
39 final Seq<T> seq,
40 final int origin,
41 final int fence
42 ) {
43 _seq = requireNonNull(seq);
44 _index = origin;
45 _fence = fence;
46 }
47
48 public SeqSpliterator(final Seq<T> seq) {
49 this(seq, 0, seq.length());
50 }
51
52 @Override
53 public void forEachRemaining(final Consumer<? super T> action) {
54 requireNonNull(action);
55
56 Seq<T> seq;
57 int i;
58 int hi;
59
60 if ((seq = _seq).length() >= (hi = _fence) &&
61 (i = _index) >= 0 && i < (_index = hi))
62 {
63 do {
64 action.accept(seq.get(i));
65 } while (++i < hi);
66 }
67 }
68
69 @Override
70 public boolean tryAdvance(final Consumer<? super T> action) {
71 if (_index >= 0 && _index < _fence) {
72 action.accept(_seq.get(_index++));
73 return true;
74 }
75 return false;
76 }
77
78 @Override
79 public Spliterator<T> trySplit() {
80 final int lo = _index;
81 final int mid = (lo + _fence) >>> 1;
82
83 return (lo >= mid)
84 ? null
85 : new SeqSpliterator<>(_seq, lo, _index = mid);
86 }
87
88 @Override
89 public long estimateSize() {
90 return _fence - _index;
91 }
92
93 @Override
94 public int characteristics() {
95 return Spliterator.NONNULL | Spliterator.SIZED | Spliterator.SUBSIZED;
96 }
97 }
|