freya_core/lifecycle/
memo.rs

1use std::{
2    mem::MaybeUninit,
3    ops::Deref,
4};
5
6use crate::{
7    prelude::{
8        ReadRef,
9        State,
10        spawn,
11        use_hook,
12    },
13    reactive_context::ReactiveContext,
14};
15
16/// Registers a callback that will run every time a [State] which was [.read()](State::read) inside, changes.
17/// It also returning a type that will get cached after the callback runs, thus allowing this to be used as a way to cache expensive values.
18/// ```rust, no_run
19/// # use freya::prelude::*;
20/// let state = use_state(|| 0);
21///
22/// let expensive_value = use_memo(move || {
23///     // The moment `.read()` is called this side effect callback gets subscribed to it
24///     let value = *state.read();
25///     value * 2
26/// });
27/// ```
28pub fn use_memo<T: 'static + PartialEq>(callback: impl FnMut() -> T + 'static) -> Memo<T> {
29    use_hook(|| Memo::create(callback))
30}
31
32pub struct Memo<T> {
33    state: State<T>,
34}
35
36impl<T> Clone for Memo<T> {
37    fn clone(&self) -> Self {
38        *self
39    }
40}
41impl<T> Copy for Memo<T> {}
42
43/// Allow calling the states as functions.
44/// Limited to `Copy` values only.
45impl<T: Copy + PartialEq + 'static> Deref for Memo<T> {
46    type Target = dyn Fn() -> T;
47
48    fn deref(&self) -> &Self::Target {
49        unsafe { Memo::deref_impl(self) }
50    }
51}
52
53impl<T: PartialEq> Memo<T> {
54    /// Adapted from https://github.com/DioxusLabs/dioxus/blob/a4aef33369894cd6872283d6d7d265303ae63913/packages/signals/src/read.rs#L246
55    /// SAFETY: You must call this function directly with `self` as the argument.
56    /// This function relies on the size of the object you return from the deref
57    /// being the same as the object you pass in
58    #[doc(hidden)]
59    unsafe fn deref_impl<'a>(memo: &Memo<T>) -> &'a dyn Fn() -> T
60    where
61        Self: Sized + 'a,
62        T: Clone + 'static,
63    {
64        // https://github.com/dtolnay/case-studies/tree/master/callable-types
65
66        // First we create a closure that captures something with the Same in memory layout as Self (MaybeUninit<Self>).
67        let uninit_callable = MaybeUninit::<Self>::uninit();
68        // Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
69        let uninit_closure = move || Memo::read(unsafe { &*uninit_callable.as_ptr() }).clone();
70
71        // Check that the size of the closure is the same as the size of Self in case the compiler changed the layout of the closure.
72        let size_of_closure = std::mem::size_of_val(&uninit_closure);
73        assert_eq!(size_of_closure, std::mem::size_of::<Self>());
74
75        // Then cast the lifetime of the closure to the lifetime of &self.
76        fn cast_lifetime<'a, T>(_a: &T, b: &'a T) -> &'a T {
77            b
78        }
79        let reference_to_closure = cast_lifetime(
80            {
81                // The real closure that we will never use.
82                &uninit_closure
83            },
84            #[allow(clippy::missing_transmute_annotations)]
85            // We transmute self into a reference to the closure. This is safe because we know that the closure has the same memory layout as Self so &Closure == &Self.
86            unsafe {
87                std::mem::transmute(memo)
88            },
89        );
90
91        // Cast the closure to a trait object.
92        reference_to_closure as &_
93    }
94}
95
96impl<T: 'static + PartialEq> Memo<T> {
97    pub fn create(mut callback: impl FnMut() -> T + 'static) -> Memo<T> {
98        let (rx, rc) = ReactiveContext::new_for_task();
99        let mut state = State::create(ReactiveContext::run(rc.clone(), &mut callback));
100        spawn(async move {
101            loop {
102                rx.notified().await;
103                state.set_if_modified(ReactiveContext::run(rc.clone(), &mut callback));
104            }
105        });
106        Memo { state }
107    }
108
109    pub fn read(&self) -> ReadRef<'static, T> {
110        self.state.read()
111    }
112
113    pub fn peek(&self) -> ReadRef<'static, T> {
114        self.state.peek()
115    }
116}