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