Skip to main content

flate2_expose/zlib/
bufread.rs

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_expose::Compression;
20/// use flate2_expose::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, 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, 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_expose::Compression;
133/// # use flate2_expose::write::ZlibEncoder;
134/// use flate2_expose::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    /// The underlying decompressor.
157    pub data: Decompress,
158}
159
160impl<R: BufRead> ZlibDecoder<R> {
161    /// Creates a new decoder which will decompress data read from the given
162    /// stream.
163    pub fn new(r: R) -> ZlibDecoder<R> {
164        ZlibDecoder {
165            obj: r,
166            data: Decompress::new(true),
167        }
168    }
169}
170
171pub fn reset_decoder_data<R>(zlib: &mut ZlibDecoder<R>) {
172    zlib.data = Decompress::new(true);
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    pub fn reset(&mut self, r: R) -> R {
184        reset_decoder_data(self);
185        mem::replace(&mut self.obj, r)
186    }
187
188    /// Acquires a reference to the underlying stream
189    pub fn get_ref(&self) -> &R {
190        &self.obj
191    }
192
193    /// Acquires a mutable reference to the underlying stream
194    ///
195    /// Note that mutation of the stream may result in surprising results if
196    /// this encoder is continued to be used.
197    pub fn get_mut(&mut self) -> &mut R {
198        &mut self.obj
199    }
200
201    /// Consumes this decoder, returning the underlying reader.
202    pub fn into_inner(self) -> R {
203        self.obj
204    }
205
206    /// Returns the number of bytes that the decompressor has consumed.
207    ///
208    /// Note that this will likely be smaller than what the decompressor
209    /// actually read from the underlying stream due to buffering.
210    pub fn total_in(&self) -> u64 {
211        self.data.total_in()
212    }
213
214    /// Returns the number of bytes that the decompressor has produced.
215    pub fn total_out(&self) -> u64 {
216        self.data.total_out()
217    }
218}
219
220impl<R: BufRead> Read for ZlibDecoder<R> {
221    fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
222        zio::read(&mut self.obj, &mut self.data, into)
223    }
224}
225
226impl<R: BufRead + Write> Write for ZlibDecoder<R> {
227    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
228        self.get_mut().write(buf)
229    }
230
231    fn flush(&mut self) -> io::Result<()> {
232        self.get_mut().flush()
233    }
234}