fury icon indicating copy to clipboard operation
fury copied to clipboard

feat(Rust): Support serialization and deserialization of trait objects

Open theweipeng opened this issue 1 year ago • 0 comments

What does this PR do?

Support serialization and deserialization of trait objects

The relationship between a trait object and a concrete type is generated by a macro and stored in a Fury instance. We can access the serializer and deserializer using the Fury type ID and Rust type ID.

Use as follows

    #[impl_polymorph]
    trait Animal {
        fn get_name(&self) -> String;
    }

    #[derive(Fury, Debug)]
    #[polymorphic_traits("Animal")]
    struct Dog {
        name: String
    }

    impl Animal for Dog {
        fn get_name(&self) -> String {
            self.name.clone()
        }
    }

    #[derive(Fury)]
    struct Person {
        pet: Box<dyn Animal>
    }

    let p = Person {
        pet: Box::new(Dog {
            name: String::from("puppy")
        })
    };
    let mut fury = Fury::default();

    fury.register::<Person>(501);
    fury.register::<Dog>(500);
    let bin = fury.serialize(&p);
    let obj: Person = fury.deserialize(&bin).unwrap();
    assert_eq!(obj.pet.get_name(), "puppy");

We should add impl_polymorph for trait which is use for serializing Box<dyn xxxx> and polymorphic_traits for struct which is use for generate code to cast upcast concete type to trait object. Note that rust not support upcast trait yet(https://github.com/rust-lang/rust/issues/65991).

theweipeng avatar Aug 11 '24 04:08 theweipeng