Skip to main content

zstd_native/
frame.rs

1//! Frame headers (RFC 8878 section 3.1.1).
2
3use crate::error::{Error, Result};
4
5pub(crate) const MAGIC: u32 = 0xFD2F_B528;
6pub(crate) const SKIPPABLE_MAGIC_MASK: u32 = 0xFFFF_FFF0;
7pub(crate) const SKIPPABLE_MAGIC: u32 = 0x184D_2A50;
8/// `ZSTD_WINDOWLOG_MAX`: the largest window log a frame header may give,
9/// 30 on 32-bit targets and 31 on 64-bit, as in libzstd (`zstd.h`); larger
10/// frames fail with [`Error::WindowTooLarge`] in every decoding mode.
11pub(crate) const WINDOWLOG_MAX: u32 = if usize::BITS == 32 { 30 } else { 31 };
12const WINDOWLOG_ABSOLUTEMIN: u32 = 10;
13/// Magic + frame header descriptor (libzstd's `ZSTD_startingInputLength`).
14pub(crate) const STARTING_INPUT_LENGTH: usize = 5;
15pub(crate) const FRAME_HEADER_SIZE_MIN: usize = 6;
16pub(crate) const BLOCK_HEADER_SIZE: usize = 3;
17
18/// A parsed zstd frame header.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct FrameHeader {
21    /// Decompressed size of the frame, when the header stores it.
22    pub content_size: Option<u64>,
23    /// Window size: how far back matches may reach.
24    pub window_size: u64,
25    /// Dictionary ID, 0 when none is stored.
26    pub dict_id: u32,
27    /// Whether the frame ends with a content checksum.
28    pub has_checksum: bool,
29    /// Size of the header in bytes, magic number included.
30    pub header_size: usize,
31}
32
33impl FrameHeader {
34    /// Parses the header of the zstd frame at the start of `src`.
35    ///
36    /// # Errors
37    ///
38    /// [`Error::UnknownFrame`] if `src` doesn't start with a zstd frame
39    /// (skippable frames included), [`Error::Truncated`] if the header is
40    /// incomplete, and [`Error::UnsupportedFrameParameter`] /
41    /// [`Error::WindowTooLarge`] for invalid headers.
42    pub fn parse(src: &[u8]) -> Result<FrameHeader> {
43        if src.len() < 4 {
44            return Err(Error::Truncated);
45        }
46        let magic = u32::from_le_bytes(src[..4].try_into().unwrap());
47        if magic != MAGIC {
48            return Err(Error::UnknownFrame);
49        }
50        let Some(&fhd) = src.get(4) else {
51            return Err(Error::Truncated);
52        };
53        let dict_code = fhd & 3;
54        let checksum = (fhd >> 2) & 1 != 0;
55        let single = (fhd >> 5) & 1 != 0;
56        let fcs_id = fhd >> 6;
57        let size = 5
58            + usize::from(!single)
59            + [0, 1, 2, 4][dict_code as usize]
60            + [usize::from(single), 2, 4, 8][fcs_id as usize];
61        if src.len() < size {
62            return Err(Error::Truncated);
63        }
64        if fhd & 0x08 != 0 {
65            return Err(Error::UnsupportedFrameParameter);
66        }
67        let mut pos = 5;
68        let mut window_size = 0u64;
69        if !single {
70            let wl = src[pos];
71            pos += 1;
72            let log = u32::from(wl >> 3) + WINDOWLOG_ABSOLUTEMIN;
73            if log > WINDOWLOG_MAX {
74                return Err(Error::WindowTooLarge);
75            }
76            let base = 1u64 << log;
77            window_size = base + (base / 8) * u64::from(wl & 7);
78        }
79        let le = |p: usize, n: usize| -> u64 {
80            let mut b = [0u8; 8];
81            b[..n].copy_from_slice(&src[p..p + n]);
82            u64::from_le_bytes(b)
83        };
84        let dict_len = [0, 1, 2, 4][dict_code as usize];
85        let dict_id = le(pos, dict_len) as u32;
86        pos += dict_len;
87        let content_size = match fcs_id {
88            0 => single.then(|| u64::from(src[pos])),
89            1 => Some(le(pos, 2) + 256),
90            2 => Some(le(pos, 4)),
91            _ => Some(le(pos, 8)),
92        };
93        if single {
94            window_size = content_size.unwrap_or(0);
95        }
96        Ok(FrameHeader {
97            content_size,
98            window_size,
99            dict_id,
100            has_checksum: checksum,
101            header_size: size,
102        })
103    }
104
105    /// Largest block (libzstd's `blockSizeMax`).
106    pub(crate) fn block_size_max(&self) -> usize {
107        self.window_size.min(crate::block::BLOCK_SIZE_MAX as u64) as usize
108    }
109}
110
111#[inline]
112pub(crate) fn read_le32(src: &[u8], pos: usize) -> u32 {
113    u32::from_le_bytes(src[pos..pos + 4].try_into().unwrap())
114}
115
116#[inline]
117pub(crate) fn is_skippable(magic: u32) -> bool {
118    magic & SKIPPABLE_MAGIC_MASK == SKIPPABLE_MAGIC
119}
120
121/// Total frame header size (magic included) from the frame header
122/// descriptor byte.
123#[inline]
124pub(crate) fn header_size(fhd: u8) -> usize {
125    let single = (fhd >> 5) & 1 != 0;
126    5 + usize::from(!single)
127        + [0, 1, 2, 4][(fhd & 3) as usize]
128        + [usize::from(single), 2, 4, 8][(fhd >> 6) as usize]
129}