Skip to main content

zu_encoding/
zstd_leaf.rs

1//! Zstd leaf (encoding id 11), the optional general-purpose stage for
2//! cold string segments where ratio matters more than decode speed.
3//! Everything else in the cascade is a lightweight encoding; this is
4//! the one deliberate exception, and it is a leaf: nothing cascades
5//! below it.
6//!
7//! The `zstd` feature links libzstd for compression and fast decode.
8//! Builds without it stay pure Rust and still read every file through
9//! ruzstd, so the default build can open a database written by a
10//! feature-full one; only `encode` needs the feature. `decode_fallback`
11//! is the ruzstd path under its own name so tests and fuzzing can pin
12//! it even when libzstd is linked.
13//!
14//! Layout: `raw_len: u32 LE`, then one zstd frame.
15
16use zu_common::{Result, ZuError};
17
18fn corrupt(detail: &str) -> ZuError {
19    ZuError::Corrupt {
20        what: "zstd",
21        detail: detail.to_string(),
22    }
23}
24
25/// Compresses `bytes` into `out`, returning the encoded byte length.
26#[cfg(feature = "zstd")]
27pub fn encode(bytes: &[u8], out: &mut Vec<u8>) -> usize {
28    let start = out.len();
29    out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
30    let frame = zstd::bulk::compress(bytes, 3).expect("in-memory compression cannot fail");
31    out.extend_from_slice(&frame);
32    out.len() - start
33}
34
35/// Splits the container into the validated length claim and the frame.
36fn claim(bytes: &[u8], max_len: usize) -> Result<(usize, &[u8])> {
37    let head = bytes.get(..4).ok_or_else(|| corrupt("truncated header"))?;
38    let raw_len = u32::from_le_bytes(head.try_into().unwrap()) as usize;
39    if raw_len > max_len {
40        return Err(corrupt("length above the caller ceiling"));
41    }
42    Ok((raw_len, &bytes[4..]))
43}
44
45/// Decodes an encoded buffer, appending at most `max_len` bytes to
46/// `out`. With the `zstd` feature this is libzstd; without it, ruzstd.
47/// A rejected payload leaves `out` untouched.
48pub fn decode(bytes: &[u8], max_len: usize, out: &mut Vec<u8>) -> Result<()> {
49    #[cfg(feature = "zstd")]
50    {
51        let (raw_len, frame) = claim(bytes, max_len)?;
52        let base = out.len();
53        // An empty destination decompresses straight into spare
54        // capacity, the WriteBuf path, which skips zeroing the range
55        // first; libzstd never reads it. Appending after existing
56        // content takes the slice path, since WriteBuf on a Vec always
57        // writes from the front.
58        let result = if base == 0 {
59            out.reserve(raw_len);
60            zstd::bulk::Decompressor::new().and_then(|mut d| d.decompress_to_buffer(frame, out))
61        } else {
62            out.resize(base + raw_len, 0);
63            zstd::bulk::decompress_to_buffer(frame, &mut out[base..])
64        };
65        match result {
66            Ok(n) if n == raw_len => {
67                out.truncate(base + raw_len);
68                Ok(())
69            }
70            Ok(_) => {
71                out.truncate(base);
72                Err(corrupt("frame length disagrees with the claim"))
73            }
74            Err(_) => {
75                out.truncate(base);
76                Err(corrupt("malformed frame"))
77            }
78        }
79    }
80    #[cfg(not(feature = "zstd"))]
81    {
82        decode_fallback(bytes, max_len, out)
83    }
84}
85
86/// The pure Rust read path, always available regardless of features.
87pub fn decode_fallback(bytes: &[u8], max_len: usize, out: &mut Vec<u8>) -> Result<()> {
88    use std::io::Read;
89    let (raw_len, frame) = claim(bytes, max_len)?;
90    let mut reader = frame;
91    let mut decoder = ruzstd::decoding::StreamingDecoder::new(&mut reader)
92        .map_err(|_| corrupt("malformed frame header"))?;
93    let base = out.len();
94    out.resize(base + raw_len, 0);
95    if decoder.read_exact(&mut out[base..]).is_err() {
96        out.truncate(base);
97        return Err(corrupt("frame ends before the claimed length"));
98    }
99    // One byte past the claim distinguishes an exact frame from one
100    // that kept going; anything but a clean EOF is a lying claim.
101    if !matches!(decoder.read(&mut [0u8]), Ok(0)) {
102        out.truncate(base);
103        return Err(corrupt("frame length disagrees with the claim"));
104    }
105    Ok(())
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    /// `printf 'the quick brown fox jumps over the lazy dog; ' x40`
113    /// through `zstd -3`, so the pure Rust read path has a real frame
114    /// to chew on even when the encoder is compiled out.
115    const FIXTURE_RAW_LEN: usize = 1800;
116    const FIXTURE_FRAME: &[u8] = &[
117        0x28, 0xB5, 0x2F, 0xFD, 0x04, 0x58, 0xBD, 0x01, 0x00, 0xC4, 0x02, 0x74, 0x68, 0x65, 0x20,
118        0x71, 0x75, 0x69, 0x63, 0x6B, 0x20, 0x62, 0x72, 0x6F, 0x77, 0x6E, 0x20, 0x66, 0x6F, 0x78,
119        0x20, 0x6A, 0x75, 0x6D, 0x70, 0x73, 0x20, 0x6F, 0x76, 0x65, 0x72, 0x20, 0x74, 0x68, 0x65,
120        0x20, 0x6C, 0x61, 0x7A, 0x79, 0x20, 0x64, 0x6F, 0x67, 0x3B, 0x02, 0x00, 0xD4, 0x42, 0xF5,
121        0x01, 0x43, 0x98, 0x65, 0x0D, 0x2D, 0x33, 0x91,
122    ];
123
124    fn fixture() -> Vec<u8> {
125        let mut buf = (FIXTURE_RAW_LEN as u32).to_le_bytes().to_vec();
126        buf.extend_from_slice(FIXTURE_FRAME);
127        buf
128    }
129
130    #[test]
131    fn fallback_reads_a_real_frame() {
132        let mut out = Vec::new();
133        decode_fallback(&fixture(), FIXTURE_RAW_LEN, &mut out).unwrap();
134        let expected: Vec<u8> = "the quick brown fox jumps over the lazy dog; "
135            .bytes()
136            .cycle()
137            .take(FIXTURE_RAW_LEN)
138            .collect();
139        assert_eq!(out, expected);
140        let mut via_decode = Vec::new();
141        decode(&fixture(), FIXTURE_RAW_LEN, &mut via_decode).unwrap();
142        assert_eq!(via_decode, out);
143    }
144
145    #[test]
146    fn corrupt_and_hostile() {
147        for decode in [
148            decode as fn(&[u8], usize, &mut Vec<u8>) -> Result<()>,
149            decode_fallback,
150        ] {
151            let mut out = vec![7u8];
152            assert!(decode(&[1, 2], 16, &mut out).is_err());
153            // A flood claim dies on the ceiling before any allocation.
154            let mut flood = u32::MAX.to_le_bytes().to_vec();
155            flood.extend_from_slice(FIXTURE_FRAME);
156            assert!(decode(&flood, 1 << 20, &mut out).is_err());
157            // Claims off by one in both directions are rejected.
158            for lie in [FIXTURE_RAW_LEN - 1, FIXTURE_RAW_LEN + 1] {
159                let mut buf = (lie as u32).to_le_bytes().to_vec();
160                buf.extend_from_slice(FIXTURE_FRAME);
161                assert!(decode(&buf, 1 << 20, &mut out).is_err());
162            }
163            // A truncated frame and plain garbage are rejected.
164            let mut cut = fixture();
165            cut.truncate(cut.len() - 9);
166            assert!(decode(&cut, FIXTURE_RAW_LEN, &mut out).is_err());
167            let mut garbage = 100u32.to_le_bytes().to_vec();
168            garbage.extend_from_slice(&[0xAB; 40]);
169            assert!(decode(&garbage, 100, &mut out).is_err());
170            assert_eq!(out, [7], "a rejected payload must not touch out");
171        }
172    }
173
174    #[cfg(feature = "zstd")]
175    #[test]
176    fn roundtrip_both_read_paths() {
177        let text: Vec<u8> = (0..2000u32)
178            .flat_map(|i| format!("{i}\t{}\n", i * 37).into_bytes())
179            .collect();
180        for values in [Vec::new(), vec![0u8; 10], text] {
181            let mut buf = Vec::new();
182            let len = encode(&values, &mut buf);
183            assert_eq!(len, buf.len());
184            let mut fast = Vec::new();
185            decode(&buf, values.len(), &mut fast).unwrap();
186            assert_eq!(fast, values);
187            let mut pure = Vec::new();
188            decode_fallback(&buf, values.len(), &mut pure).unwrap();
189            assert_eq!(pure, values);
190        }
191    }
192}