rusty_zlib 0.1.4

Remade-With-Rust fork of zlib-rs: a memory-safe, pure-Rust zlib (deflate/inflate, zlib and gzip), measured and tuned for the MATA stack
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! miniz_oxide-compatible DEFLATE compression (feature `miniz-compat`).
//!
//! A vendored copy of the compressor from [miniz_oxide](https://github.com/Frommi/miniz_oxide)
//! 0.8.9, kept verbatim so that its output is byte-for-byte identical to miniz_oxide 0.8.9 for
//! every level (0-10) and every input. Use it where an encoder's output is pinned to miniz_oxide;
//! use [`crate::Deflate`] / [`crate::compress_slice`] otherwise (zlib-compatible output).
//!
//! The API mirrors miniz_oxide's: replacing the `miniz_oxide::` path prefix with
//! `rusty_zlib::compat::miniz::` ports a caller of `miniz_oxide::deflate::*` mechanically.
//! The items of `miniz_oxide::deflate` are available both here and under [`deflate`].
//!
//! ```
//! use rusty_zlib::compat::miniz::deflate::compress_to_vec_zlib;
//! let compressed = compress_to_vec_zlib(b"Hello, Hello, Hello!", 9);
//! assert_eq!(compressed[0], 0x78);
//! ```
//!
//! Decompression is not part of this module; any inflate (for example [`crate::decompress_slice`])
//! reads the output.
//!
//! Vendored from miniz_oxide 0.8.9 (src/lib.rs and src/deflate/mod.rs). Copyright (c) Frommi,
//! oyvindln and miniz_oxide contributors. miniz_oxide is licensed "MIT OR Zlib OR Apache-2.0";
//! rusty_zlib uses it under the Zlib licence.
//!
//! rusty_zlib changes (none affects the compressed bytes):
//! - the crate root (`src/lib.rs`: `MZFlush`, `MZStatus`, `MZError`, `DataFormat`, `MZResult`,
//!   `StreamResult`) and `src/deflate/mod.rs` are merged into this one module, so module paths
//!   are adapted (`crate::deflate::` becomes `crate::compat::miniz::`);
//! - the `rustc-dep-of-std` cfg gates are resolved to their default (feature off) branch;
//! - Adler-32 comes from `crate::adler32` instead of the `adler2` crate (see `shared.rs`);
//! - unit tests that used miniz_oxide's inflate decode with rusty_zlib's inflate instead;
//! - doc links into miniz_oxide's `inflate` module (not vendored) are plain text;
//! - `core::convert::From` is spelled `::core::convert::From`, and `deflate/core.rs` imports
//!   `MZError`/`MZFlush` by name instead of `use super::super::*`, since this module has a child
//!   named `core`.
#![forbid(unsafe_code)]

use crate::alloc::vec;
use crate::alloc::vec::Vec;

mod buffer;
pub mod core;
mod shared;
mod stored;
pub mod stream;
mod zlib;
use self::core::*;

pub use self::shared::update_adler32 as mz_adler32_oxide;
pub use self::shared::{MZ_ADLER32_INIT, MZ_DEFAULT_WINDOW_BITS};

/// The items of `miniz_oxide::deflate`, at the same path, so `miniz_oxide::deflate::X` ports to
/// `rusty_zlib::compat::miniz::deflate::X`.
pub mod deflate {
    pub use super::core;
    pub use super::stream;
    pub use super::{compress_to_vec, compress_to_vec_zlib, CompressionLevel};
}

// ---- from miniz_oxide 0.8.9 src/lib.rs ----

/// A list of flush types.
///
/// See <http://www.bolet.org/~pornin/deflate-flush.html> for more in-depth info.
#[repr(i32)]
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum MZFlush {
    /// Don't force any flushing.
    /// Used when more input data is expected.
    None = 0,
    /// Zlib partial flush.
    /// Currently treated as [`Sync`].
    Partial = 1,
    /// Finish compressing the currently buffered data, and output an empty raw block.
    /// Has no use in decompression.
    Sync = 2,
    /// Same as [`Sync`], but resets the compression dictionary so that further compressed
    /// data does not depend on data compressed before the flush.
    ///
    /// Has no use in decompression, and is an error to supply in that case.
    Full = 3,
    /// Attempt to flush the remaining data and end the stream.
    Finish = 4,
    /// Not implemented.
    Block = 5,
}

