fn_memo/sync/
chashmap.rs

1use chashmap::CHashMap;
2use once_cell::sync::OnceCell;
3use recur_fn::RecurFn;
4use std::cell::UnsafeCell;
5use std::hash::Hash;
6use std::mem::MaybeUninit;
7use std::sync::Arc;
8
9/// Use `CHashMap` as `Cache`.
10impl<Arg, Output> super::Cache for CHashMap<Arg, Arc<OnceCell<Output>>>
11where
12    Arg: Eq + Hash,
13{
14    type Arg = Arg;
15    type Output = Output;
16
17    fn new() -> Self {
18        CHashMap::new()
19    }
20
21    fn get(&self, arg: &Self::Arg) -> Option<Arc<OnceCell<Self::Output>>> {
22        self.get(arg).map(|arc| Arc::clone(&arc))
23    }
24
25    fn get_or_new(&self, arg: Self::Arg) -> Arc<OnceCell<Self::Output>> {
26        // `cell` stores a clone of the `Arc` in cache.
27        // `UnsafeCell<MaybeUninit<_>>` is used here because I assume
28        // the `upsert` call below will execute exactly one of its
29        // `insert` or `update` parameter, which means, `cell` will be written, and only
30        // be written once. So it's safe.
31        let cell: UnsafeCell<MaybeUninit<Arc<OnceCell<Output>>>> =
32            UnsafeCell::new(MaybeUninit::uninit());
33
34        self.upsert(
35            arg,
36            || {
37                let arc = Arc::new(OnceCell::new());
38                unsafe { (*cell.get()).as_mut_ptr().write(Arc::clone(&arc)) };
39                arc
40            },
41            |arc| {
42                unsafe { (*cell.get()).as_mut_ptr().write(Arc::clone(arc)) };
43            },
44        );
45
46        unsafe { cell.into_inner().assume_init() }
47    }
48
49    fn clear(&self) {
50        self.clear();
51    }
52}
53
54/// Creates a synchronized memoization of `f` using `CHashMap` as cache.
55pub fn memoize<Arg, Output, F>(f: F) -> impl crate::FnMemo<Arg, Output>
56where
57    Arg: Clone + Eq + Hash,
58    Output: Clone,
59    F: RecurFn<Arg, Output>,
60{
61    super::Memo::<chashmap::CHashMap<_, _>, _>::new(f)
62}