Skip to main content

rust_css_parser/parser/utils/
cache.rs

1//! Port of `src/parser/utils/cache.ts`.
2//!
3//! `memoize()` caches the results of a function by its arguments, `null` results included. In Rust the memoized
4//! functions own a [`Memo`] (usually in a `thread_local!`) keyed by their arguments.
5
6use std::cell::RefCell;
7use crate::utils::fx::HashMap;
8use std::hash::Hash;
9
10/// memoized results of a function, by arguments
11pub struct Memo<K, V> {
12    values: RefCell<HashMap<K, V>>,
13}
14
15impl<K: Eq + Hash, V: Clone> Default for Memo<K, V> {
16    fn default() -> Self {
17        Self { values: RefCell::new(HashMap::default()) }
18    }
19}
20
21impl<K: Eq + Hash, V: Clone> Memo<K, V> {
22    pub fn new() -> Self {
23        Self::default()
24    }
25
26    /// the cached value of a key, computed once. the computation may use other memoized functions
27    pub fn get_or(&self, key: K, compute: impl FnOnce(&K) -> V) -> V {
28        if let Some(value) = self.values.borrow().get(&key) {
29            return value.clone();
30        }
31        let value = compute(&key);
32        self.values.borrow_mut().insert(key, value.clone());
33        value
34    }
35}