1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use crate::compression::{
    CodecImplementation, CompressionCodec, CompressionCodecType, DecompressResult,
};
use crate::error::{Error, Result};
use crate::header::CodecType;
use flate2::{Decompress, FlushDecompress};

/// Deflate (zlib) decompression codec.
///
/// ## Format Details
/// CHD compresses Deflate hunks without a zlib header.
///
/// ## Buffer Restrictions
/// Each compressed Deflate hunk decompresses to a hunk-sized chunk.
/// The input buffer must contain exactly enough data to fill the output buffer
/// when decompressed.
pub struct ZlibCodec {
    engine: Decompress,
}

impl CodecImplementation for ZlibCodec {
    fn new(_: u32) -> Result<Self> {
        Ok(ZlibCodec {
            engine: Decompress::new(false),
        })
    }

    fn decompress(&mut self, input: &[u8], output: &mut [u8]) -> Result<DecompressResult> {
        self.engine.reset(false);
        let status = self
            .engine
            .decompress(input, output, FlushDecompress::Finish)
            .map_err(|_| Error::DecompressionError)?;

        if status == flate2::Status::BufError {
            return Err(Error::DecompressionError);
        }

        let total_out = self.engine.total_out();
        if self.engine.total_out() != output.len() as u64 {
            return Err(Error::DecompressionError);
        }

        Ok(DecompressResult::new(
            total_out as usize,
            self.engine.total_in() as usize,
        ))
    }
}

impl CompressionCodecType for ZlibCodec {
    fn codec_type(&self) -> CodecType {
        CodecType::Zlib
    }
}

impl CompressionCodec for ZlibCodec {}