AnyTrait

Trait AnyTrait 

Source
pub trait AnyTrait: 'static {
    // Required methods
    fn type_ids(&self) -> &'static [TypeIdConst];
    unsafe fn cast_to(&self, trait_num: usize) -> usize;
    unsafe fn cast_to_mut(&mut self, trait_num: usize) -> usize;
}
Expand description

§AnyTrait

Don’t implement manually

use #[derive(AnySubTrait)]


Imagine a Concrete type and all its subtraits
AnyTrait lets you walk up and down the traits safely

With ::core::any::Any you can only cast between the concrete type and Any.
With AnyTrait you can do that, plus any other trait in the middle

AnyTrait is not necessarily fast as it needs check and track the list of traits you are allowed to cast to.

Required Methods§

Source

fn type_ids(&self) -> &'static [TypeIdConst]

returns a list of all possible traits that you can up/downcast to
This list always has at least two elements:

  • id 0: TypeIdConst::of::<dyn AnyType>
  • id 1: TypeIdConst::of::<YourConcreteType>

Only the rest of the list (aka: from index 2) is ordered, so we can run a binary search there if there are many types.

Source

unsafe fn cast_to(&self, trait_num: usize) -> usize

very unsafe. don’t use. internal only. Horror here. go away.

cast self to a trait in the .type_ids() list.
the pointer to the ref to the type in the list is then converted to usize.

panics if list length is exceeded.

Source

unsafe fn cast_to_mut(&mut self, trait_num: usize) -> usize

very unsafe. don’t use. internal only. Horror here. go away.

cast self to a trait in the .type_ids() list.
the pointer to the ref to the type in the list is then converted to usize.

panics if list length is exceeded.

Implementations§

Source§

impl dyn AnyTrait

Source

pub fn trait_idx<T: ?Sized + 'static>(&self) -> Option<usize>

Search the list of possible traits.

If self can be cast to the generic parameter, return the index of the type in the list

Source

pub fn downcast_ref<T: ?Sized + 'static>(&self) -> Option<&T>

Safe cast to reference to a generic type.

Only return Some(…) if it is safe to do so.

Source

pub fn downcast_mut<T: ?Sized + 'static>(&mut self) -> Option<&mut T>

Safe cast to mutable reference to a generic type.

Only return Some(…) if it is safe to do so.

Implementors§