Expand description

Multitrait Object

This crate provides a pointer type that allows casting into all registered traits for a given type. This is done by storing the pointer to the v-table for each trait implementation on the type as well as the pointer to the data.

Safety

All unsafe parts are perfectly safe as far as my understanding goes. As this crate is still in an early stage there might be some side effects that haven’t been noticed yet.

Usage

use multi_trait_object::*;
use std::fmt::Debug;

#[derive(Debug)]
struct MyStruct {
     a: u64,
}

trait MyTrait {}
trait MyOtherTrait {}

impl MyTrait for MyStruct{}
impl MyOtherTrait for MyStruct {}

impl_trait_object!(MyStruct, dyn MyTrait, dyn MyOtherTrait, dyn Debug);

fn main() {
    let obj = MyStruct {
        a: 5
    };

    let mto = obj.into_multitrait();

    {
        let debug = mto.downcast_trait::<dyn Debug>().unwrap();
        println!("{:?}", debug);
        let my_trait = mto.downcast_trait::<dyn MyTrait>().unwrap();
    }
    
    let trait_box: Box<dyn MyTrait> = mto.downcast_trait_boxed::<dyn MyTrait>().unwrap();    
}

License

Apache-2.0

Macros

Registers multiple trait_impl on a multitrait object

Implements the IntoMultitrait trait on the defined type.

Structs

A container to store data with the associated type and trait objects allowing for casting down to trait_impl or the concrete type

Traits

Compares the given value with an Any trait object. Register this trait if you want to compare two Multitrait objects with the TryPartialEq trait.

Returns a raw pointer to the cloned data. This will leak the memory of the underlying pointer. This trait is implemented for all types that implement clone so you can pass this trait to the object constructor. This way the given object can be cloned with TryClone.

Tries to compare the MultitraitObject with another object and returns Some(bool) when the underlying type implements PartialEq and has the PartialEqAny trait registered on the object.