[][src]Trait rkyv_dyn::ArchiveDyn

pub trait ArchiveDyn: TypeNameDyn {
    pub fn archive_dyn(
        &self,
        writer: &mut dyn WriteDyn
    ) -> Result<DynResolver, DynError>; }

A trait object that can be serialized.

To add archive support for a trait object:

  1. Add archive_dyn on your trait to make an archive-compatible version of it. By default, it will be named "Archive" + your trait name.
  2. Implement Archive and TypeName for the types you want to make trait objects of.
  3. Implement your trait for your type and add the attribute #[archive_dyn] to it. Make sure to implement your trait for your archived type as well.

Then you're ready to serialize boxed trait objects!

Even though your unarchived values are boxed as archive trait objects, your archived values are boxed as regular trait objects. This is because your unarchived values have to implement ArchiveDyn but your archived values do not.

Examples

See archive_dyn for customization options.

use rkyv::{
    Aligned,
    Archive,
    ArchiveBuffer,
    Archived,
    archived_value,
    WriteExt,
};
use rkyv_dyn::archive_dyn;
use rkyv_typename::TypeName;

#[archive_dyn]
trait ExampleTrait {
    fn value(&self) -> String;
}

#[derive(Archive, TypeName)]
struct StringStruct(String);

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

impl ExampleTrait for Archived<StringStruct> {
    fn value(&self) -> String {
        self.0.as_str().to_string()
    }
}

#[derive(Archive, TypeName)]
struct IntStruct(i32);

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

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

let boxed_int = Box::new(IntStruct(42)) as Box<dyn ArchiveExampleTrait>;
let boxed_string = Box::new(StringStruct("hello world".to_string())) as Box<dyn ArchiveExampleTrait>;
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, int_pos) };
let archived_string = unsafe { archived_value::<Box<dyn ArchiveExampleTrait>, _>(&buf, string_pos) };
assert_eq!(archived_int.value(), "42");
assert_eq!(archived_string.value(), "hello world");

Required methods

pub fn archive_dyn(
    &self,
    writer: &mut dyn WriteDyn
) -> Result<DynResolver, DynError>

Writes the value to the writer and returns a resolver that can create an ArchivedDyn reference.

Loading content...

Implementors

impl<T: Archive + TypeName> ArchiveDyn for T[src]

Loading content...