A rust type to store an object with all associated traits
You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
trivernis db608c8eb1
Change register_traits to create_object to not associate wrong v-tables
Signed-off-by: trivernis <trivernis@protonmail.com>
3 years ago
.idea Add MultitraitObject implementation 3 years ago
src Change register_traits to create_object to not associate wrong v-tables 3 years ago
.gitignore Add MultitraitObject implementation 3 years ago
Cargo.toml Change register_traits to create_object to not associate wrong v-tables 3 years ago
LICENSE Create LICENSE 3 years ago
README.md Fixup macro paths and remove prelude mod 3 years ago

README.md

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