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