impl MZFlush {
    /// Create an MZFlush value from an integer value.
    ///
    /// Returns `MZError::Param` on invalid values.
    pub fn new(flush: i32) -> Result<Self, MZError> {
        match flush {
            0 => Ok(MZFlush::None),
            1 | 2 => Ok(MZFlush::Sync),
            3 => Ok(MZFlush::Full),
            4 => Ok(MZFlush::Finish),
            _ => Err(MZError::Param),
        }
    }
}

/// A list of miniz successful status codes.
///
/// These are emitted as the [`Ok`] side of a [`MZResult`] in the [`StreamResult`] returned from
/// [`deflate::stream::deflate()`] or `inflate::stream::inflate()`.
#[repr(i32)]
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum MZStatus {
    /// Operation succeeded.
    ///
    /// Some data was decompressed or compressed; see the byte counters in the [`StreamResult`] for
    /// details.
    Ok = 0,

    /// Operation succeeded and end of deflate stream was found.
    ///
    /// X-ref `TINFLStatus::Done` or
    /// [`TDEFLStatus::Done`][deflate::core::TDEFLStatus::Done] for `inflate` or `deflate`
    /// respectively.
    StreamEnd = 1,

    /// Unused
    NeedDict = 2,
}

/// A list of miniz failed status codes.
///
/// These are emitted as the [`Err`] side of a [`MZResult`] in the [`StreamResult`] returned from
/// [`deflate::stream::deflate()`] or `inflate::stream::inflate()`.
#[repr(i32)]
#[derive(Hash, Debug, Copy, Clone, PartialEq, Eq)]
pub enum MZError {
    /// Unused
    ErrNo = -1,

    /// General stream error.
    ///
    /// See `inflate::stream::inflate()` docs for details of how it can occur there.
    ///
    /// See [`deflate::stream::deflate()`] docs for how it can in principle occur there, though it's
    /// believed impossible in practice.
    Stream = -2,

    /// Error in inflation; see `inflate::stream::inflate()` for details.
    ///
    /// Not returned from [`deflate::stream::deflate()`].
    Data = -3,

    /// Unused
    Mem = -4,

    /// Buffer-related error.
    ///
    /// See the docs of [`deflate::stream::deflate()`] or `inflate::stream::inflate()` for details
    /// of when it would trigger in the one you're using.
    Buf = -5,

    /// Unused
    Version = -6,

    /// Bad parameters.
    ///
    /// This can be returned from [`deflate::stream::deflate()`] in the case of bad parameters.  See
    /// [`TDEFLStatus::BadParam`][deflate::core::TDEFLStatus::BadParam].
    Param = -10_000,
}

/// How compressed data is wrapped.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum DataFormat {
    /// Wrapped using the [zlib](http://www.zlib.org/rfc-zlib.html) format.
    Zlib,
    /// Zlib wrapped but ignore and don't compute the adler32 checksum.
    /// Currently only used for inflate, behaves the same as Zlib for compression.
    ZLibIgnoreChecksum,
    /// Raw DEFLATE.
    Raw,
}

impl DataFormat {
    pub fn from_window_bits(window_bits: i32) -> DataFormat {
        if window_bits > 0 {
            DataFormat::Zlib
        } else {
            DataFormat::Raw
        }
    }

    pub fn to_window_bits(self) -> i32 {
        match self {
            DataFormat::Zlib | DataFormat::ZLibIgnoreChecksum => {
                self::shared::MZ_DEFAULT_WINDOW_BITS
            }
            DataFormat::Raw => -self::shared::MZ_DEFAULT_WINDOW_BITS,
        }
    }
}

/// `Result` alias for all miniz status codes both successful and failed.
pub type MZResult = Result<MZStatus, MZError>;

