Skip to main content

flate2/zlib/
write.rs

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