guardian_db/
message_marshaler.rs

1use crate::error::GuardianError;
2use crate::traits::{MessageExchangeHeads, MessageMarshaler};
3use serde_json;
4
5/// Wrapper que adapta serde_json::Error para GuardianError
6pub struct GuardianJSONMarshaler {
7    inner: JSONMarshaler,
8}
9
10impl Default for GuardianJSONMarshaler {
11    fn default() -> Self {
12        Self::new()
13    }
14}
15
16impl GuardianJSONMarshaler {
17    pub fn new() -> Self {
18        Self {
19            inner: JSONMarshaler::new(),
20        }
21    }
22}
23
24impl MessageMarshaler for GuardianJSONMarshaler {
25    type Error = GuardianError;
26
27    fn marshal(&self, m: &MessageExchangeHeads) -> std::result::Result<Vec<u8>, Self::Error> {
28        self.inner
29            .marshal(m)
30            .map_err(|e| GuardianError::Other(format!("Marshal error: {}", e)))
31    }
32
33    fn unmarshal(&self, data: &[u8]) -> std::result::Result<MessageExchangeHeads, Self::Error> {
34        self.inner
35            .unmarshal(data)
36            .map_err(|e| GuardianError::Other(format!("Unmarshal error: {}", e)))
37    }
38}
39
40/// Uma struct vazia que implementa o trait `MessageMarshaler`
41/// para codificar e decodificar mensagens no formato JSON.
42#[derive(Default, Debug, Clone, Copy)]
43pub struct JSONMarshaler;
44
45impl JSONMarshaler {
46    pub fn new() -> Self {
47        Self
48    }
49}
50
51// Implementação do trait `MessageMarshaler` para a struct `JSONMarshaler`.
52impl MessageMarshaler for JSONMarshaler {
53    // O tipo de erro retornado pelas funções é o erro padrão de `serde_json`.
54    type Error = serde_json::Error;
55
56    /// Serializa uma struct `MessageExchangeHeads` para um vetor de bytes (`Vec<u8>`)
57    /// usando `serde_json::to_vec`.
58    fn marshal(&self, m: &MessageExchangeHeads) -> std::result::Result<Vec<u8>, Self::Error> {
59        serde_json::to_vec(m)
60    }
61
62    /// Desserializa um slice de bytes (`&[u8]`) para uma struct `MessageExchangeHeads`
63    /// usando `serde_json::from_slice`.
64    fn unmarshal(&self, data: &[u8]) -> std::result::Result<MessageExchangeHeads, Self::Error> {
65        serde_json::from_slice(data)
66    }
67}