pub trait Serialize: Sized {
// Required methods
fn serialize_header<T: Write>(&self, writer: &mut T) -> Result<()>;
fn serialize_body<T: Write>(&self, writer: &mut T) -> Result<()>;
fn load<T: Read>(reader: &mut T) -> Result<Self>;
fn size_in_elements(&self) -> usize;
// Provided methods
fn serialize<T: Write>(&self, writer: &mut T) -> Result<()> { ... }
fn size_in_bytes(&self) -> usize { ... }
}Expand description
Serialize a data structure.
self.size_in_elements() should always be nonzero.
A structure that implements Serialize may also have an associated function size_by_params.
The function determines the size of a serialized structure with the given parameters in u64 elements without building the structure.
§Examples
use simple_sds_sbwt::serialize::Serialize;
use simple_sds_sbwt::serialize;
use std::{fs, io, mem};
#[derive(PartialEq, Eq, Debug)]
struct Example(i32, u32);
impl Serialize for Example {
fn serialize_header<T: io::Write>(&self, _: &mut T) -> io::Result<()> {
Ok(())
}
fn serialize_body<T: io::Write>(&self, writer: &mut T) -> io::Result<()> {
let bytes: [u8; mem::size_of::<Self>()] = unsafe { mem::transmute_copy(self) };
writer.write_all(&bytes)?;
Ok(())
}
fn load<T: io::Read>(reader: &mut T) -> io::Result<Self> {
let mut bytes = [0u8; mem::size_of::<Self>()];
reader.read_exact(&mut bytes)?;
let value: Example = unsafe { mem::transmute_copy(&bytes) };
Ok(value)
}
fn size_in_elements(&self) -> usize {
1
}
}
let example = Example(-123, 456);
assert_eq!(example.size_in_bytes(), 8);
let filename = serialize::temp_file_name("serialize");
serialize::serialize_to(&example, &filename).unwrap();
let copy: Example = serialize::load_from(&filename).unwrap();
assert_eq!(copy, example);
fs::remove_file(&filename).unwrap();Required Methods§
Sourcefn load<T: Read>(reader: &mut T) -> Result<Self>
fn load<T: Read>(reader: &mut T) -> Result<Self>
Loads the struct from the reader.
§Errors
Any errors from the reader may be passed through.
ErrorKind::InvalidData should be used to indicate that the data failed sanity checks.
Sourcefn size_in_elements(&self) -> usize
fn size_in_elements(&self) -> usize
Returns the size of the serialized struct in u64 elements.
This is usually closely related to the size of the in-memory struct.
Provided Methods§
Sourcefn serialize<T: Write>(&self, writer: &mut T) -> Result<()>
fn serialize<T: Write>(&self, writer: &mut T) -> Result<()>
Serializes the struct to the writer.
Equivalent to calling Serialize::serialize_header and Serialize::serialize_body.
§Errors
Any errors from the writer may be passed through.
Sourcefn size_in_bytes(&self) -> usize
fn size_in_bytes(&self) -> usize
Returns the size of the serialized struct in bytes.
This is usually closely related to the size of the in-memory struct.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.