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
//! `std::io` adapters over the streaming engines (feature `std`).
//!
//! | Type | Reads or writes | Does |
//! |---|---|---|
//! | [`Reader`] | reads from a compressed `Read` | decompresses |
//! | [`Writer`] | writes to a `Write` | compresses |
//! | [`Encoder`] | reads from a plain `Read` | compresses |
//! | [`DecodeWriter`] | writes to a `Write` | decompresses |
//!
//! Each holds one 32 KiB buffer besides its engine. Decoders take
//! [`Limits`]; errors come out as `std::io::Error` wrapping the crate's
//! [`Error`](crate::Error).
//!
//! ```
//! use std::io::{Read, Write};
//!
//! use compress_lib::{Format, Level, io};
//!
//! let mut w = io::Writer::new(Vec::new(), Format::Gzip, Level::DEFAULT);
//! w.write_all(b"through std::io")?;
//! let packed = w.finish()?;
//!
//! let mut r = io::Reader::new(&packed[..], Format::Gzip);
//! let mut text = String::new();
//! r.read_to_string(&mut text)?;
//! assert_eq!(text, "through std::io");
//! # Ok::<(), std::io::Error>(())
//! ```

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

use crate::{Decoder, Encoder as FormatEncoder, Format, Level, Limits, Status, deflate::Flush};

const BUF: usize = 32 * 1024;

/// Decompresses while reading from a compressed source.
///
/// Reading past the end of the compressed stream returns 0. Data after the
/// stream is left unread in the source as far as the 32 KiB buffer allows
/// (use [`Reader::into_inner`] with care), and the stream must be complete:
/// a source that ends early is `UnexpectedEof`.
///
/// # Examples
///
/// ```
/// use std::io::Read;
///
/// use compress_lib::{Format, io::Reader, zlib};
///
/// let packed = zlib::compress(b"read me");
/// let mut out = Vec::new();
/// Reader::new(&packed[..], Format::Zlib).read_to_end(&mut out)?;
/// assert_eq!(out, b"read me");
/// # Ok::<(), std::io::Error>(())
/// ```
#[derive(Debug)]
pub struct Reader<R> {
    inner: R,
    decoder: Decoder,
    buf: Box<[u8]>,
    pos: usize,
    len: usize,
    eof: bool,
}

impl<R: Read> Reader<R> {
    /// Reads `format` from `inner` with the default limits.
    ///
    /// # Examples
    ///
    /// ```
    /// let r = compress_lib::io::Reader::new(&b""[..], compress_lib::Format::Gzip);
    /// # let _ = r;
    /// ```
    pub fn new(inner: R, format: Format) -> Self {
        Self {
            inner,
            decoder: Decoder::new(format),
            buf: vec![0; BUF].into_boxed_slice(),
            pos: 0,
            len: 0,
            eof: false,
        }
    }

    /// Sets the limits checked while decoding.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::{Format, Limits, io::Reader};
    ///
    /// let r = Reader::new(&b""[..], Format::Gzip).with_limits(Limits::new().with_max_output(1 << 20));
    /// # let _ = r;
    /// ```
    #[must_use]
    pub fn with_limits(mut self, limits: Limits) -> Self {
        self.decoder = self.decoder.with_limits(limits);
        self
    }

    /// The source, consuming the reader.
    ///
    /// # Examples
    ///
    /// ```
    /// let r = compress_lib::io::Reader::new(&b"xyz"[..], compress_lib::Format::Gzip);
    /// let _source: &[u8] = r.into_inner();
    /// ```
    pub fn into_inner(self) -> R {
        self.inner
    }
}

impl<R: Read> Read for Reader<R> {
    fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
        if out.is_empty() || self.decoder.is_done() {
            return Ok(0);
        }
        loop {
            if self.pos == self.len && !self.eof {
                self.len = self.inner.read(&mut self.buf)?;
                self.pos = 0;
                self.eof = self.len == 0;
            }
            let input = &self.buf[self.pos..self.len];
            let p = if self.eof {
                self.decoder.finish(input, out)?
            } else {
                self.decoder.decompress(input, out)?
            };
            self.pos += p.consumed;
            if p.produced > 0 || p.status == Status::Done {
                return Ok(p.produced);
            }
        }
    }
}

