compression_codecs/zrip/
decoder.rs1use crate::{
2 zrip::params::{max_window, DParameter},
3 DecodeV2,
4};
5use compression_core::util::{PartialBuffer, WriteBuffer};
6use std::io;
7use zrip::push::{PushDecoder, Status};
8
9#[derive(Debug)]
10pub struct ZripDecoder {
11 decoder: PushDecoder,
12}
13
14impl Default for ZripDecoder {
15 fn default() -> Self {
16 Self::new_with_params(&[])
17 }
18}
19
20impl ZripDecoder {
21 pub fn new() -> Self {
22 Self::default()
23 }
24
25 pub fn new_with_params(params: &[DParameter]) -> Self {
26 let mut decoder = PushDecoder::new();
27 if let Some(max) = max_window(params) {
28 decoder = decoder.max_window(max);
29 }
30 Self { decoder }
31 }
32
33 pub fn new_with_dict(dictionary: &[u8]) -> io::Result<Self> {
34 let dict = zrip::Dictionary::from_bytes(dictionary)
35 .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
36 Ok(Self {
37 decoder: PushDecoder::with_dict(dict),
38 })
39 }
40
41 fn process(
42 &mut self,
43 input: &[u8],
44 output: &mut WriteBuffer<'_>,
45 ) -> io::Result<(usize, Status)> {
46 let progress = self
48 .decoder
49 .decode_uninit(input, unsafe { output.unwritten_mut() })
50 .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
51 unsafe { output.assume_init_and_advance(progress.produced) };
53 Ok((progress.consumed, progress.status))
54 }
55}
56
57impl DecodeV2 for ZripDecoder {
58 fn reinit(&mut self) -> io::Result<()> {
59 self.decoder.reset();
60 Ok(())
61 }
62
63 fn decode(
64 &mut self,
65 input: &mut PartialBuffer<&[u8]>,
66 output: &mut WriteBuffer<'_>,
67 ) -> io::Result<bool> {
68 if self.decoder.at_frame_end() {
71 return Ok(true);
72 }
73 let (consumed, status) = self.process(input.unwritten(), output)?;
74 input.advance(consumed);
75 Ok(status == Status::Finished)
76 }
77
78 fn flush(&mut self, output: &mut WriteBuffer<'_>) -> io::Result<bool> {
79 let (_, status) = self.process(&[], output)?;
80 Ok(status != Status::NeedsOutput)
81 }
82
83 fn finish(&mut self, output: &mut WriteBuffer<'_>) -> io::Result<bool> {
84 let (_, status) = self.process(&[], output)?;
85 if status == Status::NeedsOutput {
86 return Ok(false);
87 }
88 if self.decoder.at_frame_end() {
90 Ok(true)
91 } else {
92 Err(io::Error::new(
93 io::ErrorKind::UnexpectedEof,
94 "zstd stream did not finish",
95 ))
96 }
97 }
98}