Skip to main content

structured_zstd/decoding/
streaming_decoder.rs

1//! The [StreamingDecoder] wraps a [FrameDecoder] and provides a Read impl that decodes data when necessary
2
3use core::borrow::BorrowMut;
4
5use crate::common::MAX_BLOCK_SIZE;
6use crate::decoding::errors::FrameDecoderError;
7use crate::decoding::{BlockDecodingStrategy, DictionaryHandle, FrameDecoder};
8#[cfg(not(feature = "std"))]
9use crate::io::ErrorKind;
10use crate::io::{Error, Read};
11
12/// High level Zstandard frame decoder that can be used to decompress a given Zstandard frame.
13///
14/// This decoder implements `io::Read`, so you can interact with it by calling
15/// `io::Read::read_to_end` / `io::Read::read_exact` or passing this to another library / module as a source for the decoded content
16///
17/// If you need more control over how decompression takes place, you can use
18/// the lower level [FrameDecoder], which allows for greater control over how
19/// decompression takes place but the implementor must call
20/// [FrameDecoder::decode_blocks] repeatedly to decode the entire frame.
21///
22/// ## Caveat
23/// Plain `read` / `read_exact` operate on the single frame this decoder was
24/// initialised with: they do not advance into following frames. `read_to_end`,
25/// by contrast, is specialised to consume a finite source to EOF, decoding
26/// concatenated frames and skipping skippable frames along the way.
27///
28/// To recover the bytes that follow one frame WITHOUT consuming the rest of the
29/// source, recreate the decoder manually and handle
30/// [crate::decoding::errors::ReadFrameHeaderError::SkipFrame]
31/// errors by skipping forward the `length` amount of bytes, see <https://github.com/KillingSpark/zstd-rs/issues/57>
32///
33/// ```no_run
34/// // `File` is std-only; `read_to_end` itself is available under no_std too.
35/// #[cfg(feature = "std")]
36/// {
37///     use std::fs::File;
38///     use std::io::Read;
39///     use structured_zstd::decoding::StreamingDecoder;
40///
41///     // Read a Zstandard archive from the filesystem then decompress it into a vec.
42///     let mut f: File = todo!("Read a .zstd archive from somewhere");
43///     let mut decoder = StreamingDecoder::new(f).unwrap();
44///     let mut result = Vec::new();
45///     Read::read_to_end(&mut decoder, &mut result).unwrap();
46/// }
47/// ```
48pub struct StreamingDecoder<READ: Read, DEC: BorrowMut<FrameDecoder>> {
49    pub decoder: DEC,
50    source: READ,
51    /// Dictionary the decoder was constructed with, if any. Retained so the
52    /// `read_to_end` paths can re-initialise FOLLOWING concatenated frames with
53    /// the same forced dictionary (a plain re-init resolves dictionaries by
54    /// frame id only and would lose a forced dict for frames omitting the id).
55    /// Cheap to hold: `DictionaryHandle` is an `Arc`/`Rc` handle.
56    dict: Option<DictionaryHandle>,
57}
58
59impl<READ: Read, DEC: BorrowMut<FrameDecoder>> StreamingDecoder<READ, DEC> {
60    pub fn new_with_decoder(
61        mut source: READ,
62        mut decoder: DEC,
63    ) -> Result<StreamingDecoder<READ, DEC>, FrameDecoderError> {
64        decoder.borrow_mut().init(&mut source)?;
65        Ok(StreamingDecoder {
66            decoder,
67            source,
68            dict: None,
69        })
70    }
71}
72
73impl<READ: Read> StreamingDecoder<READ, FrameDecoder> {
74    pub fn new(
75        mut source: READ,
76    ) -> Result<StreamingDecoder<READ, FrameDecoder>, FrameDecoderError> {
77        let mut decoder = FrameDecoder::new();
78        decoder.init(&mut source)?;
79        Ok(StreamingDecoder {
80            decoder,
81            source,
82            dict: None,
83        })
84    }
85
86    /// Create a streaming decoder using a pre-parsed dictionary handle.
87    ///
88    /// # Warning
89    ///
90    /// This constructor initializes the underlying [`FrameDecoder`] with
91    /// `dict`, even if a frame header omits the optional dictionary ID.
92    /// Callers must only use it when they already know the stream was encoded
93    /// with this dictionary; otherwise decoded output can be silently
94    /// corrupted.
95    pub fn new_with_dictionary_handle(
96        mut source: READ,
97        dict: &DictionaryHandle,
98    ) -> Result<StreamingDecoder<READ, FrameDecoder>, FrameDecoderError> {
99        let mut decoder = FrameDecoder::new();
100        decoder.init_with_dict_handle(&mut source, dict)?;
101        Ok(StreamingDecoder {
102            decoder,
103            source,
104            dict: Some(dict.clone()),
105        })
106    }
107
108    /// Create a streaming decoder using a serialized dictionary blob.
109    ///
110    /// # Warning
111    ///
112    /// This API forwards to [`StreamingDecoder::new_with_dictionary_handle`]
113    /// and therefore applies the decoded dictionary to frames whose headers may
114    /// omit the optional dictionary ID. Only use it when the stream is known to
115    /// be encoded with that dictionary.
116    pub fn new_with_dictionary_bytes(
117        source: READ,
118        raw_dictionary: &[u8],
119    ) -> Result<StreamingDecoder<READ, FrameDecoder>, FrameDecoderError> {
120        let dict = DictionaryHandle::decode_dict(raw_dictionary)?;
121        Self::new_with_dictionary_handle(source, &dict)
122    }
123}
124
125impl<READ: Read, DEC: BorrowMut<FrameDecoder>> StreamingDecoder<READ, DEC> {
126    /// Gets a reference to the underlying reader.
127    pub fn get_ref(&self) -> &READ {
128        &self.source
129    }
130
131    /// Gets a mutable reference to the underlying reader.
132    ///
133    /// It is inadvisable to directly read from the underlying reader.
134    pub fn get_mut(&mut self) -> &mut READ {
135        &mut self.source
136    }
137
138    /// Destructures this object into the inner reader.
139    pub fn into_inner(self) -> READ
140    where
141        READ: Sized,
142    {
143        self.source
144    }
145
146    /// Destructures this object into both the inner reader and [FrameDecoder].
147    pub fn into_parts(self) -> (READ, DEC)
148    where
149        READ: Sized,
150    {
151        (self.source, self.decoder)
152    }
153
154    /// Destructures this object into the inner [FrameDecoder].
155    pub fn into_frame_decoder(self) -> DEC {
156        self.decoder
157    }
158}
159
160impl<READ: Read, DEC: BorrowMut<FrameDecoder>> Read for StreamingDecoder<READ, DEC> {
161    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
162        let decoder = self.decoder.borrow_mut();
163        if decoder.is_finished() && decoder.can_collect() == 0 {
164            // Frame fully decoded and fully drained: the running XXH64 digest
165            // is final, so a `Verify`-mode decoder validates the content
166            // checksum at this finish point. No-op in other modes.
167            #[cfg(feature = "hash")]
168            if let Err(e) = decoder.verify_content_checksum() {
169                #[cfg(feature = "std")]
170                return Err(Error::other(e));
171                #[cfg(not(feature = "std"))]
172                return Err(Error::new(ErrorKind::Other, alloc::boxed::Box::new(e)));
173            }
174            //No more bytes can ever be decoded
175            return Ok(0);
176        }
177
178        // Interleave bounded decode with draining so the decode window
179        // (`RingBuffer`) stays near `window_size` instead of accumulating the
180        // whole request before a single end-of-call drain. `read_to_end` hands
181        // ever-larger buffers; decoding `buf.len()` worth into the ring up
182        // front grew it far past the window (repeated `reserve_amortized`
183        // alloc+copy). Decode at most one block worth per step, then drain
184        // what is now collectable into `buf`, mirroring upstream zstd's
185        // window-bounded flush loop.
186        let mut written = 0;
187        while written < buf.len() {
188            // Drain whatever is collectable now (retaining `window_size` until
189            // the frame finishes). Reclaims the ring promptly so the next
190            // decode step reuses the same capacity.
191            written += decoder.read(&mut buf[written..])?;
192            if written == buf.len() || decoder.is_finished() {
193                break;
194            }
195            // Decode one bounded chunk. `UptoBytes` may overshoot a little but
196            // is capped to one block, so the ring's live region stays within
197            // `window_size + MAX_BLOCK_SIZE`.
198            let step = (buf.len() - written).min(MAX_BLOCK_SIZE as usize);
199            if let Err(e) =
200                decoder.decode_blocks(&mut self.source, BlockDecodingStrategy::UptoBytes(step))
201            {
202                #[cfg(feature = "std")]
203                {
204                    return Err(Error::other(e));
205                }
206                #[cfg(not(feature = "std"))]
207                {
208                    return Err(Error::new(ErrorKind::Other, alloc::boxed::Box::new(e)));
209                }
210            }
211        }
212
213        // The loop can finish AND fully drain a frame within this same call
214        // (decode last block, then drain it into `buf`). Validate here too when
215        // the frame is finished and nothing is left to collect, but ONLY when
216        // this call wrote no bytes: the `Read` contract forbids returning `Err`
217        // after bytes were delivered, so when `written > 0` the verify is
218        // deferred to the next call, where the top early-return runs it and
219        // returns `Err` on the zero-byte path. Idempotent with that top check.
220        #[cfg(feature = "hash")]
221        if written == 0
222            && decoder.is_finished()
223            && decoder.can_collect() == 0
224            && let Err(e) = decoder.verify_content_checksum()
225        {
226            #[cfg(feature = "std")]
227            return Err(Error::other(e));
228            #[cfg(not(feature = "std"))]
229            return Err(Error::new(ErrorKind::Other, alloc::boxed::Box::new(e)));
230        }
231
232        Ok(written)
233    }
234
235    /// Decode-in-place fast path for whole-frame consumption. Instead of the
236    /// generic `read` loop (decode block -> `RingBuffer` -> copy into the
237    /// caller buffer), buffer the (compressed, hence small) source and decode
238    /// STRAIGHT into `output`'s spare capacity via the single-copy direct path,
239    /// pre-sized from the frame's declared content size. Only taken when the
240    /// decoder is at a frame boundary (nothing partially decoded / undrained);
241    /// otherwise it falls back to the generic grow-and-`read` loop so a caller
242    /// that mixed `read` with `read_to_end` still gets correct output.
243    ///
244    /// Per the `Read::read_to_end` contract this consumes the source to EOF: if
245    /// the stream holds several concatenated frames they are ALL decoded (and
246    /// skippable frames skipped). To recover bytes that follow a single frame,
247    /// use `read` plus the
248    /// [`SkipFrame`](crate::decoding::errors::ReadFrameHeaderError::SkipFrame)
249    /// recreate-the-decoder pattern instead.
250    #[cfg(feature = "std")]
251    fn read_to_end(&mut self, output: &mut alloc::vec::Vec<u8>) -> Result<usize, Error> {
252        let start_total = output.len();
253        // `new()` already read the frame header, so the fast path applies when
254        // the decoder sits at the start of that frame with nothing decoded yet.
255        let at_start = {
256            let d = self.decoder.borrow_mut();
257            d.is_at_frame_start() && d.can_collect() == 0
258        };
259        // Clone the (cheap Arc/Rc) dict handle out so the `decoder` borrow below
260        // does not conflict with borrowing `self.dict`.
261        let dict = self.dict.clone();
262        if at_start {
263            let mut compressed = alloc::vec::Vec::new();
264            self.source.read_to_end(&mut compressed)?;
265            self.decoder
266                .borrow_mut()
267                .decode_current_frame_to_vec(&compressed, output, dict.as_ref())
268                .map_err(Error::other)?;
269            return Ok(output.len() - start_total);
270        }
271        // Mid-frame fallback: drain the partially-read CURRENT frame through the
272        // generic path, then decode any FOLLOWING concatenated frames so
273        // read_to_end still consumes the source to true EOF.
274        loop {
275            let start = output.len();
276            output.resize(start + MAX_BLOCK_SIZE as usize, 0);
277            // On error, drop the just-grown (zeroed) tail before propagating so
278            // the caller never observes bytes that were never decoded.
279            let n = match self.read(&mut output[start..]) {
280                Ok(n) => n,
281                Err(e) => {
282                    output.truncate(start);
283                    return Err(e);
284                }
285            };
286            output.truncate(start + n);
287            if n == 0 {
288                break;
289            }
290        }
291        // Current frame fully drained; `source` is positioned at the next frame.
292        let mut rest = alloc::vec::Vec::new();
293        self.source.read_to_end(&mut rest)?;
294        if !rest.is_empty() {
295            let mut input = rest.as_slice();
296            self.decoder
297                .borrow_mut()
298                .decode_concatenated_frames_to_vec(&mut input, output, dict.as_ref())
299                .map_err(Error::other)?;
300        }
301        Ok(output.len() - start_total)
302    }
303
304    /// no_std counterpart of the decode-in-place `read_to_end` fast path above
305    /// (the no_std `Read::read_to_end` returns `()` instead of the byte count).
306    #[cfg(not(feature = "std"))]
307    fn read_to_end(&mut self, output: &mut alloc::vec::Vec<u8>) -> Result<(), Error> {
308        let at_start = {
309            let d = self.decoder.borrow_mut();
310            d.is_at_frame_start() && d.can_collect() == 0
311        };
312        // Cheap Arc/Rc clone so the `decoder` borrow does not conflict with
313        // borrowing `self.dict`.
314        let dict = self.dict.clone();
315        if at_start {
316            let mut compressed = alloc::vec::Vec::new();
317            self.source.read_to_end(&mut compressed)?;
318            self.decoder
319                .borrow_mut()
320                .decode_current_frame_to_vec(&compressed, output, dict.as_ref())
321                .map_err(|e| Error::new(ErrorKind::Other, alloc::boxed::Box::new(e)))?;
322            return Ok(());
323        }
324        // Mid-frame fallback: drain the partial CURRENT frame, then decode the
325        // FOLLOWING concatenated frames so the source is consumed to true EOF.
326        loop {
327            let start = output.len();
328            output.resize(start + MAX_BLOCK_SIZE as usize, 0);
329            // On error, drop the just-grown (zeroed) tail before propagating so
330            // the caller never observes bytes that were never decoded.
331            let n = match self.read(&mut output[start..]) {
332                Ok(n) => n,
333                Err(e) => {
334                    output.truncate(start);
335                    return Err(e);
336                }
337            };
338            output.truncate(start + n);
339            if n == 0 {
340                break;
341            }
342        }
343        let mut rest = alloc::vec::Vec::new();
344        self.source.read_to_end(&mut rest)?;
345        if !rest.is_empty() {
346            let mut input = rest.as_slice();
347            self.decoder
348                .borrow_mut()
349                .decode_concatenated_frames_to_vec(&mut input, output, dict.as_ref())
350                .map_err(|e| Error::new(ErrorKind::Other, alloc::boxed::Box::new(e)))?;
351        }
352        Ok(())
353    }
354}
355
356#[cfg(test)]
357mod tests;