1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//! Closure Cacher abstracts memoization on provided closure by storing
//! its data in a hashmap and returning references to its output
use std::collections::HashMap;
use std::cmp::Eq;
use std::hash::Hash;

/// Cacher Struct that allows provision of a closure and 
/// memoizes its output
/// # Examples
/// ```
/// use closure_cacher::Cacher;
/// let mut cacher = Cacher::new(|x| x + 1);
/// assert_eq!(cacher.get(&1), &2);
/// ```
pub struct Cacher<I, O, T>
where 
    T: Fn(I) -> O,
{
    calc: T,
    cache: HashMap<I, O>
}

impl<I: Eq + Hash + Copy, O, T> Cacher<I, O, T> 
where
    T: Fn(I) -> O
{
    /// Creates new Cacher instance
    pub fn new(calc: T) -> Cacher<I, O, T> {
        Cacher {
            calc,
            cache: HashMap::new()
        }
    }

    /// Get reference value by applying the cacher provided closure
    pub fn get(&mut self, n: &I) -> &O {
        self.cache.entry(*n).or_insert((self.calc)(*n))
    }
}

/// RefCacher Struct that allows provision of a closure and 
/// memoizes its output using references for its input values
/// # Examples
/// ```
/// use closure_cacher::RefCacher;
/// let mut ref_cacher = RefCacher::new(|x| x + 1);
/// assert_eq!(ref_cacher.get(&1), &2);
/// ```

// TODO(khalil): Is there a better way to reabstracted both caching structures
//               since they are very similar
pub struct RefCacher<'a, I, O, T>
where
    T: Fn(&'a I) -> O
{
    calc: T,
    cache: HashMap<&'a I, O>
}

impl<'a, I: Eq + Hash, O, T> RefCacher<'a, I, O, T> 
where
    T: Fn(&'a I) -> O
{
    /// Creates new RefCacher instance
    pub fn new(calc: T) -> RefCacher<'a, I, O, T> {
        RefCacher {
            calc,
            cache: HashMap::new()
        }
    }

    /// Get reference to value by applying the cacher provided closure
    pub fn get(&mut self, n: &'a I) -> &O {
        self.cache.entry(n).or_insert((self.calc)(n))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn returns_closure_output_with_input_copy() {
        let mut cacher = Cacher::new(|x| x + 1);
        assert_eq!(cacher.get(&5), &6);
    }

    #[test]
    fn returns_closure_output_with_input_referenced() {
        let mut cacher = Cacher::new(|x| x + 1);
        assert_eq!(cacher.get(&5), &6);
    }
}