zstd-native 0.2.0+zstd.1.6.0

Fastest pure Rust Zstandard (zstd) compression and decompression: byte-identical with libzstd 1.6.0 and faster than C. No C code, no_std.
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
//! `std::io` adapters: [`Decoder`] (`Read`) and [`Encoder`] (`Write`).

use std::boxed::Box;
use std::io::{self, BufRead, BufReader, Read, Write};
use std::string::String;
use std::vec;
use std::vec::Vec;

use crate::dict::Dictionary;
use crate::enc::{EncoderDictionary, EndOp, StreamEncoder};
use crate::error::Error;
use crate::stream::StreamDecoder;

/// Decompresses a zstd stream from a reader (`std::io::Read`), frame after
/// frame, like the `zstd` crate's `Decoder`.
///
/// ```
/// use std::io::Read;
/// # let compressed: &[u8] = &[0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x05, 0x29, 0x00, 0x00, 0x68, 0x65, 0x6c, 0x6c, 0x6f];
/// let mut out = String::new();
/// zstd_native::Decoder::new(compressed).read_to_string(&mut out)?;
/// assert_eq!(out, "hello");
/// # Ok::<(), std::io::Error>(())
/// ```
///
/// Input that ends inside a frame is an [`io::ErrorKind::UnexpectedEof`]
/// error; corrupt input is [`io::ErrorKind::InvalidData`] (the source is an
/// [`Error`]). Empty input is zero frames: empty output, as with
/// libzstd (the `zstd` crate's reader reports an error there instead).
///
/// [`read_to_end`](Read::read_to_end) (and `read_to_string`) decode
/// straight into the `Vec`, growing it (reserving a frame's content size
/// up front, up to the window limit), without the window buffer and the
/// copy out of it that [`read`](Read::read) needs.
#[derive(Debug)]
pub struct Decoder<R> {
    reader: R,
    dec: StreamDecoder,
    failed: bool,
}

impl<R: Read> Decoder<BufReader<R>> {
    /// Reads from `reader` through a buffer (use [`with_buffer`](Decoder::with_buffer)
    /// for a reader that already buffers, such as a `&[u8]`).
    pub fn new(reader: R) -> Self {
        Decoder::with_buffer(BufReader::with_capacity(128 << 10, reader))
    }
}

impl<R: BufRead> Decoder<R> {
    /// Reads from a buffered reader.
    pub fn with_buffer(reader: R) -> Self {
        Decoder {
            reader,
            dec: StreamDecoder::new(),
            failed: false,
        }
    }

    /// Reads from a buffered reader, using `dict` for every frame.
    pub fn with_dictionary(reader: R, dict: Dictionary) -> Self {
        Decoder {
            reader,
            dec: StreamDecoder::with_dictionary(dict),
            failed: false,
        }
    }

    /// Sets the largest window accepted (see [`StreamDecoder::set_window_log_max`]).
    pub fn set_window_log_max(&mut self, log: u32) {
        self.dec.set_window_log_max(log);
    }

    /// The underlying reader.
    pub fn get_ref(&self) -> &R {
        &self.reader
    }

    /// The underlying reader, mutably (reading from it directly loses the
    /// decoder's place in the stream).
    pub fn get_mut(&mut self) -> &mut R {
        &mut self.reader
    }

    /// Returns the underlying reader.
    pub fn into_inner(self) -> R {
        self.reader
    }
}

impl<R: BufRead> Read for Decoder<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        if self.failed {
            return Err(io::Error::other("zstd decoder failed earlier"));
        }
        loop {
            let input = self.reader.fill_buf()?;
            let eof = input.is_empty();
            let p = match self.dec.decode(input, buf) {
                Ok(p) => p,
                Err(e) => {
                    self.failed = true;
                    return Err(e.into());
                }
            };
            self.reader.consume(p.read);
            if p.written > 0 {
                return Ok(p.written);
            }
            if eof {
                return if p.at_frame_boundary {
                    Ok(0)
                } else {
                    self.failed = true;
                    Err(Error::Truncated.into())
                };
            }
        }
    }

    /// Decodes straight into `buf`, growing it (by a frame's content size
    /// when the header gives it), without the window buffer and the copy
    /// out of it that [`read`](Read::read) needs.
    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
        if self.failed {
            return Err(io::Error::other("zstd decoder failed earlier"));
        }
        let start = buf.len();
        let r = self.read_to_end_direct(buf);
        if r.is_err() && !self.failed {
            // A reader error: later reads go on from the window buffer.
            if let Err(e) = self.dec.leave_direct(buf) {
                self.failed = true;
                return Err(e.into());
            }
        }
        r.map(|()| buf.len() - start)
    }

    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
        // `Read`'s default would go through `read`, not `read_to_end`.
        let old = buf.len();
        let mut v = core::mem::take(buf).into_bytes();
        let r = self.read_to_end(&mut v);
        match String::from_utf8(v) {
            Ok(s) => {
                *buf = s;
                r
            }
            Err(e) => {
                // As `Read::read_to_string`: no invalid text is appended.
                let mut v = e.into_bytes();
                v.truncate(old);
                *buf = String::from_utf8(v).expect("the text before was valid UTF-8");
                r.and(Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "stream did not contain valid UTF-8",
                )))
            }
        }
    }
}

