Skip to main content

mirascript_vm/value/arena/
handle.rs

1use std::{any::Any, fmt, hash, marker::PhantomData};
2
3use super::{ArenaKey, MiraArray, MiraFunction, MiraModule, MiraRecord, MiraValue};
4
5/// A compact, runtime-checked handle to an arena-managed value.
6pub struct MiraHandle<T: Any + ?Sized> {
7    pub(super) key: ArenaKey,
8    marker: PhantomData<&'static T>,
9}
10
11impl<T: Any + ?Sized> Copy for MiraHandle<T> {}
12
13impl<T: Any + ?Sized> Clone for MiraHandle<T> {
14    fn clone(&self) -> Self {
15        *self
16    }
17}
18
19impl<T: Any + ?Sized> fmt::Debug for MiraHandle<T> {
20    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
21        formatter
22            .debug_struct("MiraHandle")
23            .field("arena", &self.key.arena_id().get())
24            .field("slot", &self.key.index())
25            .finish()
26    }
27}
28
29impl<T: Any + ?Sized> PartialEq for MiraHandle<T> {
30    fn eq(&self, other: &Self) -> bool {
31        self.key == other.key
32    }
33}
34
35impl<T: Any + ?Sized> Eq for MiraHandle<T> {}
36
37impl<T: Any + ?Sized> hash::Hash for MiraHandle<T> {
38    fn hash<H: hash::Hasher>(&self, state: &mut H) {
39        self.key.hash(state);
40    }
41}
42
43impl<T: Any + ?Sized> MiraHandle<T> {
44    pub(super) const fn new(key: ArenaKey) -> Self {
45        Self {
46            key,
47            marker: PhantomData,
48        }
49    }
50
51    pub(crate) const fn payload(self) -> [u8; 6] {
52        self.key.payload()
53    }
54
55    pub(crate) const fn from_payload(payload: [u8; 6]) -> Self {
56        Self::new(ArenaKey::from_payload(payload))
57    }
58}
59
60macro_rules! impl_cast {
61    ($t:ty, $f:ident) => {
62        impl From<MiraHandle<$t>> for MiraValue {
63            fn from(value: MiraHandle<$t>) -> Self {
64                Self::$f(value)
65            }
66        }
67    };
68}
69
70impl_cast!(dyn MiraArray, array);
71impl_cast!(dyn MiraRecord, record);
72impl_cast!(dyn MiraFunction, function);
73impl_cast!(dyn MiraModule, module);
74impl_cast!(String, string);
75
76macro_rules! impl_handle_cast {
77    ($trait:path, $erase:ident) => {
78        impl<T: $trait + ?Sized> MiraHandle<T> {
79            /// Erase the concrete Rust type while preserving its MiraScript category.
80            pub const fn $erase(self) -> MiraHandle<dyn $trait> {
81                MiraHandle::new(self.key)
82            }
83        }
84
85        impl MiraHandle<dyn $trait> {
86            /// Reinterpret an erased handle as a concrete typed handle.
87            ///
88            /// The subsequent Runtime lookup still validates the concrete type,
89            /// so a wrong generated cast returns an error rather than dereferencing
90            /// an invalid pointer.
91            #[doc(hidden)]
92            pub unsafe fn upcast<T: $trait>(self) -> MiraHandle<T> {
93                MiraHandle::new(self.key)
94            }
95        }
96    };
97}
98
99impl_handle_cast!(MiraArray, erase_array);
100impl_handle_cast!(MiraRecord, erase_record);
101impl_handle_cast!(MiraFunction, erase_function);
102impl_handle_cast!(MiraModule, erase_module);
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107    use crate::value::arena::ArenaId;
108
109    impl<T: Any + ?Sized> MiraHandle<T> {
110        pub(crate) fn empty() -> Self {
111            Self {
112                key: ArenaKey::new(ArenaId::from(1), 1, "test").unwrap(),
113                marker: PhantomData,
114            }
115        }
116    }
117
118    #[test]
119    fn test_fmt() {
120        let handle =
121            MiraHandle::<dyn MiraArray>::new(ArenaKey::new(ArenaId::from(1), 2, "array").unwrap());
122        let expected = "MiraHandle { arena: 1, slot: 2 }";
123        assert_eq!(format!("{handle:?}"), expected);
124    }
125}