compress-lib 0.8.0

DEFLATE, zlib, and gzip for Rust services: streaming and sans-IO with bounded memory, hard limits against decompression bombs, WebSocket permessage-deflate (RFC 7692) support, no unsafe code, and zero third-party dependencies.
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
//! One decoder and one encoder type for code that picks the format at run
//! time (an HTTP layer choosing by `Content-Encoding`, for example).

use alloc::vec::Vec;

use crate::{
    Error, ErrorKind, Level, Limits, Progress,
    deflate::{Deflater, Flush, Inflater},
    gzip, zlib,
};

/// A compressed format.
///
/// # Examples
///
/// ```
/// use compress_lib::{Format, gzip, zlib};
///
/// assert_eq!(Format::detect(&gzip::compress(b"x")), Some(Format::Gzip));
/// assert_eq!(Format::detect(&zlib::compress(b"x")), Some(Format::Zlib));
/// assert_eq!(Format::detect(b"plain text"), None);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Format {
    /// Raw DEFLATE (RFC 1951): no header, no checksum.
    Raw,
    /// zlib (RFC 1950); also HTTP's `deflate` content coding.
    Zlib,
    /// gzip (RFC 1952); HTTP's `gzip` content coding.
    Gzip,
}

impl Format {
    /// Recognises gzip by its magic number and zlib by its header check.
    /// Raw DEFLATE has no header and is never guessed. Needs at least two
    /// bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::Format;
    ///
    /// assert_eq!(Format::detect(&[0x1F, 0x8B]), Some(Format::Gzip));
    /// assert_eq!(Format::detect(&[0x78, 0x9C]), Some(Format::Zlib));
    /// assert_eq!(Format::detect(&[0x78]), None);
    /// ```
    #[must_use]
    pub fn detect(data: &[u8]) -> Option<Format> {
        match data {
            [0x1F, 0x8B, ..] => Some(Format::Gzip),
            [cmf, flg, ..] if zlib::header_ok(*cmf, *flg) => Some(Format::Zlib),
            _ => None,
        }
    }
}

/// Decompresses a complete gzip or zlib stream, detected from its first
/// bytes, with the default [`Limits`].
///
/// # Errors
///
/// [`ErrorKind::InvalidHeader`] when the data is neither; otherwise as
/// [`gzip::decompress`] or [`zlib::decompress`].
///
/// # Examples
///
/// ```
/// use compress_lib as compress;
///
/// assert_eq!(compress::decompress(&compress::gzip::compress(b"either"))?, b"either");
/// assert_eq!(compress::decompress(&compress::zlib::compress(b"either"))?, b"either");
/// # Ok::<(), compress_lib::Error>(())
/// ```
pub fn decompress(data: &[u8]) -> Result<Vec<u8>, Error> {
    decompress_with(data, Limits::new())
}

/// As [`decompress`], with the given limits.
///
/// # Errors
///
/// As [`decompress`].
///
/// # Examples
///
/// ```
/// use compress_lib as compress;
///
/// let limits = compress::Limits::new().with_max_output(1 << 20);
/// assert_eq!(compress::decompress_with(&compress::gzip::compress(b"x"), limits)?, b"x");
/// # Ok::<(), compress_lib::Error>(())
/// ```
pub fn decompress_with(data: &[u8], limits: Limits) -> Result<Vec<u8>, Error> {
    match Format::detect(data) {
        Some(Format::Gzip) => gzip::decompress_with(data, limits),
        Some(Format::Zlib) => zlib::decompress_with(data, limits),
        _ => Err(Error::new(ErrorKind::InvalidHeader, 0)),
    }
}

#[derive(Debug)]
enum Inner<R, Z, G> {
    Raw(R),
    Zlib(Z),
    Gzip(G),
}

/// A streaming decoder for any [`Format`].
///
/// # Examples
///
/// ```
/// use compress_lib::{Decoder, Format, gzip};
///
/// let mut dec = Decoder::new(Format::Gzip);
/// let mut out = Vec::new();
/// dec.finish_vec(&gzip::compress(b"any format"), &mut out)?;
/// assert_eq!(out, b"any format");
/// # Ok::<(), compress_lib::Error>(())
/// ```
#[derive(Debug)]
pub struct Decoder(Inner<Inflater, zlib::Decoder, gzip::Decoder>);

impl Decoder {
    /// A decoder for `format` with the default limits.
    ///
    /// # Examples
    ///
    /// ```
    /// let dec = compress_lib::Decoder::new(compress_lib::Format::Zlib);
    /// assert_eq!(dec.format(), compress_lib::Format::Zlib);
    /// ```
    #[must_use]
    pub fn new(format: Format) -> Self {
        Self(match format {
            Format::Raw => Inner::Raw(Inflater::new()),
            Format::Zlib => Inner::Zlib(zlib::Decoder::new()),
            Format::Gzip => Inner::Gzip(gzip::Decoder::new()),
        })
    }

