Skip to main content

utopia_compression/
lz4.rs

1//! LZ4.
2
3use crate::{Algorithm, Compression, Error, Sink};
4
5/// LZ4 blocks with ext-lz4's framing: the uncompressed size as a 4-byte
6/// little-endian prefix, then one LZ4 block.
7///
8/// Level 0 (the default) is LZ4's fast mode; levels 1 to 12 are its high
9/// compression (HC) mode. Output is byte for byte PHP's `lz4_compress()`
10/// (LZ4 1.10.0).
11///
12/// ```
13/// use utopia_compression::{Algorithm, Lz4};
14///
15/// let lz4 = Lz4::new();
16/// let body = lz4.compress(b"This is a demo string")?;
17/// assert_eq!(body.len(), 27);
18/// assert_eq!(lz4.decompress(&body)?, b"This is a demo string");
19/// # Ok::<(), utopia_compression::Error>(())
20/// ```
21///
22/// ```php
23/// use Utopia\Compression\Algorithms\LZ4;
24///
25/// $lz4 = new LZ4();
26/// $body = $lz4->compress('This is a demo string');
27/// echo strlen($body), "\n"; // 27
28/// echo $lz4->decompress($body), "\n"; // This is a demo string
29/// ```
30///
31/// Requires the `lz4` feature. PHP: `Utopia\Compression\Algorithms\LZ4`.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
33pub struct Lz4 {
34    level: i64,
35}
36
37impl Lz4 {
38    /// LZ4 in fast mode (level 0).
39    ///
40    /// PHP: `new LZ4()`.
41    pub const fn new() -> Self {
42        Lz4 { level: 0 }
43    }
44
45    /// LZ4 at `level`, unchecked: a level outside `0` to `12` makes
46    /// [`Algorithm::compress`] fail with [`Error::Codec`], as in PHP.
47    ///
48    /// PHP: `new LZ4($level)`.
49    pub const fn with_level(level: i64) -> Self {
50        Lz4 { level }
51    }
52
53    /// The level: 0 for fast mode, 1 to 12 for high compression.
54    ///
55    /// PHP: `getLevel()`.
56    pub const fn level(&self) -> i64 {
57        self.level
58    }
59
60    /// Sets the level. Fails with [`Error::InvalidArgument`] outside `0` to
61    /// `12`.
62    ///
63    /// PHP: `setLevel($level)`.
64    pub fn set_level(&mut self, level: i64) -> Result<(), Error> {
65        if !(0..=12).contains(&level) {
66            return Err(Error::InvalidArgument("Level must be between 0 and 12".into()));
67        }
68        self.level = level;
69        Ok(())
70    }
71
72    /// Whether this build has LZ4 (the `lz4` feature).
73    ///
74    /// PHP: `LZ4::isSupported()`, whether `lz4_compress()` exists.
75    pub const fn is_supported() -> bool {
76        cfg!(feature = "lz4")
77    }
78
79    /// [`Algorithm::compress`], appended to `out`.
80    pub fn compress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
81        imp::compress(data, self.level, out)
82    }
83
84    /// [`Algorithm::decompress`], appended to `out`.
85    pub fn decompress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
86        imp::decompress(data, out)
87    }
88}
89
90impl Algorithm for Lz4 {
91    fn name(&self) -> &str {
92        Compression::LZ4
93    }
94
95    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
96        let mut out = Vec::new();
97        self.compress_into(data, &mut out)?;
98        Ok(out)
99    }
100
101    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
102        let mut out = Vec::new();
103        self.decompress_into(data, &mut out)?;
104        Ok(out)
105    }
106
107    fn supported(&self) -> bool {
108        Self::is_supported()
109    }
110}
111
112#[cfg(feature = "lz4")]
113mod imp {
114    //! ext-lz4's `php_lz4_compress()` and `php_lz4_uncompress()`: the same calls into LZ4
115    //! 1.10.0 with the same sizes, the output written where it ends up rather than into a
116    //! buffer it is then copied out of.
117
118    use std::os::raw::{c_char, c_int};
119
120    use lz4_sys as l;
121
122    use crate::sink::{append, spare};
123    use crate::{Error, Sink};
124
125    /// `PHP_LZ4_CLEVEL_MAX`.
126    const MAX_LEVEL: c_int = 12;
127
128    /// The most an LZ4 block expands: under 255 output bytes per input byte (a match length
129    /// grows by 255 per extra byte), so a size prefix claiming more is not reserved. The
130    /// margin keeps the decoder's end-of-buffer checks as far away as with PHP's buffer.
131    const MAX_RATIO: usize = 255;
132    const MARGIN: usize = 4096;
133
134    /// Whether `malloc(size)` succeeds, which PHP asks for a size prefix larger than the block
135    /// can expand to (the block's own bound is what is reserved here): when the system refuses
136    /// it, PHP warns, and so does this.
137    fn allocatable(size: usize) -> bool {
138        use std::alloc::{GlobalAlloc, Layout, System};
139        let Ok(layout) = Layout::from_size_align(size, 1) else { return false };
140        // SAFETY: a layout of non-zero size; the block is freed straight away, never touched.
141        unsafe {
142            let block = System.alloc(layout);
143            if block.is_null() {
144                return false;
145            }
146            System.dealloc(block, layout);
147        }
148        true
149    }
150
151    fn data_error() -> Error {
152        Error::Codec("lz4_uncompress : data error".into())
153    }
154
155    /// A pointer LZ4 may read through for an empty input: an empty slice's is dangling, and
156    /// LZ4's high-compression mode reads through it on x86-64 (a segfault).
157    fn input(data: &[u8]) -> *const c_char {
158        static BYTE: [u8; 1] = [0];
159        if data.is_empty() { BYTE.as_ptr().cast() } else { data.as_ptr().cast() }
160    }
161
162    /// `lz4_compress($data, $level)`: the input's length as a 4-byte little-endian `int`,
163    /// then one block, fast at level 0 and high compression at 1 to 12, into a buffer of
164    /// `LZ4_compressBound(len) + 4` bytes of which LZ4 is told one less.
165    pub(super) fn compress<S: Sink + ?Sized>(data: &[u8], level: i64, out: &mut S) -> Result<(), Error> {
166        // PHP takes the length and the level as C ints.
167        let (len, level) = (data.len() as c_int, level as c_int);
168        // SAFETY: a pure function (0 for a length LZ4 cannot take).
169        let bound = unsafe { l::LZ4_compressBound(len) };
170        let size = bound as usize + 4;
171        let start = out.len();
172        if !out.grow(start + size) {
173            return Err(Error::Codec("lz4_compress : memory error".into()));
174        }
175        let (at, _) = spare(out);
176        // SAFETY: room for `size` bytes was made, the prefix's 4 and LZ4's `bound - 1` (plus
177        // one); the input covers `data`.
178        let written = unsafe {
179            at.cast::<[u8; 4]>().write(len.to_le_bytes());
180            let block = at.add(4).cast::<c_char>();
181            match level {
182                0 => l::LZ4_compress_default(input(data), block, len, bound - 1),
183                1..=MAX_LEVEL => l::LZ4_compress_HC(input(data), block, len, bound - 1, level),
184                _ => {
185                    return Err(Error::Codec(format!(
186                        "lz4_compress: compression level ({level}) must be within 1..{MAX_LEVEL}"
187                    )));
188                }
189            }
190        };
191        if written <= 0 {
192            return Err(Error::Codec("lz4_compress : data error".into()));
193        }
194        // SAFETY: LZ4 wrote `written` bytes after the prefix.
195        unsafe { out.set_len(start + 4 + written as usize) };
196        Ok(())
197    }
198
199    /// `lz4_uncompress($data)`: the size prefix, then `LZ4_decompress_safe` into a buffer of
200    /// that size. An empty result is a failure too, as in PHP.
201    ///
202    /// PHP allocates the prefix's size with `malloc()`, outside its memory limit, then copies
203    /// the result into a string. The result goes straight into the sink here, which reserves
204    /// no more than a block can expand to; when even that is not to be had, it decodes into a
205    /// buffer of its own and copies, as PHP does.
206    pub(super) fn decompress<S: Sink + ?Sized>(data: &[u8], out: &mut S) -> Result<(), Error> {
207        // PHP checks the length as a C int.
208        let len = data.len() as c_int;
209        let Some(prefix) = data.first_chunk::<4>().filter(|_| len >= 4) else {
210            return Err(data_error());
211        };
212        let size = i32::from_le_bytes(*prefix);
213        if size < 0 {
214            return Err(Error::Codec("lz4_uncompress : allocate size error".into()));
215        }
216        let block = &data[4..];
217        let capacity = (size as usize).min(block.len().saturating_mul(MAX_RATIO).saturating_add(MARGIN));
218        // PHP's `malloc(var_len + 1)`, the sum a C int (so 0x7fffffff asks for a negative size,
219        // which fails): its warning, before decoding.
220        if capacity < size as usize && !allocatable(size.wrapping_add(1) as isize as usize) {
221            return Err(Error::Codec("lz4_uncompress : memory error".into()));
222        }
223        let decode = |at: *mut u8| {
224            // SAFETY: `at` has room for `capacity` bytes; the block covers what follows the
225            // prefix, its length as PHP computes it.
226            unsafe { l::LZ4_decompress_safe(block.as_ptr().cast(), at.cast(), len - 4, capacity as c_int) }
227        };
228        let start = out.len();
229        if out.reserve(start + capacity) {
230            let (at, _) = spare(out);
231            let written = decode(at);
232            if written <= 0 {
233                return Err(data_error());
234            }
235            // SAFETY: LZ4 wrote `written` bytes into the room.
236            unsafe { out.set_len(start + written as usize) };
237            return Ok(());
238        }
239        let mut buffer = Vec::<u8>::new();
240        if buffer.try_reserve_exact(capacity).is_err() {
241            return Err(Error::Codec("lz4_uncompress : memory error".into()));
242        }
243        let written = decode(buffer.as_mut_ptr());
244        if written <= 0 {
245            return Err(data_error());
246        }
247        // SAFETY: LZ4 wrote `written` bytes into the buffer.
248        unsafe { buffer.set_len(written as usize) };
249        if !append(out, &buffer) {
250            return Err(Error::Codec("lz4_uncompress : memory error".into()));
251        }
252        Ok(())
253    }
254}
255
256#[cfg(not(feature = "lz4"))]
257mod imp {
258    use crate::{Error, Sink};
259
260    pub(super) fn compress<S: Sink + ?Sized>(_: &[u8], _: i64, _: &mut S) -> Result<(), Error> {
261        Err(Error::undefined("lz4_compress"))
262    }
263
264    pub(super) fn decompress<S: Sink + ?Sized>(_: &[u8], _: &mut S) -> Result<(), Error> {
265        Err(Error::undefined("lz4_uncompress"))
266    }
267}
268
269#[cfg(all(test, feature = "lz4"))]
270mod tests {
271    use super::*;
272
273    #[test]
274    fn levels() {
275        let mut lz4 = Lz4::new();
276        assert_eq!(lz4.set_level(13), Err(Error::InvalidArgument("Level must be between 0 and 12".into())));
277        let data = b"Lorem ipsum dolor sit amet ".repeat(500);
278        for level in 0..=12 {
279            lz4.set_level(level).unwrap();
280            assert_eq!(lz4.decompress(&lz4.compress(&data).unwrap()).unwrap(), data);
281        }
282        assert_eq!(
283            Lz4::with_level(13).compress(b"x"),
284            Err(Error::Codec("lz4_compress: compression level (13) must be within 1..12".into()))
285        );
286    }
287
288    #[test]
289    fn empty() {
290        let lz4 = Lz4::new();
291        assert_eq!(lz4.compress(b"").unwrap(), b"\0\0\0\0\0");
292        // High compression of an empty input crashed on x86-64.
293        for level in 1..=12 {
294            assert_eq!(Lz4::with_level(level).compress(b"").unwrap(), b"\0\0\0\0\0");
295        }
296        assert_eq!(lz4.decompress(b"\0\0\0\0\0"), Err(Error::Codec("lz4_uncompress : data error".into())));
297    }
298
299    #[test]
300    fn prefixes() {
301        let lz4 = Lz4::new();
302        let body = lz4.compress(b"This is a demo string").unwrap();
303        assert_eq!(&body[..4], &21u32.to_le_bytes());
304        assert_eq!(lz4.decompress(b"abc"), Err(Error::Codec("lz4_uncompress : data error".into())));
305        assert_eq!(
306            lz4.decompress(b"\xff\xff\xff\xffabc"),
307            Err(Error::Codec("lz4_uncompress : allocate size error".into()))
308        );
309        // A prefix larger than the block: the block's own length decides.
310        let mut large = body.clone();
311        large[..4].copy_from_slice(&0x0fff_0000u32.to_le_bytes());
312        assert_eq!(lz4.decompress(&large).unwrap(), b"This is a demo string");
313        // PHP's `var_len + 1` overflows a C int for the largest prefix.
314        large[..4].copy_from_slice(&0x7fff_ffffu32.to_le_bytes());
315        assert_eq!(lz4.decompress(&large), Err(Error::Codec("lz4_uncompress : memory error".into())));
316        // A prefix smaller than the output: LZ4 refuses to write past it.
317        let mut small = body;
318        small[..4].copy_from_slice(&20u32.to_le_bytes());
319        assert_eq!(lz4.decompress(&small), Err(Error::Codec("lz4_uncompress : data error".into())));
320        // A level PHP's C int makes 0 is fast mode.
321        assert_eq!(Lz4::with_level(1 << 32).compress(b"abc").unwrap(), lz4.compress(b"abc").unwrap());
322    }
323}