001/*
002 * Copyright © 2025 CUI-OpenSource-Software (info@cuioss.de)
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package de.cuioss.test.generator.internal.net.java.quickcheck.generator.support;
017
018import de.cuioss.test.generator.internal.net.java.quickcheck.Generator;
019
020import java.util.Iterator;
021import java.util.Objects;
022
023import static java.lang.Math.max;
024
025public class IteratorGenerator<T> implements Generator<Iterator<T>> {
026
027    public static final int MIN_SIZE = 0;
028
029    // why call the default size max_size if this size does not limit the upper
030    // bound for all lists? ListGenerator(Generator, int int) does not define
031    // any limit on max, so i think max_size does not reflect what the value
032    // is used for. previously it was named default_size but should better
033    // be named like default_max_size
034    public static final int MAX_SIZE = 10;
035
036    private final Generator<? extends T> content;
037    private final Generator<Integer> size;
038
039    public IteratorGenerator(Generator<? extends T> content) {
040        this(content, MIN_SIZE, MAX_SIZE);
041    }
042
043    public IteratorGenerator(Generator<? extends T> content, int min, int max) {
044        this(content, new IntegerGenerator(min, max));
045    }
046
047    public IteratorGenerator(Generator<? extends T> content, Generator<Integer> size) {
048        Objects.requireNonNull(content, "content");
049        Objects.requireNonNull(size, "size");
050
051        this.content = content;
052        this.size = size;
053    }
054
055    @Override
056    public Iterator<T> next() {
057        final int localSize = max(MIN_SIZE, this.size.next());
058        return new Iterator<>() {
059
060            private int i;
061
062            @Override
063            public boolean hasNext() {
064                return i < localSize;
065            }
066
067            @Override
068            @SuppressWarnings("java:S2272") // owolff: For generator by design
069            public T next() {
070                i++;
071                return content.next();
072
073            }
074
075            @Override
076            public void remove() {
077                throw new UnsupportedOperationException("remove not supported.");
078            }
079        };
080    }
081}