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
93
94
use std::{
any::{Any, TypeId},
cell::RefCell,
collections::HashMap,
hash::Hash,
mem,
rc::Rc,
};
type SharedMemoData = Rc<RefCell<MemoData>>;
#[derive(Clone, Default)]
pub struct MemoCache(SharedMemoData);
impl MemoCache {
pub fn new() -> Self {
Self::default()
}
pub fn frame(&self) -> MemoFrame {
MemoFrame(self.0.clone())
}
}
pub struct MemoFrame(SharedMemoData);
impl MemoFrame {
pub fn cache<Key, Value, ValueFn>(&self, key: Key, value_fn: ValueFn) -> Value
where
Key: 'static + Eq + Hash,
Value: 'static + Clone,
ValueFn: FnOnce() -> Value,
{
let mut memo = self.0.borrow_mut();
let current_memos = Self::memo_map::<Key, Value>(&mut memo.current_memoized);
let value = current_memos.remove(&key).unwrap_or_else(value_fn);
let next_memos = Self::memo_map::<Key, Value>(&mut memo.next_memoized);
let previous_value = next_memos.insert(key, value.clone());
assert!(
previous_value.is_none(),
"Keys can't be reused within a frame"
);
value
}
fn memo_map<'a, Key: 'static, Value: 'static>(
any_map: &'a mut AnyMap,
) -> &'a mut HashMap<Key, Value> {
let type_key = (TypeId::of::<Key>(), TypeId::of::<Value>());
any_map
.entry(type_key)
.or_insert_with(|| Box::new(HashMap::<Key, Value>::new()))
.downcast_mut()
.unwrap()
}
}
impl Drop for MemoFrame {
fn drop(&mut self) {
let mut memo = self.0.borrow_mut();
memo.current_memoized = mem::take(&mut memo.next_memoized);
}
}
type AnyMap = HashMap<(TypeId, TypeId), Box<dyn Any>>;
#[derive(Default)]
struct MemoData {
current_memoized: AnyMap,
next_memoized: AnyMap,
}