001/*
002 * Licensed to the author under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. 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 */
017package de.cuioss.test.generator.internal.net.java.quickcheck.generator.support;
018
019import static java.lang.Math.max;
020
021import java.util.ArrayList;
022import java.util.List;
023import java.util.Objects;
024
025import de.cuioss.test.generator.internal.net.java.quickcheck.Generator;
026
027public class ListGenerator<T> implements Generator<List<T>> {
028
029    public static final int MIN_SIZE = 0;
030    // why call the default size max_size if this size does not limit the upper
031    // bound for all lists? ListGenerator(Generator, int int) does not define
032    // any limit on max, so i think max_size does not reflect what the value
033    // is used for. previously it was named default_size but should better
034    // be named like default_max_size
035    public static final int MAX_SIZE = 10;
036
037    private final Generator<? extends T> content;
038    private final Generator<Integer> size;
039
040    public ListGenerator(Generator<? extends T> content) {
041        this(content, MIN_SIZE, MAX_SIZE);
042    }
043
044    public ListGenerator(Generator<? extends T> content, int min, int max) {
045        this(content, new IntegerGenerator(min, max));
046    }
047
048    public ListGenerator(Generator<? extends T> content, Generator<Integer> size) {
049        Objects.requireNonNull(content, "content");
050        Objects.requireNonNull(size, "size");
051
052        this.content = content;
053        this.size = size;
054    }
055
056    @Override
057    public List<T> next() {
058        int size = max(MIN_SIZE, this.size.next());
059        List<T> list = new ArrayList<>(size);
060        for (int i = 0; i < size; i++)
061            list.add(this.content.next());
062        return list;
063    }
064}