bitcapybara / budmq

A simple distributed pub/sub MQ inspired by Apache Pulsar
MIT License
1 stars 0 forks source link

Use zerocopy for serialize and deserialize #105

Open bitcapybara opened 8 months ago

bitcapybara commented 8 months ago

rkyvv/zerocopy......

bitcapybara commented 8 months ago
use rkyv::{Archive, Deserialize, Serialize};

#[derive(Archive, Deserialize, Serialize, Debug, PartialEq)]
// This will generate a PartialEq impl between our unarchived and archived types
#[archive(compare(PartialEq))]
// We can pass attributes through to generated types with archive_attr
#[archive_attr(derive(Debug))]
struct Test {
    int: u8,
    string: String,
    option: Option<Vec<i32>>,
}

let value = Test {
    int: 42,
    string: "hello world".to_string(),
    option: Some(vec![1, 2, 3, 4]),
};

// Serializing is as easy as a single function call
let bytes = rkyv::to_bytes::<_, 256>(&value).unwrap();

// You can use the safe API with the validation feature turned on,
// or you can use the unsafe API (shown here) for maximum performance
let archived = unsafe { rkyv::archived_root::<Test>(&bytes[..]) };
assert_eq!(archived, &value);

// And you can always deserialize back to the original type
let deserialized: Test = archived.deserialize(&mut rkyv::Infallible).unwrap();
assert_eq!(deserialized, value);