use crate::FnMemo;
use recur_fn::RecurFn;
use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::hash::Hash;
pub trait Cache {
type Arg;
type Output;
fn new() -> Self;
fn get(&self, arg: &Self::Arg) -> Option<&Self::Output>;
fn cache(&mut self, arg: Self::Arg, result: Self::Output);
fn clear(&mut self);
}
impl<Arg: Clone + Eq + Hash, Output: Clone> Cache for HashMap<Arg, Output> {
type Arg = Arg;
type Output = Output;
fn new() -> Self {
HashMap::new()
}
fn get(&self, arg: &Arg) -> Option<&Output> {
HashMap::get(self, arg);
self.get(arg)
}
fn cache(&mut self, arg: Arg, result: Output) {
self.insert(arg, result);
}
fn clear(&mut self) {
self.clear();
}
}
impl<Output: Clone> Cache for Vec<Option<Output>> {
type Arg = usize;
type Output = Output;
fn new() -> Self {
Vec::new()
}
fn get(&self, arg: &usize) -> Option<&Output> {
self.as_slice().get(*arg)?.as_ref()
}
fn cache(&mut self, arg: usize, result: Output) {
if arg >= self.len() {
self.resize(arg + 1, None);
}
self[arg] = Some(result);
}
fn clear(&mut self) {
self.clear();
}
}
pub struct Memo<C, F> {
cache: UnsafeCell<C>,
f: F,
}
impl<C: Cache, F: RecurFn<C::Arg, C::Output>> Memo<C, F>
where
C::Arg: Clone,
C::Output: Clone,
{
pub fn new(f: F) -> Memo<C, F> {
Memo {
cache: UnsafeCell::new(C::new()),
f,
}
}
}
impl<C: Cache, F: RecurFn<C::Arg, C::Output>> FnMemo<C::Arg, C::Output> for Memo<C, F>
where
C::Arg: Clone,
C::Output: Clone,
{
fn call(&self, arg: C::Arg) -> C::Output {
if let Some(result) = unsafe { &*self.cache.get() }.get(&arg) {
return result.clone();
}
let result = self.f.body(|arg| self.call(arg), arg.clone());
unsafe { &mut *self.cache.get() }.cache(arg, result.clone());
result
}
fn clear_cache(&self) {
unsafe { &mut *self.cache.get() }.clear()
}
}
pub fn memoize<Arg, Output, F>(f: F) -> impl FnMemo<Arg, Output>
where
Arg: Clone + Eq + Hash,
Output: Clone,
F: RecurFn<Arg, Output>,
{
Memo::<std::collections::HashMap<_, _>, _>::new(f)
}
pub fn memoize_seq<Output, F>(f: F) -> impl FnMemo<usize, Output>
where
Output: Clone,
F: RecurFn<usize, Output>,
{
Memo::<Vec<_>, _>::new(f)
}