/// A structure containing the result of a call to the inflate or deflate streaming functions.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct StreamResult {
    /// The number of bytes consumed from the input slice.
    pub bytes_consumed: usize,
    /// The number of bytes written to the output slice.
    pub bytes_written: usize,
    /// The return status of the call.
    pub status: MZResult,
}

impl StreamResult {
    #[inline]
    pub const fn error(error: MZError) -> StreamResult {
        StreamResult {
            bytes_consumed: 0,
            bytes_written: 0,
            status: Err(error),
        }
    }
}

impl ::core::convert::From<StreamResult> for MZResult {
    fn from(res: StreamResult) -> Self {
        res.status
    }
}

impl ::core::convert::From<&StreamResult> for MZResult {
    fn from(res: &StreamResult) -> Self {
        res.status
    }
}

// ---- from miniz_oxide 0.8.9 src/deflate/mod.rs ----

/// How much processing the compressor should do to compress the data.
/// `NoCompression` and `Bestspeed` have special meanings, the other levels determine the number
/// of checks for matches in the hash chains and whether to use lazy or greedy parsing.
#[repr(i32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum CompressionLevel {
    /// Don't do any compression, only output uncompressed blocks.
    NoCompression = 0,
    /// Fast compression. Uses a special compression routine that is optimized for speed.
    BestSpeed = 1,
    /// Slow/high compression. Do a lot of checks to try to find good matches.
    BestCompression = 9,
    /// Even more checks, can be very slow.
    UberCompression = 10,
    /// Default compromise between speed and compression.
    DefaultLevel = 6,
    /// Use the default compression level.
    DefaultCompression = -1,
}

// Missing safe rust analogue (this and mem-to-mem are quite similar)
/*
fn tdefl_compress(
    d: Option<&mut CompressorOxide>,
    in_buf: *const c_void,
    in_size: Option<&mut usize>,
    out_buf: *mut c_void,
    out_size: Option<&mut usize>,
    flush: TDEFLFlush,
) -> TDEFLStatus {
    let res = match d {
        None => {
            in_size.map(|size| *size = 0);
            out_size.map(|size| *size = 0);
            (TDEFLStatus::BadParam, 0, 0)
        },
        Some(compressor) => {
            let callback_res = CallbackOxide::new(
                compressor.callback_func.clone(),
                in_buf,
                in_size,
                out_buf,
                out_size,
            );

            if let Ok(mut callback) = callback_res {
                let res = compress(compressor, &mut callback, flush);
                callback.update_size(Some(res.1), Some(res.2));
                res
            } else {
                (TDEFLStatus::BadParam, 0, 0)
            }
        }
    };
    res.0
}*/

// Missing safe rust analogue
/*
fn tdefl_init(
    d: Option<&mut CompressorOxide>,
    put_buf_func: PutBufFuncPtr,
    put_buf_user: *mut c_void,
    flags: c_int,
) -> TDEFLStatus {
    if let Some(d) = d {
        *d = CompressorOxide::new(
            put_buf_func.map(|func|
                CallbackFunc { put_buf_func: func, put_buf_user: put_buf_user }
            ),
            flags as u32,
        );
        TDEFLStatus::Okay
    } else {
        TDEFLStatus::BadParam
    }
}*/

// Missing safe rust analogue (though maybe best served by flate2 front-end instead)
/*
fn tdefl_compress_mem_to_output(
    buf: *const c_void,
    buf_len: usize,
    put_buf_func: PutBufFuncPtr,
    put_buf_user: *mut c_void,
    flags: c_int,
) -> bool*/

// Missing safe Rust analogue
/*
fn tdefl_compress_mem_to_mem(
    out_buf: *mut c_void,
    out_buf_len: usize,
    src_buf: *const c_void,
    src_buf_len: usize,
    flags: c_int,
) -> usize*/

/// Compress the input data to a vector, using the specified compression level (0-10).
pub fn compress_to_vec(input: &[u8], level: u8) -> Vec<u8> {
    compress_to_vec_inner(input, level, 0, 0)
}

/// Compress the input data to a vector, using the specified compression level (0-10), and with a
/// zlib wrapper.
pub fn compress_to_vec_zlib(input: &[u8], level: u8) -> Vec<u8> {
    compress_to_vec_inner(input, level, 1, 0)
}

