firefly_types/encode.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
use alloc::vec::Vec;
pub trait Encode<'a>
where
Self: core::marker::Sized + serde::Deserialize<'a> + serde::Serialize,
{
/// Load object from bytes generated by [`Encode::encode`].
///
/// # Errors
///
/// May return an error if the buffer does not contain a valid object.
fn decode(s: &'a [u8]) -> Result<Self, postcard::Error> {
postcard::from_bytes(s)
}
/// Encode the object as a Vec.
///
/// If you want to avoid dynamic allocations, use [`Encode::encode_buf`] instead.
///
/// # Errors
///
/// In theory, may return an error if any of the types cannot be serialized by
/// postcard. However, all the types defined in this crate are very simple,
/// so it shouldn't happen.
fn encode_vec(&self) -> Result<Vec<u8>, postcard::Error> {
postcard::to_allocvec(self)
}
/// 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_buf<'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 object.
#[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()
}
}