Trait object serialization for rkyv.


API Documentation

Book

Sister Crates:


rkyv_dyn in action

```rust use rkyv::{ Aligned, Archive, ArchiveBuffer, Archived, archivedvalue, Write, }; use rkyvdyn::archivedyn; use rkyvtypename::TypeName;

[archive_dyn]

trait ExampleTrait { fn value(&self) -> String; }

[derive(Archive)]

[archive(derive(TypeName))]

struct StringStruct(String);

[archive_dyn]

impl ExampleTrait for StringStruct { fn value(&self) -> String { self.0.clone() } }

impl ExampleTrait for Archived { fn value(&self) -> String { self.0.asstr().tostring() } }

[derive(Archive)]

[archive(derive(TypeName))]

struct IntStruct(i32);

[archive_dyn]

impl ExampleTrait for IntStruct { fn value(&self) -> String { format!("{}", self.0) } }

impl ExampleTrait for Archived { fn value(&self) -> String { format!("{}", self.0) } }

fn main() { let boxedint = Box::new(IntStruct(42)) as Box; let boxedstring = Box::new(StringStruct("hello world".to_string())) as Box;

let mut writer = ArchiveBuffer::new(Aligned([0u8; 256]));
let int_pos = writer.archive(&boxed_int)
    .expect("failed to archive boxed int");
let string_pos = writer.archive(&boxed_string)
    .expect("failed to archive boxed string");
let buf = writer.into_inner();

let archived_int = unsafe { archived_value::<Box<dyn ArchiveExampleTrait>>(buf.as_ref(), int_pos) };
let archived_string = unsafe { archived_value::<Box<dyn ArchiveExampleTrait>>(buf.as_ref(), string_pos) };
assert_eq!(archived_int.value(), "42");
assert_eq!(archived_string.value(), "hello world");

} ```