impl<R: BufRead> Decoder<R> {
    /// `read_to_end` until the end of the input (or an error).
    fn read_to_end_direct(&mut self, buf: &mut Vec<u8>) -> io::Result<()> {
        loop {
            let input = match self.reader.fill_buf() {
                Ok(i) => i,
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(e) => return Err(e),
            };
            let eof = input.is_empty();
            let read = match self.dec.decode_vec(input, buf) {
                Ok(n) => n,
                Err(e) => {
                    self.failed = true;
                    return Err(e.into());
                }
            };
            self.reader.consume(read);
            if eof {
                return if self.dec.at_frame_boundary() {
                    Ok(())
                } else {
                    self.failed = true;
                    Err(Error::Truncated.into())
                };
            }
        }
    }
}

/// The output buffer size of [`Encoder`]: libzstd's `ZSTD_CStreamOutSize()`
/// (a full block's compressed bound, a block header and a checksum).
const ENCODER_BUF_SIZE: usize = crate::compress_bound(128 << 10) + 3 + 4;

/// Compresses into a writer (`std::io::Write`), like the `zstd` crate's
/// `Encoder`: one zstd frame, ended by [`finish`](Encoder::finish). The
/// output is byte-identical to libzstd 1.6.0's streaming compressor's
/// (`ZSTD_compressStream2`) for the same level, writes and flushes.
///
/// ```
/// use std::io::Write;
/// let mut enc = zstd_native::Encoder::new(Vec::new(), 3);
/// enc.write_all(b"hello hello hello hello")?;
/// let compressed = enc.finish()?;
/// assert_eq!(zstd_native::decompress(&compressed).unwrap(), b"hello hello hello hello");
/// # Ok::<(), std::io::Error>(())
/// ```
///
/// [`flush`](Write::flush) compresses the data written so far and writes
/// it out (`ZSTD_e_flush`), without ending the frame. Dropping the encoder
/// without calling [`finish`](Encoder::finish) leaves the frame
/// incomplete. Errors are [`io::ErrorKind::InvalidInput`] for a pledged
/// size that doesn't match, [`io::ErrorKind::InvalidData`] for the others
/// (the source is an [`Error`]).
#[derive(Debug)]
pub struct Encoder<W: Write> {
    writer: W,
    enc: StreamEncoder,
    buf: Box<[u8]>,
}

impl<W: Write> Encoder<W> {
    /// Compresses at `level` (see [`compress`](crate::compress)) into `writer`.
    pub fn new(writer: W, level: i32) -> Self {
        Encoder {
            writer,
            enc: StreamEncoder::new(level),
            buf: vec![0u8; ENCODER_BUF_SIZE].into_boxed_slice(),
        }
    }

    /// Compresses at `level` with the dictionary `dict` (see
    /// [`Compressor::set_dictionary`](crate::Compressor::set_dictionary))
    /// into `writer`, like the `zstd` crate's `Encoder::with_dictionary`.
    ///
    /// ```
    /// use std::io::Write;
    /// let dict = b"hello world, hello there";
    /// let mut enc = zstd_native::Encoder::with_dictionary(Vec::new(), 3, dict)?;
    /// enc.write_all(b"hello there, hello world")?;
    /// let compressed = enc.finish()?;
    /// let dict = zstd_native::Dictionary::new(dict).unwrap();
    /// let mut d = zstd_native::Decompressor::with_dictionary(dict);
    /// assert_eq!(d.decompress(&compressed).unwrap(), b"hello there, hello world");
    /// # Ok::<(), std::io::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// [`io::ErrorKind::InvalidData`] if a zstd-format dictionary is
    /// corrupt.
    pub fn with_dictionary(writer: W, level: i32, dict: &[u8]) -> io::Result<Self> {
        Ok(Encoder {
            writer,
            enc: StreamEncoder::with_dictionary(level, dict).map_err(enc_err)?,
            buf: vec![0u8; ENCODER_BUF_SIZE].into_boxed_slice(),
        })
    }

    /// Compresses with a prepared dictionary, at its level, into `writer`
    /// (the `zstd` crate's `Encoder::with_prepared_dictionary`).
    pub fn with_prepared_dictionary(writer: W, dict: &EncoderDictionary) -> Self {
        Encoder {
            writer,
            enc: StreamEncoder::with_prepared_dictionary(dict),
            buf: vec![0u8; ENCODER_BUF_SIZE].into_boxed_slice(),
        }
    }

