fuel_core_storage/
codec.rs

1//! The module contains the traits for encoding and decoding the types(a.k.a Codec).
2//! It implements common codecs and encoders, but it is always possible to define own codecs.
3
4use crate::kv_store::Value;
5use core::ops::Deref;
6
7#[cfg(feature = "std")]
8use std::borrow::Cow;
9
10#[cfg(not(feature = "std"))]
11use alloc::borrow::Cow;
12
13pub mod manual;
14pub mod postcard;
15pub mod primitive;
16pub mod raw;
17
18/// The trait is usually implemented by the encoder that stores serialized objects.
19pub trait Encoder {
20    /// Returns the serialized object as a slice.
21    fn as_bytes(&self) -> Cow<'_, [u8]>;
22}
23
24/// The trait encodes the type to the bytes and passes it to the `Encoder`,
25/// which stores it and provides a reference to it. That gives more
26/// flexibility and more performant encoding, allowing the use of slices and arrays
27/// instead of vectors in some cases. Since the [`Encoder`] returns `Cow<[u8]>`,
28/// it is always possible to take ownership of the serialized value.
29pub trait Encode<T: ?Sized> {
30    /// The encoder type that stores serialized object.
31    type Encoder<'a>: Encoder
32    where
33        T: 'a;
34
35    /// Encodes the object to the bytes and passes it to the `Encoder`.
36    fn encode(t: &T) -> Self::Encoder<'_>;
37
38    /// Returns the serialized object as an [`Value`].
39    fn encode_as_value(t: &T) -> Value {
40        Value::from(Self::encode(t).as_bytes())
41    }
42}
43
44/// The trait decodes the type from the bytes.
45pub trait Decode<T> {
46    /// Decodes the type `T` from the bytes.
47    fn decode(bytes: &[u8]) -> anyhow::Result<T>;
48
49    /// Decodes the type `T` from the [`Value`].
50    fn decode_from_value(value: Value) -> anyhow::Result<T> {
51        Self::decode(value.deref())
52    }
53}
54
55impl Encoder for Cow<'_, [u8]> {
56    fn as_bytes(&self) -> Cow<'_, [u8]> {
57        match self {
58            Cow::Borrowed(borrowed) => Cow::Borrowed(borrowed),
59            Cow::Owned(owned) => Cow::Borrowed(owned.as_ref()),
60        }
61    }
62}
63
64impl<const SIZE: usize> Encoder for [u8; SIZE] {
65    fn as_bytes(&self) -> Cow<'_, [u8]> {
66        Cow::Borrowed(self.as_slice())
67    }
68}