use rancor::Failure;
use rkyv::{with::With, Archive, Deserialize, Serialize};
mod remote {
#[derive(Debug, PartialEq)]
pub struct Foo {
pub ch: char,
pub bytes: [u8; 4],
pub _uninteresting: u32,
bar: Bar<i32>,
}
#[derive(Debug, PartialEq)]
pub struct Bar<T>(pub T);
impl Foo {
pub fn new(
ch: char,
bytes: [u8; 4],
_uninteresting: u32,
bar: Bar<i32>,
) -> Self {
Self {
ch,
bytes,
_uninteresting,
bar,
}
}
pub fn bar(&self) -> &Bar<i32> {
&self.bar
}
}
}
#[derive(Archive, Serialize, Deserialize)]
#[rkyv(remote = remote::Foo)] #[rkyv(archived = ArchivedFoo)]
struct FooDef {
ch: char,
#[rkyv(getter = remote::Foo::bar, with = BarDef)]
bar: remote::Bar<i32>,
#[rkyv(getter = get_first_byte)]
first_byte: u8,
}
fn get_first_byte(foo: &remote::Foo) -> u8 {
foo.bytes[0]
}
impl From<FooDef> for remote::Foo {
fn from(value: FooDef) -> Self {
remote::Foo::new(value.ch, [value.first_byte, 2, 3, 4], 567, value.bar)
}
}
#[derive(Archive, Serialize, Deserialize)]
#[rkyv(remote = remote::Bar<i32>)]
struct BarDef(i32);
impl From<BarDef> for remote::Bar<i32> {
fn from(BarDef(value): BarDef) -> Self {
remote::Bar(value)
}
}
fn main() -> Result<(), Failure> {
let foo = remote::Foo::new('!', [1, 2, 3, 4], 567, remote::Bar(89));
let bytes = rkyv::to_bytes(With::<remote::Foo, FooDef>::cast(&foo))?;
let archived: &ArchivedFoo = rkyv::access(&bytes)?;
let deserialized: remote::Foo =
rkyv::deserialize(With::<ArchivedFoo, FooDef>::cast(archived))?;
assert_eq!(foo, deserialized);
#[derive(Archive, Serialize, Deserialize, Debug, PartialEq)]
struct Baz {
#[rkyv(with = FooDef)]
foo: remote::Foo,
}
let baz = Baz { foo };
let bytes = rkyv::to_bytes(&baz)?;
let archived: &ArchivedBaz = rkyv::access(&bytes)?;
let deserialized: Baz = rkyv::deserialize(archived)?;
assert_eq!(baz, deserialized);
Ok(())
}
#[allow(unused)]
mod another_remote {
#[non_exhaustive] pub enum Qux {
Unit,
Tuple(i32),
Struct { value: bool },
}
}
#[allow(unused)]
#[derive(Archive, Serialize)]
#[rkyv(remote = another_remote::Qux)]
enum QuxDef {
Unit,
Struct {},
#[rkyv(other)]
Unknown,
}