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                    if bsize > src.len() - ip {
222                        return Err(Error::Truncated);
223                    }
224                    if let Sink::Vec(v) = sink {
225                        reserve(v, out, bsize + WILDCOPY_OVERLENGTH)?;
226                    }
227                    if bsize > out.cap - out.pos {
228                        return Err(Error::OutputTooSmall);
229                    }
230                    // SAFETY: `bsize` input bytes exist and the output has room.
231                    #[allow(unsafe_code)]
232                    unsafe {
233                        core::ptr::copy_nonoverlapping(
234                            src.as_ptr().add(ip),
235                            out.ptr.add(out.pos),
236                            bsize,
237                        )
238                    };
239                    out.pos += bsize;
240                    ip += bsize;
241                }
242                1 => {
243                    // RLE: `bsize` copies of one byte.
244                    if ip >= src.len() {
245                        return Err(Error::Truncated);
246                    }
247                    if let Sink::Vec(v) = sink {
248                        reserve(v, out, bsize + WILDCOPY_OVERLENGTH)?;
249                    }
250                    if bsize > out.cap - out.pos {
251                        return Err(Error::OutputTooSmall);
252                    }
253                    // SAFETY: the output has room for `bsize` bytes.
254                    #[allow(unsafe_code)]
255                    unsafe {
256                        core::ptr::write_bytes(out.ptr.add(out.pos), src[ip], bsize)
257                    };
258                    out.pos += bsize;
259                    ip += 1;
260                }
261                2 => {
262                    if bsize > src.len() - ip {
263                        return Err(Error::Truncated);
264                    }
265                    if let Sink::Vec(v) = sink {
266                        reserve(v, out, block_max + WILDCOPY_OVERLENGTH)?;
267                    }
268                    self.block.decode_block(
269                        &src[ip..ip + bsize],
270                        out,
271                        prefix,
272                        dict,
273                        dict_ent,
274                        block_max,
275                    )?;
276                    ip += bsize;
277                }
278                _ => return Err(Error::Corrupted),
279            }
280            if let Some(x) = &mut xxh {
281                // SAFETY: `start..out.pos` was just written.
282                #[allow(unsafe_code)]
283                let produced =
284                    unsafe { core::slice::from_raw_parts(out.ptr.add(start), out.pos - start) };
285                x.update(produced);
286            }
287            if last {
288                break;
289            }
290        }
291        if let Some(cs) = fh.content_size
292            && (out.pos - prefix) as u64 != cs
293        {
294            return Err(Error::Corrupted);
295        }
296        if let Some(x) = xxh {
297            if src.len() - ip < 4 {
298                return Err(Error::Truncated);
299            }
300            if frame::read_le32(src, ip) != x.digest() as u32 {
301                return Err(Error::ChecksumMismatch);
302            }
303            ip += 4;
304        }
305        Ok(ip)
306    }
307}
308
309/// Makes room for `extra` more bytes after `out.pos` in `v`.
310pub(crate) fn reserve(v: &mut Vec<u8>, out: &mut Output, extra: usize) -> Result<()> {
311    if out.cap - out.pos >= extra {
312        return Ok(());
313    }
314    // SAFETY: `out.pos` bytes were written; record them so `reserve` keeps them.
315    #[allow(unsafe_code)]
316    unsafe {
317        v.set_len(out.pos)
318    };
319    v.try_reserve(extra).map_err(|_| Error::OutputTooLarge)?;
320    out.ptr = v.as_mut_ptr();
321    out.cap = v.capacity();
322    Ok(())
323}
324
325/// Decompresses every frame in `src` into a new vector.
326///
327/// ```
328/// // A frame holding "hello" as a raw block.
329/// let compressed = [0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x05, 0x29, 0x00, 0x00, b'h', b'e', b'l', b'l', b'o'];
330/// assert_eq!(zstd_native::decompress(&compressed)?, b"hello");
331/// # Ok::<(), zstd_native::Error>(())
332/// ```
333///
334/// # Errors
335///
336/// Any [`Error`] for corrupt, truncated or unsupported input.
337pub fn decompress(src: &[u8]) -> Result<Vec<u8>> {
338    with_cached(|d| d.decompress(src))
339}
340
341/// Decompresses every frame in `src` into `dst`, returning the size.
342///
343/// # Errors
344///
345/// [`Error::OutputTooSmall`] if `dst` is too small, or any other [`Error`]
346/// for corrupt, truncated or unsupported input.
347pub fn decompress_to_slice(src: &[u8], dst: &mut [u8]) -> Result<usize> {
348    with_cached(|d| d.decompress_to_slice(src, dst))
349}
350
351/// Runs `f` with a per-thread cached [`Decompressor`] (with `std`), so the
352/// one-call functions don't allocate and zero the decoder's ~40 KB of
353/// tables on every call: that dominated small inputs.
354#[cfg(feature = "std")]
355fn with_cached<T>(f: impl FnOnce(&mut Decompressor) -> T) -> T {
356    use core::cell::Cell;
357    std::thread_local! {
358        static CACHED: Cell<Option<Box<Decompressor>>> = const { Cell::new(None) };
359    }
360    // Take it out while in use (re-entrancy and panics just make a new one).
361    let mut d = CACHED
362        .with(Cell::take)
363        .unwrap_or_else(|| Box::new(Decompressor::new()));
364    let r = f(&mut d);
365    CACHED.with(|c| c.set(Some(d)));
366    r
367}
368
369#[cfg(not(feature = "std"))]
370fn with_cached<T>(f: impl FnOnce(&mut Decompressor) -> T) -> T {
371    f(&mut Decompressor::new())
372}
373
374/// The decompressed size stored in the header of the first frame, or
375/// `None` when the header doesn't store it.
376///
377/// # Errors
378///
379/// As [`FrameHeader::parse`].
380pub fn content_size(src: &[u8]) -> Result<Option<u64>> {
381    Ok(FrameHeader::parse(src)?.content_size)
382}