Skip to main content

flare_core/common/serializer/
registry.rs

1//! 序列化器注册表
2//!
3//! 管理序列化器的注册和查找,支持用户注册自定义序列化器
4
5use super::formats::{JsonSerializer, ProtobufSerializer};
6use super::traits::Serializer;
7use crate::common::protocol::SerializationFormat;
8use std::collections::HashMap;
9use std::sync::Arc;
10use std::sync::RwLock;
11
12lazy_static::lazy_static! {
13    /// 全局序列化器注册表
14    static ref SERIALIZATION_REGISTRY: SerializationRegistry = {
15        let registry = SerializationRegistry::new();
16        // 注册内置序列化器
17        registry.register_defaults();
18        registry
19    };
20}
21
22/// 序列化器注册表
23///
24/// 管理序列化器的注册和查找
25pub struct SerializationRegistry {
26    serializers: Arc<RwLock<HashMap<String, Arc<dyn Serializer>>>>,
27}
28
29impl Default for SerializationRegistry {
30    fn default() -> Self {
31        Self {
32            serializers: Arc::new(RwLock::new(HashMap::new())),
33        }
34    }
35}
36
37impl SerializationRegistry {
38    /// 创建新的注册表
39    pub fn new() -> Self {
40        Self::default()
41    }
42
43    /// 注册内置序列化器
44    pub fn register_defaults(&self) {
45        self.register("protobuf", Arc::new(ProtobufSerializer));
46        self.register("json", Arc::new(JsonSerializer));
47    }
48
49    /// 注册序列化器
50    ///
51    /// # 参数
52    /// - `name`: 序列化器名称(用于查找)
53    /// - `serializer`: 序列化器实例
54    ///
55    /// # 示例
56    ///
57    /// ```rust,ignore
58    /// use flare_core::common::serializer::{SerializationRegistry, Serializer};
59    /// use std::sync::Arc;
60    ///
61    /// struct MySerializer;
62    /// impl Serializer for MySerializer { /* ... */ }
63    ///
64    /// let registry = SerializationRegistry::new();
65    /// registry.register("my_custom", Arc::new(MySerializer));
66    /// ```
67    pub fn register(&self, name: &str, serializer: Arc<dyn Serializer>) {
68        if let Ok(mut serializers) = self.serializers.write() {
69            serializers.insert(name.to_string(), serializer);
70        }
71    }
72
73    /// 查找序列化器
74    ///
75    /// # 参数
76    /// - `name`: 序列化器名称
77    ///
78    /// # 返回
79    /// 找到的序列化器,如果不存在则返回 None
80    pub fn find(&self, name: &str) -> Option<Arc<dyn Serializer>> {
81        self.serializers
82            .read()
83            .ok()
84            .and_then(|serializers| serializers.get(name).map(Arc::clone))
85    }
86
87    /// 根据格式类型查找序列化器
88    pub fn find_by_format(&self, format: SerializationFormat) -> Option<Arc<dyn Serializer>> {
89        let name = match format {
90            SerializationFormat::Protobuf => "protobuf",
91            SerializationFormat::Json => "json",
92        };
93        self.find(name)
94    }
95
96    /// 尝试自动检测序列化格式
97    ///
98    /// 遍历所有注册的序列化器,使用 `can_detect` 方法检测
99    pub fn auto_detect(&self, data: &[u8]) -> Vec<Arc<dyn Serializer>> {
100        let mut detected = Vec::new();
101        if let Ok(serializers) = self.serializers.read() {
102            for serializer in serializers.values() {
103                if serializer.can_detect(data) {
104                    detected.push(Arc::clone(serializer));
105                }
106            }
107        }
108        detected
109    }
110
111    /// 获取全局注册表实例
112    pub fn global() -> &'static SerializationRegistry {
113        &SERIALIZATION_REGISTRY
114    }
115}
116
117/// 序列化工具类
118///
119/// 提供便捷的序列化/反序列化方法,使用全局注册表
120pub struct SerializationUtil;
121
122impl SerializationUtil {
123    /// 根据格式类型获取序列化器
124    pub fn get_serializer(format: SerializationFormat) -> Option<Arc<dyn Serializer>> {
125        SerializationRegistry::global().find_by_format(format)
126    }
127
128    /// 根据名称获取序列化器
129    pub fn get_serializer_by_name(name: &str) -> Option<Arc<dyn Serializer>> {
130        SerializationRegistry::global().find(name)
131    }
132
133    /// 根据名称查找序列化器(便捷方法,别名)
134    pub fn find(name: &str) -> Option<Arc<dyn Serializer>> {
135        Self::get_serializer_by_name(name)
136    }
137
138    /// 尝试自动检测序列化格式
139    ///
140    /// 返回所有可能匹配的序列化器(按检测顺序)
141    pub fn auto_detect(data: &[u8]) -> Vec<Arc<dyn Serializer>> {
142        SerializationRegistry::global().auto_detect(data)
143    }
144
145    /// 注册自定义序列化器到全局注册表
146    ///
147    /// # 示例
148    ///
149    /// ```rust,ignore
150    /// use flare_core::common::serializer::{SerializationUtil, Serializer};
151    /// use std::sync::Arc;
152    ///
153    /// struct MySerializer;
154    /// impl Serializer for MySerializer { /* ... */ }
155    ///
156    /// SerializationUtil::register_custom(Arc::new(MySerializer));
157    /// ```
158    pub fn register_custom(serializer: Arc<dyn Serializer>) {
159        SerializationRegistry::global().register(serializer.name(), serializer);
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    #[test]
168    fn test_serialization_registry() {
169        let registry = SerializationRegistry::new();
170        registry.register_defaults();
171
172        assert!(registry.find("protobuf").is_some());
173        assert!(registry.find("json").is_some());
174        assert!(registry.find("unknown").is_none());
175    }
176
177    #[test]
178    fn test_auto_detect_json() {
179        let data = b"{\"message_id\":\"test\"}";
180        let registry = SerializationRegistry::new();
181        registry.register_defaults();
182
183        let serializers = registry.auto_detect(data);
184        // JSON 应该能被检测到
185        assert!(serializers.iter().any(|s| s.name() == "json"));
186    }
187}