All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.jqwik.engine.properties.arbitraries.exhaustive.FlatMappedExhaustiveGenerator Maven / Gradle / Ivy

The newest version!
package net.jqwik.engine.properties.arbitraries.exhaustive;

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

import net.jqwik.api.*;
import net.jqwik.engine.support.*;

import org.jspecify.annotations.*;

public class FlatMappedExhaustiveGenerator implements ExhaustiveGenerator {
	private final ExhaustiveGenerator baseGenerator;
	private final long maxCount;
	private final Function> mapper;

	public static  Optional calculateMaxCounts(
		ExhaustiveGenerator baseGenerator,
		Function> mapper,
		long maxNumberOfSamples
	) {
		long choices = 0;
		for (T baseValue : baseGenerator) {
			Optional> exhaustive = mapper.apply(baseValue).exhaustive(maxNumberOfSamples);
			if (!exhaustive.isPresent()) {
				return Optional.empty();
			}
			choices += exhaustive.get().maxCount();
			if (choices > maxNumberOfSamples) {
				return Optional.empty();
			}
		}
		return Optional.of(choices);
	}

	public FlatMappedExhaustiveGenerator(ExhaustiveGenerator baseGenerator, long maxCount, Function> mapper) {
		this.baseGenerator = baseGenerator;
		this.maxCount = maxCount;
		this.mapper = mapper;
	}

	@Override
	public long maxCount() {
		return maxCount;
	}

	@Override
	public Iterator iterator() {
		List> iterators =
			StreamSupport.stream(baseGenerator.spliterator(), false)
				.map(baseValue -> (Iterable) mapper.apply(baseValue).exhaustive().get())
				.collect(Collectors.toList());

		return Combinatorics.concat(iterators);
	}
}