use std::collections::BTreeMap;
use core::cmp::Ord;
use core::ops::Index;
use std::sync::Arc;
use crate::{FnCache, FnCacheMany};
pub struct BTreeCache<'f, I, O>
where
I: Ord,
{
pub(crate) cache: BTreeMap<I, O>,
f: Arc<dyn Fn(&mut Self, &I) -> O + 'f + Send + Sync>,
}
impl<'f, I, O> FnCache<I, O> for BTreeCache<'f, I, O>
where
I: Ord,
{
fn get(&mut self, input: I) -> &O {
if self.cache.contains_key(&input) {
self.cache.index(&input)
} else {
let output = self.compute(&input);
self.cache.entry(input).or_insert(output)
}
}
}
impl<'f, I, O> FnCacheMany<I, O> for BTreeCache<'f, I, O>
where
I: Ord + Clone,
{
fn get_many<const N: usize>(&mut self, inputs: [I; N]) -> [&O; N] {
for i in &inputs {
self.get(i.clone());
}
inputs.map(|i| self.cache.get(&i).unwrap())
}
}
impl<'f, I, O> BTreeCache<'f, I, O>
where
I: Ord,
{
pub fn new<F>(f: F) -> Self
where
F: Fn(&I) -> O + 'f + Send + Sync,
{
Self::recursive(move |_, x| f(x))
}
pub fn recursive<F>(f: F) -> Self
where
F: Fn(&mut Self, &I) -> O + 'f + Send + Sync,
{
Self {
cache: BTreeMap::default(),
f: Arc::new(f),
}
}
fn compute(&mut self, input: &I) -> O {
(self.f.clone())(self, input)
}
pub fn clear(&mut self) {
self.cache.clear();
}
pub fn len(&self) -> usize {
self.cache.len()
}
pub fn remove(&mut self, input: &I) -> Option<O> {
self.cache.remove(input)
}
}