    /// Sets the limits checked while decoding.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::{Decoder, Format, Limits};
    ///
    /// let dec = Decoder::new(Format::Gzip).with_limits(Limits::new().with_max_output(1 << 20));
    /// # let _ = dec;
    /// ```
    #[must_use]
    pub fn with_limits(self, limits: Limits) -> Self {
        Self(match self.0 {
            Inner::Raw(d) => Inner::Raw(d.with_limits(limits)),
            Inner::Zlib(d) => Inner::Zlib(d.with_limits(limits)),
            Inner::Gzip(d) => Inner::Gzip(d.with_limits(limits)),
        })
    }

    /// The format decoded.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::{Decoder, Format};
    ///
    /// assert_eq!(Decoder::new(Format::Raw).format(), Format::Raw);
    /// ```
    #[must_use]
    pub fn format(&self) -> Format {
        match self.0 {
            Inner::Raw(_) => Format::Raw,
            Inner::Zlib(_) => Format::Zlib,
            Inner::Gzip(_) => Format::Gzip,
        }
    }

    /// As [`Inflater::decompress`].
    ///
    /// # Errors
    ///
    /// The errors of the format's decoder.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::{Decoder, Format, deflate::Status, zlib};
    ///
    /// let mut out = [0u8; 16];
    /// let p = Decoder::new(Format::Zlib).decompress(&zlib::compress(b"abc"), &mut out)?;
    /// assert_eq!(p.status, Status::Done);
    /// # Ok::<(), compress_lib::Error>(())
    /// ```
    pub fn decompress(&mut self, input: &[u8], output: &mut [u8]) -> Result<Progress, Error> {
        match &mut self.0 {
            Inner::Raw(d) => d.decompress(input, output),
            Inner::Zlib(d) => d.decompress(input, output),
            Inner::Gzip(d) => d.decompress(input, output),
        }
    }

    /// As [`Inflater::finish`].
    ///
    /// # Errors
    ///
    /// The errors of the format's decoder, plus `UnexpectedEnd`.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::{Decoder, Format, gzip};
    ///
    /// let mut out = [0u8; 16];
    /// let p = Decoder::new(Format::Gzip).finish(&gzip::compress(b"abc"), &mut out)?;
    /// assert_eq!(&out[..p.produced], b"abc");
    /// # Ok::<(), compress_lib::Error>(())
    /// ```
    pub fn finish(&mut self, input: &[u8], output: &mut [u8]) -> Result<Progress, Error> {
        match &mut self.0 {
            Inner::Raw(d) => d.finish(input, output),
            Inner::Zlib(d) => d.finish(input, output),
            Inner::Gzip(d) => d.finish(input, output),
        }
    }

    /// As [`Inflater::decompress_vec`].
    ///
    /// # Errors
    ///
    /// The errors of the format's decoder, plus `AllocationFailed`.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::{Decoder, Format, deflate};
    ///
    /// let mut out = Vec::new();
    /// Decoder::new(Format::Raw).decompress_vec(&deflate::compress(b"raw"), &mut out)?;
    /// assert_eq!(out, b"raw");
    /// # Ok::<(), compress_lib::Error>(())
    /// ```
    pub fn decompress_vec(&mut self, input: &[u8], out: &mut Vec<u8>) -> Result<Progress, Error> {
        match &mut self.0 {
            Inner::Raw(d) => d.decompress_vec(input, out),
            Inner::Zlib(d) => d.decompress_vec(input, out),
            Inner::Gzip(d) => d.decompress_vec(input, out),
        }
    }

    /// As [`Inflater::finish_vec`].
    ///
    /// # Errors
    ///
    /// The errors of the format's decoder, plus `UnexpectedEnd` and
    /// `AllocationFailed`.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::{Decoder, Format, zlib};
    ///
    /// let mut out = Vec::new();
    /// Decoder::new(Format::Zlib).finish_vec(&zlib::compress(b"z"), &mut out)?;
    /// assert_eq!(out, b"z");
    /// # Ok::<(), compress_lib::Error>(())
    /// ```
    pub fn finish_vec(&mut self, input: &[u8], out: &mut Vec<u8>) -> Result<Progress, Error> {
        match &mut self.0 {
            Inner::Raw(d) => d.finish_vec(input, out),
            Inner::Zlib(d) => d.finish_vec(input, out),
            Inner::Gzip(d) => d.finish_vec(input, out),
        }
    }

    /// `true` once the stream ended.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(!compress_lib::Decoder::new(compress_lib::Format::Gzip).is_done());
    /// ```
    #[must_use]
    pub fn is_done(&self) -> bool {
        match &self.0 {
            Inner::Raw(d) => d.is_done(),
            Inner::Zlib(d) => d.is_done(),
            Inner::Gzip(d) => d.is_done(),
        }
    }

    /// Compressed bytes consumed.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(compress_lib::Decoder::new(compress_lib::Format::Gzip).total_in(), 0);
    /// ```
    #[must_use]
    pub fn total_in(&self) -> u64 {
        match &self.0 {
            Inner::Raw(d) => d.total_in(),
            Inner::Zlib(d) => d.total_in(),
            Inner::Gzip(d) => d.total_in(),
        }
    }

