ListGenerator.java

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

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

import java.util.List;

/**
 * Default generator for a list field.
 */
public class ListGenerator<Context extends GeneratorContext<Context>>
        implements Generator<Context, List<Object>> {
    private final PList<Object> list;

    public ListGenerator(PList<Object> list) {
        this.list = list;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Object> generate(Context ctx) {
        int       num       = ctx.nextCollectionSize();
        Generator generator = ctx.generatorForDescriptor(list.itemDescriptor());

        PList.Builder<Object> builder = list.builder(num);
        for (int i = 0; i < num; ++i) {
            builder.add(generator.generate(ctx));
        }
        return builder.build();
    }
}