baichun_framework_core/
traits.rs

1use async_trait::async_trait;
2
3use crate::error::Result;
4
5/// 数据转换特征
6pub trait Convert<T> {
7    /// 转换为目标类型
8    fn convert(&self) -> T;
9}
10
11/// 克隆转换特征
12pub trait CloneInto<T: Clone> {
13    /// 克隆并转换为目标类型
14    fn clone_into(&self) -> T;
15}
16
17/// 初始化特征
18pub trait Initialize {
19    /// 初始化
20    fn initialize(&mut self) -> Result<()>;
21}
22
23/// 验证特征
24pub trait Validate {
25    /// 验证
26    fn validate(&self) -> Result<()>;
27}
28
29/// 生命周期管理特征
30pub trait Lifecycle {
31    /// 启动
32    fn start(&mut self) -> Result<()>;
33    /// 停止
34    fn stop(&mut self) -> Result<()>;
35    /// 重启
36    fn restart(&mut self) -> Result<()>;
37}
38
39/// 异步生命周期管理特征
40#[async_trait]
41pub trait AsyncLifecycle {
42    /// 启动
43    async fn start(&mut self) -> Result<()>;
44    /// 停止
45    async fn stop(&mut self) -> Result<()>;
46    /// 重启
47    async fn restart(&mut self) -> Result<()>;
48}
49
50/// 序列化特征
51pub trait Serializer {
52    /// 序列化为字节数组
53    fn to_bytes(&self) -> Result<Vec<u8>>;
54    /// 从字节数组反序列化
55    fn from_bytes(bytes: &[u8]) -> Result<Self>
56    where
57        Self: Sized;
58}
59
60/// 克隆特征
61pub trait CloneBox {
62    /// 克隆到Box
63    fn clone_box(&self) -> Box<dyn CloneBox>;
64}
65
66impl<T> CloneBox for T
67where
68    T: 'static + Clone,
69{
70    fn clone_box(&self) -> Box<dyn CloneBox> {
71        Box::new(self.clone())
72    }
73}
74
75/// 标识特征
76pub trait Identifier {
77    /// 获取ID
78    fn id(&self) -> String;
79}
80
81/// 命名特征
82pub trait Named {
83    /// 获取名称
84    fn name(&self) -> String;
85}
86
87/// 描述特征
88pub trait Described {
89    /// 获取描述
90    fn description(&self) -> String;
91}
92
93/// 版本特征
94pub trait Versioned {
95    /// 获取版本
96    fn version(&self) -> String;
97}
98
99/// 状态特征
100pub trait State {
101    /// 获取状态
102    fn state(&self) -> String;
103    /// 是否可用
104    fn is_available(&self) -> bool;
105}
106
107/// 标记特征
108pub trait Tagged {
109    /// 获取标签
110    fn tags(&self) -> Vec<String>;
111    /// 添加标签
112    fn add_tag(&mut self, tag: String);
113    /// 移除标签
114    fn remove_tag(&mut self, tag: &str);
115    /// 是否包含标签
116    fn has_tag(&self, tag: &str) -> bool;
117}