makepad_stitch/
func_ref.rs

1use crate::{
2    func::{Func, UnguardedFunc},
3    store::{Handle, StoreId},
4};
5
6/// A nullable reference to a [`Func`].
7#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
8pub struct FuncRef(pub(crate) Option<Func>);
9
10impl FuncRef {
11    /// Creates a new [`FuncRef`].
12    pub fn new(func: impl Into<Option<Func>>) -> Self {
13        Self(func.into())
14    }
15
16    /// Creates a null [`FuncRef`].
17    pub fn null() -> Self {
18        Self(None)
19    }
20
21    /// Returns `true` if this [`FuncRef`] is null.
22    pub fn is_null(self) -> bool {
23        self.0.is_none()
24    }
25
26    /// Returns the underlying [`Func`] if this [`FuncRef`] is not null.
27    pub fn get(self) -> Option<Func> {
28        self.0
29    }
30
31    /// Converts the given [`UnguardedFuncRef`] to a [`FuncRef`].
32    ///
33    /// # Safety
34    ///
35    /// The [[`UnguardedFuncRef`] must be owned by the [`Store`] with the given [`StoreId`].
36    pub(crate) unsafe fn from_unguarded(func: UnguardedFuncRef, store_id: StoreId) -> Self {
37        Self(func.map(|func| unsafe { Func(Handle::from_unguarded(func, store_id)) }))
38    }
39
40    /// Converts this [`FuncRef`] to an [`UnguardedFuncRef`].
41    ///
42    /// # Panics
43    ///
44    /// This [`FuncRef`] is not owned by the [`Store`] with the given [`StoreId`].
45    pub(crate) fn to_unguarded(self, store_id: StoreId) -> UnguardedFuncRef {
46        self.0.map(|func| func.0.to_unguarded(store_id))
47    }
48}
49
50impl From<Func> for FuncRef {
51    fn from(func: Func) -> Self {
52        Self::new(func)
53    }
54}
55
56/// An unguarded [`FuncRef`].
57pub(crate) type UnguardedFuncRef = Option<UnguardedFunc>;