Debian Codegraph @

src/zlib/stream/inflate.rs

raw symbols SCIP
1 use std::{io, io::BufRead};
2
3 use crate::zlib::{Decompress, FlushDecompress, Status};
4
5 /// Read bytes from `rd` and decompress them using `state` into a pre-allocated fitting buffer `dst`, returning the amount of bytes written.
6 pub fn read(rd: &mut impl BufRead, state: &mut Decompress, mut dst: &mut [u8]) -> io::Result<usize> {
7 let mut total_written = 0;
8 loop {
9 let (written, consumed, ret, eof);
10 {
11 let input = rd.fill_buf()?;
12 eof = input.is_empty();
13 let before_out = state.total_out();
14 let before_in = state.total_in();
15 let flush = if eof {
16 FlushDecompress::Finish
17 } else {
18 FlushDecompress::None
19 };
20 ret = state.decompress(input, dst, flush);
21 written = (state.total_out() - before_out) as usize;
22 total_written += written;
23 dst = &mut dst[written..];
24 consumed = (state.total_in() - before_in) as usize;
25 }
26 rd.consume(consumed);
27
28 match ret {
29 // The stream has officially ended, nothing more to do here.
30 Ok(Status::StreamEnd) => return Ok(total_written),
31 // Either input our output are depleted even though the stream is not depleted yet.
32 Ok(Status::Ok | Status::BufError) if eof || dst.is_empty() => return Ok(total_written),
33 // Some progress was made in both the input and the output, it must continue to reach the end.
34 Ok(Status::Ok | Status::BufError) if consumed != 0 || written != 0 => continue,
35 // A strange state, where zlib makes no progress but isn't done either. Call it out.
36 Ok(Status::Ok | Status::BufError) => unreachable!("Definitely a bug somewhere"),
37 Err(..) => return Err(io::Error::new(io::ErrorKind::InvalidInput, "corrupt deflate stream")),
38 }
39 }
40 }