/// Compresses while writing to a destination.
///
/// `flush` writes a sync point (everything so far becomes decodable) and
/// flushes the destination; [`finish`](Writer::finish) ends the stream and
/// returns the destination. Dropping a writer without `finish` tries to end
/// the stream and ignores errors, as a drop cannot report them: call
/// `finish`.
///
/// # Examples
///
/// ```
/// use std::io::Write;
///
/// use compress_lib::{Format, Level, deflate, io::Writer};
///
/// let mut w = Writer::new(Vec::new(), Format::Raw, Level::FAST);
/// w.write_all(b"written")?;
/// assert_eq!(deflate::decompress(&w.finish()?).unwrap(), b"written");
/// # Ok::<(), std::io::Error>(())
/// ```
#[derive(Debug)]
pub struct Writer<W: Write> {
    inner: Option<W>,
    encoder: FormatEncoder,
    buf: Box<[u8]>,
    finished: bool,
}

impl<W: Write> Writer<W> {
    /// Writes `format` at `level` to `inner`.
    ///
    /// # Examples
    ///
    /// ```
    /// let w = compress_lib::io::Writer::new(Vec::new(), compress_lib::Format::Gzip, compress_lib::Level::FAST);
    /// # let _ = w;
    /// ```
    pub fn new(inner: W, format: Format, level: Level) -> Self {
        Self {
            inner: Some(inner),
            encoder: FormatEncoder::new(format, level),
            buf: vec![0; BUF].into_boxed_slice(),
            finished: false,
        }
    }

    fn pump(&mut self, mut input: &[u8], flush: Flush) -> io::Result<usize> {
        let mut taken = 0;
        let Some(inner) = self.inner.as_mut() else {
            return Err(io::Error::other("writer already finished"));
        };
        loop {
            let p = self.encoder.compress(input, &mut self.buf, flush)?;
            inner.write_all(&self.buf[..p.produced])?;
            input = &input[p.consumed..];
            taken += p.consumed;
            if p.status != Status::NeedsOutput {
                return Ok(taken);
            }
        }
    }

    /// Ends the stream and returns the destination.
    ///
    /// # Errors
    ///
    /// Errors of the destination.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::{Format, Level, io::Writer};
    ///
    /// let packed = Writer::new(Vec::new(), Format::Zlib, Level::DEFAULT).finish()?;
    /// assert_eq!(compress_lib::zlib::decompress(&packed).unwrap(), b"");
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn finish(mut self) -> io::Result<W> {
        self.pump(&[], Flush::Finish)?;
        self.finished = true;
        let mut inner = self
            .inner
            .take()
            .ok_or_else(|| io::Error::other("writer already finished"))?;
        inner.flush()?;
        Ok(inner)
    }
}

impl<W: Write> Write for Writer<W> {
    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
        self.pump(data, Flush::None)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.pump(&[], Flush::Sync)?;
        match self.inner.as_mut() {
            Some(inner) => inner.flush(),
            None => Ok(()),
        }
    }
}

impl<W: Write> Drop for Writer<W> {
    fn drop(&mut self) {
        if !self.finished && self.inner.is_some() {
            let _ = self.pump(&[], Flush::Finish);
        }
    }
}

/// Compresses while reading: reads plain data from `inner` and returns it
/// compressed.
///
/// # Examples
///
/// ```
/// use std::io::Read;
///
/// use compress_lib::{Format, Level, gzip, io::Encoder};
///
/// let mut packed = Vec::new();
/// Encoder::new(&b"plain source"[..], Format::Gzip, Level::DEFAULT).read_to_end(&mut packed)?;
/// assert_eq!(gzip::decompress(&packed).unwrap(), b"plain source");
/// # Ok::<(), std::io::Error>(())
/// ```
#[derive(Debug)]
pub struct Encoder<R> {
    inner: R,
    encoder: FormatEncoder,
    buf: Box<[u8]>,
    pos: usize,
    len: usize,
    eof: bool,
    done: bool,
}

impl<R: Read> Encoder<R> {
    /// Compresses `inner` as `format` at `level`.
    ///
    /// # Examples
    ///
    /// ```
    /// let e = compress_lib::io::Encoder::new(&b""[..], compress_lib::Format::Zlib, compress_lib::Level::FAST);
    /// # let _ = e;
    /// ```
    pub fn new(inner: R, format: Format, level: Level) -> Self {
        Self {
            inner,
            encoder: FormatEncoder::new(format, level),
            buf: vec![0; BUF].into_boxed_slice(),
            pos: 0,
            len: 0,
            eof: false,
            done: false,
        }
    }
}

