Skip to main content

flate2_expose/zlib/
read.rs

1use std::io;
2use std::io::prelude::*;
3
4use super::bufread;
5use crate::bufreader::BufReader;
6
7/// A ZLIB 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 flate2_expose::Compression;
19/// use flate2_expose::read::ZlibEncoder;
20/// use std::fs::File;
21///
22/// // Open example file and compress the contents using Read interface
23///
24/// # fn open_hello_world() -> std::io::Result<Vec<u8>> {
25/// let f = File::open("examples/hello_world.txt")?;
26/// let mut z = ZlibEncoder::new(f, Compression::fast());
27/// let mut buffer = [0;50];
28/// let byte_count = z.read(&mut buffer)?;
29/// # Ok(buffer[0..byte_count].to_vec())
30/// # }
31/// ```
32#[derive(Debug)]
33pub struct ZlibEncoder<R> {
34    inner: bufread::ZlibEncoder<BufReader<R>>,
35}
36
37impl<R: Read> ZlibEncoder<R> {
38    /// Creates a new encoder which will read uncompressed data from the given
39    /// stream and emit the compressed stream.
40    pub fn new(r: R, level: crate::Compression) -> ZlibEncoder<R> {
41        ZlibEncoder {
42            inner: bufread::ZlibEncoder::new(BufReader::new(r), level),
43        }
44    }
45}
46
47impl<R> ZlibEncoder<R> {
48    /// Resets the state of this encoder entirely, swapping out the input
49    /// stream for another.
50    ///
51    /// This function will reset the internal state of this encoder and replace
52    /// the input stream with the one provided, returning the previous input
53    /// stream. Future data read from this encoder will be the compressed
54    /// version of `r`'s data.
55    ///
56    /// Note that there may be currently buffered data when this function is
57    /// called, and in that case the buffered data is discarded.
58    pub fn reset(&mut self, r: R) -> R {
59        super::bufread::reset_encoder_data(&mut self.inner);
60        self.inner.get_mut().reset(r)
61    }
62
63    /// Acquires a reference to the underlying stream
64    pub fn get_ref(&self) -> &R {
65        self.inner.get_ref().get_ref()
66    }
67
68    /// Acquires a mutable reference to the underlying stream
69    ///
70    /// Note that mutation of the stream may result in surprising results if
71    /// this encoder is continued to be used.
72    pub fn get_mut(&mut self) -> &mut R {
73        self.inner.get_mut().get_mut()
74    }
75
76    /// Consumes this encoder, returning the underlying reader.
77    ///
78    /// Note that there may be buffered bytes which are not re-acquired as part
79    /// of this transition. It's recommended to only call this function after
80    /// EOF has been reached.
81    pub fn into_inner(self) -> R {
82        self.inner.into_inner().into_inner()
83    }
84
85    /// Returns the number of bytes that have been read into this compressor.
86    ///
87    /// Note that not all bytes read from the underlying object may be accounted
88    /// for, there may still be some active buffering.
89    pub fn total_in(&self) -> u64 {
90        self.inner.total_in()
91    }
92
93    /// Returns the number of bytes that the compressor has produced.
94    ///
95    /// Note that not all bytes may have been read yet, some may still be
96    /// buffered.
97    pub fn total_out(&self) -> u64 {
98        self.inner.total_out()
99    }
100}
101
102impl<R: Read> Read for ZlibEncoder<R> {
103    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
104        self.inner.read(buf)
105    }
106}
107
108impl<W: Read + Write> Write for ZlibEncoder<W> {
109    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
110        self.get_mut().write(buf)
111    }
112
113    fn flush(&mut self) -> io::Result<()> {
114        self.get_mut().flush()
115    }
116}
117
118/// A ZLIB decoder, or decompressor.
119///
120/// This structure implements a [`Read`] interface and takes a stream of
121/// compressed data as input, providing the decompressed data when read from.
122///
123/// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
124///
125/// # Examples
126///
127/// ```
128/// use std::io::prelude::*;
129/// use std::io;
130/// # use flate2_expose::Compression;
131/// # use flate2_expose::write::ZlibEncoder;
132/// use flate2_expose::read::ZlibDecoder;
133///
134/// # fn main() {
135/// # let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
136/// # e.write_all(b"Hello World").unwrap();
137/// # let bytes = e.finish().unwrap();
138/// # println!("{}", decode_reader(bytes).unwrap());
139/// # }
140/// #
141/// // Uncompresses a Zlib Encoded vector of bytes and returns a string or error
142/// // Here &[u8] implements Read
143///
144/// fn decode_reader(bytes: Vec<u8>) -> io::Result<String> {
145///     let mut z = ZlibDecoder::new(&bytes[..]);
146///     let mut s = String::new();
147///     z.read_to_string(&mut s)?;
148///     Ok(s)
149/// }
150/// ```
151#[derive(Debug)]
152pub struct ZlibDecoder<R> {
153    /// The underlying decoder
154    pub inner: bufread::ZlibDecoder<BufReader<R>>,
155}
156
157impl<R: Read> ZlibDecoder<R> {
158    /// Creates a new decoder which will decompress data read from the given
159    /// stream.
160    pub fn new(r: R) -> ZlibDecoder<R> {
161        ZlibDecoder::new_with_buf(r, vec![0; 32 * 1024])
162    }
163
164    /// Same as `new`, but the intermediate buffer for data is specified.
165    ///
166    /// Note that the specified buffer will only be used up to its current
167    /// length. The buffer's capacity will also not grow over time.
168    pub fn new_with_buf(r: R, buf: Vec<u8>) -> ZlibDecoder<R> {
169        ZlibDecoder {
170            inner: bufread::ZlibDecoder::new(BufReader::with_buf(buf, r)),
171        }
172    }
173}
174
175impl<R> ZlibDecoder<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 encoder 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 ZlibDecoder<R> {
228    fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
229        self.inner.read(into)
230    }
231}
232
233impl<R: Read + Write> Write for ZlibDecoder<R> {
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}