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

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

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

import java.math.*;
import java.util.*;
import java.util.stream.*;

import net.jqwik.engine.properties.arbitraries.*;

public class BigDecimalShrinkingCandidates implements ShrinkingCandidates {
	private final Range range;
	private final BigIntegerShrinkingCandidates integralShrinkCandidates;

	public BigDecimalShrinkingCandidates(Range range, BigDecimal target) {
		this.range = range;
		this.integralShrinkCandidates = new BigIntegerShrinkingCandidates(target.toBigInteger());
	}

	@Override
	public Set candidatesFor(BigDecimal value) {
		Set candidates = new HashSet<>();
		if (hasDecimals(value))
			candidates.addAll(shrinkDecimals(value));
		candidates.addAll(shrinkIntegral(value));
		return candidates;
	}

	private Set shrinkDecimals(BigDecimal value) {
		Set shrunkDecimals = new HashSet<>();
		range.ifIncluded(roundOneDigitDown(value), shrunkDecimals::add);
		range.ifIncluded(roundOneDigitUp(value), shrunkDecimals::add);
		return shrunkDecimals;
	}

	private BigDecimal roundOneDigitUp(BigDecimal value) {
		return value.setScale(value.scale() -1, BigDecimal.ROUND_UP);
	}

	private BigDecimal roundOneDigitDown(BigDecimal value) {
		return value.setScale(value.scale() -1, BigDecimal.ROUND_DOWN);
	}

	private Set shrinkIntegral(BigDecimal value) {
		return integralShrinkCandidates.candidatesFor(value.toBigInteger()) //
									   .stream() //
									   .map(BigDecimal::new) //
									   .filter(range::includes) //
									   .collect(Collectors.toSet());
	}

	private boolean hasDecimals(BigDecimal value) {
		if (value.scale() <= 0)
			return false;
		return value.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) != 0;
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy