git_features/zlib/stream/
inflate.rs

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