geezipx-core 0.5.0

Compression/decompression core engine for GeeZipX
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
517
518
519
520
521
522
523
//! Single-stream XZ and LZMA compression and decompression helpers.
//!
//! These functions work on a single byte stream — they do **not**
//! implement [`ArchiveReader`] or [`ArchiveWriter`] because xz and lzma are
//! compression formats, not archive containers.
//!
//! [`ArchiveReader`]: super::ArchiveReader
//! [`ArchiveWriter`]: super::ArchiveWriter

use std::io::{Read, Write};

use crate::config::CompressOptions;
use crate::error::{GeeZipError, GeeZipResult};

// ---------------------------------------------------------------------------
// XZ helpers
// ---------------------------------------------------------------------------

/// Compress data from `reader` into `writer` using XZ at the given level.
///
/// `level` controls the XZ compression strength:
/// - `None`: use the default level (6).
/// - `Some(0)`: no compression (store only).
/// - `Some(1)`: fastest compression.
/// - `Some(6)`: default (good balance).
/// - `Some(9)`: best compression ratio (slowest).
///
/// Returns the number of bytes read from the source (uncompressed size).
pub fn xz_compress_with_level<R: Read, W: Write>(
    reader: &mut R,
    writer: W,
    level: Option<u32>,
) -> GeeZipResult<u64> {
    let lvl = level.unwrap_or(6);
    let mut encoder = xz2::write::XzEncoder::new(writer, lvl);
    let bytes = std::io::copy(reader, &mut encoder)
        .map_err(|e| GeeZipError::io(e, "xz compression failed"))?;
    encoder
        .finish()
        .map_err(|e| GeeZipError::io(e, "xz compression finalisation failed"))?;
    Ok(bytes)
}

/// Compress data from `reader` into `writer` using XZ with full options.
///
/// Currently only `options.level` is applied; `options.jobs` is accepted
/// but ignored because the `xz2` crate does not expose a stable
/// multi-threaded XZ encoder API in its current version.
///
/// TODO: Revisit when `xz2` gets an `XzEncoder::new_with_options` or
/// equivalent multithread API, or when we migrate to a more featureful
/// xz binding (`liblzma` / `lzma-sys`).
///
/// Returns the number of bytes read from the source (uncompressed size).
pub fn xz_compress_with_options<R: Read, W: Write>(
    reader: &mut R,
    writer: W,
    options: CompressOptions,
) -> GeeZipResult<u64> {
    // TODO: apply options.effective_jobs() when xz2 supports multithread.
    xz_compress_with_level(reader, writer, options.level)
}

/// Compress data from `reader` into `writer` using XZ with the default level.
///
/// Returns the number of bytes read from the source (uncompressed size).
pub fn xz_compress<R: Read, W: Write>(reader: &mut R, writer: W) -> GeeZipResult<u64> {
    xz_compress_with_level(reader, writer, None)
}

/// Decompress XZ-compressed data from `reader` into `writer`.
///
/// Returns the number of bytes written to the output (decompressed size).
pub fn xz_decompress<R: Read, W: Write>(reader: &mut R, writer: &mut W) -> GeeZipResult<u64> {
    let mut decoder = xz2::read::XzDecoder::new_multi_decoder(reader);
    let bytes = std::io::copy(&mut decoder, writer)
        .map_err(|e| GeeZipError::io(e, "xz decompression failed"))?;
    Ok(bytes)
}

// ---------------------------------------------------------------------------
// LZMA helpers
// ---------------------------------------------------------------------------

/// Compress data from `reader` into `writer` using LZMA at the given level.
///
/// `level` controls the LZMA compression strength:
/// - `None`: use the default level (6).
/// - `Some(0)`: no compression.
/// - `Some(1..=9)`: specific compression level.
///
/// Returns the number of bytes read from the source (uncompressed size).
pub fn lzma_compress_with_level<R: Read, W: Write>(
    reader: &mut R,
    writer: W,
    level: Option<u32>,
) -> GeeZipResult<u64> {
    let lvl = level.unwrap_or(6);
    let options = xz2::stream::LzmaOptions::new_preset(lvl)
        .map_err(|e| GeeZipError::io(e.into(), "lzma options init failed"))?;
    let stream = xz2::stream::Stream::new_lzma_encoder(&options)
        .map_err(|e| GeeZipError::io(e.into(), "lzma stream init failed"))?;
    let mut encoder = xz2::write::XzEncoder::new_stream(writer, stream);
    let bytes = std::io::copy(reader, &mut encoder)
        .map_err(|e| GeeZipError::io(e, "lzma compression failed"))?;
    encoder
        .finish()
        .map_err(|e| GeeZipError::io(e, "lzma compression finalisation failed"))?;
    Ok(bytes)
}

