我建议为自定义类型实施Serialize
和实施Deserialize
。
需要注意的重要一点是,您根本不关心数据。这意味着没有理由占用内存!我们可以定义一个Reserved
将序列化为一堆字节并从字节反序列化的类型,但实际上并不需要我们的内存结构中的任何空间。
然后,只需填写 trait 实现即可:
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate bincode;
use std::fmt;
use serde::ser::SerializeTuple;
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Superblock {
magic: [u8; 16],
reserved: Reserved,
crc: u32,
}
#[derive(Debug, PartialEq)]
struct Reserved;
const RESERVED_LENGTH: usize = 492;
impl serde::Serialize for Reserved {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: serde::Serializer
{
let mut tuple = serializer.serialize_tuple(RESERVED_LENGTH)?;
for _ in 0..RESERVED_LENGTH {
tuple.serialize_element(&0xA0_u8)?; // Just to see it easily in the output
}
tuple.end()
}
}
impl<'de> serde::Deserialize<'de> for Reserved {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: serde::Deserializer<'de>
{
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Reserved;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} bytes", RESERVED_LENGTH)
}
fn visit_seq<A>(self, mut tuple: A) -> Result<Self::Value, A::Error>
where A: serde::de::SeqAccess<'de>,
{
for _ in 0..RESERVED_LENGTH {
tuple.next_element::<u8>()?;
}
Ok(Reserved)
}
}
deserializer.deserialize_tuple(RESERVED_LENGTH, Visitor)
}
}
fn main() {
let block = Superblock {
magic: [
0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f,
],
reserved: Reserved,
crc: 0xffffffff,
};
let ser = bincode::serialize(&block, bincode::Infinite).expect("Couldn't serialize");
println!("length: {}", ser.len());
println!("{:?}", ser);
let block2: Superblock = bincode::deserialize(&ser).expect("Couldn't deserialize");
assert_eq!(block, block2);
println!("{:?}", block2);
println!("Takes: {} bytes", std::mem::size_of::<Superblock>());
// prints "Takes: 20 bytes"
}