Skip to main content

zstd_native/
decoder.rs

1//! One-shot decompression: whole input in memory.
2
3use alloc::boxed::Box;
4use alloc::vec::Vec;
5
6use crate::block::{BLOCK_SIZE_MAX, BlockDecoder, Output, WILDCOPY_OVERLENGTH};
7use crate::dict::Dictionary;
8use crate::error::{Error, Result};
9use crate::frame::{self, FrameHeader};
10use crate::xxhash::Xxh64;
11
12/// A reusable decompressor (libzstd's `ZSTD_DCtx`).
13///
14/// Keeps its tables and buffers between calls, so decompressing many
15/// small inputs doesn't allocate each time, and optionally holds a
16/// [`Dictionary`].
17///
18/// ```
19/// # let compressed: &[u8] = &[0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x05, 0x29, 0x00, 0x00, 0x68, 0x65, 0x6c, 0x6c, 0x6f];
20/// let mut d = zstd_native::Decompressor::new();
21/// assert_eq!(d.decompress(compressed)?, b"hello");
22/// # Ok::<(), zstd_native::Error>(())
23/// ```
24pub struct Decompressor {
25    block: Box<BlockDecoder>,
26    dict: Option<Dictionary>,
27    /// Where the content of the dictionary of the last frame ends (an
28    /// address; 0 for none). A frame whose dictionary ends elsewhere finds
29    /// it cold (libzstd's `ddictIsCold`: `dctx->dictEnd != dictEnd`), see
30    /// `BlockDecoder::dict_cold`.
31    dict_end: usize,
32}
33
34impl core::fmt::Debug for Decompressor {
35    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
36        f.debug_struct("Decompressor")
37            .field("dict", &self.dict)
38            .finish_non_exhaustive()
39    }
40}
41
42impl Default for Decompressor {
43    fn default() -> Self {
44        Self::new()
45    }
46}
47
48/// Where a frame's output goes: a growable `Vec` or a fixed slice.
49enum Sink<'a> {
50    Vec(&'a mut Vec<u8>),
51    Slice,
52}
53
54impl Decompressor {
55    /// A decompressor without a dictionary.
56    pub fn new() -> Self {
57        Decompressor {
58            block: Box::new(BlockDecoder::new()),
59            dict: None,
60            dict_end: 0,
61        }
62    }
63
64    /// A decompressor that uses `dict` for every frame.
65    pub fn with_dictionary(dict: Dictionary) -> Self {
66        Decompressor {
67            block: Box::new(BlockDecoder::new()),
68            dict: Some(dict),
69            dict_end: 0,
70        }
71    }
72
73    /// Replaces (or removes) the dictionary.
74    pub fn set_dictionary(&mut self, dict: Option<Dictionary>) {
75        // The same dictionary installed again keeps what was built for it.
76        let same = matches!((&self.dict, &dict), (Some(a), Some(b)) if a.same(b));
77        if !same {
78            self.block.dict_changed();
79        }
80        self.dict = dict;
81    }
82
83    /// Decompresses every frame in `src` (concatenated frames and skippable
84    /// frames are allowed) into a new vector.
85    ///
86    /// # Errors
87    ///
88    /// Any [`Error`] for corrupt, truncated or unsupported input.
89    pub fn decompress(&mut self, src: &[u8]) -> Result<Vec<u8>> {
90        let mut v = Vec::new();
91        self.decompress_append(src, &mut v)?;
92        Ok(v)
93    }
94
95    /// Like [`decompress`](Self::decompress) but appends to `dst`, reusing
96    /// its capacity.
97    ///
98    /// # Errors
99    ///
100    /// Any [`Error`] for corrupt, truncated or unsupported input; `dst`
101    /// then holds the data decoded before the error.
102    pub fn decompress_append(&mut self, src: &[u8], dst: &mut Vec<u8>) -> Result<()> {
103        let mut out = Output {
104            ptr: dst.as_mut_ptr(),
105            cap: dst.capacity(),
106            pos: dst.len(),
107        };
108        let res = self.decode_frames(src, &mut out, &mut Sink::Vec(&mut *dst));
109        // SAFETY: `out.pos` only advances over bytes the decoder wrote.
110        #[allow(unsafe_code)]
111        unsafe {
112            dst.set_len(out.pos)
113        };
114        res
115    }
116
117    /// Decompresses every frame in `src` into `dst`, returning the
118    /// decompressed size.
119    ///
120    /// # Errors
121    ///
122    /// [`Error::OutputTooSmall`] if `dst` can't hold the result, or any
123    /// other [`Error`] for corrupt, truncated or unsupported input.
124    pub fn decompress_to_slice(&mut self, src: &[u8], dst: &mut [u8]) -> Result<usize> {
125        let mut out = Output {
126            ptr: dst.as_mut_ptr(),
127            cap: dst.len(),
128            pos: 0,
129        };
130        self.decode_frames(src, &mut out, &mut Sink::Slice)?;
131        Ok(out.pos)
132    }
133
134    fn decode_frames(&mut self, src: &[u8], out: &mut Output, sink: &mut Sink<'_>) -> Result<()> {
135        let mut ip = 0;
136        while src.len() - ip >= frame::STARTING_INPUT_LENGTH {
137            let magic = frame::read_le32(src, ip);
138            if frame::is_skippable(magic) {
139                if src.len() - ip < 8 {
140                    return Err(Error::Truncated);
141                }
142                let size = frame::read_le32(src, ip + 4) as usize;
143                if size > src.len() - ip - 8 {
144                    return Err(Error::Truncated);
145                }
146                ip += 8 + size;
147                continue;
148            }
149            ip += self.decode_frame(&src[ip..], out, sink)?;
150        }
151        if ip != src.len() {
152            return Err(Error::Truncated);
153        }
154        Ok(())
155    }
156
157    /// Decodes one frame; returns the input bytes it used.
158    fn decode_frame(&mut self, src: &[u8], out: &mut Output, sink: &mut Sink<'_>) -> Result<usize> {
159        if src.len() < frame::FRAME_HEADER_SIZE_MIN + frame::BLOCK_HEADER_SIZE {
160            return Err(Error::Truncated);
161        }
162        let fh = FrameHeader::parse(src)?;
163        let mut ip = fh.header_size;
164        if src.len() < ip + frame::BLOCK_HEADER_SIZE {
165            return Err(Error::Truncated);
166        }
167        let dict: &[u8] = match &self.dict {
168            Some(d) => {
169                if fh.dict_id != 0 && fh.dict_id != d.id() {
170                    return Err(Error::DictionaryMismatch);
171                }
172                self.block.start_frame(d.entropy());
173                d.content()
174            }
175            None => {
176                if fh.dict_id != 0 {
177                    return Err(Error::DictionaryMismatch);
178                }
179                self.block.start_frame(None);
180                &[]
181            }
182        };
183        let dict_ent = self.dict.as_ref().and_then(Dictionary::entropy);
184        // libzstd's `ddictIsCold`: another dictionary than the last frame's
185        // (one installed again stays warm, and so does a new one where the
186        // last one was, just written; a frame without compressed blocks
187        // uses it up too).
188        let end = self
189            .dict
190            .as_ref()
191            .map_or(0, |d| d.content().as_ptr_range().end as usize);
192        self.block.dict_cold = end != 0 && end != core::mem::replace(&mut self.dict_end, end);
193        let block_max = fh.block_size_max();
194        let prefix = out.pos;
195
196        if let Sink::Vec(v) = sink {
197            // Room for the whole frame when its size is known (bounded by
198            // what the input could possibly expand to), else per block.
199            if let Some(cs) = fh.content_size {
200                let bound = ((src.len() as u64 / 3) + 1).saturating_mul(BLOCK_SIZE_MAX as u64);
201                let want = cs.min(bound).saturating_add(WILDCOPY_OVERLENGTH as u64);
202                let want = usize::try_from(want).map_err(|_| Error::OutputTooLarge)?;
203                reserve(v, out, want)?;
204            }
205        }
206
207        let mut xxh = fh.has_checksum.then(Xxh64::new);
208        loop {
209            if src.len() - ip < frame::BLOCK_HEADER_SIZE {
210                return Err(Error::Truncated);
211            }
212            let bh = u32::from_le_bytes([src[ip], src[ip + 1], src[ip + 2], 0]);
213            ip += frame::BLOCK_HEADER_SIZE;
214            let last = bh & 1 != 0;
215            let btype = (bh >> 1) & 3;
216            let bsize = (bh >> 3) as usize;
217            let start = out.pos;
218            match btype {
219                0 => {
220                    // Raw
221                    // Block_Maximum_Size bounds what a block regenerates
222                    // (format spec 0.4.5; libzstd 1.6.0 checks it in
223                    // one-shot mode too, `ZSTD_decompressFrame`).
224                    if bsize > block_max {
225                        return Err(Error::Corrupted);
226                    }
227                    if bsize > src.len() - ip {
228                        return Err(Error::Truncated);
229                    }
230                    if let Sink::Vec(v) = sink {
231                        reserve(v, out, bsize + WILDCOPY_OVERLENGTH)?;
232                    }
233                    if bsize > out.cap - out.pos {
234                        return Err(Error::OutputTooSmall);
235                    }
236                    // SAFETY: `bsize` input bytes exist and the output has room.
237                    #[allow(unsafe_code)]
238                    unsafe {
239                        core::ptr::copy_nonoverlapping(
240                            src.as_ptr().add(ip),
241                            out.ptr.add(out.pos),
242                            bsize,
243                        )
244                    };
245                    out.pos += bsize;
246                    ip += bsize;
247                }
248                1 => {
249                    // RLE: `bsize` copies of one byte.
250                    if bsize > block_max {
251                        return Err(Error::Corrupted);
252                    }
253                    if ip >= src.len() {
254                        return Err(Error::Truncated);
255                    }
256                    if let Sink::Vec(v) = sink {
257                        reserve(v, out, bsize + WILDCOPY_OVERLENGTH)?;
258                    }
259                    if bsize > out.cap - out.pos {
260                        return Err(Error::OutputTooSmall);
261                    }
262                    // SAFETY: the output has room for `bsize` bytes.
263                    #[allow(unsafe_code)]
264                    unsafe {
265                        core::ptr::write_bytes(out.ptr.add(out.pos), src[ip], bsize)
266                    };
267                    out.pos += bsize;
268                    ip += 1;
269                }
270                2 => {
271                    if bsize > src.len() - ip {
272                        return Err(Error::Truncated);
273                    }
274                    if let Sink::Vec(v) = sink {
275                        reserve(v, out, block_max + WILDCOPY_OVERLENGTH)?;
276                    }
277                    self.block.decode_block(
278                        &src[ip..ip + bsize],
279                        out,
280                        prefix,
281                        dict,
282                        dict_ent,
283                        block_max,
284                    )?;
285                    ip += bsize;
286                }
287                _ => return Err(Error::Corrupted),
288            }
289            if let Some(x) = &mut xxh {
290                // SAFETY: `start..out.pos` was just written.
291                #[allow(unsafe_code)]
292                let produced =
293                    unsafe { core::slice::from_raw_parts(out.ptr.add(start), out.pos - start) };
294                x.update(produced);
295            }
296            if last {
297                break;
298            }
299        }
300        if let Some(cs) = fh.content_size
301            && (out.pos - prefix) as u64 != cs
302        {
303            return Err(Error::Corrupted);
304        }
305        if let Some(x) = xxh {
306            if src.len() - ip < 4 {
307                return Err(Error::Truncated);
308            }
309            if frame::read_le32(src, ip) != x.digest() as u32 {
310                return Err(Error::ChecksumMismatch);
311            }
312            ip += 4;
313        }
314        Ok(ip)
315    }
316}
317
318/// Makes room for `extra` more bytes after `out.pos` in `v`.
319pub(crate) fn reserve(v: &mut Vec<u8>, out: &mut Output, extra: usize) -> Result<()> {
320    if out.cap - out.pos >= extra {
321        return Ok(());
322    }
323    // SAFETY: `out.pos` bytes were written; record them so `reserve` keeps them.
324    #[allow(unsafe_code)]
325    unsafe {
326        v.set_len(out.pos)
327    };
328    v.try_reserve(extra).map_err(|_| Error::OutputTooLarge)?;
329    out.ptr = v.as_mut_ptr();
330    out.cap = v.capacity();
331    Ok(())
332}
333
334/// Decompresses every frame in `src` into a new vector.
335///
336/// ```
337/// // A frame holding "hello" as a raw block.
338/// let compressed = [0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x05, 0x29, 0x00, 0x00, b'h', b'e', b'l', b'l', b'o'];
339/// assert_eq!(zstd_native::decompress(&compressed)?, b"hello");
340/// # Ok::<(), zstd_native::Error>(())
341/// ```
342///
343/// # Errors
344///
345/// Any [`Error`] for corrupt, truncated or unsupported input.
346pub fn decompress(src: &[u8]) -> Result<Vec<u8>> {
347    with_cached(|d| d.decompress(src))
348}
349
350/// Decompresses every frame in `src` into `dst`, returning the size.
351///
352/// # Errors
353///
354/// [`Error::OutputTooSmall`] if `dst` is too small, or any other [`Error`]
355/// for corrupt, truncated or unsupported input.
356pub fn decompress_to_slice(src: &[u8], dst: &mut [u8]) -> Result<usize> {
357    with_cached(|d| d.decompress_to_slice(src, dst))
358}
359
360/// Runs `f` with a per-thread cached [`Decompressor`] (with `std`), so the
361/// one-call functions don't allocate and zero the decoder's ~40 KB of
362/// tables on every call: that dominated small inputs.
363#[cfg(feature = "std")]
364fn with_cached<T>(f: impl FnOnce(&mut Decompressor) -> T) -> T {
365    use core::cell::Cell;
366    std::thread_local! {
367        static CACHED: Cell<Option<Box<Decompressor>>> = const { Cell::new(None) };
368    }
369    // Take it out while in use (re-entrancy and panics just make a new one).
370    let mut d = CACHED
371        .with(Cell::take)
372        .unwrap_or_else(|| Box::new(Decompressor::new()));
373    let r = f(&mut d);
374    CACHED.with(|c| c.set(Some(d)));
375    r
376}
377
378#[cfg(not(feature = "std"))]
379fn with_cached<T>(f: impl FnOnce(&mut Decompressor) -> T) -> T {
380    f(&mut Decompressor::new())
381}
382
383/// The decompressed size stored in the header of the first frame, or
384/// `None` when the header doesn't store it.
385///
386/// # Errors
387///
388/// As [`FrameHeader::parse`].
389pub fn content_size(src: &[u8]) -> Result<Option<u64>> {
390    Ok(FrameHeader::parse(src)?.content_size)
391}