    /// Decompressed bytes produced.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(compress_lib::Decoder::new(compress_lib::Format::Gzip).total_out(), 0);
    /// ```
    #[must_use]
    pub fn total_out(&self) -> u64 {
        match &self.0 {
            Inner::Raw(d) => d.total_out(),
            Inner::Zlib(d) => d.total_out(),
            Inner::Gzip(d) => d.total_out(),
        }
    }

    /// Starts over for a new stream, keeping allocations.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut dec = compress_lib::Decoder::new(compress_lib::Format::Zlib);
    /// dec.reset();
    /// ```
    pub fn reset(&mut self) {
        match &mut self.0 {
            Inner::Raw(d) => d.reset(),
            Inner::Zlib(d) => d.reset(),
            Inner::Gzip(d) => d.reset(),
        }
    }
}

/// A streaming encoder for any [`Format`].
///
/// # Examples
///
/// ```
/// use compress_lib::{Encoder, Format, Level, deflate::Flush, gzip};
///
/// let mut enc = Encoder::new(Format::Gzip, Level::DEFAULT);
/// let mut out = Vec::new();
/// enc.compress_vec(b"response body", &mut out, Flush::Finish)?;
/// assert_eq!(gzip::decompress(&out)?, b"response body");
/// # Ok::<(), compress_lib::Error>(())
/// ```
#[derive(Debug)]
pub struct Encoder(Inner<Deflater, zlib::Encoder, gzip::Encoder>);

impl Encoder {
    /// An encoder for `format` at `level`.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::{Encoder, Format, Level};
    ///
    /// assert_eq!(Encoder::new(Format::Zlib, Level::FAST).format(), Format::Zlib);
    /// ```
    #[must_use]
    pub fn new(format: Format, level: Level) -> Self {
        Self(match format {
            Format::Raw => Inner::Raw(Deflater::new(level)),
            Format::Zlib => Inner::Zlib(zlib::Encoder::new(level)),
            Format::Gzip => Inner::Gzip(gzip::Encoder::new(level)),
        })
    }

    /// The format written.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::{Encoder, Format, Level};
    ///
    /// assert_eq!(Encoder::new(Format::Raw, Level::FAST).format(), Format::Raw);
    /// ```
    #[must_use]
    pub fn format(&self) -> Format {
        match self.0 {
            Inner::Raw(_) => Format::Raw,
            Inner::Zlib(_) => Format::Zlib,
            Inner::Gzip(_) => Format::Gzip,
        }
    }

    /// As [`Deflater::compress`], with the format's header and trailer.
    ///
    /// # Errors
    ///
    /// As `Deflater::compress`.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::{Encoder, Format, Level, deflate::{Flush, Status}};
    ///
    /// let mut enc = Encoder::new(Format::Zlib, Level::DEFAULT);
    /// let mut out = [0u8; 64];
    /// assert_eq!(enc.compress(b"abc", &mut out, Flush::Finish)?.status, Status::Done);
    /// # Ok::<(), compress_lib::Error>(())
    /// ```
    pub fn compress(
        &mut self,
        input: &[u8],
        output: &mut [u8],
        flush: Flush,
    ) -> Result<Progress, Error> {
        match &mut self.0 {
            Inner::Raw(e) => e.compress(input, output, flush),
            Inner::Zlib(e) => e.compress(input, output, flush),
            Inner::Gzip(e) => e.compress(input, output, flush),
        }
    }

    /// As [`Deflater::compress_vec`].
    ///
    /// # Errors
    ///
    /// As `compress`, plus `AllocationFailed`.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::{Encoder, Format, Level, deflate::Flush, zlib};
    ///
    /// let mut out = Vec::new();
    /// Encoder::new(Format::Zlib, Level::DEFAULT).compress_vec(b"abc", &mut out, Flush::Finish)?;
    /// assert_eq!(zlib::decompress(&out)?, b"abc");
    /// # Ok::<(), compress_lib::Error>(())
    /// ```
    pub fn compress_vec(
        &mut self,
        input: &[u8],
        out: &mut Vec<u8>,
        flush: Flush,
    ) -> Result<Progress, Error> {
        match &mut self.0 {
            Inner::Raw(e) => e.compress_vec(input, out, flush),
            Inner::Zlib(e) => e.compress_vec(input, out, flush),
            Inner::Gzip(e) => e.compress_vec(input, out, flush),
        }
    }

    /// Starts a new stream, keeping allocations.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut enc = compress_lib::Encoder::new(compress_lib::Format::Gzip, compress_lib::Level::FAST);
    /// enc.reset();
    /// ```
    pub fn reset(&mut self) {
        match &mut self.0 {
            Inner::Raw(e) => e.reset(),
            Inner::Zlib(e) => e.reset(),
            Inner::Gzip(e) => e.reset(),
        }
    }
}