pub trait Packable {
// Required methods
fn pack_sz(&self) -> usize;
fn pack(&self, out: &mut [u8]);
// Provided method
fn stream<W: Write>(&self, writer: &mut W) -> Result<usize, Error>
where Self: Sized,
for<'a> &'a Self: Packable { ... }
}Expand description
Packable objects can be serialized into an &mut [u8].
The actual serialized form of the object is left unspecified by the Packable trait.
Packable objects should avoid interior mutability to the extent necessary to ensure that anyone holding a immutable reference can assume the packed output will not change for the duration of the reference.
Required Methods§
Sourcefn pack_sz(&self) -> usize
fn pack_sz(&self) -> usize
pack_sz returns the number of bytes required to serialize the Packable object.
Sourcefn pack(&self, out: &mut [u8])
fn pack(&self, out: &mut [u8])
pack fills in the buffer out with the packed binary representation of the Packable
object. The implementor is responsible to ensure that out is exactly pack_sz() bytes
and implementations are encouraged to assert this.
The call to pack should never fail. Good Rust practices dictate that objects should use the type system to enforce their well-formed-ness. Consequently, we will assume here that any well-formed Packable that can be represented will serialize successfully. If there is a need to represent a state that cannot exist, it should be done using a different type that does not implement Packable.
§Panics
- When
out.len() != self.pack_sz()
Provided Methods§
Sourcefn stream<W: Write>(&self, writer: &mut W) -> Result<usize, Error>
fn stream<W: Write>(&self, writer: &mut W) -> Result<usize, Error>
stream writes the object to the provided writer using the same representation that would
be used in a call to pack. The implementor is responsible for making sure that the
number of bytes written is exactly equal to the number of required bytes.
A default implementation is provided that will pack a vector and then write said vector to
the file with write_all.