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