flate2/deflate/
read.rs

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