rubbo_serialization/
lib.rs

1use serde::{Serialize, Deserialize};
2use serde::ser::Error as _;
3use rubbo_core::{Error, Result};
4
5/// Serialization trait for pluggable serialization strategies
6pub trait Serialization: Send + Sync {
7    fn serialize<T: Serialize>(&self, obj: &T) -> Result<Vec<u8>>;
8    fn deserialize<T: for<'a> Deserialize<'a>>(&self, data: &[u8]) -> Result<T>;
9    fn name(&self) -> &'static str;
10}
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum SerializationType {
14    #[cfg(feature = "fastjson")]
15    Fastjson,
16    #[cfg(feature = "fastjson2")]
17    Fastjson2,
18    #[cfg(feature = "hessian2")]
19    Hessian2,
20}
21
22pub fn is_supported(name: &str) -> bool {
23    #[cfg(feature = "fastjson")]
24    if name == "fastjson" {
25        return true;
26    }
27    
28    #[cfg(feature = "fastjson2")]
29    if name == "fastjson2" {
30        return true; // Implemented as alias to fastjson for now
31    }
32
33    #[cfg(feature = "hessian2")]
34    if name == "hessian2" {
35        return true;
36    }
37    
38    // Add other supported serializations here
39    
40    false
41}
42
43pub enum SerializerImpl {
44    #[cfg(feature = "fastjson")]
45    FastJson(FastJsonSerialization),
46    #[cfg(feature = "fastjson2")]
47    FastJson2(FastJson2Serialization),
48    #[cfg(feature = "hessian2")]
49    Hessian2(Hessian2Serialization),
50}
51
52impl SerializerImpl {
53    pub fn serialize<T: Serialize>(&self, obj: &T) -> Result<Vec<u8>> {
54        match self {
55            #[cfg(feature = "fastjson")]
56            SerializerImpl::FastJson(s) => s.serialize(obj),
57            #[cfg(feature = "fastjson2")]
58            SerializerImpl::FastJson2(s) => s.serialize(obj),
59            #[cfg(feature = "hessian2")]
60            SerializerImpl::Hessian2(s) => s.serialize(obj),
61            #[allow(unreachable_patterns)]
62            _ => unreachable!("No serialization feature enabled"),
63        }
64    }
65
66    pub fn deserialize<T: for<'a> Deserialize<'a>>(&self, data: &[u8]) -> Result<T> {
67        match self {
68            #[cfg(feature = "fastjson")]
69            SerializerImpl::FastJson(s) => s.deserialize(data),
70            #[cfg(feature = "fastjson2")]
71            SerializerImpl::FastJson2(s) => s.deserialize(data),
72            #[cfg(feature = "hessian2")]
73            SerializerImpl::Hessian2(s) => s.deserialize(data),
74            #[allow(unreachable_patterns)]
75            _ => unreachable!("No serialization feature enabled"),
76        }
77    }
78}
79
80pub fn get_serializer(name: &str) -> Option<SerializerImpl> {
81    #[cfg(feature = "fastjson")]
82    if name == "fastjson" {
83        return Some(SerializerImpl::FastJson(FastJsonSerialization::new()));
84    }
85
86    #[cfg(feature = "fastjson2")]
87    if name == "fastjson2" {
88        return Some(SerializerImpl::FastJson2(FastJson2Serialization::new()));
89    }
90
91    #[cfg(feature = "hessian2")]
92    if name == "hessian2" {
93        return Some(SerializerImpl::Hessian2(Hessian2Serialization::new()));
94    }
95    
96    None
97}
98
99/// FastJson implementation of Serialization (using serde_json underneath)
100#[cfg(feature = "fastjson")]
101#[derive(Debug, Default, Clone, Copy)]
102pub struct FastJsonSerialization;
103
104#[cfg(feature = "fastjson")]
105impl FastJsonSerialization {
106    pub fn new() -> Self {
107        Self
108    }
109}
110
111#[cfg(feature = "fastjson")]
112impl Serialization for FastJsonSerialization {
113    fn serialize<T: Serialize>(&self, obj: &T) -> Result<Vec<u8>> {
114        serde_json::to_vec(obj).map_err(|e| Error::Serialization(serde_json::Error::custom(e.to_string())))
115    }
116
117    fn deserialize<T: for<'a> Deserialize<'a>>(&self, data: &[u8]) -> Result<T> {
118        serde_json::from_slice(data).map_err(|e| Error::Serialization(serde_json::Error::custom(e.to_string())))
119    }
120
121    fn name(&self) -> &'static str {
122        "fastjson"
123    }
124}
125
126/// FastJson2 implementation of Serialization
127#[cfg(feature = "fastjson2")]
128#[derive(Debug, Default, Clone, Copy)]
129pub struct FastJson2Serialization;
130
131#[cfg(feature = "fastjson2")]
132impl FastJson2Serialization {
133    pub fn new() -> Self {
134        Self
135    }
136}
137
138#[cfg(feature = "fastjson2")]
139impl Serialization for FastJson2Serialization {
140    fn serialize<T: Serialize>(&self, obj: &T) -> Result<Vec<u8>> {
141        rubbo_jsonb::to_vec(obj).map_err(|e| Error::Serialization(serde_json::Error::custom(e.to_string())))
142    }
143
144    fn deserialize<T: for<'a> Deserialize<'a>>(&self, data: &[u8]) -> Result<T> {
145        rubbo_jsonb::from_slice(data).map_err(|e| Error::Serialization(serde_json::Error::custom(e.to_string())))
146    }
147
148    fn name(&self) -> &'static str {
149        "fastjson2"
150    }
151}
152
153/// Hessian2 implementation of Serialization
154#[cfg(feature = "hessian2")]
155#[derive(Debug, Default, Clone, Copy)]
156pub struct Hessian2Serialization;
157
158#[cfg(feature = "hessian2")]
159impl Hessian2Serialization {
160    pub fn new() -> Self {
161        Self
162    }
163}
164
165#[cfg(feature = "hessian2")]
166impl Serialization for Hessian2Serialization {
167    fn serialize<T: Serialize>(&self, obj: &T) -> Result<Vec<u8>> {
168        serde_hessian::ser::to_vec(obj).map_err(|e| Error::Serialization(serde_json::Error::custom(e.to_string())))
169    }
170
171    fn deserialize<T: for<'a> Deserialize<'a>>(&self, data: &[u8]) -> Result<T> {
172        let decoder = hessian_rs::de::Deserializer::new(data);
173        let mut de = serde_hessian::de::Deserializer::new(decoder);
174        T::deserialize(&mut de).map_err(|e| Error::Serialization(serde_json::Error::custom(e.to_string())))
175    }
176
177    fn name(&self) -> &'static str {
178        "hessian2"
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    #[derive(Serialize, Deserialize, Debug, PartialEq)]
187    struct TestStruct {
188        id: i32,
189        name: String,
190    }
191
192    #[test]
193    fn test_fastjson_serialization() {
194        let serializer = FastJsonSerialization::new();
195        let data = TestStruct {
196            id: 1,
197            name: "rubbo".to_string(),
198        };
199
200        // Serialize
201        let bytes = serializer.serialize(&data).unwrap();
202        assert!(!bytes.is_empty());
203
204        // Deserialize
205        let decoded: TestStruct = serializer.deserialize(&bytes).unwrap();
206        assert_eq!(data, decoded);
207    }
208
209    #[test]
210    fn test_supported() {
211        assert!(is_supported("fastjson"));
212        assert!(!is_supported("protobuf"));
213    }
214}