/// Compress data from `reader` into `writer` using LZMA with full options.
///
/// Currently only `options.level` is applied; `options.jobs` is accepted
/// but ignored (LZMA is inherently single-stream, no multithread encoder
/// support is expected).
///
/// Returns the number of bytes read from the source (uncompressed size).
pub fn lzma_compress_with_options<R: Read, W: Write>(
    reader: &mut R,
    writer: W,
    options: CompressOptions,
) -> GeeZipResult<u64> {
    lzma_compress_with_level(reader, writer, options.level)
}

/// Compress data from `reader` into `writer` using LZMA with the default level.
///
/// Returns the number of bytes read from the source (uncompressed size).
pub fn lzma_compress<R: Read, W: Write>(reader: &mut R, writer: W) -> GeeZipResult<u64> {
    lzma_compress_with_level(reader, writer, None)
}

/// Decompress LZMA-compressed data from `reader` into `writer`.
///
/// Returns the number of bytes written to the output (decompressed size).
pub fn lzma_decompress<R: Read, W: Write>(reader: &mut R, writer: &mut W) -> GeeZipResult<u64> {
    let stream = xz2::stream::Stream::new_lzma_decoder(u64::MAX)
        .map_err(|e| GeeZipError::io(e.into(), "lzma decompression init failed"))?;
    let mut decoder = xz2::read::XzDecoder::new_stream(reader, stream);
    let bytes = std::io::copy(&mut decoder, writer)
        .map_err(|e| GeeZipError::io(e, "lzma decompression failed"))?;
    Ok(bytes)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    // ---------------------------------------------------------------
    // XZ tests
    // ---------------------------------------------------------------

    #[test]
    fn xz_roundtrip() {
        let original = b"Hello, GeeZipX! This is a test of xz compression.";
        let mut source = Cursor::new(original.as_slice());

        let compressed = {
            let mut buf = Vec::new();
            xz_compress(&mut source, &mut buf).unwrap();
            buf
        };

        assert!(
            !compressed.is_empty(),
            "compressed output should not be empty"
        );
        // XZ magic: 0xFD 0x37 0x7A 0x58 0x5A 0x00
        assert_eq!(
            &compressed[..6],
            &[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00],
            "xz magic expected"
        );

        // Decompress
        let mut decompressed = Vec::new();
        let mut compressed_reader = Cursor::new(compressed.as_slice());
        let bytes = xz_decompress(&mut compressed_reader, &mut decompressed).unwrap();

        assert_eq!(bytes, original.len() as u64);
        assert_eq!(decompressed, original);
    }

    #[test]
    fn xz_empty_data() {
        let mut source = Cursor::new(b"");
        let compressed = {
            let mut buf = Vec::new();
            xz_compress(&mut source, &mut buf).unwrap();
            buf
        };

        assert!(
            !compressed.is_empty(),
            "empty data should still produce xz stream"
        );

        let mut decompressed = Vec::new();
        let mut compressed_reader = Cursor::new(compressed.as_slice());
        let bytes = xz_decompress(&mut compressed_reader, &mut decompressed).unwrap();

        assert_eq!(bytes, 0);
        assert!(decompressed.is_empty());
    }

    #[test]
    fn xz_corrupted_data_fails() {
        let bad_data = b"this is not xz data at all!";
        let mut reader = Cursor::new(bad_data.as_slice());
        let mut output = Vec::new();

        let err = xz_decompress(&mut reader, &mut output).unwrap_err();
        let msg = err.to_string().to_lowercase();
        assert!(
            msg.contains("xz") || msg.contains("io") || msg.contains("invalid"),
            "expected xz/io error, got: {err}"
        );
    }

    #[test]
    fn xz_large_data() {
        // 1 MB of repeating data
        let original = vec![0xABu8; 1_048_576];
        let mut source = Cursor::new(original.as_slice());

        let compressed = {
            let mut buf = Vec::new();
            xz_compress(&mut source, &mut buf).unwrap();
            buf
        };

        assert!(
            compressed.len() < original.len(),
            "compressed size ({}) should be less than original ({}) for repetitive data",
            compressed.len(),
            original.len()
        );

        let mut decompressed = Vec::new();
        let mut compressed_reader = Cursor::new(compressed.as_slice());
        let bytes = xz_decompress(&mut compressed_reader, &mut decompressed).unwrap();

        assert_eq!(bytes, original.len() as u64);
        assert_eq!(decompressed, original);
    }

    #[test]
    fn xz_with_level_9() {
        let original = b"Hello, GeeZipX! Level 9 xz compression test data.";
        let mut source = Cursor::new(original.as_slice());

        let compressed = {
            let mut buf = Vec::new();
            xz_compress_with_level(&mut source, &mut buf, Some(9)).unwrap();
            buf
        };

        assert!(!compressed.is_empty());
        assert_eq!(
            &compressed[..6],
            &[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00],
            "xz magic expected"
        );

        let mut decompressed = Vec::new();
        let mut compressed_reader = Cursor::new(compressed.as_slice());
        xz_decompress(&mut compressed_reader, &mut decompressed).unwrap();
        assert_eq!(decompressed, original);
    }

    #[test]
    fn xz_with_level_0() {
        let original = b"Hello, GeeZipX! Level 0 (store) xz test.";
        let mut source = Cursor::new(original.as_slice());

        let compressed = {
            let mut buf = Vec::new();
            xz_compress_with_level(&mut source, &mut buf, Some(0)).unwrap();
            buf
        };

        assert!(!compressed.is_empty());
        assert_eq!(
            &compressed[..6],
            &[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00],
            "xz magic expected"
        );

        let mut decompressed = Vec::new();
        let mut compressed_reader = Cursor::new(compressed.as_slice());
        xz_decompress(&mut compressed_reader, &mut decompressed).unwrap();
        assert_eq!(decompressed, original);
    }

    #[test]
    fn xz_level_none_falls_back_to_default() {
        let original = b"GeeZipX default xz level test.";
        let mut source = Cursor::new(original.as_slice());

        let compressed_default = {
            let mut buf = Vec::new();
            xz_compress(&mut source, &mut buf).unwrap();
            buf
        };

        source.set_position(0);
        let compressed_with_level = {
            let mut buf = Vec::new();
            xz_compress_with_level(&mut source, &mut buf, None).unwrap();
            buf
        };

        assert!(!compressed_default.is_empty());
        assert!(!compressed_with_level.is_empty());

        // Both should decompress correctly
        let mut out1 = Vec::new();
        let mut reader1 = Cursor::new(compressed_default.as_slice());
        xz_decompress(&mut reader1, &mut out1).unwrap();
        assert_eq!(out1, original);

        let mut out2 = Vec::new();
        let mut reader2 = Cursor::new(compressed_with_level.as_slice());
        xz_decompress(&mut reader2, &mut out2).unwrap();
        assert_eq!(out2, original);
    }

    #[test]
    fn xz_truncated_stream_fails() {
        // Valid XZ magic but truncated body.
        let truncated = b"\xFD\x37\x7A\x58\x5A\x00\x00\x00";
        let mut reader = std::io::Cursor::new(truncated.as_slice());
        let mut output = Vec::new();

        let err = xz_decompress(&mut reader, &mut output).unwrap_err();
        let msg = err.to_string().to_lowercase();
        assert!(
            msg.contains("xz") || msg.contains("io") || msg.contains("invalid"),
            "expected xz/io error for truncated xz stream, got: {err}"
        );
    }

    // ---------------------------------------------------------------
    // LZMA tests
    // ---------------------------------------------------------------

    #[test]
    fn lzma_roundtrip() {
        let original = b"Hello, GeeZipX! This is a test of lzma compression.";
        let mut source = Cursor::new(original.as_slice());

        let compressed = {
            let mut buf = Vec::new();
            lzma_compress(&mut source, &mut buf).unwrap();
            buf
        };

        assert!(
            !compressed.is_empty(),
            "compressed output should not be empty"
        );

        // Decompress
        let mut decompressed = Vec::new();
        let mut compressed_reader = Cursor::new(compressed.as_slice());
        let bytes = lzma_decompress(&mut compressed_reader, &mut decompressed).unwrap();

        assert_eq!(bytes, original.len() as u64);
        assert_eq!(decompressed, original);
    }

    #[test]
    fn lzma_empty_data() {
        let mut source = Cursor::new(b"");
        let compressed = {
            let mut buf = Vec::new();
            lzma_compress(&mut source, &mut buf).unwrap();
            buf
        };

        assert!(
            !compressed.is_empty(),
            "empty data should still produce lzma stream"
        );

        let mut decompressed = Vec::new();
        let mut compressed_reader = Cursor::new(compressed.as_slice());
        let bytes = lzma_decompress(&mut compressed_reader, &mut decompressed).unwrap();

        assert_eq!(bytes, 0);
        assert!(decompressed.is_empty());
    }

    #[test]
    fn lzma_corrupted_data_fails() {
        let bad_data = b"this is not lzma data at all!";
        let mut reader = Cursor::new(bad_data.as_slice());
        let mut output = Vec::new();

        let err = lzma_decompress(&mut reader, &mut output).unwrap_err();
        let msg = err.to_string().to_lowercase();
        assert!(
            msg.contains("lzma") || msg.contains("io") || msg.contains("invalid"),
            "expected lzma/io error, got: {err}"
        );
    }

    #[test]
    fn lzma_large_data() {
        let original = vec![0xCDu8; 1_048_576];
        let mut source = Cursor::new(original.as_slice());

        let compressed = {
            let mut buf = Vec::new();
            lzma_compress(&mut source, &mut buf).unwrap();
            buf
        };

        assert!(
            compressed.len() < original.len(),
            "compressed size ({}) should be less than original ({}) for repetitive data",
            compressed.len(),
            original.len()
        );

        let mut decompressed = Vec::new();
        let mut compressed_reader = Cursor::new(compressed.as_slice());
        let bytes = lzma_decompress(&mut compressed_reader, &mut decompressed).unwrap();

        assert_eq!(bytes, original.len() as u64);
        assert_eq!(decompressed, original);
    }

    #[test]
    fn lzma_with_level_9() {
        let original = b"Hello, GeeZipX! Level 9 lzma compression test data.";
        let mut source = Cursor::new(original.as_slice());

        let compressed = {
            let mut buf = Vec::new();
            lzma_compress_with_level(&mut source, &mut buf, Some(9)).unwrap();
            buf
        };

        assert!(!compressed.is_empty());

        let mut decompressed = Vec::new();
        let mut compressed_reader = Cursor::new(compressed.as_slice());
        lzma_decompress(&mut compressed_reader, &mut decompressed).unwrap();
        assert_eq!(decompressed, original);
    }

    #[test]
    fn lzma_with_level_0() {
        let original = b"Hello, GeeZipX! Level 0 (store) lzma test.";
        let mut source = Cursor::new(original.as_slice());

        let compressed = {
            let mut buf = Vec::new();
            lzma_compress_with_level(&mut source, &mut buf, Some(0)).unwrap();
            buf
        };

        assert!(!compressed.is_empty());

        let mut decompressed = Vec::new();
        let mut compressed_reader = Cursor::new(compressed.as_slice());
        lzma_decompress(&mut compressed_reader, &mut decompressed).unwrap();
        assert_eq!(decompressed, original);
    }

    #[test]
    fn lzma_level_none_falls_back_to_default() {
        let original = b"GeeZipX default lzma level test.";
        let mut source = Cursor::new(original.as_slice());

        let compressed_default = {
            let mut buf = Vec::new();
            lzma_compress(&mut source, &mut buf).unwrap();
            buf
        };

        source.set_position(0);
        let compressed_with_level = {
            let mut buf = Vec::new();
            lzma_compress_with_level(&mut source, &mut buf, None).unwrap();
            buf
        };

        assert!(!compressed_default.is_empty());
        assert!(!compressed_with_level.is_empty());

        let mut out1 = Vec::new();
        let mut reader1 = Cursor::new(compressed_default.as_slice());
        lzma_decompress(&mut reader1, &mut out1).unwrap();
        assert_eq!(out1, original);

        let mut out2 = Vec::new();
        let mut reader2 = Cursor::new(compressed_with_level.as_slice());
        lzma_decompress(&mut reader2, &mut out2).unwrap();
        assert_eq!(out2, original);
    }

    #[test]
    fn lzma_truncated_stream_fails() {
        let truncated = b"\x5D\x00\x00\x00\x00\x00\x00\x00";
        let mut reader = std::io::Cursor::new(truncated.as_slice());
        let mut output = Vec::new();

        let err = lzma_decompress(&mut reader, &mut output).unwrap_err();
        let msg = err.to_string().to_lowercase();
        assert!(
            msg.contains("lzma") || msg.contains("io") || msg.contains("invalid"),
            "expected lzma/io error for truncated lzma stream, got: {err}"
        );
    }
}