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

net.jqwik.engine.facades.Memoize Maven / Gradle / Ivy

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

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

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

class Memoize {

	private static Store, Integer, Boolean>, RandomGenerator>> generatorStore() {
		return Store.getOrCreate(Memoize.class, Lifespan.PROPERTY, () -> new LruCache<>(500));
	}

	@SuppressWarnings("unchecked")
	static  RandomGenerator memoizedGenerator(
			Arbitrary arbitrary,
			int genSize,
			boolean withEdgeCases,
			Supplier> generatorSupplier
	) {
		Tuple3, Integer, Boolean> key = Tuple.of(arbitrary, genSize, withEdgeCases);

		RandomGenerator generator = computeIfAbsent(
				generatorStore().get(),
				key,
				ignore -> generatorSupplier.get()
		);
		return (RandomGenerator) generator;
	}

	// Had to roll my on computeIfAbsent because HashMap.computeIfAbsent()
	// does not allow modifications of the map within the mapping function
	private static  V computeIfAbsent(
			Map cache,
			K key,
			Function mappingFunction
	) {
		V result = cache.get(key);

		if (result == null) {
			result = mappingFunction.apply(key);
			cache.put(key, result);
		}

		return result;
	}

}