Crates.io | rkyv_dyn |
lib.rs | rkyv_dyn |
version | 0.7.44 |
source | src |
created_at | 2020-11-11 16:37:15.385956 |
updated_at | 2024-02-04 02:40:52.235833 |
description | Trait object support for rkyv |
homepage | |
repository | https://github.com/rkyv/rkyv |
max_upload_size | |
id | 311301 |
size | 44,901 |
Trait object serialization for rkyv.
use rkyv::{
archived_value,
ser::{
serializers::AllocSerializer,
Serializer,
},
Archive,
Archived,
Deserialize,
Infallible,
Serialize,
};
use rkyv_dyn::archive_dyn;
use rkyv_typename::TypeName;
#[archive_dyn(deserialize)]
trait ExampleTrait {
fn value(&self) -> String;
}
#[derive(Archive, Serialize, Deserialize)]
#[archive_attr(derive(TypeName))]
struct StringStruct(String);
#[archive_dyn(deserialize)]
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, Serialize, Deserialize)]
#[archive_attr(derive(TypeName))]
struct IntStruct(i32);
#[archive_dyn(deserialize)]
impl ExampleTrait for IntStruct {
fn value(&self) -> String {
format!("{}", self.0)
}
}
impl ExampleTrait for Archived<IntStruct> {
fn value(&self) -> String {
format!("{}", self.0)
}
}
#[test]
fn main() {
let boxed_int = Box::new(IntStruct(42)) as Box<dyn SerializeExampleTrait>;
let boxed_string = Box::new(StringStruct("hello world".to_string())) as Box<dyn SerializeExampleTrait>;
let mut serializer = AllocSerializer::<256>::default();
let int_pos = serializer.serialize_value(&boxed_int).unwrap();
let string_pos = serializer.serialize_value(&boxed_string).unwrap();
let buf = serializer.into_serializer().into_inner();
let archived_int = unsafe { archived_value::<Box<dyn SerializeExampleTrait>>(buf.as_ref(), int_pos) };
let archived_string = unsafe { archived_value::<Box<dyn SerializeExampleTrait>>(buf.as_ref(), string_pos) };
assert_eq!(archived_int.value(), "42");
assert_eq!(archived_string.value(), "hello world");
let deserialized_int: Box<dyn SerializeExampleTrait> = archived_int.deserialize(&mut Infallible).unwrap();
let deserialized_string: Box<dyn SerializeExampleTrait> = archived_string.deserialize(&mut Infallible).unwrap();
assert_eq!(deserialized_int.value(), "42");
assert_eq!(deserialized_string.value(), "hello world");
}