Coverage Report

Created: 2025-07-12 07:18

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