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