net.jqwik.engine.properties.arbitraries.DefaultArrayArbitrary Maven / Gradle / Ivy
package net.jqwik.engine.properties.arbitraries;
import java.lang.reflect.*;
import java.util.*;
import java.util.function.*;
import net.jqwik.api.*;
import net.jqwik.api.arbitraries.*;
import net.jqwik.engine.properties.*;
import net.jqwik.engine.properties.arbitraries.exhaustive.*;
import net.jqwik.engine.properties.shrinking.*;
import org.jspecify.annotations.*;
public class DefaultArrayArbitrary extends MultivalueArbitraryBase implements ArrayArbitrary {
public static ArrayArbitrary forArrayType(Arbitrary elementArbitrary, Class arrayClass) {
if (!arrayClass.isArray()) {
String message = String.format("<%s> is not an array type.", arrayClass);
throw new IllegalArgumentException(message);
}
return new DefaultArrayArbitrary<>(elementArbitrary, arrayClass.getComponentType());
}
public static ArrayArbitrary forComponentType(Arbitrary elementArbitrary, Class> componentType) {
return new DefaultArrayArbitrary<>(elementArbitrary, componentType);
}
private final Class> componentClass;
public DefaultArrayArbitrary(Arbitrary elementArbitrary, Class> componentClass) {
super(elementArbitrary);
this.componentClass = componentClass;
}
@Override
public ArrayArbitrary ofMinSize(int minSize) {
return (ArrayArbitrary) super.ofMinSize(minSize);
}
@Override
public ArrayArbitrary ofMaxSize(int maxSize) {
return (ArrayArbitrary) super.ofMaxSize(maxSize);
}
@Override
public ArrayArbitrary withSizeDistribution(RandomDistribution distribution) {
return (ArrayArbitrary) super.withSizeDistribution(distribution);
}
@Override
public RandomGenerator generator(int genSize) {
return createListGenerator(genSize, false).map(this::toArray);
}
@Override
public RandomGenerator generatorWithEmbeddedEdgeCases(int genSize) {
return createListGenerator(genSize, true).map(this::toArray);
}
@Override
public Optional> exhaustive(long maxNumberOfSamples) {
return ExhaustiveGenerators
.list(elementArbitrary, minSize, maxSize(), uniquenessExtractors, maxNumberOfSamples)
.map(generator -> generator.map(this::toArray));
}
@Override
public EdgeCases edgeCases(int maxEdgeCases) {
return EdgeCasesSupport.map(
edgeCases(
(elements, minSize1) -> new ShrinkableList<>(elements, minSize1, maxSize(), uniquenessExtractors, elementArbitrary),
maxEdgeCases
),
this::toArray
);
}
@SuppressWarnings("unchecked")
private A toArray(List from) {
A array = (A) Array.newInstance(componentClass, from.size());
for (int i = 0; i < from.size(); i++) {
Array.set(array, i, from.get(i));
}
return array;
}
@SuppressWarnings("unchecked")
@Override
protected Iterable toIterable(A array) {
return () -> Arrays.stream((T[]) array).iterator();
}
@Override
public ArrayArbitrary uniqueElements() {
return (ArrayArbitrary) super.uniqueElements();
}
@Override
public ArrayArbitrary uniqueElements(Function super T, ?> by) {
FeatureExtractor featureExtractor = by::apply;
return (ArrayArbitrary) super.uniqueElements(featureExtractor);
}
}