Skip to main content

flate2/deflate/
read.rs

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