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
46
47
48
49
50
51
52
#[cfg(feature = "avro")]
pub mod avro;
#[cfg(feature = "json")]
pub mod json;
#[cfg(feature = "prost")]
pub mod prost;
#[cfg(feature = "protobuf")]
pub mod protobuf;

/// Serialization and deserialization error.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// an error occurred during the deserialization of the data
    #[error("deserialization error: {0}")]
    Deserialization(#[source] Box<dyn std::error::Error + Sync + Send>),
    /// an error occurred while converting the persisted data to the application data
    #[error("conversion error")]
    Conversion,
}

/// The `Serializer` trait defines the behavior for serializing values of type `T`.
pub trait Serializer<T> {
    /// Serializes a value of type `T` into a byte vector.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to be serialized.
    ///
    /// # Returns
    ///
    /// A byte vector containing the serialized representation of the value.
    fn serialize(&self, value: T) -> Vec<u8>;
}

/// The `Deserializer` trait defines the behavior for deserializing values of type `T`.
pub trait Deserializer<T> {
    /// Deserializes a byte vector into a value of type `T`.
    ///
    /// # Arguments
    ///
    /// * `data` - The byte vector to be deserialized.
    ///
    /// # Returns
    ///
    /// A `Result` containing the deserialized value on success, or an error on failure.
    fn deserialize(&self, data: Vec<u8>) -> Result<T, Error>;
}

/// The `Serde` trait combines the `Serializer` and `Deserializer` traits for convenience.
pub trait Serde<T>: Serializer<T> + Deserializer<T> {}

impl<K, T> Serde<T> for K where K: Serializer<T> + Deserializer<T> {}