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