-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request 'Non-static type support for
component
crate' (#…
…45) from non-static-component into main Reviewed-on: https://codeberg.org/DM-Earth/rimecraft/pulls/45 Reviewed-by: C191239 <[email protected]>
- Loading branch information
Showing
5 changed files
with
242 additions
and
153 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
use std::any::TypeId; | ||
|
||
pub trait Any { | ||
#[inline(always)] | ||
fn type_id(&self) -> TypeId { | ||
typeid::of::<Self>() | ||
} | ||
} | ||
|
||
impl<T: ?Sized> Any for T {} | ||
|
||
impl dyn Any + Send + Sync + '_ { | ||
pub unsafe fn downcast_ref<T>(&self) -> Option<&T> { | ||
if (*self).type_id() == typeid::of::<T>() { | ||
unsafe { Some(&*(self as *const dyn Any as *const T)) } | ||
} else { | ||
None | ||
} | ||
} | ||
|
||
pub unsafe fn downcast_mut<T>(&mut self) -> Option<&mut T> { | ||
if (*self).type_id() == typeid::of::<T>() { | ||
unsafe { Some(&mut *(self as *mut dyn Any as *mut T)) } | ||
} else { | ||
None | ||
} | ||
} | ||
} | ||
|
||
pub unsafe fn downcast<'a, T>( | ||
any: Box<dyn Any + Send + Sync + 'a>, | ||
) -> Result<Box<T>, Box<dyn Any + Send + Sync + 'a>> { | ||
if (*any).type_id() == typeid::of::<T>() { | ||
unsafe { Ok(Box::from_raw(Box::into_raw(any) as *mut T)) } | ||
} else { | ||
Err(any) | ||
} | ||
} |
Oops, something went wrong.