fuel_data_parser/
lib.rs

1use std::fmt::Debug;
2
3/// Serialization/Deserialization error types.
4#[derive(Debug, thiserror::Error)]
5pub enum SerdeError {
6    #[error(transparent)]
7    Json(#[from] serde_json::Error),
8}
9
10/// Data parser error types.
11#[derive(Debug, thiserror::Error)]
12pub enum DataParserError {
13    #[error("An error occurred during JSON encoding: {0}")]
14    EncodeJson(#[source] SerdeError),
15    #[error("An error occurred during JSON decoding: {0}")]
16    DecodeJson(#[source] SerdeError),
17}
18
19#[derive(Debug, Clone, strum::EnumIter, strum_macros::Display)]
20pub enum SerializationType {
21    #[strum(serialize = "json")]
22    Json,
23}
24
25#[async_trait::async_trait]
26pub trait DataEncoder:
27    serde::Serialize
28    + serde::de::DeserializeOwned
29    + Clone
30    + Send
31    + Sync
32    + Debug
33    + std::marker::Sized
34{
35    fn data_parser() -> DataParser {
36        DataParser::default()
37    }
38
39    fn encode_json(&self) -> Result<Vec<u8>, DataParserError> {
40        Self::data_parser().encode_json(self)
41    }
42
43    fn decode_json(encoded: &[u8]) -> Result<Self, DataParserError> {
44        Self::data_parser().decode_json(encoded)
45    }
46
47    fn to_json_value(&self) -> Result<serde_json::Value, DataParserError> {
48        Self::data_parser().to_json_value(self)
49    }
50}
51
52#[derive(Clone)]
53pub struct DataParser {
54    pub serialization_type: SerializationType,
55}
56
57impl Default for DataParser {
58    fn default() -> Self {
59        Self {
60            serialization_type: SerializationType::Json,
61        }
62    }
63}
64
65impl DataParser {
66    pub fn encode_json<T: DataEncoder>(
67        &self,
68        data: &T,
69    ) -> Result<Vec<u8>, DataParserError> {
70        serde_json::to_vec(&data)
71            .map_err(|e| DataParserError::EncodeJson(SerdeError::Json(e)))
72    }
73
74    pub fn to_json_value<T: serde::Serialize>(
75        &self,
76        data: &T,
77    ) -> Result<serde_json::Value, DataParserError> {
78        serde_json::to_value(data)
79            .map_err(|e| DataParserError::EncodeJson(SerdeError::Json(e)))
80    }
81
82    pub fn decode_json<T: DataEncoder>(&self, data: &[u8]) -> Result<T, DataParserError> {
83        serde_json::from_slice(data)
84            .map_err(|e| DataParserError::DecodeJson(SerdeError::Json(e)))
85    }
86}
87
88#[cfg(test)]
89mod tests {
90    use pretty_assertions::assert_eq;
91
92    use super::*;
93
94    #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
95    struct TestData {
96        field: String,
97    }
98
99    impl DataEncoder for TestData {}
100
101    #[tokio::test]
102    async fn test_encode_decode() {
103        let parser = DataParser::default();
104        let original_data = TestData {
105            field: "test".to_string(),
106        };
107        let encoded = parser.encode_json(&original_data).unwrap();
108        let decoded: TestData = parser.decode_json(&encoded).unwrap();
109        assert_eq!(original_data, decoded);
110    }
111}