use crate::noise_fns::NoiseFn;
use std::cell::{Cell, RefCell};
#[derive(Clone, Debug)]
pub struct Cache<Source> {
pub source: Source,
value: Cell<Option<f64>>,
point: RefCell<Vec<f64>>,
}
impl<Source> Cache<Source> {
pub fn new(source: Source) -> Self {
Cache {
source,
value: Cell::new(None),
point: RefCell::new(Vec::new()),
}
}
}
impl<Source> NoiseFn<[f64; 2]> for Cache<Source>
where
Source: NoiseFn<[f64; 2]>,
{
fn get(&self, point: [f64; 2]) -> f64 {
match self.value.get() {
Some(value) if quick_eq(&*self.point.borrow(), &point) => value,
Some(_) | None => {
let value = self.source.get(point);
self.value.set(Some(value));
let mut cached_point = self.point.borrow_mut();
cached_point.clear();
cached_point.extend_from_slice(&point);
value
}
}
}
}
impl<Source> NoiseFn<[f64; 3]> for Cache<Source>
where
Source: NoiseFn<[f64; 3]>,
{
fn get(&self, point: [f64; 3]) -> f64 {
match self.value.get() {
Some(value) if quick_eq(&*self.point.borrow(), &point) => value,
Some(_) | None => {
let value = self.source.get(point);
self.value.set(Some(value));
let mut cached_point = self.point.borrow_mut();
cached_point.clear();
cached_point.extend_from_slice(&point);
value
}
}
}
}
impl<Source> NoiseFn<[f64; 4]> for Cache<Source>
where
Source: NoiseFn<[f64; 4]>,
{
fn get(&self, point: [f64; 4]) -> f64 {
match self.value.get() {
Some(value) if quick_eq(&*self.point.borrow(), &point) => value,
Some(_) | None => {
let value = self.source.get(point);
self.value.set(Some(value));
let mut cached_point = self.point.borrow_mut();
cached_point.clear();
cached_point.extend_from_slice(&point);
value
}
}
}
}
fn quick_eq(a: &[f64], b: &[f64]) -> bool {
assert_eq!(a.len(), b.len());
a.iter().eq(b)
}