flate2/zlib/
read.rs

1use std::io;
2use std::io::prelude::*;
3
4use super::bufread;
5use crate::bufreader::BufReader;
6use crate::Decompress;
7
8/// A ZLIB encoder, or compressor.
9///
10/// This structure implements a [`Read`] interface. When read from, it reads
11/// uncompressed data from the underlying [`Read`] and provides the compressed data.
12///
13/// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
14///
15/// # Examples
16///
17/// ```
18/// use std::io::prelude::*;
19/// use flate2::Compression;
20/// use flate2::read::ZlibEncoder;
21/// use std::fs::File;
22///
23/// // Open example file and compress the contents using Read interface
24///
25/// # fn open_hello_world() -> std::io::Result<Vec<u8>> {
26/// let f = File::open("examples/hello_world.txt")?;
27/// let mut z = ZlibEncoder::new(f, Compression::fast());
28/// let mut buffer = Vec::new();
29/// z.read_to_end(&mut buffer)?;
30/// # Ok(buffer)
31/// # }
32/// ```
33#[derive(Debug)]
34pub struct ZlibEncoder<R> {
35    inner: bufread::ZlibEncoder<BufReader<R>>,
36}
37
38impl<R: Read> ZlibEncoder<R> {
39    /// Creates a new encoder which will read uncompressed data from the given
40    /// stream and emit the compressed stream.
41    pub fn new(r: R, level: crate::Compression) -> ZlibEncoder<R> {
42        ZlibEncoder {
43            inner: bufread::ZlibEncoder::new(BufReader::new(r), level),
44        }
45    }
46
47    /// Creates a new encoder with the given `compression` settings which will
48    /// read uncompressed data from the given stream `r` and emit the compressed stream.
49    pub fn new_with_compress(r: R, compression: crate::Compress) -> ZlibEncoder<R> {
50        ZlibEncoder {
51            inner: bufread::ZlibEncoder::new_with_compress(BufReader::new(r), compression),
52        }
53    }
54}
55
56impl<R> ZlibEncoder<R> {
57    /// Resets the state of this encoder entirely, swapping out the input
58    /// stream for another.
59    ///
60    /// This function will reset the internal state of this encoder and replace
61    /// the input stream with the one provided, returning the previous input
62    /// stream. Future data read from this encoder will be the compressed
63    /// version of `r`'s data.
64    ///
65    /// Note that there may be currently buffered data when this function is
66    /// called, and in that case the buffered data is discarded.
67    pub fn reset(&mut self, r: R) -> R {
68        super::bufread::reset_encoder_data(&mut self.inner);
69        self.inner.get_mut().reset(r)
70    }
71
72    /// Acquires a reference to the underlying stream
73    pub fn get_ref(&self) -> &R {
74        self.inner.get_ref().get_ref()
75    }
76
77    /// Acquires a mutable reference to the underlying stream
78    ///
79    /// Note that mutation of the stream may result in surprising results if
80    /// this encoder is continued to be used.
81    pub fn get_mut(&mut self) -> &mut R {
82        self.inner.get_mut().get_mut()
83    }
84
85    /// Consumes this encoder, returning the underlying reader.
86    ///
87    /// Note that there may be buffered bytes which are not re-acquired as part
88    /// of this transition. It's recommended to only call this function after
89    /// EOF has been reached.
90    pub fn into_inner(self) -> R {
91        self.inner.into_inner().into_inner()
92    }
93
94    /// Returns the number of bytes that have been read into this compressor.
95    ///
96    /// Note that not all bytes read from the underlying object may be accounted
97    /// for, there may still be some active buffering.
98    pub fn total_in(&self) -> u64 {
99        self.inner.total_in()
100    }
101
102    /// Returns the number of bytes that the compressor has produced.
103    ///
104    /// Note that not all bytes may have been read yet, some may still be
105    /// buffered.
106    pub fn total_out(&self) -> u64 {
107        self.inner.total_out()
108    }
109}
110
111impl<R: Read> Read for ZlibEncoder<R> {
112    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
113        self.inner.read(buf)
114    }
115}
116
117impl<W: Read + Write> Write for ZlibEncoder<W> {
118    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
119        self.get_mut().write(buf)
120    }
121
122    fn flush(&mut self) -> io::Result<()> {
123        self.get_mut().flush()
124    }
125}
126
127/// A ZLIB decoder, or decompressor.
128///
129/// This structure implements a [`Read`] interface. When read from, it reads
130/// compressed data from the underlying [`Read`] and provides the uncompressed data.
131///
132/// After reading a single member of the ZLIB data this reader will return
133/// Ok(0) even if there are more bytes available in the underlying reader.
134/// `ZlibDecoder` may have read additional bytes past the end of the ZLIB data.
135/// If you need the following bytes, wrap the `Reader` in a `std::io::BufReader`
136/// and use `bufread::ZlibDecoder` instead.
137///
138/// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
139///
140/// # Examples
141///
142/// ```
143/// use std::io::prelude::*;
144/// use std::io;
145/// # use flate2::Compression;
146/// # use flate2::write::ZlibEncoder;
147/// use flate2::read::ZlibDecoder;
148///
149/// # fn main() {
150/// # let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
151/// # e.write_all(b"Hello World").unwrap();
152/// # let bytes = e.finish().unwrap();
153/// # println!("{}", decode_reader(bytes).unwrap());
154/// # }
155/// #
156/// // Uncompresses a Zlib Encoded vector of bytes and returns a string or error
157/// // Here &[u8] implements Read
158///
159/// fn decode_reader(bytes: Vec<u8>) -> io::Result<String> {
160///     let mut z = ZlibDecoder::new(&bytes[..]);
161///     let mut s = String::new();
162///     z.read_to_string(&mut s)?;
163///     Ok(s)
164/// }
165/// ```
166#[derive(Debug)]
167pub struct ZlibDecoder<R> {
168    inner: bufread::ZlibDecoder<BufReader<R>>,
169}
170
171impl<R: Read> ZlibDecoder<R> {
172    /// Creates a new decoder which will decompress data read from the given
173    /// stream.
174    pub fn new(r: R) -> ZlibDecoder<R> {
175        ZlibDecoder::new_with_buf(r, vec![0; 32 * 1024])
176    }
177
178    /// Creates a new decoder which will decompress data read from the given
179    /// stream `r`, using `buf` as backing to speed up reading.
180    ///
181    /// Note that the specified buffer will only be used up to its current
182    /// length. The buffer's capacity will also not grow over time.
183    pub fn new_with_buf(r: R, buf: Vec<u8>) -> ZlibDecoder<R> {
184        ZlibDecoder {
185            inner: bufread::ZlibDecoder::new(BufReader::with_buf(buf, r)),
186        }
187    }
188
189    /// Creates a new decoder which will decompress data read from the given
190    /// stream `r`, along with `decompression` settings.
191    pub fn new_with_decompress(r: R, decompression: Decompress) -> ZlibDecoder<R> {
192        ZlibDecoder::new_with_decompress_and_buf(r, vec![0; 32 * 1024], decompression)
193    }
194
195    /// Creates a new decoder which will decompress data read from the given
196    /// stream `r`, using `buf` as backing to speed up reading,
197    /// along with `decompression` settings to configure decoder.
198    ///
199    /// Note that the specified buffer will only be used up to its current
200    /// length. The buffer's capacity will also not grow over time.
201    pub fn new_with_decompress_and_buf(
202        r: R,
203        buf: Vec<u8>,
204        decompression: Decompress,
205    ) -> ZlibDecoder<R> {
206        ZlibDecoder {
207            inner: bufread::ZlibDecoder::new_with_decompress(
208                BufReader::with_buf(buf, r),
209                decompression,
210            ),
211        }
212    }
213}
214
215impl<R> ZlibDecoder<R> {
216    /// Resets the state of this decoder entirely, swapping out the input
217    /// stream for another.
218    ///
219    /// This will reset the internal state of this decoder and replace the
220    /// input stream with the one provided, returning the previous input
221    /// stream. Future data read from this decoder will be the decompressed
222    /// version of `r`'s data.
223    ///
224    /// Note that there may be currently buffered data when this function is
225    /// called, and in that case the buffered data is discarded.
226    pub fn reset(&mut self, r: R) -> R {
227        super::bufread::reset_decoder_data(&mut self.inner);
228        self.inner.get_mut().reset(r)
229    }
230
231    /// Acquires a reference to the underlying stream
232    pub fn get_ref(&self) -> &R {
233        self.inner.get_ref().get_ref()
234    }
235
236    /// Acquires a mutable reference to the underlying stream
237    ///
238    /// Note that mutation of the stream may result in surprising results if
239    /// this decoder is continued to be used.
240    pub fn get_mut(&mut self) -> &mut R {
241        self.inner.get_mut().get_mut()
242    }
243
244    /// Consumes this decoder, returning the underlying reader.
245    ///
246    /// Note that there may be buffered bytes which are not re-acquired as part
247    /// of this transition. It's recommended to only call this function after
248    /// EOF has been reached.
249    pub fn into_inner(self) -> R {
250        self.inner.into_inner().into_inner()
251    }
252
253    /// Returns the number of bytes that the decompressor has consumed.
254    ///
255    /// Note that this will likely be smaller than what the decompressor
256    /// actually read from the underlying stream due to buffering.
257    pub fn total_in(&self) -> u64 {
258        self.inner.total_in()
259    }
260
261    /// Returns the number of bytes that the decompressor has produced.
262    pub fn total_out(&self) -> u64 {
263        self.inner.total_out()
264    }
265}
266
267impl<R: Read> Read for ZlibDecoder<R> {
268    fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
269        self.inner.read(into)
270    }
271}
272
273impl<R: Read + Write> Write for ZlibDecoder<R> {
274    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
275        self.get_mut().write(buf)
276    }
277
278    fn flush(&mut self) -> io::Result<()> {
279        self.get_mut().flush()
280    }
281}