1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use serde_json;

use super::{StateCodec, StateKeyCodec};
use crate::codec::StateValueCodec;

/// A [`StateValueCodec`] that uses [`serde_json`] for all values.
#[derive(Debug, Default, PartialEq, Eq, Clone, serde::Serialize, serde::Deserialize)]
pub struct JsonCodec;

impl<K> StateKeyCodec<K> for JsonCodec
where
    K: serde::Serialize,
{
    fn encode_key(&self, key: &K) -> Vec<u8> {
        serde_json::to_vec(key).expect("Failed to serialize value")
    }
}

impl<V> StateValueCodec<V> for JsonCodec
where
    V: serde::Serialize + for<'a> serde::Deserialize<'a>,
{
    type Error = serde_json::Error;

    fn encode_value(&self, value: &V) -> Vec<u8> {
        serde_json::to_vec(value).expect("Failed to serialize value")
    }

    fn try_decode_value(&self, bytes: &[u8]) -> Result<V, Self::Error> {
        serde_json::from_slice(bytes)
    }
}

impl StateCodec for JsonCodec {
    type KeyCodec = Self;
    type ValueCodec = Self;

    fn key_codec(&self) -> &Self::KeyCodec {
        self
    }

    fn value_codec(&self) -> &Self::ValueCodec {
        self
    }
}