SetGenerator.java

package net.morimekta.providence.testing.generator.defaults;

import net.morimekta.providence.descriptor.PSet;
import net.morimekta.providence.testing.generator.Generator;
import net.morimekta.providence.testing.generator.GeneratorContext;

import java.util.Set;

/**
 * Default generator for set fields.
 */
public class SetGenerator<Context extends GeneratorContext<Context>>
        implements Generator<Context, Set<Object>> {
    private final PSet<Object>            set;

    public SetGenerator(PSet<Object> set) {
        this.set = set;
    }

    @Override
    public Set<Object> generate(Context ctx) {
        int                   num       = ctx.nextCollectionSize();
        Generator<Context, ?> generator = ctx.generatorForDescriptor(set.itemDescriptor());

        // Sets does not necessary allow conflicting items.
        PSet.Builder<Object> builder = set.builder(num);
        for (int i = 0; i < num; ++i) {
            builder.add(generator.generate(ctx));
        }
        return builder.build();
    }
}