Skip to main content

async_compression_issue_150_workaround/codec/xz/
decoder.rs

1use crate::{codec::Decode, util::PartialBuffer};
2
3use std::io::{Error, ErrorKind, Result};
4
5#[derive(Debug)]
6pub struct XzDecoder {
7    inner: crate::codec::Xz2Decoder,
8    skip_padding: Option<u8>,
9}
10
11impl XzDecoder {
12    pub fn new() -> Self {
13        Self {
14            inner: crate::codec::Xz2Decoder::new(),
15            skip_padding: None,
16        }
17    }
18}
19
20impl Decode for XzDecoder {
21    fn reinit(&mut self) -> Result<()> {
22        self.skip_padding = Some(4);
23        self.inner.reinit()
24    }
25
26    fn decode(
27        &mut self,
28        input: &mut PartialBuffer<impl AsRef<[u8]>>,
29        output: &mut PartialBuffer<impl AsRef<[u8]> + AsMut<[u8]>>,
30    ) -> Result<bool> {
31        if let Some(ref mut count) = self.skip_padding {
32            while input.unwritten().first() == Some(&0) {
33                input.advance(1);
34                *count -= 1;
35                if *count == 0 {
36                    *count = 4;
37                }
38            }
39            if input.unwritten().is_empty() {
40                return Ok(true);
41            }
42            // If this is non-padding then it cannot start with null bytes, so it must be invalid
43            // padding
44            if *count != 4 {
45                return Err(Error::new(
46                    ErrorKind::InvalidData,
47                    "stream padding was not a multiple of 4 bytes",
48                ));
49            }
50            self.skip_padding = None;
51        }
52        self.inner.decode(input, output)
53    }
54
55    fn flush(
56        &mut self,
57        output: &mut PartialBuffer<impl AsRef<[u8]> + AsMut<[u8]>>,
58    ) -> Result<bool> {
59        if self.skip_padding.is_some() {
60            return Ok(true);
61        }
62        self.inner.flush(output)
63    }
64
65    fn finish(
66        &mut self,
67        output: &mut PartialBuffer<impl AsRef<[u8]> + AsMut<[u8]>>,
68    ) -> Result<bool> {
69        if self.skip_padding.is_some() {
70            return Ok(true);
71        }
72        self.inner.finish(output)
73    }
74}