silkenweb_reactive/
memo.rs

1//! Memoize functions across frames.
2//!
3//! Typically a [`MemoCache`] will last the duration of a UI component, whereas
4//! a [`MemoFrame`] will last the duration of a single render.
5use 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/// [`MemoCache`] holds the map of keys to cached values.
17#[derive(Clone, Default)]
18pub struct MemoCache(SharedMemoData);
19
20impl MemoCache {
21    pub fn new() -> Self {
22        Self::default()
23    }
24
25    /// Start a new *frame*. Values will only be cached until the next *frame*.
26    /// If a value is used before [`MemoFrame`] is destroyed, it will be cached
27    /// for the next frame, otherwise it will be removed from the cache.
28    pub fn frame(&self) -> MemoFrame {
29        MemoFrame(self.0.clone())
30    }
31}
32
33/// A [`MemoFrame`] represents the scope of a *frame* for the [`MemoCache`].
34pub struct MemoFrame(SharedMemoData);
35
36impl MemoFrame {
37    /// Lookup a value in the cache.
38    ///
39    /// If a value is not there, it will be generated using `value_fn`. All
40    /// functional dependencies of `value_fn` should be included in `key`.
41    ///
42    /// The value will be cached for the next frame, whether it's new or
43    /// existing.
44    ///
45    /// It is up to the client to use a key that uniquely identifies the
46    /// functional dependencies of variables captured by `value_fn`.
47    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}