impl<R: Read> Read for Encoder<R> {
    fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
        if out.is_empty() || self.done {
            return Ok(0);
        }
        loop {
            if self.pos == self.len && !self.eof {
                self.len = self.inner.read(&mut self.buf)?;
                self.pos = 0;
                self.eof = self.len == 0;
            }
            let flush = if self.eof { Flush::Finish } else { Flush::None };
            let p = self
                .encoder
                .compress(&self.buf[self.pos..self.len], out, flush)?;
            self.pos += p.consumed;
            if p.status == Status::Done && self.eof {
                self.done = true;
            }
            if p.produced > 0 || self.done {
                return Ok(p.produced);
            }
        }
    }
}

/// Decompresses while writing: compressed data written in comes out plain
/// in `inner`.
///
/// Bytes after the end of the stream are refused (`InvalidData`).
/// [`finish`](DecodeWriter::finish) checks that the stream was complete.
///
/// # Examples
///
/// ```
/// use std::io::Write;
///
/// use compress_lib::{Format, gzip, io::DecodeWriter};
///
/// let mut w = DecodeWriter::new(Vec::new(), Format::Gzip);
/// w.write_all(&gzip::compress(b"decoded on write"))?;
/// assert_eq!(w.finish()?, b"decoded on write");
/// # Ok::<(), std::io::Error>(())
/// ```
#[derive(Debug)]
pub struct DecodeWriter<W: Write> {
    inner: W,
    decoder: Decoder,
    buf: Box<[u8]>,
}

impl<W: Write> DecodeWriter<W> {
    /// Decodes `format` into `inner` with the default limits.
    ///
    /// # Examples
    ///
    /// ```
    /// let w = compress_lib::io::DecodeWriter::new(Vec::new(), compress_lib::Format::Zlib);
    /// # let _ = w;
    /// ```
    pub fn new(inner: W, format: Format) -> Self {
        Self {
            inner,
            decoder: Decoder::new(format),
            buf: vec![0; BUF].into_boxed_slice(),
        }
    }

    /// Sets the limits checked while decoding.
    ///
    /// # Examples
    ///
    /// ```
    /// use compress_lib::{Format, Limits, io::DecodeWriter};
    ///
    /// let w = DecodeWriter::new(Vec::new(), Format::Zlib).with_limits(Limits::new().with_max_output(1 << 20));
    /// # let _ = w;
    /// ```
    #[must_use]
    pub fn with_limits(mut self, limits: Limits) -> Self {
        self.decoder = self.decoder.with_limits(limits);
        self
    }

    fn pump(&mut self, mut data: &[u8], last: bool) -> io::Result<usize> {
        let mut taken = 0;
        loop {
            let p = if last {
                self.decoder.finish(data, &mut self.buf)?
            } else {
                self.decoder.decompress(data, &mut self.buf)?
            };
            self.inner.write_all(&self.buf[..p.produced])?;
            data = &data[p.consumed..];
            taken += p.consumed;
            match p.status {
                Status::NeedsOutput => continue,
                Status::Done if !data.is_empty() => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        crate::Error::new(crate::ErrorKind::TrailingData, self.decoder.total_in()),
                    ));
                }
                _ => return Ok(taken),
            }
        }
    }

    /// Checks that the stream ended and returns the destination.
    ///
    /// # Errors
    ///
    /// `UnexpectedEof` when the stream is incomplete; errors of the
    /// destination.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::io::Write;
    ///
    /// use compress_lib::{Format, zlib, io::DecodeWriter};
    ///
    /// let packed = zlib::compress(b"whole");
    /// let mut w = DecodeWriter::new(Vec::new(), Format::Zlib);
    /// w.write_all(&packed[..packed.len() - 2])?;
    /// assert_eq!(w.finish().unwrap_err().kind(), std::io::ErrorKind::UnexpectedEof);
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn finish(mut self) -> io::Result<W> {
        self.pump(&[], true)?;
        self.inner.flush()?;
        Ok(self.inner)
    }
}

impl<W: Write> Write for DecodeWriter<W> {
    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
        self.pump(data, false)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}