Simplify API by introducing the Dynamic and Array type aliases.
This commit is contained in:
29
src/any.rs
29
src/any.rs
@@ -1,12 +1,15 @@
|
||||
use std::any::{type_name, Any as StdAny, TypeId};
|
||||
use std::fmt;
|
||||
|
||||
pub type Variant = dyn Any;
|
||||
pub type Dynamic = Box<Variant>;
|
||||
|
||||
pub trait Any: StdAny {
|
||||
fn type_id(&self) -> TypeId;
|
||||
|
||||
fn type_name(&self) -> String;
|
||||
|
||||
fn box_clone(&self) -> Box<dyn Any>;
|
||||
fn into_dynamic(&self) -> Dynamic;
|
||||
|
||||
/// This type may only be implemented by `rhai`.
|
||||
#[doc(hidden)]
|
||||
@@ -27,7 +30,7 @@ where
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn box_clone(&self) -> Box<dyn Any> {
|
||||
fn into_dynamic(&self) -> Dynamic {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
|
||||
@@ -36,15 +39,15 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl dyn Any {
|
||||
impl Variant {
|
||||
//#[inline]
|
||||
// fn box_clone(&self) -> Box<dyn Any> {
|
||||
// Any::box_clone(self)
|
||||
// fn into_dynamic(&self) -> Box<Variant> {
|
||||
// Any::into_dynamic(self)
|
||||
// }
|
||||
#[inline]
|
||||
pub fn is<T: Any>(&self) -> bool {
|
||||
let t = TypeId::of::<T>();
|
||||
let boxed = <dyn Any as Any>::type_id(self);
|
||||
let boxed = <Variant as Any>::type_id(self);
|
||||
|
||||
t == boxed
|
||||
}
|
||||
@@ -52,7 +55,7 @@ impl dyn Any {
|
||||
#[inline]
|
||||
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
|
||||
if self.is::<T>() {
|
||||
unsafe { Some(&*(self as *const dyn Any as *const T)) }
|
||||
unsafe { Some(&*(self as *const Variant as *const T)) }
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -61,20 +64,20 @@ impl dyn Any {
|
||||
#[inline]
|
||||
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
|
||||
if self.is::<T>() {
|
||||
unsafe { Some(&mut *(self as *mut dyn Any as *mut T)) }
|
||||
unsafe { Some(&mut *(self as *mut Variant as *mut T)) }
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for Box<dyn Any> {
|
||||
impl Clone for Dynamic {
|
||||
fn clone(&self) -> Self {
|
||||
Any::box_clone(self.as_ref() as &dyn Any)
|
||||
Any::into_dynamic(self.as_ref() as &Variant)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for dyn Any {
|
||||
impl fmt::Debug for Variant {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.pad("?")
|
||||
}
|
||||
@@ -84,11 +87,11 @@ pub trait AnyExt: Sized {
|
||||
fn downcast<T: Any + Clone>(self) -> Result<Box<T>, Self>;
|
||||
}
|
||||
|
||||
impl AnyExt for Box<dyn Any> {
|
||||
impl AnyExt for Dynamic {
|
||||
fn downcast<T: Any + Clone>(self) -> Result<Box<T>, Self> {
|
||||
if self.is::<T>() {
|
||||
unsafe {
|
||||
let raw: *mut dyn Any = Box::into_raw(self);
|
||||
let raw: *mut Variant = Box::into_raw(self);
|
||||
Ok(Box::from_raw(raw as *mut T))
|
||||
}
|
||||
} else {
|
||||
|
Reference in New Issue
Block a user