Debian Codegraph @

debian/rust-vendor/flate2/src/zio.rs

raw
1 use crate::io;
2 use crate::io::{BufRead, Write};
3 use alloc::vec::Vec;
4 use core::mem;
5
6 use crate::{
7 Compress, CompressError, Decompress, DecompressError, FlushCompress, FlushDecompress, Status,
8 };
9
10 #[derive(Debug)]
11 pub struct Writer<W: Write, D: Ops> {
12 obj: Option<W>,
13 pub data: D,
14 buf: Vec<u8>,
15 }
16
17 pub trait Ops {
18 type Error: Into<io::Error>;
19 type Flush: Flush;
20 fn total_in(&self) -> u64;
21 fn total_out(&self) -> u64;
22 fn run(
23 &mut self,
24 input: &[u8],
25 output: &mut [u8],
26 flush: Self::Flush,
27 ) -> Result<Status, Self::Error>;
28 fn run_vec(
29 &mut self,
30 input: &[u8],
31 output: &mut Vec<u8>,
32 flush: Self::Flush,
33 ) -> Result<Status, Self::Error>;
34 }
35
36 impl Ops for Compress {
37 type Error = CompressError;
38 type Flush = FlushCompress;
39 fn total_in(&self) -> u64 {
40 self.total_in()
41 }
42 fn total_out(&self) -> u64 {
43 self.total_out()
44 }
45 fn run(
46 &mut self,
47 input: &[u8],
48 output: &mut [u8],
49 flush: FlushCompress,
50 ) -> Result<Status, CompressError> {
51 self.compress(input, output, flush)
52 }
53 fn run_vec(
54 &mut self,
55 input: &[u8],
56 output: &mut Vec<u8>,
57 flush: FlushCompress,
58 ) -> Result<Status, CompressError> {
59 self.compress_vec(input, output, flush)
60 }
61 }
62
63 impl Ops for Decompress {
64 type Error = DecompressError;
65 type Flush = FlushDecompress;
66 fn total_in(&self) -> u64 {
67 self.total_in()
68 }
69 fn total_out(&self) -> u64 {
70 self.total_out()
71 }
72 fn run(
73 &mut self,
74 input: &[u8],
75 output: &mut [u8],
76 flush: FlushDecompress,
77 ) -> Result<Status, DecompressError> {
78 self.decompress(input, output, flush)
79 }
80 fn run_vec(
81 &mut self,
82 input: &[u8],
83 output: &mut Vec<u8>,
84 flush: FlushDecompress,
85 ) -> Result<Status, DecompressError> {
86 self.decompress_vec(input, output, flush)
87 }
88 }
89
90 pub trait Flush {
91 fn none() -> Self;
92 fn sync() -> Self;
93 fn finish() -> Self;
94 }
95
96 impl Flush for FlushCompress {
97 fn none() -> Self {
98 FlushCompress::None
99 }
100
101 fn sync() -> Self {
102 FlushCompress::Sync
103 }
104
105 fn finish() -> Self {
106 FlushCompress::Finish
107 }
108 }
109
110 impl Flush for FlushDecompress {
111 fn none() -> Self {
112 FlushDecompress::None
113 }
114
115 fn sync() -> Self {
116 FlushDecompress::Sync
117 }
118
119 fn finish() -> Self {
120 FlushDecompress::Finish
121 }
122 }
123
124 pub fn read<R, D>(obj: &mut R, data: &mut D, dst: &mut [u8]) -> io::Result<usize>
125 where
126 R: BufRead,
127 D: Ops,
128 {
129 loop {
130 let (read, consumed, ret, eof);
131 {
132 let input = obj.fill_buf()?;
133 eof = input.is_empty();
134 let before_out = data.total_out();
135 let before_in = data.total_in();
136 let flush = if eof {
137 D::Flush::finish()
138 } else {
139 D::Flush::none()
140 };
141 ret = data.run(input, dst, flush);
142 read = (data.total_out() - before_out) as usize;
143 consumed = (data.total_in() - before_in) as usize;
144 }
145 obj.consume(consumed);
146
147 match ret {
148 // If we haven't read any data and we haven't hit EOF yet,
149 // then we need to keep asking for more data because if we
150 // return that 0 bytes of data have been read then it will
151 // be interpreted as EOF.
152 Ok(Status::Ok | Status::BufError) if read == 0 && !eof && !dst.is_empty() => continue,
153 // If we haven't read any data and we have hit EOF, then the
154 // deflate stream is incomplete.
155 Ok(Status::Ok | Status::BufError) if read == 0 && eof && !dst.is_empty() => {
156 return Err(io::Error::new(
157 io::ErrorKind::UnexpectedEof,
158 "incomplete deflate stream",
159 ));
160 }
161 Ok(Status::Ok | Status::BufError | Status::StreamEnd) => return Ok(read),
162
163 Err(..) => {
164 return Err(io::Error::new(
165 io::ErrorKind::InvalidInput,
166 "corrupt deflate stream",
167 ))
168 }
169 }
170 }
171 }
172
173 impl<W: Write, D: Ops> Writer<W, D> {
174 pub fn new(w: W, d: D) -> Writer<W, D> {
175 Writer {
176 obj: Some(w),
177 data: d,
178 buf: Vec::with_capacity(32 * 1024),
179 }
180 }
181
182 pub fn finish(&mut self) -> io::Result<()> {
183 loop {
184 self.dump()?;
185
186 let before = self.data.total_out();
187 self.data
188 .run_vec(&[], &mut self.buf, Flush::finish())
189 .map_err(Into::into)?;
190 if before == self.data.total_out() {
191 return Ok(());
192 }
193 }
194 }
195
196 pub fn replace(&mut self, w: W) -> W {
197 self.buf.clear();
198 mem::replace(self.get_mut(), w)
199 }
200
201 pub fn get_ref(&self) -> &W {
202 self.obj.as_ref().unwrap()
203 }
204
205 pub fn get_mut(&mut self) -> &mut W {
206 self.obj.as_mut().unwrap()
207 }
208
209 // Note that this should only be called if the outer object is just about
210 // to be consumed!
211 //
212 // (e.g. an implementation of `into_inner`)
213 pub fn take_inner(&mut self) -> W {
214 self.obj.take().unwrap()
215 }
216
217 pub fn is_present(&self) -> bool {
218 self.obj.is_some()
219 }
220
221 // Returns total written bytes and status of underlying codec
222 pub(crate) fn write_with_status(&mut self, buf: &[u8]) -> io::Result<(usize, Status)> {
223 // miniz isn't guaranteed to actually write any of the buffer provided,
224 // it may be in a flushing mode where it's just giving us data before
225 // we're actually giving it any data. We don't want to spuriously return
226 // `Ok(0)` when possible as it will cause calls to write_all() to fail.
227 // As a result we execute this in a loop to ensure that we try our
228 // darndest to write the data.
229 loop {
230 self.dump()?;
231
232 let before_in = self.data.total_in();
233 let ret = self.data.run_vec(buf, &mut self.buf, D::Flush::none());
234 let written = (self.data.total_in() - before_in) as usize;
235 let is_stream_end = matches!(ret, Ok(Status::StreamEnd));
236
237 if !buf.is_empty() && written == 0 && ret.is_ok() && !is_stream_end {
238 continue;
239 }
240 return match ret {
241 Ok(st) => match st {
242 Status::Ok | Status::BufError | Status::StreamEnd => Ok((written, st)),
243 },
244 Err(..) => Err(io::Error::new(
245 io::ErrorKind::InvalidInput,
246 "corrupt deflate stream",
247 )),
248 };
249 }
250 }
251
252 fn dump(&mut self) -> io::Result<()> {
253 // TODO: should manage this buffer not with `drain` but probably more of
254 // a deque-like strategy.
255 while !self.buf.is_empty() {
256 let n = self.obj.as_mut().unwrap().write(&self.buf)?;
257 if n == 0 {
258 return Err(io::ErrorKind::WriteZero.into());
259 }
260 self.buf.drain(..n);
261 }
262 Ok(())
263 }
264 }
265
266 impl<W: Write, D: Ops> Write for Writer<W, D> {
267 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
268 self.write_with_status(buf).map(|res| res.0)
269 }
270
271 fn flush(&mut self) -> io::Result<()> {
272 self.data
273 .run_vec(&[], &mut self.buf, Flush::sync())
274 .map_err(Into::into)?;
275
276 // Unfortunately miniz doesn't actually tell us when we're done with
277 // pulling out all the data from the internal stream. To remedy this we
278 // have to continually ask the stream for more memory until it doesn't
279 // give us a chunk of memory the same size as our own internal buffer,
280 // at which point we assume it's reached the end.
281 loop {
282 self.dump()?;
283 let before = self.data.total_out();
284 self.data
285 .run_vec(&[], &mut self.buf, Flush::none())
286 .map_err(Into::into)?;
287 if before == self.data.total_out() {
288 break;
289 }
290 }
291
292 self.obj.as_mut().unwrap().flush()
293 }
294 }
295
296 impl<W: Write, D: Ops> Drop for Writer<W, D> {
297 fn drop(&mut self) {
298 if self.obj.is_some() {
299 let _ = self.finish();
300 }
301 }
302 }