Skip to main content

haagenti_lz4/
compress.rs

1//! LZ4 compressor implementation.
2//!
3//! This module provides both standard LZ4 compression and LZ4-HC (high compression)
4//! when the `hc` feature is enabled.
5//!
6//! ## Compression Level Mapping
7//!
8//! - `None`: No compression (passthrough)
9//! - `Fast`: Standard LZ4 (fastest)
10//! - `Default`: Standard LZ4
11//! - `Best`: LZ4-HC level 9 (if `hc` feature enabled, else standard LZ4)
12//! - `Ultra`: LZ4-HC level 9 (if `hc` feature enabled, else standard LZ4)
13//! - `Custom(1-3)`: Standard LZ4
14//! - `Custom(4-9)`: LZ4-HC at that level (if `hc` feature enabled)
15
16use haagenti_core::{
17    Algorithm, CompressionLevel, CompressionStats, Compressor, Flush, Result, StreamingCompressor,
18};
19
20use crate::block::{compress_block, max_compressed_size};
21
22/// LZ4 compressor.
23#[derive(Debug, Clone)]
24pub struct Lz4Compressor {
25    level: CompressionLevel,
26    stats: Option<CompressionStats>,
27}
28
29impl Lz4Compressor {
30    /// Create a new LZ4 compressor with default settings.
31    pub fn new() -> Self {
32        Self {
33            level: CompressionLevel::Default,
34            stats: None,
35        }
36    }
37
38    /// Create a new LZ4 compressor with specified level.
39    pub fn with_level(level: CompressionLevel) -> Self {
40        Self { level, stats: None }
41    }
42}
43
44impl Default for Lz4Compressor {
45    fn default() -> Self {
46        Self::new()
47    }
48}
49
50impl Compressor for Lz4Compressor {
51    fn algorithm(&self) -> Algorithm {
52        Algorithm::Lz4
53    }
54
55    fn level(&self) -> CompressionLevel {
56        self.level
57    }
58
59    fn compress(&self, input: &[u8]) -> Result<Vec<u8>> {
60        let start = std::time::Instant::now();
61
62        let max_size = max_compressed_size(input.len());
63        let mut output = vec![0u8; max_size];
64
65        let compressed_len = self.compress_to(input, &mut output)?;
66        output.truncate(compressed_len);
67
68        let elapsed = start.elapsed();
69
70        // Store stats (in a real implementation, this would be thread-safe)
71        let _stats = CompressionStats::from_operation(
72            Algorithm::Lz4,
73            input.len(),
74            compressed_len,
75            elapsed.as_micros() as u64,
76        );
77
78        Ok(output)
79    }
80
81    fn compress_to(&self, input: &[u8], output: &mut [u8]) -> Result<usize> {
82        // Determine if we should use HC
83        #[cfg(feature = "hc")]
84        {
85            let hc_level = match self.level {
86                CompressionLevel::Best => Some(9),
87                CompressionLevel::Ultra => Some(9),
88                CompressionLevel::Custom(l) if l >= 4 => Some(l.min(9) as usize),
89                _ => None,
90            };
91
92            if let Some(level) = hc_level {
93                return crate::hc::compress_hc(input, output, level);
94            }
95        }
96
97        // Fall back to standard LZ4
98        compress_block(input, output)
99    }
100
101    fn max_compressed_size(&self, input_len: usize) -> usize {
102        max_compressed_size(input_len)
103    }
104
105    fn stats(&self) -> Option<CompressionStats> {
106        self.stats.clone()
107    }
108}
109
110/// Streaming LZ4 compressor.
111#[derive(Debug)]
112pub struct Lz4StreamingCompressor {
113    #[allow(dead_code)] // Reserved for future LZ4-HC support
114    level: CompressionLevel,
115    buffer: Vec<u8>,
116    block_size: usize,
117    started: bool,
118}
119
120impl Lz4StreamingCompressor {
121    /// Create a new streaming compressor.
122    pub fn new() -> Self {
123        Self {
124            level: CompressionLevel::Default,
125            buffer: Vec::new(),
126            block_size: 65536, // 64KB blocks
127            started: false,
128        }
129    }
130
131    /// Create with specified block size.
132    pub fn with_block_size(block_size: usize) -> Self {
133        Self {
134            level: CompressionLevel::Default,
135            buffer: Vec::with_capacity(block_size),
136            block_size,
137            started: false,
138        }
139    }
140}
141
142impl Default for Lz4StreamingCompressor {
143    fn default() -> Self {
144        Self::new()
145    }
146}
147
148impl StreamingCompressor for Lz4StreamingCompressor {
149    fn algorithm(&self) -> Algorithm {
150        Algorithm::Lz4
151    }
152
153    fn begin(&mut self) -> Result<()> {
154        self.buffer.clear();
155        self.started = true;
156        Ok(())
157    }
158
159    fn compress_chunk(
160        &mut self,
161        input: &[u8],
162        output: &mut [u8],
163        flush: Flush,
164    ) -> Result<(usize, usize)> {
165        // Add input to buffer
166        self.buffer.extend_from_slice(input);
167        let bytes_read = input.len();
168        let mut bytes_written = 0;
169
170        // Compress full blocks
171        while self.buffer.len() >= self.block_size || matches!(flush, Flush::Finish | Flush::Sync) {
172            let to_compress = self.buffer.len().min(self.block_size);
173            if to_compress == 0 {
174                break;
175            }
176
177            let chunk = &self.buffer[..to_compress];
178            let written = compress_block(chunk, &mut output[bytes_written..])?;
179            bytes_written += written;
180
181            self.buffer.drain(..to_compress);
182
183            if self.buffer.is_empty() {
184                break;
185            }
186        }
187
188        Ok((bytes_read, bytes_written))
189    }
190
191    fn finish(&mut self, output: &mut [u8]) -> Result<usize> {
192        if self.buffer.is_empty() {
193            return Ok(0);
194        }
195
196        let written = compress_block(&self.buffer, output)?;
197        self.buffer.clear();
198        self.started = false;
199        Ok(written)
200    }
201
202    fn reset(&mut self) {
203        self.buffer.clear();
204        self.started = false;
205    }
206}