async_compression_issue_150_workaround/codec/xz2/
decoder.rs1use crate::{codec::Decode, util::PartialBuffer};
2
3use std::fmt::{Debug, Formatter, Result as FmtResult};
4use std::io::Result;
5use xz2::stream::{Action, Status, Stream};
6
7pub struct Xz2Decoder {
8 stream: Stream,
9}
10
11impl Debug for Xz2Decoder {
12 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
13 write!(f, "LzmaDecoder")
14 }
15}
16
17impl Xz2Decoder {
18 pub fn new() -> Self {
19 Self {
20 stream: Stream::new_auto_decoder(u64::max_value(), 0).unwrap(),
21 }
22 }
23}
24
25impl Decode for Xz2Decoder {
26 fn reinit(&mut self) -> Result<()> {
27 *self = Self::new();
28 Ok(())
29 }
30
31 fn decode(
32 &mut self,
33 input: &mut PartialBuffer<impl AsRef<[u8]>>,
34 output: &mut PartialBuffer<impl AsRef<[u8]> + AsMut<[u8]>>,
35 ) -> Result<bool> {
36 let previous_in = self.stream.total_in() as usize;
37 let previous_out = self.stream.total_out() as usize;
38
39 let status = self
40 .stream
41 .process(input.unwritten(), output.unwritten_mut(), Action::Run)?;
42
43 input.advance(self.stream.total_in() as usize - previous_in);
44 output.advance(self.stream.total_out() as usize - previous_out);
45
46 match status {
47 Status::Ok => Ok(false),
48 Status::StreamEnd => Ok(true),
49 Status::GetCheck => panic!("Unexpected lzma integrity check"),
50 Status::MemNeeded => Err(std::io::Error::new(
51 std::io::ErrorKind::Other,
52 "More memory needed",
53 )),
54 }
55 }
56
57 fn flush(
58 &mut self,
59 _output: &mut PartialBuffer<impl AsRef<[u8]> + AsMut<[u8]>>,
60 ) -> Result<bool> {
61 Ok(true)
63 }
64
65 fn finish(
66 &mut self,
67 output: &mut PartialBuffer<impl AsRef<[u8]> + AsMut<[u8]>>,
68 ) -> Result<bool> {
69 let previous_out = self.stream.total_out() as usize;
70
71 let status = self
72 .stream
73 .process(&[], output.unwritten_mut(), Action::Finish)?;
74
75 output.advance(self.stream.total_out() as usize - previous_out);
76
77 match status {
78 Status::Ok => Ok(false),
79 Status::StreamEnd => Ok(true),
80 Status::GetCheck => panic!("Unexpected lzma integrity check"),
81 Status::MemNeeded => Err(std::io::Error::new(
82 std::io::ErrorKind::Other,
83 "More memory needed",
84 )),
85 }
86 }
87}