fuel_core_storage/codec/
raw.rs

1//! The module contains the implementation of the `Raw` codec.
2//! The codec is used for types that are already represented by bytes
3//! and can be deserialized into bytes-based objects.
4
5use crate::codec::{
6    Decode,
7    Encode,
8};
9
10#[cfg(feature = "std")]
11use std::borrow::Cow;
12
13#[cfg(not(feature = "std"))]
14use alloc::borrow::Cow;
15
16/// The codec is used for types that are already represented by bytes.
17pub struct Raw;
18
19impl<T> Encode<T> for Raw
20where
21    T: ?Sized + AsRef<[u8]>,
22{
23    type Encoder<'a>
24        = Cow<'a, [u8]>
25    where
26        T: 'a;
27
28    fn encode(t: &T) -> Self::Encoder<'_> {
29        Cow::Borrowed(t.as_ref())
30    }
31}
32
33impl<T> Decode<T> for Raw
34where
35    for<'a> T: TryFrom<&'a [u8]>,
36{
37    fn decode(bytes: &[u8]) -> anyhow::Result<T> {
38        T::try_from(bytes).map_err(|_| anyhow::anyhow!("Unable to decode bytes"))
39    }
40}