/// Simple function to compress data to a vec.
fn compress_to_vec_inner(mut input: &[u8], level: u8, window_bits: i32, strategy: i32) -> Vec<u8> {
    // The comp flags function sets the zlib flag if the window_bits parameter is > 0.
    let flags = create_comp_flags_from_zip_params(level.into(), window_bits, strategy);
    let mut compressor = CompressorOxide::new(flags);
    let mut output = vec![0; ::core::cmp::max(input.len() / 2, 2)];

    let mut out_pos = 0;
    loop {
        let (status, bytes_in, bytes_out) = compress(
            &mut compressor,
            input,
            &mut output[out_pos..],
            TDEFLFlush::Finish,
        );
        out_pos += bytes_out;

        match status {
            TDEFLStatus::Done => {
                output.truncate(out_pos);
                break;
            }
            TDEFLStatus::Okay if bytes_in <= input.len() => {
                input = &input[bytes_in..];

                // We need more space, so resize the vector.
                if output.len().saturating_sub(out_pos) < 30 {
                    output.resize(output.len() * 2, 0)
                }
            }
            // Not supposed to happen unless there is a bug.
            _ => panic!("Bug! Unexpectedly failed to compress!"),
        }
    }

    output
}

#[cfg(test)]
mod test {
    use super::{compress_to_vec, compress_to_vec_inner, CompressionStrategy};
    use crate::compat::miniz::test_util::decompress_to_vec;
    use alloc::vec;

    /// Test deflate example.
    ///
    /// Check if the encoder produces the same code as the example given by Mark Adler here:
    /// https://stackoverflow.com/questions/17398931/deflate-encoding-with-static-huffman-codes/17415203
    #[test]
    fn compress_small() {
        let test_data = b"Deflate late";
        let check = [
            0x73, 0x49, 0x4d, 0xcb, 0x49, 0x2c, 0x49, 0x55, 0x00, 0x11, 0x00,
        ];

        let res = compress_to_vec(test_data, 1);
        assert_eq!(&check[..], res.as_slice());

        let res = compress_to_vec(test_data, 9);
        assert_eq!(&check[..], res.as_slice());
    }

    #[test]
    fn compress_huff_only() {
        let test_data = b"Deflate late";

        let res = compress_to_vec_inner(test_data, 1, 0, CompressionStrategy::HuffmanOnly as i32);
        let d = decompress_to_vec(res.as_slice()).expect("Failed to decompress!");
        assert_eq!(test_data, d.as_slice());
    }

    #[test]
    fn compress_rle() {
        let test_data = b"Deflate late";

        let res = compress_to_vec_inner(test_data, 1, 0, CompressionStrategy::RLE as i32);
        let d = decompress_to_vec(res.as_slice()).expect("Failed to decompress!");
        assert_eq!(test_data, d.as_slice());
    }

    /// Test that a raw block compresses fine.
    #[test]
    fn compress_raw() {
        let text = b"Hello, zlib!";
        let encoded = {
            let len = text.len();
            let notlen = !len;
            let mut encoded = vec![
                1,
                len as u8,
                (len >> 8) as u8,
                notlen as u8,
                (notlen >> 8) as u8,
            ];
            encoded.extend_from_slice(&text[..]);
            encoded
        };

        let res = compress_to_vec(text, 0);
        assert_eq!(encoded, res.as_slice());
    }

    #[test]
    fn short() {
        let test_data = [10, 10, 10, 10, 10, 55];
        let c = compress_to_vec(&test_data, 9);

        let d = decompress_to_vec(c.as_slice()).expect("Failed to decompress!");
        assert_eq!(&test_data, d.as_slice());
        // Check that a static block is used here, rather than a raw block
        // , so the data is actually compressed.
        // (The optimal compressed length would be 5, but neither miniz nor zlib manages that either
        // as neither checks matches against the byte at index 0.)
        assert!(c.len() <= 6);
    }
}

