crush-core 0.3.0

High-performance parallel compression library core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Compression functionality
//!
//! Provides the public `compress()` API that compresses data using the default
//! DEFLATE plugin and wraps it with a Crush header.

use crate::cancel::CancellationToken;
use crate::error::Result;
use crate::plugin::registry::{get_default_plugin, get_plugin_by_magic};
use crate::plugin::timeout::{run_with_timeout_and_cancel_scoped, run_with_timeout_scoped};
use crate::plugin::{CrushHeader, FileMetadata, PluginSelector, ScoringWeights};
use crc32fast::Hasher;
use std::sync::Arc;
use std::time::Duration;

/// Default timeout for compression operations (0 = no timeout)
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(0);

/// Compression options for plugin selection and scoring
#[derive(Clone)]
pub struct CompressionOptions {
    /// Optional plugin name for manual override
    plugin_name: Option<String>,

    /// Scoring weights for automatic selection
    weights: ScoringWeights,

    /// Timeout for compression operation
    timeout: Duration,

    /// Optional file metadata
    file_metadata: Option<FileMetadata>,

    /// Optional cancellation token for Ctrl+C support
    cancel_token: Option<Arc<dyn CancellationToken>>,
}

impl CompressionOptions {
    /// Create new compression options with default settings
    #[must_use]
    pub fn new() -> Self {
        Self {
            plugin_name: None,
            weights: ScoringWeights::default(),
            timeout: DEFAULT_TIMEOUT,
            file_metadata: None,
            cancel_token: None,
        }
    }

    /// Specify a plugin by name (manual override)
    #[must_use]
    pub fn with_plugin(mut self, name: &str) -> Self {
        self.plugin_name = Some(name.to_string());
        self
    }

    /// Set custom scoring weights
    #[must_use]
    pub fn with_weights(mut self, weights: ScoringWeights) -> Self {
        self.weights = weights;
        self
    }

    /// Set timeout for compression operation
    #[must_use]
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set file metadata
    #[must_use]
    pub fn with_file_metadata(mut self, metadata: FileMetadata) -> Self {
        self.file_metadata = Some(metadata);
        self
    }

    /// Set cancellation token for Ctrl+C support
    #[must_use]
    pub fn with_cancel_token(mut self, token: Arc<dyn CancellationToken>) -> Self {
        self.cancel_token = Some(token);
        self
    }
}

impl std::fmt::Debug for CompressionOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CompressionOptions")
            .field("plugin_name", &self.plugin_name)
            .field("weights", &self.weights)
            .field("timeout", &self.timeout)
            .field("file_metadata", &self.file_metadata)
            .field(
                "cancel_token",
                &self.cancel_token.as_ref().map(|_| "Some(...)"),
            )
            .finish()
    }
}

impl Default for CompressionOptions {
    fn default() -> Self {
        Self::new()
    }
}

/// Compress data using the default compression algorithm
///
/// Uses the DEFLATE plugin (magic number `0x43525100`) to compress the input data.
/// The compressed output includes a 16-byte Crush header with:
/// - Magic number identifying the plugin
/// - Original uncompressed size
/// - CRC32 checksum of the compressed payload
///
/// # Errors
///
/// Returns an error if:
/// - No default plugin is available (should never happen - DEFLATE is always registered)
/// - Compression operation fails
///
/// # Examples
///
/// ```
/// use crush_core::{init_plugins, compress};
///
/// init_plugins().expect("Plugin initialization failed");
/// let data = b"Hello, world!";
/// let compressed = compress(data).expect("Compression failed");
/// assert!(!compressed.is_empty());
/// ```
pub fn compress(input: &[u8]) -> Result<Vec<u8>> {
    // Get the default DEFLATE plugin from registry
    let plugin = get_default_plugin().ok_or_else(|| {
        crate::error::PluginError::NotFound(
            "Default DEFLATE plugin not found. Call init_plugins() first.".to_string(),
        )
    })?;

    let default_magic = [0x43, 0x52, 0x01, 0x00];

    // Slice D: borrow `input` directly via a scoped thread — avoids a full-input clone on the hot path.
    let compressed_payload = std::thread::scope(|s| {
        run_with_timeout_scoped(s, DEFAULT_TIMEOUT, |cancel_flag| {
            plugin.compress(input, cancel_flag)
        })
    })?;

    // Calculate CRC32 of compressed payload
    let mut hasher = Hasher::new();
    hasher.update(&compressed_payload);
    let crc32 = hasher.finalize();

    // Create header with original size and CRC32
    let header = CrushHeader::new(default_magic, input.len() as u64).with_crc32();

    // Build final output: header + compressed payload
    let mut output = Vec::with_capacity(CrushHeader::SIZE + 4 + compressed_payload.len());
    output.extend_from_slice(&header.to_bytes());
    output.extend_from_slice(&crc32.to_le_bytes());
    output.extend_from_slice(&compressed_payload);

    Ok(output)
}

