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