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

net.jqwik.engine.properties.shrinking.FlatMappedShrinkable Maven / Gradle / Ivy

There is a newer version: 1.9.1
Show newest version
package net.jqwik.engine.properties.shrinking;

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

import net.jqwik.api.*;

public class FlatMappedShrinkable implements Shrinkable {

	private final Shrinkable toMap;
	private final Function> mapper;
	private final long randomSeed;
	private final Shrinkable shrinkable;
	private final U value;

	public FlatMappedShrinkable(Shrinkable toMap, Function> mapper, int genSize, long randomSeed) {
		this(toMap, value -> mapper.apply(value).generator(genSize), randomSeed);
	}

	public FlatMappedShrinkable(Shrinkable toMap, Function> mapper, long randomSeed) {
		this.toMap = toMap;
		this.mapper = mapper;
		this.randomSeed = randomSeed;
		this.shrinkable = generateShrinkable(toMap.value());
		this.value = shrinkable.value();
	}

	private Shrinkable generateShrinkable(T value) {
		RandomGenerator generator = mapper.apply(value);
		return generator.next(new Random(randomSeed));
	}

	@Override
	public ShrinkingSequence shrink(Falsifier falsifier) {
		Falsifier toMapFalsifier = aT -> falsifier.test(generateShrinkable(aT).value());
		return toMap.shrink(toMapFalsifier) //
					.map(result -> result.map(shrinkableT -> new FlatMappedShrinkable<>(result.shrinkable(), mapper, randomSeed))) //
					.andThen(aShrinkable -> {
						FlatMappedShrinkable flatMappedShrinkable = (FlatMappedShrinkable) aShrinkable;
						return flatMappedShrinkable.shrinkable.shrink(falsifier);
					});
	}

	@Override
	public U value() {
		return value;
	}

	@Override
	public ShrinkingDistance distance() {
		return toMap.distance().append(shrinkable.distance());
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (!(o instanceof FlatMappedShrinkable)) return false;
		FlatMappedShrinkable that = (FlatMappedShrinkable) o;
		return Objects.equals(shrinkable.value(), that.value());
	}

	@Override
	public int hashCode() {
		return Objects.hash(shrinkable.value());
	}

	@Override
	public String toString() {
		return String.format("FlatMapped<%s>(%s)|%s", value().getClass().getSimpleName(), value(), toMap);
	}

}