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