Skip to main content

flate2/deflate/
write.rs

1use crate::io;
2use crate::io::{Read, Write};
3
4use crate::zio;
5use crate::{Compress, Decompress};
6
7/// A DEFLATE encoder, or compressor.
8///
9/// This structure implements a [`Write`] interface and takes a stream of
10/// uncompressed data, writing the compressed data to the wrapped writer.
11///
12/// [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
13///
14/// # Examples
15///
16/// ```
17/// use std::io::prelude::*;
18/// use flate2::Compression;
19/// use flate2::write::DeflateEncoder;
20///
21/// // Vec<u8> implements Write to print the compressed bytes of sample string
22/// # fn main() {
23///
24/// let mut e = DeflateEncoder::new(Vec::new(), Compression::default());
25/// e.write_all(b"Hello World").unwrap();
26/// println!("{:?}", e.finish().unwrap());
27/// # }
28/// ```
29#[derive(Debug)]
30pub struct DeflateEncoder<W: Write> {
31    inner: zio::Writer<W, Compress>,
32}
33
34impl<W: Write> DeflateEncoder<W> {
35    /// Creates a new encoder which will write compressed data to the stream
36    /// given at the given compression level.
37    ///
38    /// When this encoder is dropped or unwrapped the final pieces of data will
39    /// be flushed.
40    pub fn new(w: W, level: crate::Compression) -> DeflateEncoder<W> {
41        DeflateEncoder {
42            inner: zio::Writer::new(w, Compress::new(level, false)),
43        }
44    }
45
46    /// Acquires a reference to the underlying writer.
47    pub fn get_ref(&self) -> &W {
48        self.inner.get_ref()
49    }
50
51    /// Acquires a mutable reference to the underlying writer.
52    ///
53    /// The underlying writer may be mutated or replaced as long as this
54    /// preserves the bytes and ordering of the logical output stream.
55    /// Concatenate output from each writer to reconstruct the complete stream.
56    ///
57    /// Replacing the writer does not require [`flush`](Write::flush). Call it
58    /// first when all input accepted so far must be decodable without output
59    /// from later writes. This inserts a sync-flush point and changes the output
60    /// bitstream. This is useful before applying [`std::mem::take`] to
61    /// [`get_mut`](Self::get_mut) when forwarding the stream incrementally.
62    ///
63    /// To start a new stream, use [`reset`](Self::reset); replacing the writer
64    /// does not reset this encoder.
65    pub fn get_mut(&mut self) -> &mut W {
66        self.inner.get_mut()
67    }
68
69    /// Resets the state of this encoder entirely, swapping out the output
70    /// stream for another.
71    ///
72    /// This function will finish encoding the current stream into the current
73    /// output stream before swapping out the two output streams. If the stream
74    /// cannot be finished an error is returned.
75    ///
76    /// After the current stream has been finished, this will reset the internal
77    /// state of this encoder and replace the output stream with the one
78    /// provided, returning the previous output stream. Future data written to
79    /// this encoder will be the compressed into the stream `w` provided.
80    ///
81    /// # Errors
82    ///
83    /// This function will perform I/O to complete this stream, and any I/O
84    /// errors which occur will be returned from this function.
85    pub fn reset(&mut self, w: W) -> io::Result<W> {
86        self.inner.finish()?;
87        self.inner.data.reset();
88        Ok(self.inner.replace(w))
89    }
90
91    /// Attempt to finish this output stream, writing out final chunks of data.
92    ///
93    /// Note that this function can only be used once data has finished being
94    /// written to the output stream. Once this function returns `Ok(())`, further
95    /// calls to `write` return `Ok(0)` or an error. Call [`reset`](Self::reset) to
96    /// start a new stream.
97    ///
98    /// # Errors
99    ///
100    /// This function will perform I/O to complete this stream, and any I/O
101    /// errors which occur will be returned from this function.
102    pub fn try_finish(&mut self) -> io::Result<()> {
103        self.inner.finish()
104    }
105
106    /// Consumes this encoder, flushing the output stream.
107    ///
108    /// This will flush the underlying data stream, close off the compressed
109    /// stream and, if successful, return the contained writer.
110    ///
111    /// Note that this function may not be suitable to call in a situation where
112    /// the underlying stream is an asynchronous I/O stream. To finish a stream
113    /// the `try_finish` (or `shutdown`) method should be used instead. To
114    /// re-acquire ownership of a stream it is safe to call this method after
115    /// `try_finish` or `shutdown` has returned `Ok`.
116    ///
117    /// # Errors
118    ///
119    /// This function will perform I/O to complete this stream, and any I/O
120    /// errors which occur will be returned from this function.
121    pub fn finish(mut self) -> io::Result<W> {
122        self.inner.finish()?;
123        Ok(self.inner.take_inner())
124    }
125
126    /// Consumes this encoder, flushing the output stream.
127    ///
128    /// This will flush the underlying data stream and then return the contained
129    /// writer if the flush succeeded.
130    /// The compressed stream will not closed but only flushed. This
131    /// means that obtained byte array can be extended by another deflated
132    /// stream. To close the stream add the two bytes 0x3 and 0x0.
133    ///
134    /// # Errors
135    ///
136    /// This function will perform I/O to complete this stream, and any I/O
137    /// errors which occur will be returned from this function.
138    pub fn flush_finish(mut self) -> io::Result<W> {
139        self.inner.flush()?;
140        Ok(self.inner.take_inner())
141    }
142
143    /// Returns the number of bytes that have been written to this compressor.
144    ///
145    /// Note that not all bytes written to this object may be accounted for,
146    /// there may still be some active buffering.
147    pub fn total_in(&self) -> u64 {
148        self.inner.data.total_in()
149    }
150
151    /// Returns the number of bytes that the compressor has produced.
152    ///
153    /// Note that not all bytes may have been written yet, some may still be
154    /// buffered.
155    pub fn total_out(&self) -> u64 {
156        self.inner.data.total_out()
157    }
158}
159
160impl<W: Write> Write for DeflateEncoder<W> {
161    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
162        self.inner.write(buf)
163    }
164
165    fn flush(&mut self) -> io::Result<()> {
166        self.inner.flush()
167    }
168}
169
170impl<W: Read + Write> Read for DeflateEncoder<W> {
171    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
172        self.inner.get_mut().read(buf)
173    }
174}
175
176/// A DEFLATE decoder, or decompressor.
177///
178/// This structure implements a [`Write`] and will emit a stream of decompressed
179/// data when fed a stream of compressed data.
180///
181/// After decoding a single member of the DEFLATE data this writer will return the number of bytes up to
182/// to the end of the DEFLATE member and subsequent writes will return Ok(0) allowing the caller to
183/// handle any data following the DEFLATE member.
184///
185/// [`Write`]: https://doc.rust-lang.org/std/io/trait.Read.html
186///
187/// # Examples
188///
189/// ```
190/// use std::io::prelude::*;
191/// use std::io;
192/// # use flate2::Compression;
193/// # use flate2::write::DeflateEncoder;
194/// use flate2::write::DeflateDecoder;
195///
196/// # fn main() {
197/// #    let mut e = DeflateEncoder::new(Vec::new(), Compression::default());
198/// #    e.write_all(b"Hello World").unwrap();
199/// #    let bytes = e.finish().unwrap();
200/// #    println!("{}", decode_writer(bytes).unwrap());
201/// # }
202/// // Uncompresses a Deflate Encoded vector of bytes and returns a string or error
203/// // Here Vec<u8> implements Write
204/// fn decode_writer(bytes: Vec<u8>) -> io::Result<String> {
205///    let mut writer = Vec::new();
206///    let mut deflater = DeflateDecoder::new(writer);
207///    deflater.write_all(&bytes[..])?;
208///    writer = deflater.finish()?;
209///    let return_string = String::from_utf8(writer).expect("String parsing error");
210///    Ok(return_string)
211/// }
212/// ```
213#[derive(Debug)]
214pub struct DeflateDecoder<W: Write> {
215    inner: zio::Writer<W, Decompress>,
216}
217
218impl<W: Write> DeflateDecoder<W> {
219    /// Creates a new decoder which will write uncompressed data to the stream.
220    ///
221    /// When this encoder is dropped or unwrapped the final pieces of data will
222    /// be flushed.
223    pub fn new(w: W) -> DeflateDecoder<W> {
224        DeflateDecoder {
225            inner: zio::Writer::new(w, Decompress::new(false)),
226        }
227    }
228
229    /// Acquires a reference to the underlying writer.
230    pub fn get_ref(&self) -> &W {
231        self.inner.get_ref()
232    }
233
234    /// Acquires a mutable reference to the underlying writer.
235    ///
236    /// The underlying writer may be mutated or replaced as long as this
237    /// preserves the bytes and ordering of the logical output stream.
238    /// Concatenate output from each writer to reconstruct the complete stream.
239    ///
240    /// Replacing the writer does not require [`flush`](Write::flush). Call it
241    /// first to write all decompressed output currently available to the
242    /// current writer. This is useful before applying [`std::mem::take`] to
243    /// [`get_mut`](Self::get_mut) when forwarding output incrementally.
244    ///
245    /// To start a new stream, use [`reset`](Self::reset); replacing the writer
246    /// does not reset this decoder.
247    pub fn get_mut(&mut self) -> &mut W {
248        self.inner.get_mut()
249    }
250
251    /// Resets the state of this decoder entirely, swapping out the output
252    /// stream for another.
253    ///
254    /// Any pending output will be written to the current output stream before
255    /// swapping out the two output streams.
256    ///
257    /// This will then reset the internal state of this decoder and replace the
258    /// output stream with the one provided, returning the previous output
259    /// stream. Future data written to this decoder will be decompressed into
260    /// the output stream `w`.
261    ///
262    /// # Errors
263    ///
264    /// This function will perform I/O to write any pending output, and if that
265    /// I/O returns an error then that will be returned from this function.
266    pub fn reset(&mut self, w: W) -> io::Result<W> {
267        self.inner.drain()?;
268        self.inner.data = Decompress::new(false);
269        Ok(self.inner.replace(w))
270    }
271
272    /// Attempt to finish this output stream, writing out final chunks of data.
273    ///
274    /// Note that this function can only be used once data has finished being
275    /// written to the output stream. After this function is called then further
276    /// calls to `write` may result in a panic.
277    ///
278    /// # Panics
279    ///
280    /// Attempts to write data to this stream may result in a panic after this
281    /// function is called.
282    ///
283    /// # Errors
284    ///
285    /// This function will perform I/O to finish the stream, returning any
286    /// errors which happen.
287    pub fn try_finish(&mut self) -> io::Result<()> {
288        self.inner.finish()
289    }
290
291    /// Consumes this encoder, flushing the output stream.
292    ///
293    /// This will flush the underlying data stream and then return the contained
294    /// writer if the flush succeeded.
295    ///
296    /// Note that this function may not be suitable to call in a situation where
297    /// the underlying stream is an asynchronous I/O stream. To finish a stream
298    /// the `try_finish` (or `shutdown`) method should be used instead. To
299    /// re-acquire ownership of a stream it is safe to call this method after
300    /// `try_finish` or `shutdown` has returned `Ok`.
301    ///
302    /// # Errors
303    ///
304    /// This function will perform I/O to complete this stream, and any I/O
305    /// errors which occur will be returned from this function.
306    pub fn finish(mut self) -> io::Result<W> {
307        self.inner.finish()?;
308        Ok(self.inner.take_inner())
309    }
310
311    /// Returns the number of bytes that the decompressor has consumed for
312    /// decompression.
313    ///
314    /// Note that this will likely be smaller than the number of bytes
315    /// successfully written to this stream due to internal buffering.
316    pub fn total_in(&self) -> u64 {
317        self.inner.data.total_in()
318    }
319
320    /// Returns the number of bytes that the decompressor has written to its
321    /// output stream.
322    pub fn total_out(&self) -> u64 {
323        self.inner.data.total_out()
324    }
325}
326
327impl<W: Write> Write for DeflateDecoder<W> {
328    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
329        self.inner.write(buf)
330    }
331
332    fn flush(&mut self) -> io::Result<()> {
333        self.inner.flush()
334    }
335}
336
337impl<W: Read + Write> Read for DeflateDecoder<W> {
338    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
339        self.inner.get_mut().read(buf)
340    }
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346    use crate::Compression;
347    use alloc::string::String;
348    use alloc::vec::Vec;
349
350    const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
351        Hello World Hello World Hello World Hello World Hello World \
352        Hello World Hello World Hello World Hello World Hello World \
353        Hello World Hello World Hello World Hello World Hello World \
354        Hello World Hello World Hello World Hello World Hello World";
355
356    // DeflateDecoder consumes one zlib archive and then returns 0 for subsequent writes, allowing any
357    // additional data to be consumed by the caller.
358    #[test]
359    fn decode_extra_data() {
360        let compressed = {
361            let mut e = DeflateEncoder::new(Vec::new(), Compression::default());
362            e.write_all(STR.as_ref()).unwrap();
363            let mut b = e.finish().unwrap();
364            b.push(b'x');
365            b
366        };
367
368        let mut writer = Vec::new();
369        let mut decoder = DeflateDecoder::new(writer);
370        let mut consumed_bytes = 0;
371        loop {
372            let n = decoder.write(&compressed[consumed_bytes..]).unwrap();
373            if n == 0 {
374                break;
375            }
376            consumed_bytes += n;
377        }
378        writer = decoder.finish().unwrap();
379        let actual = String::from_utf8(writer).expect("String parsing error");
380        assert_eq!(actual, STR);
381        assert_eq!(&compressed[consumed_bytes..], b"x");
382    }
383}