/// Test-only decoding helpers backed by rusty_zlib's inflate (stand-ins for miniz_oxide's
/// `inflate::decompress_to_vec{,_zlib}` used by the vendored unit tests).
#[cfg(test)]
pub(crate) mod test_util {
    use crate::alloc::vec;
    use crate::alloc::vec::Vec;
    use crate::{decompress_slice, InflateConfig};

    fn decompress(input: &[u8], window_bits: i32) -> Result<Vec<u8>, crate::ReturnCode> {
        let mut size = input.len() * 4 + 64;
        loop {
            let mut out = vec![0u8; size];
            let (res, rc) = decompress_slice(&mut out, input, InflateConfig { window_bits });
            match rc {
                crate::ReturnCode::Ok => {
                    let n = res.len();
                    out.truncate(n);
                    return Ok(out);
                }
                crate::ReturnCode::BufError if size < (1 << 30) => size *= 2,
                other => return Err(other),
            }
        }
    }

    pub fn decompress_to_vec(input: &[u8]) -> Result<Vec<u8>, crate::ReturnCode> {
        decompress(input, -15)
    }

    pub fn decompress_to_vec_zlib(input: &[u8]) -> Result<Vec<u8>, crate::ReturnCode> {
        decompress(input, 15)
    }
}

/// rusty_zlib's own tests: every level's output must decode with rusty_zlib's inflate.
#[cfg(test)]
mod roundtrip {
    use super::test_util::{decompress_to_vec, decompress_to_vec_zlib};
    use super::{
        compress_to_vec, compress_to_vec_zlib, stream, CompressorOxide, MZFlush, MZStatus,
    };
    use crate::alloc::boxed::Box;
    use crate::alloc::vec;
    use crate::alloc::vec::Vec;

    fn corpus() -> Vec<Vec<u8>> {
        let mut text = Vec::new();
        for i in 0..20_000u32 {
            text.extend_from_slice(b"the quick brown fox ");
            text.extend_from_slice(&i.to_le_bytes());
        }
        let mut x = 0x1234_5678u32;
        let noise: Vec<u8> = (0..100_000)
            .map(|_| {
                x ^= x << 13;
                x ^= x >> 17;
                x ^= x << 5;
                x as u8
            })
            .collect();
        vec![
            Vec::new(),
            vec![7],
            b"Deflate late".to_vec(),
            vec![0; 300_000],
            text,
            noise,
        ]
    }

    #[test]
    fn one_shot_all_levels() {
        for data in corpus() {
            for level in 0..=10 {
                let raw = compress_to_vec(&data, level);
                assert_eq!(decompress_to_vec(&raw).unwrap(), data, "raw level {level}");
                let z = compress_to_vec_zlib(&data, level);
                assert_eq!(
                    decompress_to_vec_zlib(&z).unwrap(),
                    data,
                    "zlib level {level}"
                );
            }
        }
    }

    #[test]
    fn streaming_with_flushes() {
        for data in corpus() {
            for level in [0u8, 1, 4, 6, 9, 10] {
                let mut c = Box::<CompressorOxide>::default();
                c.set_format_and_level(super::DataFormat::Zlib, level);
                let mut out = Vec::new();
                let mut buf = [0u8; 777];
                for (i, chunk) in data.chunks(10_007).enumerate() {
                    let flush = [MZFlush::None, MZFlush::Sync, MZFlush::Full][i % 3];
                    let mut input = chunk;
                    loop {
                        let r = stream::deflate(&mut c, input, &mut buf, flush);
                        out.extend_from_slice(&buf[..r.bytes_written]);
                        input = &input[r.bytes_consumed..];
                        if input.is_empty() && r.bytes_written < buf.len() {
                            break;
                        }
                    }
                }
                loop {
                    let r = stream::deflate(&mut c, &[], &mut buf, MZFlush::Finish);
                    out.extend_from_slice(&buf[..r.bytes_written]);
                    if r.status == Ok(MZStatus::StreamEnd) {
                        break;
                    }
                    assert!(r.status.is_ok());
                }
                assert_eq!(decompress_to_vec_zlib(&out).unwrap(), data, "level {level}");
            }
        }
    }
}