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.ArrayList;
021import java.util.Collection;
022import java.util.Collections;
023import java.util.HashSet;
024import java.util.List;
025import java.util.Set;
026
027import static java.util.Objects.requireNonNull;
028
029public class SubsetGenerator<T> implements Generator<Set<T>> {
030
031    private final List<T> superset;
032    private final Generator<Integer> sizes;
033
034    public SubsetGenerator(Iterable<T> superset, Generator<Integer> size) {
035        requireNonNull(superset, "superset");
036        requireNonNull(size, "size");
037        var list = new ArrayList<T>();
038        superset.forEach(list::add);
039        this.superset = list;
040        this.sizes = size;
041    }
042
043    public SubsetGenerator(Iterable<T> superset) {
044        requireNonNull(superset, "superset");
045        var list = new ArrayList<T>();
046        superset.forEach(list::add);
047        this.superset = list;
048        this.sizes = new IntegerGenerator(0, list.size());
049    }
050
051    @Override
052    public Set<T> next() {
053        Collections.shuffle(superset);
054        int size = sizes.next();
055        if (size < 0) {
056            throw new IllegalArgumentException("Size must be non-negative");
057        }
058        if (maxSize(superset) < size) {
059            throw new IllegalArgumentException("Size must not exceed superset size");
060        }
061        return new HashSet<>(superset.subList(0, size));
062    }
063
064    private static <T> int maxSize(Collection<T> superset) {
065        return superset.size();
066    }
067
068}