Skip to main content

utopia_compression/
zstd.rs

1//! Zstandard.
2
3use crate::{Algorithm, Compression, Error, Sink};
4
5/// Zstandard (RFC 8878): `Content-Encoding: zstd`.
6///
7/// Compresses at level 3 unless told otherwise, one frame with the content size in its
8/// header. Output is byte for byte PHP's `zstd_compress()` (libzstd 1.5.7). Decompressing
9/// reads the first frame, like `zstd_uncompress()`.
10///
11/// ```
12/// use utopia_compression::{Algorithm, Zstd};
13///
14/// let zstd = Zstd::new();
15/// let body = zstd.compress(b"This is a demo string")?;
16/// assert_eq!(body.len(), 30);
17/// assert_eq!(zstd.decompress(&body)?, b"This is a demo string");
18/// # Ok::<(), utopia_compression::Error>(())
19/// ```
20///
21/// ```php
22/// use Utopia\Compression\Algorithms\Zstd;
23///
24/// $zstd = new Zstd();
25/// $body = $zstd->compress('This is a demo string');
26/// echo strlen($body), "\n"; // 30
27/// echo $zstd->decompress($body), "\n"; // This is a demo string
28/// ```
29///
30/// Requires the `zstd` feature. PHP: `Utopia\Compression\Algorithms\Zstd`.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct Zstd {
33    level: i64,
34}
35
36impl Default for Zstd {
37    fn default() -> Self {
38        Self::new()
39    }
40}
41
42impl Zstd {
43    /// Zstandard at level 3.
44    ///
45    /// PHP: `new Zstd()`.
46    pub const fn new() -> Self {
47        Zstd { level: 3 }
48    }
49
50    /// Zstandard at `level`, unchecked: zstd's negative (fast) levels work, and a level above
51    /// 22 makes [`Algorithm::compress`] fail with [`Error::Codec`], as in PHP.
52    ///
53    /// PHP: `new Zstd($level)`.
54    pub const fn with_level(level: i64) -> Self {
55        Zstd { level }
56    }
57
58    /// The level.
59    ///
60    /// PHP: `getLevel()`.
61    pub const fn level(&self) -> i64 {
62        self.level
63    }
64
65    /// Sets the level. Fails with [`Error::InvalidArgument`] outside `1` to `22`.
66    ///
67    /// PHP: `setLevel($level)`.
68    pub fn set_level(&mut self, level: i64) -> Result<(), Error> {
69        if !(1..=22).contains(&level) {
70            return Err(Error::InvalidArgument("Level must be between 1 and 22".into()));
71        }
72        self.level = level;
73        Ok(())
74    }
75
76    /// Whether this build has Zstandard (the `zstd` feature).
77    ///
78    /// PHP: `Zstd::isSupported()`, whether `zstd_compress()` exists.
79    pub const fn is_supported() -> bool {
80        cfg!(feature = "zstd")
81    }
82
83    /// [`Algorithm::compress`], appended to `out`.
84    pub fn compress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
85        imp::compress(data, self.level, out)
86    }
87
88    /// [`Algorithm::decompress`], appended to `out`.
89    pub fn decompress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
90        imp::decompress(data, out)
91    }
92}
93
94impl Algorithm for Zstd {
95    fn name(&self) -> &str {
96        Compression::ZSTD
97    }
98
99    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
100        let mut out = Vec::new();
101        self.compress_into(data, &mut out)?;
102        Ok(out)
103    }
104
105    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
106        let mut out = Vec::new();
107        self.decompress_into(data, &mut out)?;
108        Ok(out)
109    }
110
111    fn supported(&self) -> bool {
112        Self::is_supported()
113    }
114}
115
116#[cfg(feature = "zstd")]
117mod imp {
118    //! ext-zstd's `zstd_compress()` and `zstd_uncompress()`: the same streaming calls into
119    //! libzstd with the same buffer sizes, each call's output written where it ends up rather
120    //! than into a buffer it is then copied out of.
121    //!
122    //! Each call creates its context and frees it, as PHP does: a kept context carries state
123    //! from one call to the next that changes which error a corrupt frame reports. The sink's
124    //! allocator ([`Sink::allocator`]) makes that cheap where it has a faster one than `malloc()`.
125
126    use std::ffi::{CStr, c_void};
127
128    use zstd_safe::zstd_sys as z;
129
130    use crate::sink::spare;
131    use crate::{Allocator, Error, Sink};
132
133    fn codec(function: &str, code: usize) -> Error {
134        // SAFETY: libzstd returns a static NUL-terminated string for any code.
135        let name = unsafe { CStr::from_ptr(z::ZSTD_getErrorName(code)) };
136        Error::Codec(format!("{function}(): {}", name.to_string_lossy()))
137    }
138
139    fn is_error(code: usize) -> bool {
140        // SAFETY: a pure function of its argument.
141        unsafe { z::ZSTD_isError(code) != 0 }
142    }
143
144    /// `allocator` as libzstd takes one.
145    fn custom(allocator: Option<Allocator>) -> Option<z::ZSTD_customMem> {
146        allocator.map(|allocator| z::ZSTD_customMem {
147            customAlloc: Some(allocator.alloc as unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void),
148            customFree: Some(allocator.free as unsafe extern "C" fn(*mut c_void, *mut c_void)),
149            opaque: allocator.opaque,
150        })
151    }
152
153    /// A compression context, freed when dropped.
154    struct CCtx(*mut z::ZSTD_CCtx);
155
156    impl CCtx {
157        /// A new context, as `ZSTD_createCCtx()` makes one, on `allocator`.
158        fn new(allocator: Option<Allocator>) -> Option<Self> {
159            // SAFETY: creates a context or returns null; the allocator outlives it (the call).
160            let cctx = unsafe {
161                match custom(allocator) {
162                    Some(memory) => z::ZSTD_createCCtx_advanced(memory),
163                    None => z::ZSTD_createCCtx(),
164                }
165            };
166            (!cctx.is_null()).then_some(CCtx(cctx))
167        }
168    }
169
170    impl Drop for CCtx {
171        fn drop(&mut self) {
172            // SAFETY: created by ZSTD_createCCtx(_advanced) and freed only here.
173            unsafe { z::ZSTD_freeCCtx(self.0) };
174        }
175    }
176
177    /// A decompression context, freed when dropped.
178    struct DCtx(*mut z::ZSTD_DCtx);
179
180    impl DCtx {
181        /// A new context, as `ZSTD_createDCtx()` makes one, on `allocator`.
182        fn new(allocator: Option<Allocator>) -> Option<Self> {
183            // SAFETY: creates a context or returns null; the allocator outlives it (the call).
184            let dctx = unsafe {
185                match custom(allocator) {
186                    Some(memory) => z::ZSTD_createDCtx_advanced(memory),
187                    None => z::ZSTD_createDCtx(),
188                }
189            };
190            (!dctx.is_null()).then_some(DCtx(dctx))
191        }
192    }
193
194    impl Drop for DCtx {
195        fn drop(&mut self) {
196            // SAFETY: created by ZSTD_createDCtx(_advanced) and freed only here.
197            unsafe { z::ZSTD_freeDCtx(self.0) };
198        }
199    }
200
201    /// Makes room for `window` more bytes after what `out` holds.
202    fn room<S: Sink + ?Sized>(out: &mut S, window: usize) -> bool {
203        let (len, capacity) = (out.len(), out.capacity());
204        len + window <= capacity || out.grow((len + window).max(capacity + capacity / 2))
205    }
206
207    /// `zstd_compress()`: `ZSTD_compressStream2(ZSTD_e_end)` until it is done, each call into
208    /// a window of `ZSTD_CStreamOutSize()` bytes.
209    ///
210    /// A window that holds the whole bound of the input lets libzstd compress in one pass
211    /// rather than block by block; PHP's does for inputs up to a block (128 KiB), so the
212    /// window here is the smaller of the two, the same choice.
213    pub(super) fn compress<S: Sink + ?Sized>(data: &[u8], level: i64, out: &mut S) -> Result<(), Error> {
214        // SAFETY: pure functions.
215        let (max, bound, window) =
216            unsafe { (z::ZSTD_maxCLevel(), z::ZSTD_compressBound(data.len()), z::ZSTD_CStreamOutSize()) };
217        if level > i64::from(max) {
218            return Err(Error::Codec(format!(
219                "zstd_compress(): compression level ({level}) must be within 1..{max} or smaller then 0"
220            )));
221        }
222        let window = window.min(bound);
223        let fail = || Error::Codec("zstd_compress(): insufficient memory".into());
224        out.reserve(out.len() + bound + window);
225        let cctx = CCtx::new(out.allocator())
226            .ok_or_else(|| Error::Codec("zstd_compress(): failed to create compress context".into()))?;
227        // SAFETY: a live context. PHP resets the session and sets the level, cast to a C int (a
228        // refused level ignored).
229        unsafe {
230            z::ZSTD_CCtx_reset(cctx.0, z::ZSTD_ResetDirective::ZSTD_reset_session_only);
231            z::ZSTD_CCtx_setParameter(cctx.0, z::ZSTD_cParameter::ZSTD_c_compressionLevel, level as i32);
232        }
233        let mut input = z::ZSTD_inBuffer { src: data.as_ptr().cast(), size: data.len(), pos: 0 };
234        loop {
235            if !room(out, window) {
236                return Err(fail());
237            }
238            let (at, _) = spare(out);
239            let mut output = z::ZSTD_outBuffer { dst: at.cast(), size: window, pos: 0 };
240            // SAFETY: the context is live; the input covers `data` and the output `window`
241            // bytes of room in `out`, both alive for the call.
242            let remaining = unsafe {
243                z::ZSTD_compressStream2(cctx.0, &raw mut output, &raw mut input, z::ZSTD_EndDirective::ZSTD_e_end)
244            };
245            if is_error(remaining) {
246                return Err(codec("zstd_compress", remaining));
247            }
248            // SAFETY: libzstd wrote `pos` bytes into the room.
249            unsafe { out.set_len(out.len() + output.pos) };
250            if remaining == 0 {
251                return Ok(());
252            }
253        }
254    }
255
256    /// `zstd_uncompress()`: a window of the frame's content size (`ZSTD_DStreamOutSize()` when
257    /// the frame does not say), grown by that much whenever a call fills it, until the input
258    /// is used up or the first frame ends. A truncated frame gives what it decoded, as in PHP.
259    pub(super) fn decompress<S: Sink + ?Sized>(data: &[u8], out: &mut S) -> Result<(), Error> {
260        let not_zstd = || Error::Codec("zstd_uncompress(): it was not compressed by zstd".into());
261        // zstd-sys builds every legacy decoder (ZSTD_LEGACY_SUPPORT=1); PHP's libzstd is built
262        // with the default ZSTD_LEGACY_SUPPORT=5, which knows frames from v0.5 on only.
263        if let Some(magic) = data.first_chunk::<4>()
264            && matches!(u32::from_le_bytes(*magic), 0x1EB5_2FFD | 0xFD2F_B522..=0xFD2F_B524)
265        {
266            return Err(not_zstd());
267        }
268        // SAFETY: reads at most `data.len()` bytes of `data`.
269        let size = unsafe { z::ZSTD_getFrameContentSize(data.as_ptr().cast(), data.len()) };
270        // SAFETY: a pure function.
271        let chunk = unsafe { z::ZSTD_DStreamOutSize() };
272        let mut window = match size {
273            size if size == z::ZSTD_CONTENTSIZE_ERROR as u64 => return Err(not_zstd()),
274            size if size == z::ZSTD_CONTENTSIZE_UNKNOWN as u64 => chunk,
275            // A size past the address space: PHP's allocation of it fails the same way.
276            size => usize::try_from(size).unwrap_or(usize::MAX),
277        };
278        let fail = || Error::Codec("zstd_uncompress(): insufficient memory".into());
279        // PHP allocates the window before anything else, so a frame claiming more than the
280        // memory there is fails as early.
281        if !out.grow(out.len().saturating_add(window)) {
282            return Err(fail());
283        }
284        let dctx = DCtx::new(out.allocator())
285            .ok_or_else(|| Error::Codec("zstd_uncompress(): failed to prepare uncompression".into()))?;
286        // SAFETY: a live context.
287        unsafe { z::ZSTD_DCtx_reset(dctx.0, z::ZSTD_ResetDirective::ZSTD_reset_session_only) };
288        let mut input = z::ZSTD_inBuffer { src: data.as_ptr().cast(), size: data.len(), pos: 0 };
289        let mut filled = 0;
290        while input.pos < input.size {
291            if filled == window {
292                window += chunk;
293            }
294            if !room(out, window) {
295                return Err(fail());
296            }
297            let (at, _) = spare(out);
298            let mut output = z::ZSTD_outBuffer { dst: at.cast(), size: window, pos: 0 };
299            // SAFETY: the context is live; the input covers `data` and the output `window`
300            // bytes of room in `out`, both alive for the call.
301            let hint = unsafe { z::ZSTD_decompressStream(dctx.0, &raw mut output, &raw mut input) };
302            if is_error(hint) {
303                return Err(codec("zstd_uncompress", hint));
304            }
305            filled = output.pos;
306            // SAFETY: libzstd wrote `pos` bytes into the room.
307            unsafe { out.set_len(out.len() + filled) };
308            if hint == 0 {
309                break;
310            }
311        }
312        Ok(())
313    }
314}
315
316#[cfg(not(feature = "zstd"))]
317mod imp {
318    use crate::{Error, Sink};
319
320    pub(super) fn compress<S: Sink + ?Sized>(_: &[u8], _: i64, _: &mut S) -> Result<(), Error> {
321        Err(Error::undefined("zstd_compress"))
322    }
323
324    pub(super) fn decompress<S: Sink + ?Sized>(_: &[u8], _: &mut S) -> Result<(), Error> {
325        Err(Error::undefined("zstd_uncompress"))
326    }
327}
328
329#[cfg(all(test, feature = "zstd"))]
330mod tests {
331    use super::*;
332
333    #[test]
334    fn levels() {
335        let mut zstd = Zstd::new();
336        assert_eq!(zstd.set_level(0), Err(Error::InvalidArgument("Level must be between 1 and 22".into())));
337        let data = b"Lorem ipsum dolor sit amet ".repeat(500);
338        for level in [-5, -1, 0, 1, 3, 9, 19, 22] {
339            let zstd = Zstd::with_level(level);
340            assert_eq!(zstd.decompress(&zstd.compress(&data).unwrap()).unwrap(), data);
341        }
342        assert_eq!(
343            Zstd::with_level(23).compress(b"x"),
344            Err(Error::Codec("zstd_compress(): compression level (23) must be within 1..22 or smaller then 0".into()))
345        );
346    }
347
348    #[test]
349    fn known_output() {
350        assert_eq!(
351            Zstd::new().compress(b"This is a demo string").unwrap(),
352            b"\x28\xb5\x2f\xfd\x20\x15\xa9\x00\x00This is a demo string"
353        );
354    }
355
356    #[test]
357    fn large_input_in_blocks() {
358        // Larger than a block, so compressed in PHP's window by window.
359        let data: Vec<u8> = (0..1_000_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 27) as u8).collect();
360        let first = Zstd::new().compress(&data).unwrap();
361        assert_eq!(Zstd::new().compress(&data).unwrap(), first);
362        assert_eq!(Zstd::new().decompress(&first).unwrap(), data);
363    }
364
365    #[test]
366    fn truncated_and_invalid() {
367        let data = b"Lorem ipsum dolor sit amet ".repeat(5000);
368        let body = Zstd::new().compress(&data).unwrap();
369        // A truncated frame gives what it decoded, without an error, as in PHP.
370        let partial = Zstd::new().decompress(&body[..body.len() / 2]).unwrap();
371        assert!(data.starts_with(&partial));
372        let not_zstd = Err(Error::Codec("zstd_uncompress(): it was not compressed by zstd".into()));
373        assert_eq!(Zstd::new().decompress(b""), not_zstd);
374        assert_eq!(Zstd::new().decompress(b"garbage"), not_zstd);
375    }
376}