Coverage Report

Created: 2025-08-09 07:28

/rust/registry/src/index.crates.io-6f17d22bba15001f/flate2-1.1.2/src/zlib/read.rs
Line
Count
Source (jump to first uncovered line)
1
use std::io;
2
use std::io::prelude::*;
3
4
use super::bufread;
5
use crate::bufreader::BufReader;
6
use crate::Decompress;
7
8
/// A ZLIB 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 flate2::Compression;
20
/// use flate2::read::ZlibEncoder;
21
/// use std::fs::File;
22
///
23
/// // Open example file and compress the contents using Read interface
24
///
25
/// # fn open_hello_world() -> std::io::Result<Vec<u8>> {
26
/// let f = File::open("examples/hello_world.txt")?;
27
/// let mut z = ZlibEncoder::new(f, Compression::fast());
28
/// let mut buffer = Vec::new();
29
/// z.read_to_end(&mut buffer)?;
30
/// # Ok(buffer)
31
/// # }
32
/// ```
33
#[derive(Debug)]
34
pub struct ZlibEncoder<R> {
35
    inner: bufread::ZlibEncoder<BufReader<R>>,
36
}
37
38
impl<R: Read> ZlibEncoder<R> {
39
    /// Creates a new encoder which will read uncompressed data from the given
40
    /// stream and emit the compressed stream.
41
0
    pub fn new(r: R, level: crate::Compression) -> ZlibEncoder<R> {
42
0
        ZlibEncoder {
43
0
            inner: bufread::ZlibEncoder::new(BufReader::new(r), level),
44
0
        }
45
0
    }
46
47
    /// Creates a new encoder with the given `compression` settings which will
48
    /// read uncompressed data from the given stream `r` and emit the compressed stream.
49
0
    pub fn new_with_compress(r: R, compression: crate::Compress) -> ZlibEncoder<R> {
50
0
        ZlibEncoder {
51
0
            inner: bufread::ZlibEncoder::new_with_compress(BufReader::new(r), compression),
52
0
        }
53
0
    }
54
}
55
56
impl<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
    ///
65
    /// Note that there may be currently buffered data when this function is
66
    /// called, and in that case the buffered data is discarded.
67
0
    pub fn reset(&mut self, r: R) -> R {
68
0
        super::bufread::reset_encoder_data(&mut self.inner);
69
0
        self.inner.get_mut().reset(r)
70
0
    }
71
72
    /// Acquires a reference to the underlying stream
73
0
    pub fn get_ref(&self) -> &R {
74
0
        self.inner.get_ref().get_ref()
75
0
    }
76
77
    /// Acquires a mutable reference to the underlying stream
78
    ///
79
    /// Note that mutation of the stream may result in surprising results if
80
    /// this encoder is continued to be used.
81
0
    pub fn get_mut(&mut self) -> &mut R {
82
0
        self.inner.get_mut().get_mut()
83
0
    }
84
85
    /// Consumes this encoder, returning the underlying reader.
86
    ///
87
    /// Note that there may be buffered bytes which are not re-acquired as part
88
    /// of this transition. It's recommended to only call this function after
89
    /// EOF has been reached.
90
0
    pub fn into_inner(self) -> R {
91
0
        self.inner.into_inner().into_inner()
92
0
    }
93
94
    /// Returns the number of bytes that have been read into this compressor.
95
    ///
96
    /// Note that not all bytes read from the underlying object may be accounted
97
    /// for, there may still be some active buffering.
98
0
    pub fn total_in(&self) -> u64 {
99
0
        self.inner.total_in()
100
0
    }
101
102
    /// Returns the number of bytes that the compressor has produced.
103
    ///
104
    /// Note that not all bytes may have been read yet, some may still be
105
    /// buffered.
106
0
    pub fn total_out(&self) -> u64 {
107
0
        self.inner.total_out()
108
0
    }
109
}
110
111
impl<R: Read> Read for ZlibEncoder<R> {
112
0
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
113
0
        self.inner.read(buf)
114
0
    }
115
}
116
117
impl<W: Read + Write> Write for ZlibEncoder<W> {
118
0
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
119
0
        self.get_mut().write(buf)
120
0
    }
121
122
0
    fn flush(&mut self) -> io::Result<()> {
123
0
        self.get_mut().flush()
124
0
    }
