use std::{any::Any, fmt, hash, marker::PhantomData};
use crate::MiraExtern;
use super::{ArenaKey, MiraArray, MiraFunction, MiraModule, MiraRecord, MiraValue};
pub struct MiraHandle<T: Any + ?Sized> {
pub(super) key: ArenaKey,
marker: PhantomData<&'static T>,
}
impl<T: Any + ?Sized> Copy for MiraHandle<T> {}
impl<T: Any + ?Sized> Clone for MiraHandle<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T: Any + ?Sized> fmt::Debug for MiraHandle<T> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("MiraHandle")
.field("arena", &self.key.arena_id().get())
.field("slot", &self.key.index())
.finish()
}
}
impl<T: Any + ?Sized> PartialEq for MiraHandle<T> {
fn eq(&self, other: &Self) -> bool {
self.key == other.key
}
}
impl<T: Any + ?Sized> Eq for MiraHandle<T> {}
impl<T: Any + ?Sized> hash::Hash for MiraHandle<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.key.hash(state);
}
}
impl<T: Any + ?Sized> MiraHandle<T> {
pub(super) const fn new(key: ArenaKey) -> Self {
Self {
key,
marker: PhantomData,
}
}
pub(crate) const fn payload(self) -> [u8; 6] {
self.key.payload()
}
pub(crate) const fn from_payload(payload: [u8; 6]) -> Self {
Self::new(ArenaKey::from_payload(payload))
}
}
macro_rules! impl_cast {
($t:ty, $f:ident) => {
impl From<MiraHandle<$t>> for MiraValue {
fn from(value: MiraHandle<$t>) -> Self {
Self::$f(value)
}
}
};
}
impl_cast!(dyn MiraArray, array);
impl_cast!(dyn MiraRecord, record);
impl_cast!(dyn MiraFunction, function);
impl_cast!(dyn MiraModule, module);
impl_cast!(String, string);
macro_rules! impl_handle_cast {
($trait:path, $erase:ident) => {
impl<T: $trait + ?Sized> MiraHandle<T> {
pub const fn $erase(self) -> MiraHandle<dyn $trait> {
MiraHandle::new(self.key)
}
}
impl MiraHandle<dyn $trait> {
#[doc(hidden)]
pub unsafe fn upcast<T: $trait + ?Sized>(self) -> MiraHandle<T> {
MiraHandle::new(self.key)
}
}
};
}
impl_handle_cast!(MiraArray, erase_array);
impl_handle_cast!(MiraRecord, erase_record);
impl_handle_cast!(MiraFunction, erase_function);
impl_handle_cast!(MiraModule, erase_module);
pub type MiraStringHandle = MiraHandle<String>;
pub type MiraArrayHandle = MiraHandle<dyn MiraArray>;
pub type MiraRecordHandle = MiraHandle<dyn MiraRecord>;
pub type MiraFunctionHandle = MiraHandle<dyn MiraFunction>;
pub type MiraModuleHandle = MiraHandle<dyn MiraModule>;
pub type MiraExternHandle = MiraHandle<dyn MiraExtern>;
#[cfg(test)]
mod tests {
use super::*;
use crate::value::arena::ArenaId;
impl<T: Any + ?Sized> MiraHandle<T> {
pub(crate) fn empty() -> Self {
Self {
key: ArenaKey::new(ArenaId::from(1), 1, "test").unwrap(),
marker: PhantomData,
}
}
}
#[test]
fn test_fmt() {
let handle =
MiraHandle::<dyn MiraArray>::new(ArenaKey::new(ArenaId::from(1), 2, "array").unwrap());
let expected = "MiraHandle { arena: 1, slot: 2 }";
assert_eq!(format!("{handle:?}"), expected);
}
}