flate2/zlib/
bufread.rs

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