    /// Declares the size of the data to be written (see
    /// [`StreamEncoder::set_pledged_src_size`]): the frame header then
    /// holds it. Must be called before the first write.
    ///
    /// # Errors
    ///
    /// [`io::ErrorKind::InvalidInput`] after the first write.
    pub fn set_pledged_src_size(&mut self, size: Option<u64>) -> io::Result<()> {
        self.enc
            .set_pledged_src_size(size)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
    }

    /// Ends the frame with a content checksum (see
    /// [`StreamEncoder::set_checksum`]; the `zstd` crate's
    /// `Encoder::include_checksum`). Must be called before the first write.
    ///
    /// ```
    /// use std::io::Write;
    /// let mut enc = zstd_native::Encoder::new(Vec::new(), 3);
    /// enc.set_checksum(true)?;
    /// enc.write_all(b"checked, checked, checked")?;
    /// let compressed = enc.finish()?;
    /// assert_eq!(zstd_native::decompress(&compressed).unwrap(), b"checked, checked, checked");
    /// # Ok::<(), std::io::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// [`io::ErrorKind::InvalidInput`] after the first write.
    pub fn set_checksum(&mut self, on: bool) -> io::Result<()> {
        self.enc
            .set_checksum(on)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
    }

    /// Writes the content size into the frame header when it is pledged
    /// (see [`StreamEncoder::set_content_size_flag`]; the `zstd` crate's
    /// `Encoder::include_contentsize`). Must be called before the first
    /// write.
    ///
    /// # Errors
    ///
    /// [`io::ErrorKind::InvalidInput`] after the first write.
    pub fn set_content_size_flag(&mut self, on: bool) -> io::Result<()> {
        self.enc
            .set_content_size_flag(on)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
    }

    /// Writes the dictionary's ID into the frame header (see
    /// [`StreamEncoder::set_dict_id_flag`]; the `zstd` crate's
    /// `Encoder::include_dictid`). Must be called before the first write.
    ///
    /// # Errors
    ///
    /// [`io::ErrorKind::InvalidInput`] after the first write.
    pub fn set_dict_id_flag(&mut self, on: bool) -> io::Result<()> {
        self.enc
            .set_dict_id_flag(on)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
    }

    /// Compresses with `n` worker threads (see
    /// [`StreamEncoder::set_workers`]; the `zstd` crate's
    /// `Encoder::multithread`), with libzstd's output for the same worker
    /// count. Must be called before the first write.
    ///
    /// ```
    /// use std::io::Write;
    /// let data = b"hello hello hello hello ".repeat(100_000);
    /// let mut enc = zstd_native::Encoder::new(Vec::new(), 3);
    /// enc.set_workers(4)?;
    /// enc.write_all(&data)?;
    /// let compressed = enc.finish()?;
    /// assert_eq!(zstd_native::decompress(&compressed).unwrap(), data);
    /// # Ok::<(), std::io::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// [`io::ErrorKind::InvalidInput`] after the first write.
    pub fn set_workers(&mut self, n: u32) -> io::Result<()> {
        self.enc
            .set_workers(n)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
    }

    /// The underlying writer.
    pub fn get_ref(&self) -> &W {
        &self.writer
    }

    /// The underlying writer, mutably (writing to it directly corrupts the
    /// compressed stream).
    pub fn get_mut(&mut self) -> &mut W {
        &mut self.writer
    }

    /// Ends the frame (`ZSTD_e_end`), writes out everything and returns the
    /// writer.
    ///
    /// # Errors
    ///
    /// As the writer's, or as [`StreamEncoder::compress`].
    pub fn finish(mut self) -> io::Result<W> {
        self.run(EndOp::End)?;
        self.writer.flush()?;
        Ok(self.writer)
    }

    /// Runs `op` (flush or end) with no more input until it completes.
    fn run(&mut self, op: EndOp) -> io::Result<()> {
        loop {
            let p = self.enc.compress(&[], &mut self.buf, op).map_err(enc_err)?;
            self.writer.write_all(&self.buf[..p.written])?;
            if p.remaining == 0 {
                return Ok(());
            }
        }
    }
}

/// Maps a compression error to an I/O error.
fn enc_err(e: Error) -> io::Error {
    let kind = match e {
        Error::SrcSizeWrong | Error::StageWrong => io::ErrorKind::InvalidInput,
        Error::MemoryAllocation => io::ErrorKind::OutOfMemory,
        _ => io::ErrorKind::InvalidData,
    };
    io::Error::new(kind, e)
}

impl<W: Write> Write for Encoder<W> {
    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
        if data.is_empty() {
            return Ok(0);
        }
        loop {
            let p = self
                .enc
                .compress(data, &mut self.buf, EndOp::Continue)
                .map_err(enc_err)?;
            self.writer.write_all(&self.buf[..p.written])?;
            if p.read > 0 {
                return Ok(p.read);
            }
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        self.run(EndOp::Flush)?;
        self.writer.flush()
    }
}