Skip to main content

oxirs_cluster/compression/
codecs.rs

1//! Compression codec implementations for oxirs-cluster.
2//!
3//! Provides a `Compressor` trait with four built-in implementations:
4//! - `IdentityCodec` — no-op, always available
5//! - `RleCodec`      — pure-Rust run-length encoding for repetitive data
6//! - `Lz4Codec`      — fast LZ4 via oxiarc-lz4 (Pure Rust)
7//! - `ZstdCodec`     — balanced Zstandard via oxiarc-zstd (Pure Rust)
8
9use thiserror::Error;
10
11/// Error type for all codec operations.
12#[derive(Debug, Error)]
13pub enum CompressionError {
14    /// Compression produced an error.
15    #[error("Compression failed: {0}")]
16    CompressFailed(String),
17    /// Decompression produced an error.
18    #[error("Decompression failed: {0}")]
19    DecompressFailed(String),
20    /// The requested codec name is not in the registry.
21    #[error("Unknown codec: {0}")]
22    UnknownCodec(String),
23}
24
25/// Trait that every codec must implement.
26///
27/// Implementations must be `Send + Sync` so they can be stored in an `Arc`
28/// and shared across threads.
29pub trait Compressor: Send + Sync {
30    /// Short stable identifier for this codec (e.g. `"identity"`, `"rle"`).
31    fn name(&self) -> &'static str;
32
33    /// Compress `data` and return the compressed bytes.
34    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, CompressionError>;
35
36    /// Decompress `data` and return the original bytes.
37    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, CompressionError>;
38}
39
40// ---------------------------------------------------------------------------
41// Identity codec
42// ---------------------------------------------------------------------------
43
44/// Identity (no-op) codec.  The safe default — data is returned unchanged.
45pub struct IdentityCodec;
46
47impl Compressor for IdentityCodec {
48    fn name(&self) -> &'static str {
49        "identity"
50    }
51
52    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, CompressionError> {
53        Ok(data.to_vec())
54    }
55
56    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, CompressionError> {
57        Ok(data.to_vec())
58    }
59}
60
61// ---------------------------------------------------------------------------
62// RLE codec
63// ---------------------------------------------------------------------------
64
65/// Simple run-length encoding codec (pure Rust, no external crate).
66///
67/// # Wire format
68/// A sequence of `[count: u8][byte: u8]` pairs where `count ∈ [1, 255]`.
69/// Runs longer than 255 bytes are split into multiple pairs.
70pub struct RleCodec;
71
72impl Compressor for RleCodec {
73    fn name(&self) -> &'static str {
74        "rle"
75    }
76
77    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, CompressionError> {
78        if data.is_empty() {
79            return Ok(Vec::new());
80        }
81
82        let mut out = Vec::with_capacity(data.len().min(data.len() * 2 / 3 + 16));
83        let mut i = 0usize;
84
85        while i < data.len() {
86            let byte = data[i];
87            let mut count: u8 = 1;
88            while i + (count as usize) < data.len()
89                && data[i + (count as usize)] == byte
90                && count < u8::MAX
91            {
92                count += 1;
93            }
94            out.push(count);
95            out.push(byte);
96            i += count as usize;
97        }
98        Ok(out)
99    }
100
101    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, CompressionError> {
102        if data.is_empty() {
103            return Ok(Vec::new());
104        }
105        if data.len() % 2 != 0 {
106            return Err(CompressionError::DecompressFailed(
107                "RLE data length must be even".into(),
108            ));
109        }
110
111        let capacity: usize = data.chunks_exact(2).map(|c| c[0] as usize).sum();
112        let mut out = Vec::with_capacity(capacity);
113
114        for chunk in data.chunks_exact(2) {
115            let count = chunk[0] as usize;
116            let byte = chunk[1];
117            out.extend(std::iter::repeat(byte).take(count));
118        }
119        Ok(out)
120    }
121}
122
123// ---------------------------------------------------------------------------
124// LZ4 codec (oxiarc-lz4 — Pure Rust)
125// ---------------------------------------------------------------------------
126
127/// LZ4 codec backed by `oxiarc-lz4` (Pure Rust, no C).
128///
129/// Optimised for **fast** compression and decompression at moderate ratios.
130pub struct Lz4Codec;
131
132impl Compressor for Lz4Codec {
133    fn name(&self) -> &'static str {
134        "lz4"
135    }
136
137    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, CompressionError> {
138        oxiarc_lz4::compress(data)
139            .map_err(|e| CompressionError::CompressFailed(format!("LZ4: {e}")))
140    }
141
142    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, CompressionError> {
143        // Allow up to 256 MiB decompressed output
144        oxiarc_lz4::decompress(data, 256 * 1024 * 1024)
145            .map_err(|e| CompressionError::DecompressFailed(format!("LZ4: {e}")))
146    }
147}
148
149// ---------------------------------------------------------------------------
150// Zstd codec (oxiarc-zstd — Pure Rust)
151// ---------------------------------------------------------------------------
152
153/// Zstandard codec backed by `oxiarc-zstd` (Pure Rust, no C).
154///
155/// Compression level 3 is the default (balanced speed/ratio).
156pub struct ZstdCodec {
157    level: i32,
158}
159
160impl ZstdCodec {
161    /// Create a new Zstd codec with a specific compression level (1-21).
162    pub fn new(level: i32) -> Self {
163        ZstdCodec { level }
164    }
165
166    /// Create with the default level (3).
167    pub fn default_level() -> Self {
168        ZstdCodec { level: 3 }
169    }
170}
171
172impl Compressor for ZstdCodec {
173    fn name(&self) -> &'static str {
174        "zstd"
175    }
176
177    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, CompressionError> {
178        oxiarc_zstd::encode_all(data, self.level)
179            .map_err(|e| CompressionError::CompressFailed(format!("Zstd: {e}")))
180    }
181
182    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, CompressionError> {
183        oxiarc_zstd::decode_all(data)
184            .map_err(|e| CompressionError::DecompressFailed(format!("Zstd: {e}")))
185    }
186}
187
188// ---------------------------------------------------------------------------
189// Tests
190// ---------------------------------------------------------------------------
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    // --- IdentityCodec ---
197
198    #[test]
199    fn identity_empty() {
200        let c = IdentityCodec;
201        let d = c.compress(&[]).unwrap();
202        assert_eq!(c.decompress(&d).unwrap(), Vec::<u8>::new());
203    }
204
205    #[test]
206    fn identity_round_trip() {
207        let c = IdentityCodec;
208        let data: Vec<u8> = (0u8..=255).collect();
209        assert_eq!(c.decompress(&c.compress(&data).unwrap()).unwrap(), data);
210    }
211
212    // --- RleCodec ---
213
214    #[test]
215    fn rle_empty() {
216        let c = RleCodec;
217        assert_eq!(c.compress(&[]).unwrap(), Vec::<u8>::new());
218        assert_eq!(c.decompress(&[]).unwrap(), Vec::<u8>::new());
219    }
220
221    #[test]
222    fn rle_single_run() {
223        let c = RleCodec;
224        let data = vec![0u8; 100];
225        let enc = c.compress(&data).unwrap();
226        assert_eq!(enc, vec![100u8, 0u8]);
227        assert_eq!(c.decompress(&enc).unwrap(), data);
228    }
229
230    #[test]
231    fn rle_round_trip_all_unique() {
232        let c = RleCodec;
233        let data: Vec<u8> = (0u8..=127).collect();
234        assert_eq!(c.decompress(&c.compress(&data).unwrap()).unwrap(), data);
235    }
236
237    #[test]
238    fn rle_compresses_repetitive() {
239        let c = RleCodec;
240        let data = vec![42u8; 200];
241        let enc = c.compress(&data).unwrap();
242        // Should be encoded as two pairs: [255, 42, 42, 42] (split at 255 + 200-255 overflow)
243        // i.e. [200, 42] would be the case if count < 255
244        // 200 < 255 so single pair [200, 42]
245        assert_eq!(enc.len(), 2);
246        assert!(enc.len() < data.len());
247        assert_eq!(c.decompress(&enc).unwrap(), data);
248    }
249
250    #[test]
251    fn rle_decompression_odd_input_error() {
252        let c = RleCodec;
253        let result = c.decompress(&[1u8]);
254        assert!(result.is_err());
255    }
256
257    // --- Lz4Codec ---
258
259    #[test]
260    fn lz4_empty() {
261        let c = Lz4Codec;
262        let enc = c.compress(&[]).unwrap();
263        assert_eq!(c.decompress(&enc).unwrap(), Vec::<u8>::new());
264    }
265
266    #[test]
267    fn lz4_round_trip_repetitive() {
268        let c = Lz4Codec;
269        let data = b"hello world ".repeat(500);
270        let enc = c.compress(&data).unwrap();
271        assert!(enc.len() < data.len());
272        assert_eq!(c.decompress(&enc).unwrap(), data);
273    }
274
275    #[test]
276    fn lz4_round_trip_diverse() {
277        let c = Lz4Codec;
278        let data: Vec<u8> = (0u8..=255).cycle().take(1024).collect();
279        assert_eq!(c.decompress(&c.compress(&data).unwrap()).unwrap(), data);
280    }
281
282    // --- ZstdCodec ---
283
284    #[test]
285    fn zstd_empty() {
286        let c = ZstdCodec::default_level();
287        let enc = c.compress(&[]).unwrap();
288        assert_eq!(c.decompress(&enc).unwrap(), Vec::<u8>::new());
289    }
290
291    #[test]
292    fn zstd_round_trip_repetitive() {
293        let c = ZstdCodec::new(3);
294        let data = b"oxirs cluster ".repeat(500);
295        let enc = c.compress(&data).unwrap();
296        assert!(enc.len() < data.len());
297        assert_eq!(c.decompress(&enc).unwrap(), data);
298    }
299
300    #[test]
301    fn zstd_round_trip_diverse() {
302        let c = ZstdCodec::default_level();
303        let data: Vec<u8> = (0u8..=255).cycle().take(2048).collect();
304        assert_eq!(c.decompress(&c.compress(&data).unwrap()).unwrap(), data);
305    }
306}