planetiler/planetiler-core/src/main/java/com/onthegomap/planetiler/util/CacheByZoom.java

43 wiersze
1.3 KiB
Java
Czysty Zwykły widok Historia

package com.onthegomap.planetiler.util;
2021-05-19 10:44:28 +00:00
import com.onthegomap.planetiler.config.PlanetilerConfig;
2021-05-19 10:44:28 +00:00
import java.util.function.IntFunction;
2021-09-10 00:46:20 +00:00
/**
* Caches a value that changes by integer zoom level to avoid recomputing it.
*
* @param <T> return type of the function
*/
2021-05-19 10:44:28 +00:00
public class CacheByZoom<T> {
private final int minzoom;
private final Object[] values;
private final IntFunction<T> supplier;
private CacheByZoom(int minzoom, int maxzoom, IntFunction<T> supplier) {
this.minzoom = minzoom;
values = new Object[maxzoom + 1 - minzoom];
this.supplier = supplier;
}
2021-09-10 00:46:20 +00:00
/**
* Returns a cache for {@code supplier} that can handle a min/max zoom range specified in {@code config}.
*
* @param supplier function that will be called with each zoom-level to get the value
* @param <T> return type of the function
* @return a cache for {@code supplier} by zom
*/
2022-09-23 10:49:09 +00:00
public static <T> CacheByZoom<T> create(IntFunction<T> supplier) {
return new CacheByZoom<>(0, PlanetilerConfig.MAX_MAXZOOM, supplier);
2021-05-19 10:44:28 +00:00
}
public T get(int zoom) {
@SuppressWarnings("unchecked") T[] casted = (T[]) values;
int off = zoom - minzoom;
if (values[off] != null) {
return casted[off];
}
return casted[off] = supplier.apply(zoom);
}
}