firefly_types/encode.rs
pub trait Encode<'a>
where
Self: core::marker::Sized + serde::Deserialize<'a> + serde::Serialize,
{
/// Load object from bytes generated by [`Badges::encode`].
///
/// # Errors
///
/// May return an error if the buffer does not contain valid object.
fn decode(s: &'a [u8]) -> Result<Self, postcard::Error> {
postcard::from_bytes(s)
}
/// Encode the object using the buffer.
///
/// The buffer is required to avoid allocations on the crate side.
/// Use [`Encode::size`] to calculate the required buffer size.
///
/// # Errors
///
/// May return an error if the buffer is not big enough.
fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b mut [u8], postcard::Error> {
postcard::to_slice(self, buf)
}
/// Calculate the buffer size required to encode the badges.
#[must_use]
#[allow(clippy::missing_panics_doc)]
fn size(&self) -> usize {
let flavor = postcard::ser_flavors::Size::default();
postcard::serialize_with_flavor(self, flavor).unwrap()
}
}