silkenweb_reactive/
memo.rs1use std::{
6 any::{Any, TypeId},
7 cell::RefCell,
8 collections::HashMap,
9 hash::Hash,
10 mem,
11 rc::Rc,
12};
13
14type SharedMemoData = Rc<RefCell<MemoData>>;
15
16#[derive(Clone, Default)]
18pub struct MemoCache(SharedMemoData);
19
20impl MemoCache {
21 pub fn new() -> Self {
22 Self::default()
23 }
24
25 pub fn frame(&self) -> MemoFrame {
29 MemoFrame(self.0.clone())
30 }
31}
32
33pub struct MemoFrame(SharedMemoData);
35
36impl MemoFrame {
37 pub fn cache<Key, Value, ValueFn>(&self, key: Key, value_fn: ValueFn) -> Value
48 where
49 Key: 'static + Eq + Hash,
50 Value: 'static + Clone,
51 ValueFn: FnOnce() -> Value,
52 {
53 let mut memo = self.0.borrow_mut();
54
55 let current_memos = Self::memo_map::<Key, Value>(&mut memo.current_memoized);
56 let value = current_memos.remove(&key).unwrap_or_else(value_fn);
57
58 let next_memos = Self::memo_map::<Key, Value>(&mut memo.next_memoized);
59 let previous_value = next_memos.insert(key, value.clone());
60
61 assert!(
62 previous_value.is_none(),
63 "Keys can't be reused within a frame"
64 );
65
66 value
67 }
68
69 fn memo_map<'a, Key: 'static, Value: 'static>(
70 any_map: &'a mut AnyMap,
71 ) -> &'a mut HashMap<Key, Value> {
72 let type_key = (TypeId::of::<Key>(), TypeId::of::<Value>());
73 any_map
74 .entry(type_key)
75 .or_insert_with(|| Box::new(HashMap::<Key, Value>::new()))
76 .downcast_mut()
77 .unwrap()
78 }
79}
80
81impl Drop for MemoFrame {
82 fn drop(&mut self) {
83 let mut memo = self.0.borrow_mut();
84 memo.current_memoized = mem::take(&mut memo.next_memoized);
85 }
86}
87
88type AnyMap = HashMap<(TypeId, TypeId), Box<dyn Any>>;
89
90#[derive(Default)]
91struct MemoData {
92 current_memoized: AnyMap,
93 next_memoized: AnyMap,
94}