rhai/src/any.rs

107 lines
2.2 KiB
Rust
Raw Normal View History

2019-09-30 19:57:21 +02:00
use std::any::{type_name, Any as StdAny, TypeId};
2017-12-20 12:16:14 +01:00
use std::fmt;
pub type Variant = dyn Any;
pub type Dynamic = Box<Variant>;
2017-12-20 12:16:14 +01:00
pub trait Any: StdAny {
fn type_id(&self) -> TypeId;
2019-09-30 19:57:21 +02:00
fn type_name(&self) -> String;
fn into_dynamic(&self) -> Dynamic;
2017-12-20 12:16:14 +01:00
/// This type may only be implemented by `rhai`.
#[doc(hidden)]
fn _closed(&self) -> _Private;
}
impl<T> Any for T
2019-09-18 12:21:07 +02:00
where
T: Clone + StdAny + ?Sized,
2017-12-20 12:16:14 +01:00
{
#[inline]
fn type_id(&self) -> TypeId {
TypeId::of::<T>()
}
2019-09-30 19:57:21 +02:00
fn type_name(&self) -> String {
type_name::<T>().to_string()
}
2017-12-20 12:16:14 +01:00
#[inline]
fn into_dynamic(&self) -> Dynamic {
2017-12-20 12:16:14 +01:00
Box::new(self.clone())
}
2019-09-18 12:21:07 +02:00
fn _closed(&self) -> _Private {
_Private
2017-12-20 12:16:14 +01:00
}
2019-09-18 12:21:07 +02:00
}
2017-12-20 12:16:14 +01:00
impl Variant {
2019-09-18 12:21:07 +02:00
//#[inline]
// fn into_dynamic(&self) -> Box<Variant> {
// Any::into_dynamic(self)
2019-09-18 12:21:07 +02:00
// }
2017-12-20 12:16:14 +01:00
#[inline]
pub fn is<T: Any>(&self) -> bool {
let t = TypeId::of::<T>();
let boxed = <Variant as Any>::type_id(self);
2017-12-20 12:16:14 +01:00
t == boxed
}
#[inline]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
if self.is::<T>() {
unsafe { Some(&*(self as *const Variant as *const T)) }
2017-12-20 12:16:14 +01:00
} else {
None
}
}
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
unsafe { Some(&mut *(self as *mut Variant as *mut T)) }
2017-12-20 12:16:14 +01:00
} else {
None
}
}
}
impl Clone for Dynamic {
2017-12-20 12:16:14 +01:00
fn clone(&self) -> Self {
Any::into_dynamic(self.as_ref())
2017-12-20 12:16:14 +01:00
}
}
impl fmt::Debug for Variant {
2019-09-18 12:21:07 +02:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("?")
2017-12-20 12:16:14 +01:00
}
}
pub trait AnyExt: Sized {
fn downcast<T: Any + Clone>(self) -> Result<Box<T>, Self>;
}
impl AnyExt for Dynamic {
2017-12-20 12:16:14 +01:00
fn downcast<T: Any + Clone>(self) -> Result<Box<T>, Self> {
if self.is::<T>() {
unsafe {
let raw: *mut Variant = Box::into_raw(self);
2017-12-20 12:16:14 +01:00
Ok(Box::from_raw(raw as *mut T))
}
} else {
Err(self)
}
}
}
/// Private type which ensures that `rhai::Any` can only
/// be implemented by this crate.
#[doc(hidden)]
pub struct _Private;