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