001/* 002 * Java Genetic Algorithm Library (jenetics-7.2.0). 003 * Copyright (c) 2007-2023 Franz Wilhelmstötter 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 * 017 * Author: 018 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) 019 */ 020package io.jenetics.ext.internal.util; 021 022import java.util.ArrayList; 023import java.util.List; 024import java.util.Objects; 025import java.util.Spliterator; 026import java.util.function.Consumer; 027import java.util.function.Supplier; 028 029/** 030 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> 031 * @version 4.1 032 * @since 4.1 033 */ 034public class CyclicSpliterator<T> implements Spliterator<T> { 035 036 private final List<Supplier<Spliterator<T>>> _spliterators; 037 038 private ConcatSpliterator<T> _concat = null; 039 040 public CyclicSpliterator(final List<Supplier<Spliterator<T>>> spliterators) { 041 spliterators.forEach(Objects::requireNonNull); 042 _spliterators = new ArrayList<>(spliterators); 043 } 044 045 @Override 046 public boolean tryAdvance(final Consumer<? super T> action) { 047 boolean advance = true; 048 if (_spliterators.isEmpty()) { 049 advance = false; 050 } else { 051 if (!spliterator().tryAdvance(action)) { 052 _concat = null; 053 } 054 } 055 056 return advance; 057 } 058 059 @Override 060 public Spliterator<T> trySplit() { 061 return new CyclicSpliterator<>(_spliterators); 062 } 063 064 @Override 065 public long estimateSize() { 066 return Long.MAX_VALUE; 067 } 068 069 @Override 070 public int characteristics() { 071 return Spliterator.ORDERED; 072 } 073 074 private ConcatSpliterator<T> spliterator() { 075 if (_concat == null) { 076 _concat = new ConcatSpliterator<>( 077 _spliterators.stream() 078 .map(Supplier::get) 079 .toList() 080 ); 081 } 082 083 return _concat; 084 } 085 086}