/// Compress data with custom options (plugin selection, scoring weights)
///
/// Provides fine-grained control over plugin selection through either:
/// - Manual plugin override by name
/// - Automatic selection with custom scoring weights
///
/// # Errors
///
/// Returns an error if:
/// - Specified plugin is not found (manual override)
/// - No plugins are available (automatic selection)
/// - Compression operation fails
/// - Operation exceeds the specified timeout (0 = no timeout)
///
/// # Examples
///
/// ```
/// use crush_core::{init_plugins, compress_with_options, CompressionOptions};
///
/// init_plugins().expect("Plugin initialization failed");
/// let data = b"Hello, world!";
///
/// // Use default automatic selection
/// let options = CompressionOptions::default();
/// let compressed = compress_with_options(data, &options).expect("Compression failed");
///
/// // Manual override: specify plugin by name
/// let options = CompressionOptions::default().with_plugin("deflate");
/// let compressed = compress_with_options(data, &options).expect("Compression failed");
/// ```
pub fn compress_with_options(input: &[u8], options: &CompressionOptions) -> Result<Vec<u8>> {
    // Check if already cancelled before starting
    if let Some(ref token) = options.cancel_token {
        if token.is_cancelled() {
            return Err(crate::error::CrushError::Cancelled);
        }
    }

    // Select plugin based on options
    let selector = PluginSelector::new(options.weights);

    let selected_metadata = if let Some(ref plugin_name) = options.plugin_name {
        // Manual override
        selector.select_by_name(plugin_name)?
    } else {
        // Automatic selection
        selector.select()?
    };

    // Get the actual plugin from registry
    let plugin = get_plugin_by_magic(selected_metadata.magic_number).ok_or_else(|| {
        crate::error::PluginError::NotFound(format!(
            "Plugin '{}' metadata found but not in registry",
            selected_metadata.name
        ))
    })?;

    let timeout = options.timeout;
    let cancel_token = options.cancel_token.clone();

    // Slice D: borrow `input` directly via a scoped thread — avoids a full-input clone.
    let compressed_payload = std::thread::scope(|s| {
        run_with_timeout_and_cancel_scoped(s, timeout, cancel_token, |cancel_flag| {
            plugin.compress(input, cancel_flag)
        })
    })?;

    // Handle file metadata
    let metadata_bytes = options
        .file_metadata
        .as_ref()
        .map_or(Vec::new(), super::plugin::metadata::FileMetadata::to_bytes);

    let mut payload_with_metadata = Vec::new();
    if !metadata_bytes.is_empty() {
        #[allow(clippy::cast_possible_truncation)]
        let metadata_len = metadata_bytes.len() as u16; // FileMetadata is always < 64KB
        payload_with_metadata.extend_from_slice(&metadata_len.to_le_bytes());
        payload_with_metadata.extend_from_slice(&metadata_bytes);
    }
    payload_with_metadata.extend_from_slice(&compressed_payload);

    // Calculate CRC32 of compressed payload + metadata
    let mut hasher = Hasher::new();
    hasher.update(&payload_with_metadata);
    let crc32 = hasher.finalize();

    // Create header with original size and CRC32
    let mut header =
        CrushHeader::new(selected_metadata.magic_number, input.len() as u64).with_crc32();
    if !metadata_bytes.is_empty() {
        header = header.with_metadata();
    }

    // Build final output: header + CRC32 + payload_with_metadata
    let mut output = Vec::with_capacity(CrushHeader::SIZE + 4 + payload_with_metadata.len());
    output.extend_from_slice(&header.to_bytes());
    output.extend_from_slice(&crc32.to_le_bytes());
    output.extend_from_slice(&payload_with_metadata);

    Ok(output)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::init_plugins;

    #[test]
    #[allow(clippy::unwrap_used)]
    fn test_compress_basic() {
        init_plugins().unwrap();
        let data = b"Hello, Crush!";
        let compressed = compress(data).unwrap();

        // Should have at least the header
        assert!(compressed.len() >= CrushHeader::SIZE);

        // Header should have correct magic number
        assert_eq!(&compressed[0..4], &[0x43, 0x52, 0x01, 0x00]);
    }

    #[test]
    #[allow(clippy::unwrap_used)]
    fn test_compress_empty() {
        init_plugins().unwrap();
        let data = b"";
        let compressed = compress(data).unwrap();

        // Even empty data gets a header
        assert!(compressed.len() >= CrushHeader::SIZE);
    }

    #[test]
    #[allow(clippy::unwrap_used)]
    fn test_compress_large() {
        init_plugins().unwrap();
        let data = vec![0x42; 1_000_000]; // 1MB of repeated bytes
        let compressed = compress(&data).unwrap();

        // Should compress well (repeated data)
        assert!(compressed.len() < data.len() / 2);
    }

    // CompressionOptions tests
    #[test]
    fn test_compression_options_default() {
        let options = CompressionOptions::default();
        assert_eq!(options.timeout, DEFAULT_TIMEOUT);
        assert!(options.plugin_name.is_none());
        assert!(options.file_metadata.is_none());
        assert!(options.cancel_token.is_none());
    }

    #[test]
    fn test_compression_options_new() {
        let options = CompressionOptions::new();
        assert_eq!(options.timeout, DEFAULT_TIMEOUT);
    }

    #[test]
    fn test_compression_options_with_plugin() {
        let options = CompressionOptions::new().with_plugin("deflate");
        assert_eq!(options.plugin_name, Some("deflate".to_string()));
    }

    #[test]
    fn test_compression_options_with_weights() {
        let weights = ScoringWeights {
            throughput: 0.5,
            compression_ratio: 0.5,
        };
        let options = CompressionOptions::new().with_weights(weights);
        assert!((options.weights.throughput - 0.5).abs() < f64::EPSILON);
        assert!((options.weights.compression_ratio - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_compression_options_with_timeout() {
        let timeout = Duration::from_secs(10);
        let options = CompressionOptions::new().with_timeout(timeout);
        assert_eq!(options.timeout, timeout);
    }

    #[test]
    fn test_compression_options_with_file_metadata() {
        let metadata = FileMetadata {
            mtime: Some(1_234_567_890),
            #[cfg(unix)]
            permissions: Some(0o644),
        };
        let options = CompressionOptions::new().with_file_metadata(metadata);
        assert!(options.file_metadata.is_some());
    }

    #[test]
    fn test_compression_options_with_cancel_token() {
        use crate::cancel::AtomicCancellationToken;
        let token: Arc<dyn CancellationToken> = Arc::new(AtomicCancellationToken::new());
        let options = CompressionOptions::new().with_cancel_token(token);
        assert!(options.cancel_token.is_some());
    }

    #[test]
    fn test_compression_options_debug() {
        let options = CompressionOptions::new().with_plugin("test");
        let debug_str = format!("{options:?}");
        assert!(debug_str.contains("CompressionOptions"));
        assert!(debug_str.contains("test"));
    }

    // compress_with_options tests
    #[test]
    #[allow(clippy::unwrap_used)]
    fn test_compress_with_options_default() {
        init_plugins().unwrap();
        let data = b"Test data for compression";
        let options = CompressionOptions::default();
        let compressed = compress_with_options(data, &options).unwrap();

        assert!(compressed.len() >= CrushHeader::SIZE);
    }

    #[test]
    #[allow(clippy::unwrap_used)]
    fn test_compress_with_options_manual_plugin() {
        init_plugins().unwrap();
        let data = b"Test data";
        let options = CompressionOptions::default().with_plugin("deflate");
        let compressed = compress_with_options(data, &options).unwrap();

        assert!(compressed.len() >= CrushHeader::SIZE);
        assert_eq!(&compressed[0..4], &[0x43, 0x52, 0x01, 0x00]); // DEFLATE magic
    }

    #[test]
    #[allow(clippy::unwrap_used)]
    fn test_compress_with_options_invalid_plugin() {
        init_plugins().unwrap();
        let data = b"Test data";
        let options = CompressionOptions::default().with_plugin("nonexistent");
        let result = compress_with_options(data, &options);

        assert!(result.is_err());
    }

    #[test]
    #[allow(clippy::unwrap_used)]
    fn test_compress_with_options_with_metadata() {
        init_plugins().unwrap();
        let data = b"Test data with metadata";
        let metadata = FileMetadata {
            mtime: Some(1_234_567_890),
            #[cfg(unix)]
            permissions: Some(0o644),
        };
        let options = CompressionOptions::default().with_file_metadata(metadata);
        let compressed = compress_with_options(data, &options).unwrap();

        // Should have header + metadata
        assert!(compressed.len() > CrushHeader::SIZE + 4); // +4 for metadata length
    }

    #[test]
    #[allow(clippy::unwrap_used)]
    fn test_compress_with_options_cancellation() {
        use crate::cancel::AtomicCancellationToken;

        init_plugins().unwrap();
        let data = b"Test data";
        let token = Arc::new(AtomicCancellationToken::new());
        token.cancel(); // Cancel before compression

        let options = CompressionOptions::default().with_cancel_token(token);
        let result = compress_with_options(data, &options);

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            crate::error::CrushError::Cancelled
        ));
    }

    #[test]
    #[allow(clippy::unwrap_used)]
    fn test_compress_with_options_timeout() {
        init_plugins().unwrap();
        let data = vec![0u8; 10_000_000]; // Large data
        let options = CompressionOptions::default().with_timeout(Duration::from_nanos(1)); // Extremely short timeout

        let result = compress_with_options(&data, &options);
        // May succeed or timeout depending on system speed
        // Just verify it doesn't panic
        let _ = result;
    }

    #[test]
    #[allow(clippy::unwrap_used)]
    fn test_compress_with_options_zero_timeout() {
        init_plugins().unwrap();
        let data = b"Test with no timeout";
        let options = CompressionOptions::default().with_timeout(Duration::from_secs(0)); // No timeout

        let result = compress_with_options(data, &options);
        assert!(result.is_ok());
    }

    #[test]
    #[allow(clippy::unwrap_used)]
    fn test_compress_roundtrip_with_options() {
        use crate::decompress;

        init_plugins().unwrap();
        let original = b"Roundtrip test data with options";
        let options = CompressionOptions::default();
        let compressed = compress_with_options(original, &options).unwrap();
        let result = decompress(&compressed).unwrap();

        assert_eq!(result.data, original);
    }

    #[test]
    #[allow(clippy::unwrap_used)]
    fn test_compression_options_builder_chain() {
        use crate::cancel::AtomicCancellationToken;

        let metadata = FileMetadata {
            mtime: Some(1_234_567_890),
            #[cfg(unix)]
            permissions: Some(0o644),
        };
        let weights = ScoringWeights {
            throughput: 0.7,
            compression_ratio: 0.3,
        };
        let token: Arc<dyn CancellationToken> = Arc::new(AtomicCancellationToken::new());

        // Test method chaining
        let options = CompressionOptions::new()
            .with_plugin("deflate")
            .with_weights(weights)
            .with_timeout(Duration::from_secs(30))
            .with_file_metadata(metadata)
            .with_cancel_token(token);

        assert_eq!(options.plugin_name, Some("deflate".to_string()));
        assert!((options.weights.throughput - 0.7).abs() < f64::EPSILON);
        assert_eq!(options.timeout, Duration::from_secs(30));
        assert!(options.file_metadata.is_some());
        assert!(options.cancel_token.is_some());
    }
}