fuel_core_storage/codec/
postcard.rs

1//! The module contains the implementation of the `Postcard` codec.
2//! Any type that implements `serde::Serialize` and `serde::Deserialize`
3//! can use the `Postcard` codec to be encoded/decoded into/from bytes.
4//! The `serde` serialization and deserialization add their own overhead,
5//! so this codec shouldn't be used for simple types.
6
7use crate::codec::{
8    Decode,
9    Encode,
10};
11
12#[cfg(feature = "std")]
13use std::borrow::Cow;
14
15#[cfg(not(feature = "std"))]
16use alloc::borrow::Cow;
17
18/// The codec is used to serialized/deserialized types that supports `serde::Serialize` and `serde::Deserialize`.
19pub struct Postcard;
20
21impl<T> Encode<T> for Postcard
22where
23    T: ?Sized + serde::Serialize,
24{
25    type Encoder<'a>
26        = Cow<'a, [u8]>
27    where
28        T: 'a;
29
30    fn encode(value: &T) -> Self::Encoder<'_> {
31        Cow::Owned(postcard::to_allocvec(value).expect(
32            "It should be impossible to fail unless serialization is not implemented, which is not true for our types.",
33        ))
34    }
35}
36
37impl<T> Decode<T> for Postcard
38where
39    T: serde::de::DeserializeOwned,
40{
41    fn decode(bytes: &[u8]) -> anyhow::Result<T> {
42        Ok(postcard::from_bytes(bytes)?)
43    }
44}