125
}
126
127
/// A ZLIB decoder, or decompressor.
128
///
129
/// This structure implements a [`Read`] interface. When read from, it reads
130
/// compressed data from the underlying [`Read`] and provides the uncompressed data.
131
///
132
/// After reading a single member of the ZLIB data this reader will return
133
/// Ok(0) even if there are more bytes available in the underlying reader.
134
/// `ZlibDecoder` may have read additional bytes past the end of the ZLIB data.
135
/// If you need the following bytes, wrap the `Reader` in a `std::io::BufReader`
136
/// and use `bufread::ZlibDecoder` instead.
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
0
    pub fn new(r: R) -> ZlibDecoder<R> {
175
0
        ZlibDecoder::new_with_buf(r, vec![0; 32 * 1024])
176
0
    }
177
178
    /// Creates a new decoder which will decompress data read from the given
179
    /// stream `r`, using `buf` as backing to speed up reading.
180
    ///
181
    /// Note that the specified buffer will only be used up to its current
182
    /// length. The buffer's capacity will also not grow over time.
183
0
    pub fn new_with_buf(r: R, buf: Vec<u8>) -> ZlibDecoder<R> {
184
0
        ZlibDecoder {
185
0
            inner: bufread::ZlibDecoder::new(BufReader::with_buf(buf, r)),
186
0
        }
187
0
    }
188
189
    /// Creates a new decoder which will decompress data read from the given
190
    /// stream `r`, along with `decompression` settings.
191
0
    pub fn new_with_decompress(r: R, decompression: Decompress) -> ZlibDecoder<R> {
192
0
        ZlibDecoder::new_with_decompress_and_buf(r, vec![0; 32 * 1024], decompression)
193
0
    }
194
195
    /// Creates a new decoder which will decompress data read from the given
196
    /// stream `r`, using `buf` as backing to speed up reading,
197
    /// along with `decompression` settings to configure decoder.
198
    ///
199
    /// Note that the specified buffer will only be used up to its current
200
    /// length. The buffer's capacity will also not grow over time.
201
0
    pub fn new_with_decompress_and_buf(
202
0
        r: R,
203
0
        buf: Vec<u8>,
204
0
        decompression: Decompress,
205
0
    ) -> ZlibDecoder<R> {
206
0
        ZlibDecoder {
207
0
            inner: bufread::ZlibDecoder::new_with_decompress(
208
0
                BufReader::with_buf(buf, r),
209
0
                decompression,
210
0
            ),
211
0
        }
212
0
    }
213
}
214
215
impl<R> ZlibDecoder<R> {
216
    /// Resets the state of this decoder entirely, swapping out the input
217
    /// stream for another.
218
    ///
219
    /// This will reset the internal state of this decoder and replace the
220
    /// input stream with the one provided, returning the previous input
221
    /// stream. Future data read from this decoder will be the decompressed
222
    /// version of `r`'s data.
223
    ///
224
    /// Note that there may be currently buffered data when this function is
225
    /// called, and in that case the buffered data is discarded.
226
0
    pub fn reset(&mut self, r: R) -> R {
227
0
        super::bufread::reset_decoder_data(&mut self.inner);
228
0
        self.inner.get_mut().reset(r)
229
0
    }
230
231
    /// Acquires a reference to the underlying stream
232
0
    pub fn get_ref(&self) -> &R {
233
0
        self.inner.get_ref().get_ref()
234
0
    }
235
236
    /// Acquires a mutable reference to the underlying stream
237
    ///
238
    /// Note that mutation of the stream may result in surprising results if
239
    /// this decoder is continued to be used.
240
0
    pub fn get_mut(&mut self) -> &mut R {
241
0
        self.inner.get_mut().get_mut()
242
0
    }
243
244
    /// Consumes this decoder, returning the underlying reader.
245
    ///
246
    /// Note that there may be buffered bytes which are not re-acquired as part
247
    /// of this transition. It's recommended to only call this function after
248
    /// EOF has been reached.
249
0
    pub fn into_inner(self) -> R {
250
0
        self.inner.into_inner().into_inner()
251
0
    }
252
253
    /// Returns the number of bytes that the decompressor has consumed.
254
    ///
255
    /// Note that this will likely be smaller than what the decompressor
256
    /// actually read from the underlying stream due to buffering.
257
0
    pub fn total_in(&self) -> u64 {
258
0
        self.inner.total_in()
259
0
    }
260
261
    /// Returns the number of bytes that the decompressor has produced.
262
0
    pub fn total_out(&self) -> u64 {
263
0
        self.inner.total_out()
264
0
    }
265
}
266
267
impl<R: Read> Read for ZlibDecoder<R> {
268
0
    fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
269
0
        self.inner.read(into)
270
0
    }
271
}
272
273
impl<R: Read + Write> Write for ZlibDecoder<R> {
274
0
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
275
0
        self.get_mut().write(buf)
276
0
    }
277
278
0
    fn flush(&mut self) -> io::Result<()> {
279
0
        self.get_mut().flush()
280
0
    }
281
}