Skip to main content

weavatrix_memory/
codec.rs

1use crate::Result;
2
3/// Deterministic serialization boundary used by durable stores.
4pub trait Codec<T> {
5    /// Encodes one value.
6    ///
7    /// # Errors
8    ///
9    /// Returns a codec-specific serialization error.
10    fn encode(&self, value: &T) -> Result<Vec<u8>>;
11
12    /// Decodes one complete value.
13    ///
14    /// # Errors
15    ///
16    /// Returns a codec-specific deserialization error.
17    fn decode(&self, bytes: &[u8]) -> Result<T>;
18}
19
20#[cfg(feature = "json")]
21#[derive(Debug, Clone, Copy, Default)]
22pub struct JsonCodec;
23
24#[cfg(feature = "json")]
25impl<T> Codec<T> for JsonCodec
26where
27    T: serde::Serialize + serde::de::DeserializeOwned,
28{
29    fn encode(&self, value: &T) -> Result<Vec<u8>> {
30        serde_json::to_vec(value).map_err(|error| crate::MemoryError::Codec {
31            message: error.to_string(),
32        })
33    }
34
35    fn decode(&self, bytes: &[u8]) -> Result<T> {
36        serde_json::from_slice(bytes).map_err(|error| crate::MemoryError::Codec {
37            message: error.to_string(),
38        })
39    }
40}