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
use std::collections::HashMap;
use std::cmp::Eq;
use std::hash::Hash;
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
{
pub fn new(calc: T) -> Cacher<I, O, T> {
Cacher {
calc,
cache: HashMap::new()
}
}
pub fn get(&mut self, n: &I) -> &O {
self.cache.entry(*n).or_insert((self.calc)(*n))
}
}
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
{
pub fn new(calc: T) -> RefCacher<'a, I, O, T> {
RefCacher {
calc,
cache: HashMap::new()
}
}
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);
}
}