flare_core/common/compression/traits.rs
1//! 压缩器 Trait 定义
2//!
3//! 定义标准压缩接口,方便用户实现自定义压缩算法
4
5use super::algorithms::CompressionAlgorithm;
6use crate::common::error::Result;
7
8/// 压缩器标准接口
9///
10/// 实现此 trait 以支持自定义压缩算法
11///
12/// # 示例
13///
14/// ```rust
15/// use flare_core::common::compression::{Compressor, CompressionAlgorithm};
16/// use flare_core::common::error::Result;
17///
18/// struct MyCustomCompressor;
19///
20/// impl Compressor for MyCustomCompressor {
21/// fn compress(&self, data: &[u8]) -> Result<Vec<u8>> {
22/// // 实现压缩逻辑
23/// Ok(data.to_vec())
24/// }
25///
26/// fn decompress(&self, data: &[u8]) -> Result<Vec<u8>> {
27/// // 实现解压逻辑
28/// Ok(data.to_vec())
29/// }
30///
31/// fn algorithm(&self) -> CompressionAlgorithm {
32/// CompressionAlgorithm::None
33/// }
34///
35/// fn name(&self) -> &'static str {
36/// "my_custom"
37/// }
38///
39/// fn can_detect(&self, data: &[u8]) -> bool {
40/// // 实现魔数检测逻辑
41/// false
42/// }
43/// }
44/// ```
45pub trait Compressor: Send + Sync {
46 /// 压缩数据
47 ///
48 /// # 参数
49 /// - `data`: 要压缩的原始数据
50 ///
51 /// # 返回
52 /// 压缩后的数据
53 fn compress(&self, data: &[u8]) -> Result<Vec<u8>>;
54
55 /// 解压数据
56 ///
57 /// # 参数
58 /// - `data`: 要解压的压缩数据
59 ///
60 /// # 返回
61 /// 解压后的原始数据
62 fn decompress(&self, data: &[u8]) -> Result<Vec<u8>>;
63
64 /// 获取压缩算法类型
65 fn algorithm(&self) -> CompressionAlgorithm;
66
67 /// 获取压缩器名称(用于注册和查找)
68 ///
69 /// 名称应该是唯一的,用于在注册表中标识压缩器
70 fn name(&self) -> &'static str {
71 // 注意:由于 algorithm() 返回的 CompressionAlgorithm 可能包含 Custom(String),
72 // 这里需要特殊处理。对于内置算法,返回静态字符串;对于自定义算法,需要在实现中覆盖此方法
73 match self.algorithm() {
74 CompressionAlgorithm::None => "none",
75 CompressionAlgorithm::Gzip => "gzip",
76 CompressionAlgorithm::Zstd => "zstd",
77 CompressionAlgorithm::Custom(_) => {
78 // 自定义算法必须在实现中覆盖 name() 方法
79 panic!("Custom compression algorithm must override name() method")
80 }
81 }
82 }
83
84 /// 检测数据是否使用此压缩算法(通过魔数等)
85 ///
86 /// # 参数
87 /// - `data`: 待检测的数据(通常是数据的前几个字节)
88 ///
89 /// # 返回
90 /// 如果数据可能是由此压缩器压缩的,返回 `true`
91 fn can_detect(&self, _data: &[u8]) -> bool {
92 false
93 }
94}