Skip to main content

zstd_native/
io.rs

1//! `std::io` adapters: [`Decoder`] (`Read`) and [`Encoder`] (`Write`).
2
3use std::boxed::Box;
4use std::io::{self, BufRead, BufReader, Read, Write};
5use std::string::String;
6use std::vec;
7use std::vec::Vec;
8
9use crate::dict::Dictionary;
10use crate::enc::{EncoderDictionary, EndOp, StreamEncoder};
11use crate::error::Error;
12use crate::stream::StreamDecoder;
13
14/// Decompresses a zstd stream from a reader (`std::io::Read`), frame after
15/// frame, like the `zstd` crate's `Decoder`.
16///
17/// ```
18/// use std::io::Read;
19/// # let compressed: &[u8] = &[0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x05, 0x29, 0x00, 0x00, 0x68, 0x65, 0x6c, 0x6c, 0x6f];
20/// let mut out = String::new();
21/// zstd_native::Decoder::new(compressed).read_to_string(&mut out)?;
22/// assert_eq!(out, "hello");
23/// # Ok::<(), std::io::Error>(())
24/// ```
25///
26/// Input that ends inside a frame is an [`io::ErrorKind::UnexpectedEof`]
27/// error; corrupt input is [`io::ErrorKind::InvalidData`] (the source is an
28/// [`Error`]). Empty input is zero frames: empty output, as with
29/// libzstd (the `zstd` crate's reader reports an error there instead).
30///
31/// [`read_to_end`](Read::read_to_end) (and `read_to_string`) decode
32/// straight into the `Vec`, growing it (reserving a frame's content size
33/// up front, up to the window limit), without the window buffer and the
34/// copy out of it that [`read`](Read::read) needs.
35#[derive(Debug)]
36pub struct Decoder<R> {
37    reader: R,
38    dec: StreamDecoder,
39    failed: bool,
40}
41
42impl<R: Read> Decoder<BufReader<R>> {
43    /// Reads from `reader` through a buffer (use [`with_buffer`](Decoder::with_buffer)
44    /// for a reader that already buffers, such as a `&[u8]`).
45    pub fn new(reader: R) -> Self {
46        Decoder::with_buffer(BufReader::with_capacity(128 << 10, reader))
47    }
48}
49
50impl<R: BufRead> Decoder<R> {
51    /// Reads from a buffered reader.
52    pub fn with_buffer(reader: R) -> Self {
53        Decoder {
54            reader,
55            dec: StreamDecoder::new(),
56            failed: false,
57        }
58    }
59
60    /// Reads from a buffered reader, using `dict` for every frame.
61    pub fn with_dictionary(reader: R, dict: Dictionary) -> Self {
62        Decoder {
63            reader,
64            dec: StreamDecoder::with_dictionary(dict),
65            failed: false,
66        }
67    }
68
69    /// Sets the largest window accepted (see [`StreamDecoder::set_window_log_max`]).
70    pub fn set_window_log_max(&mut self, log: u32) {
71        self.dec.set_window_log_max(log);
72    }
73
74    /// The underlying reader.
75    pub fn get_ref(&self) -> &R {
76        &self.reader
77    }
78
79    /// The underlying reader, mutably (reading from it directly loses the
80    /// decoder's place in the stream).
81    pub fn get_mut(&mut self) -> &mut R {
82        &mut self.reader
83    }
84
85    /// Returns the underlying reader.
86    pub fn into_inner(self) -> R {
87        self.reader
88    }
89}
90
91impl<R: BufRead> Read for Decoder<R> {
92    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
93        if buf.is_empty() {
94            return Ok(0);
95        }
96        if self.failed {
97            return Err(io::Error::other("zstd decoder failed earlier"));
98        }
99        loop {
100            let input = self.reader.fill_buf()?;
101            let eof = input.is_empty();
102            let p = match self.dec.decode(input, buf) {
103                Ok(p) => p,
104                Err(e) => {
105                    self.failed = true;
106                    return Err(e.into());
107                }
108            };
109            self.reader.consume(p.read);
110            if p.written > 0 {
111                return Ok(p.written);
112            }
113            if eof {
114                return if p.at_frame_boundary {
115                    Ok(0)
116                } else {
117                    self.failed = true;
118                    Err(Error::Truncated.into())
119                };
120            }
121        }
122    }
123
124    /// Decodes straight into `buf`, growing it (by a frame's content size
125    /// when the header gives it), without the window buffer and the copy
126    /// out of it that [`read`](Read::read) needs.
127    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
128        if self.failed {
129            return Err(io::Error::other("zstd decoder failed earlier"));
130        }
131        let start = buf.len();
132        let r = self.read_to_end_direct(buf);
133        if r.is_err() && !self.failed {
134            // A reader error: later reads go on from the window buffer.
135            if let Err(e) = self.dec.leave_direct(buf) {
136                self.failed = true;
137                return Err(e.into());
138            }
139        }
140        r.map(|()| buf.len() - start)
141    }
142
143    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
144        // `Read`'s default would go through `read`, not `read_to_end`.
145        let old = buf.len();
146        let mut v = core::mem::take(buf).into_bytes();
147        let r = self.read_to_end(&mut v);
148        match String::from_utf8(v) {
149            Ok(s) => {
150                *buf = s;
151                r
152            }
153            Err(e) => {
154                // As `Read::read_to_string`: no invalid text is appended.
155                let mut v = e.into_bytes();
156                v.truncate(old);
157                *buf = String::from_utf8(v).expect("the text before was valid UTF-8");
158                r.and(Err(io::Error::new(
159                    io::ErrorKind::InvalidData,
160                    "stream did not contain valid UTF-8",
161                )))
162            }
163        }
164    }
165}
166
167impl<R: BufRead> Decoder<R> {
168    /// `read_to_end` until the end of the input (or an error).
169    fn read_to_end_direct(&mut self, buf: &mut Vec<u8>) -> io::Result<()> {
170        loop {
171            let input = match self.reader.fill_buf() {
172                Ok(i) => i,
173                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
174                Err(e) => return Err(e),
175            };
176            let eof = input.is_empty();
177            let read = match self.dec.decode_vec(input, buf) {
178                Ok(n) => n,
179                Err(e) => {
180                    self.failed = true;
181                    return Err(e.into());
182                }
183            };
184            self.reader.consume(read);
185            if eof {
186                return if self.dec.at_frame_boundary() {
187                    Ok(())
188                } else {
189                    self.failed = true;
190                    Err(Error::Truncated.into())
191                };
192            }
193        }
194    }
195}
196
197/// The output buffer size of [`Encoder`]: libzstd's `ZSTD_CStreamOutSize()`
198/// (a full block's compressed bound, a block header and a checksum).
199const ENCODER_BUF_SIZE: usize = crate::compress_bound(128 << 10) + 3 + 4;
200
201/// Compresses into a writer (`std::io::Write`), like the `zstd` crate's
202/// `Encoder`: one zstd frame, ended by [`finish`](Encoder::finish). The
203/// output is byte-identical to libzstd 1.5.7's streaming compressor's
204/// (`ZSTD_compressStream2`) for the same level, writes and flushes.
205///
206/// ```
207/// use std::io::Write;
208/// let mut enc = zstd_native::Encoder::new(Vec::new(), 3);
209/// enc.write_all(b"hello hello hello hello")?;
210/// let compressed = enc.finish()?;
211/// assert_eq!(zstd_native::decompress(&compressed).unwrap(), b"hello hello hello hello");
212/// # Ok::<(), std::io::Error>(())
213/// ```
214///
215/// [`flush`](Write::flush) compresses the data written so far and writes
216/// it out (`ZSTD_e_flush`), without ending the frame. Dropping the encoder
217/// without calling [`finish`](Encoder::finish) leaves the frame
218/// incomplete. Errors are [`io::ErrorKind::InvalidInput`] for a pledged
219/// size that doesn't match, [`io::ErrorKind::InvalidData`] for the others
220/// (the source is an [`Error`]).
221#[derive(Debug)]
222pub struct Encoder<W: Write> {
223    writer: W,
224    enc: StreamEncoder,
225    buf: Box<[u8]>,
226}
227
228impl<W: Write> Encoder<W> {
229    /// Compresses at `level` (see [`compress`](crate::compress)) into `writer`.
230    pub fn new(writer: W, level: i32) -> Self {
231        Encoder {
232            writer,
233            enc: StreamEncoder::new(level),
234            buf: vec![0u8; ENCODER_BUF_SIZE].into_boxed_slice(),
235        }
236    }
237
238    /// Compresses at `level` with the dictionary `dict` (see
239    /// [`Compressor::set_dictionary`](crate::Compressor::set_dictionary))
240    /// into `writer`, like the `zstd` crate's `Encoder::with_dictionary`.
241    ///
242    /// ```
243    /// use std::io::Write;
244    /// let dict = b"hello world, hello there";
245    /// let mut enc = zstd_native::Encoder::with_dictionary(Vec::new(), 3, dict)?;
246    /// enc.write_all(b"hello there, hello world")?;
247    /// let compressed = enc.finish()?;
248    /// let dict = zstd_native::Dictionary::new(dict).unwrap();
249    /// let mut d = zstd_native::Decompressor::with_dictionary(dict);
250    /// assert_eq!(d.decompress(&compressed).unwrap(), b"hello there, hello world");
251    /// # Ok::<(), std::io::Error>(())
252    /// ```
253    ///
254    /// # Errors
255    ///
256    /// [`io::ErrorKind::InvalidData`] if a zstd-format dictionary is
257    /// corrupt.
258    pub fn with_dictionary(writer: W, level: i32, dict: &[u8]) -> io::Result<Self> {
259        Ok(Encoder {
260            writer,
261            enc: StreamEncoder::with_dictionary(level, dict).map_err(enc_err)?,
262            buf: vec![0u8; ENCODER_BUF_SIZE].into_boxed_slice(),
263        })
264    }
265
266    /// Compresses with a prepared dictionary, at its level, into `writer`
267    /// (the `zstd` crate's `Encoder::with_prepared_dictionary`).
268    pub fn with_prepared_dictionary(writer: W, dict: &EncoderDictionary) -> Self {
269        Encoder {
270            writer,
271            enc: StreamEncoder::with_prepared_dictionary(dict),
272            buf: vec![0u8; ENCODER_BUF_SIZE].into_boxed_slice(),
273        }
274    }
275
276    /// Declares the size of the data to be written (see
277    /// [`StreamEncoder::set_pledged_src_size`]): the frame header then
278    /// holds it. Must be called before the first write.
279    ///
280    /// # Errors
281    ///
282    /// [`io::ErrorKind::InvalidInput`] after the first write.
283    pub fn set_pledged_src_size(&mut self, size: Option<u64>) -> io::Result<()> {
284        self.enc
285            .set_pledged_src_size(size)
286            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
287    }
288
289    /// Ends the frame with a content checksum (see
290    /// [`StreamEncoder::set_checksum`]; the `zstd` crate's
291    /// `Encoder::include_checksum`). Must be called before the first write.
292    ///
293    /// ```
294    /// use std::io::Write;
295    /// let mut enc = zstd_native::Encoder::new(Vec::new(), 3);
296    /// enc.set_checksum(true)?;
297    /// enc.write_all(b"checked, checked, checked")?;
298    /// let compressed = enc.finish()?;
299    /// assert_eq!(zstd_native::decompress(&compressed).unwrap(), b"checked, checked, checked");
300    /// # Ok::<(), std::io::Error>(())
301    /// ```
302    ///
303    /// # Errors
304    ///
305    /// [`io::ErrorKind::InvalidInput`] after the first write.
306    pub fn set_checksum(&mut self, on: bool) -> io::Result<()> {
307        self.enc
308            .set_checksum(on)
309            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
310    }
311
312    /// Writes the content size into the frame header when it is pledged
313    /// (see [`StreamEncoder::set_content_size_flag`]; the `zstd` crate's
314    /// `Encoder::include_contentsize`). Must be called before the first
315    /// write.
316    ///
317    /// # Errors
318    ///
319    /// [`io::ErrorKind::InvalidInput`] after the first write.
320    pub fn set_content_size_flag(&mut self, on: bool) -> io::Result<()> {
321        self.enc
322            .set_content_size_flag(on)
323            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
324    }
325
326    /// Writes the dictionary's ID into the frame header (see
327    /// [`StreamEncoder::set_dict_id_flag`]; the `zstd` crate's
328    /// `Encoder::include_dictid`). Must be called before the first write.
329    ///
330    /// # Errors
331    ///
332    /// [`io::ErrorKind::InvalidInput`] after the first write.
333    pub fn set_dict_id_flag(&mut self, on: bool) -> io::Result<()> {
334        self.enc
335            .set_dict_id_flag(on)
336            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
337    }
338
339    /// Compresses with `n` worker threads (see
340    /// [`StreamEncoder::set_workers`]; the `zstd` crate's
341    /// `Encoder::multithread`), with libzstd's output for the same worker
342    /// count. Must be called before the first write.
343    ///
344    /// ```
345    /// use std::io::Write;
346    /// let data = b"hello hello hello hello ".repeat(100_000);
347    /// let mut enc = zstd_native::Encoder::new(Vec::new(), 3);
348    /// enc.set_workers(4)?;
349    /// enc.write_all(&data)?;
350    /// let compressed = enc.finish()?;
351    /// assert_eq!(zstd_native::decompress(&compressed).unwrap(), data);
352    /// # Ok::<(), std::io::Error>(())
353    /// ```
354    ///
355    /// # Errors
356    ///
357    /// [`io::ErrorKind::InvalidInput`] after the first write.
358    pub fn set_workers(&mut self, n: u32) -> io::Result<()> {
359        self.enc
360            .set_workers(n)
361            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
362    }
363
364    /// The underlying writer.
365    pub fn get_ref(&self) -> &W {
366        &self.writer
367    }
368
369    /// The underlying writer, mutably (writing to it directly corrupts the
370    /// compressed stream).
371    pub fn get_mut(&mut self) -> &mut W {
372        &mut self.writer
373    }
374
375    /// Ends the frame (`ZSTD_e_end`), writes out everything and returns the
376    /// writer.
377    ///
378    /// # Errors
379    ///
380    /// As the writer's, or as [`StreamEncoder::compress`].
381    pub fn finish(mut self) -> io::Result<W> {
382        self.run(EndOp::End)?;
383        self.writer.flush()?;
384        Ok(self.writer)
385    }
386
387    /// Runs `op` (flush or end) with no more input until it completes.
388    fn run(&mut self, op: EndOp) -> io::Result<()> {
389        loop {
390            let p = self.enc.compress(&[], &mut self.buf, op).map_err(enc_err)?;
391            self.writer.write_all(&self.buf[..p.written])?;
392            if p.remaining == 0 {
393                return Ok(());
394            }
395        }
396    }
397}
398
399/// Maps a compression error to an I/O error.
400fn enc_err(e: Error) -> io::Error {
401    let kind = match e {
402        Error::SrcSizeWrong | Error::StageWrong => io::ErrorKind::InvalidInput,
403        Error::MemoryAllocation => io::ErrorKind::OutOfMemory,
404        _ => io::ErrorKind::InvalidData,
405    };
406    io::Error::new(kind, e)
407}
408
409impl<W: Write> Write for Encoder<W> {
410    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
411        if data.is_empty() {
412            return Ok(0);
413        }
414        loop {
415            let p = self
416                .enc
417                .compress(data, &mut self.buf, EndOp::Continue)
418                .map_err(enc_err)?;
419            self.writer.write_all(&self.buf[..p.written])?;
420            if p.read > 0 {
421                return Ok(p.read);
422            }
423        }
424    }
425
426    fn flush(&mut self) -> io::Result<()> {
427        self.run(EndOp::Flush)?;
428        self.writer.flush()
429    }
430}