sov_state/codec/
bcs_codec.rs

1use super::{StateCodec, StateKeyCodec};
2use crate::codec::StateValueCodec;
3
4/// A [`StateCodec`] that uses [`bcs`] for all keys and values.
5#[derive(Debug, Default, PartialEq, Eq, Clone, serde::Serialize, serde::Deserialize)]
6pub struct BcsCodec;
7
8impl<K> StateKeyCodec<K> for BcsCodec
9where
10    K: serde::Serialize,
11{
12    fn encode_key(&self, key: &K) -> Vec<u8> {
13        bcs::to_bytes(key).expect("Failed to serialize key")
14    }
15}
16
17impl<V> StateValueCodec<V> for BcsCodec
18where
19    V: serde::Serialize + for<'a> serde::Deserialize<'a>,
20{
21    type Error = bcs::Error;
22
23    fn encode_value(&self, value: &V) -> Vec<u8> {
24        bcs::to_bytes(value).expect("Failed to serialize value")
25    }
26
27    fn try_decode_value(&self, bytes: &[u8]) -> Result<V, Self::Error> {
28        bcs::from_bytes(bytes)
29    }
30}
31
32impl StateCodec for BcsCodec {
33    type KeyCodec = Self;
34    type ValueCodec = Self;
35
36    fn key_codec(&self) -> &Self::KeyCodec {
37        self
38    }
39
40    fn value_codec(&self) -> &Self::ValueCodec {
41        self
42    }
43}