Skip to main content

utopia_compression/
brotli.rs

1//! Brotli.
2
3use std::borrow::Cow;
4
5use crate::{Algorithm, Compression, Error, Sink};
6
7/// The kind of data Brotli tunes its encoding for.
8///
9/// PHP: `BROTLI_GENERIC`, `BROTLI_TEXT`, `BROTLI_FONT`.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum Mode {
12    /// Any data (the default).
13    #[default]
14    Generic,
15    /// UTF-8 text.
16    Text,
17    /// WOFF 2.0 fonts.
18    Font,
19}
20
21/// Brotli (RFC 7932): `Content-Encoding: br`.
22///
23/// Compresses at quality [`Brotli::DEFAULT_LEVEL`] (11) unless
24/// [`Brotli::set_level`] says otherwise, with a 4 MiB window (`lgwin` 22).
25/// Decompressing accepts what `brotli_uncompress()` accepts, including
26/// trailing bytes after the stream.
27///
28/// ```
29/// use utopia_compression::{Algorithm, Brotli};
30///
31/// let mut brotli = Brotli::new();
32/// brotli.set_level(4)?;
33/// let body = brotli.compress(b"This is a demo string")?;
34/// assert_eq!(brotli.decompress(&body)?, b"This is a demo string");
35/// assert_eq!(brotli.content_encoding(), "br");
36/// # Ok::<(), utopia_compression::Error>(())
37/// ```
38///
39/// ```php
40/// use Utopia\Compression\Algorithms\Brotli;
41///
42/// $brotli = new Brotli();
43/// $brotli->setLevel(4);
44/// $body = $brotli->compress('This is a demo string');
45/// echo $brotli->decompress($body), "\n"; // This is a demo string
46/// echo $brotli->getContentEncoding(), "\n"; // br
47/// ```
48///
49/// The codec is C brotli 1.2.1, the library PHP's ext-brotli links, called the way
50/// `brotli_compress()` calls it: the output is PHP's, byte for byte, at every quality.
51///
52/// Requires the `brotli` feature. PHP: `Utopia\Compression\Algorithms\Brotli`.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct Brotli {
55    level: u32,
56    mode: Mode,
57}
58
59impl Default for Brotli {
60    fn default() -> Self {
61        Self::new()
62    }
63}
64
65impl Brotli {
66    /// The lowest quality. PHP: `BROTLI_COMPRESS_LEVEL_MIN`.
67    pub const MIN_LEVEL: u32 = 0;
68    /// The highest quality. PHP: `BROTLI_COMPRESS_LEVEL_MAX`.
69    pub const MAX_LEVEL: u32 = 11;
70    /// The quality of a new instance. PHP: `BROTLI_COMPRESS_LEVEL_DEFAULT`.
71    pub const DEFAULT_LEVEL: u32 = 11;
72
73    /// Brotli at quality 11 in generic mode.
74    ///
75    /// PHP: `new Brotli()`.
76    pub const fn new() -> Self {
77        Brotli { level: Self::DEFAULT_LEVEL, mode: Mode::Generic }
78    }
79
80    /// The quality, `0` to `11`.
81    ///
82    /// PHP: `getLevel()`.
83    pub const fn level(&self) -> u32 {
84        self.level
85    }
86
87    /// Sets the quality. Fails with [`Error::InvalidArgument`] outside `0`
88    /// to `11`.
89    ///
90    /// PHP: `setLevel($level)`.
91    pub fn set_level(&mut self, level: i64) -> Result<(), Error> {
92        if level < i64::from(Self::MIN_LEVEL) || level > i64::from(Self::MAX_LEVEL) {
93            return Err(Error::InvalidArgument(format!(
94                "Level must be between {} and {}",
95                Self::MIN_LEVEL,
96                Self::MAX_LEVEL
97            )));
98        }
99        self.level = level as u32;
100        Ok(())
101    }
102
103    /// Tunes the encoding for any data (the default).
104    ///
105    /// PHP: `useGenericMode()`.
106    pub fn use_generic_mode(&mut self) {
107        self.mode = Mode::Generic;
108    }
109
110    /// Meant to tune the encoding for UTF-8 text, but keeps generic mode, as
111    /// PHP does.
112    ///
113    /// PHP: `useTextMode()`, which sets `BROTLI_GENERIC` (a quirk kept for
114    /// identical output).
115    pub fn use_text_mode(&mut self) {
116        self.mode = Mode::Generic;
117    }
118
119    /// Meant to tune the encoding for WOFF 2.0 fonts, but keeps generic
120    /// mode, as PHP does.
121    ///
122    /// PHP: `useFontMode()`, which sets `BROTLI_GENERIC` (a quirk kept for
123    /// identical output).
124    pub fn use_font_mode(&mut self) {
125        self.mode = Mode::Generic;
126    }
127
128    /// The mode the encoder runs in.
129    pub const fn mode(&self) -> Mode {
130        self.mode
131    }
132
133    /// Whether this build has Brotli (the `brotli` feature).
134    ///
135    /// PHP: `Brotli::isSupported()`, whether `brotli_compress()` exists.
136    pub const fn is_supported() -> bool {
137        cfg!(feature = "brotli")
138    }
139
140    /// [`Algorithm::compress`], appended to `out`.
141    pub fn compress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
142        let mode = match self.mode {
143            Mode::Generic => 0,
144            Mode::Text => 1,
145            Mode::Font => 2,
146        };
147        imp::compress(data, i64::from(self.level), mode, out)
148    }
149
150    /// Compresses `data` into `out` at `level` and `mode` (`BROTLI_GENERIC`, `BROTLI_TEXT` or
151    /// `BROTLI_FONT`: 0, 1 or 2), unchecked, as `brotli_compress($data, $level, $mode)` takes
152    /// them: either out of range fails with [`Error::Codec`] and PHP's warning.
153    ///
154    /// PHP: `compress()` on a subclass that set `$level` or `$mode` itself.
155    pub fn compress_with<S: Sink + ?Sized>(data: &[u8], level: i64, mode: i64, out: &mut S) -> Result<(), Error> {
156        imp::compress(data, level, mode, out)
157    }
158
159    /// [`Algorithm::decompress`], appended to `out`.
160    pub fn decompress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
161        imp::decompress(data, out)
162    }
163}
164
165impl Algorithm for Brotli {
166    fn name(&self) -> &str {
167        Compression::BROTLI
168    }
169
170    fn content_encoding(&self) -> Cow<'_, str> {
171        Cow::Borrowed("br")
172    }
173
174    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
175        let mut out = Vec::new();
176        self.compress_into(data, &mut out)?;
177        Ok(out)
178    }
179
180    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
181        let mut out = Vec::new();
182        self.decompress_into(data, &mut out)?;
183        Ok(out)
184    }
185
186    fn supported(&self) -> bool {
187        Self::is_supported()
188    }
189}
190
191#[cfg(feature = "brotli")]
192mod imp {
193    //! ext-brotli's `brotli_compress()` and `brotli_uncompress()`: the same calls into C brotli
194    //! 1.2.1 (the library PHP links), each call's output written where it ends up rather than
195    //! into a buffer it is then copied out of, its encoder on the sink's allocator
196    //! ([`Sink::allocator`]). The decoder stays on `malloc()`: its ring buffer, sized to the
197    //! stream, was slower to take from PHP's allocator.
198
199    use brotlic_sys as b;
200
201    use crate::sink::spare;
202    use crate::{Error, Sink};
203
204    /// `BROTLI_DEFAULT_WINDOW`, which PHP asks for with an `lgwin` of 0.
205    const WINDOW: u32 = b::BROTLI_DEFAULT_WINDOW as u32;
206
207    /// The output chunk of `brotli_uncompress()` (`PHP_BROTLI_BUFFER_SIZE`).
208    const CHUNK: usize = 1 << 19;
209
210    /// The output size past which it grows by a quarter rather than a chunk.
211    const GEOMETRIC: usize = 8 << 20;
212
213    /// The sink's allocator as brotli takes one; none for brotli's default (`malloc()`).
214    fn allocator<S: Sink + ?Sized>(out: &S) -> (b::brotli_alloc_func, b::brotli_free_func, *mut std::ffi::c_void) {
215        match out.allocator() {
216            Some(allocator) => (Some(allocator.alloc), Some(allocator.free), allocator.opaque),
217            None => (None, None, std::ptr::null_mut()),
218        }
219    }
220
221    /// An encoder, destroyed when dropped.
222    struct Encoder(*mut b::BrotliEncoderState);
223
224    impl Drop for Encoder {
225        fn drop(&mut self) {
226            // SAFETY: created by BrotliEncoderCreateInstance and destroyed only here.
227            unsafe { b::BrotliEncoderDestroyInstance(self.0) };
228        }
229    }
230
231    /// A decoder, destroyed when dropped.
232    struct Decoder(*mut b::BrotliDecoderState);
233
234    impl Drop for Decoder {
235        fn drop(&mut self) {
236            // SAFETY: created by BrotliDecoderCreateInstance and destroyed only here.
237            unsafe { b::BrotliDecoderDestroyInstance(self.0) };
238        }
239    }
240
241    /// `brotli_compress($data, $level, $mode)`: the encoder's parameters checked and set as
242    /// `php_brotli_context_create_encoder_ex()` does (a level or mode out of range is PHP's
243    /// warning), then `BROTLI_OPERATION_FINISH` over the whole input until the encoder is
244    /// done, each call into a window of `max(BrotliEncoderMaxCompressedSize(len), 64)` bytes.
245    pub(super) fn compress<S: Sink + ?Sized>(data: &[u8], level: i64, mode: i64, out: &mut S) -> Result<(), Error> {
246        // SAFETY: a pure function.
247        let window = unsafe { b::BrotliEncoderMaxCompressedSize(data.len()) }.max(64);
248        let start = out.len();
249        let (alloc, free, opaque) = allocator(out);
250        // SAFETY: creates an encoder on the sink's allocator (or the default), or returns null.
251        let encoder = Encoder(unsafe { b::BrotliEncoderCreateInstance(alloc, free, opaque) });
252        if encoder.0.is_null() {
253            return Err(Error::Codec("brotli_compress(): failed to prepare compression".into()));
254        }
255        if !(0..=11).contains(&level) {
256            return Err(Error::Codec(format!(
257                "brotli_compress(): failed to compression level ({level}): must be within 0..11"
258            )));
259        }
260        if !(0..=2).contains(&mode) {
261            return Err(Error::Codec(format!(
262                "brotli_compress(): failed to compression mode ({mode}): must be BROTLI_GENERIC(0)|BROTLI_TEXT(1)|BROTLI_FONT(2)"
263            )));
264        }
265        // SAFETY: a live encoder.
266        let set = unsafe {
267            b::BrotliEncoderSetParameter(encoder.0, b::BrotliEncoderParameter_BROTLI_PARAM_QUALITY, level as u32) != 0
268                && b::BrotliEncoderSetParameter(encoder.0, b::BrotliEncoderParameter_BROTLI_PARAM_LGWIN, WINDOW) != 0
269                && b::BrotliEncoderSetParameter(encoder.0, b::BrotliEncoderParameter_BROTLI_PARAM_MODE, mode as u32)
270                    != 0
271        };
272        if !set {
273            return Err(Error::Codec("brotli_compress(): failed to set compression parameters".into()));
274        }
275        let (mut available_in, mut next_in) = (data.len(), data.as_ptr());
276        // SAFETY: a live encoder.
277        while unsafe { b::BrotliEncoderIsFinished(encoder.0) } == 0 {
278            let len = out.len();
279            if !out.grow((len + window).max(if len == start { 0 } else { out.capacity() + out.capacity() / 2 })) {
280                return Err(Error::Codec("brotli_compress(): insufficient memory".into()));
281            }
282            let (at, _) = spare(out);
283            let (mut available_out, mut next_out) = (window, at);
284            // SAFETY: the encoder is live; the input covers what is left of `data` and the
285            // output `window` bytes of room in `out`.
286            let ok = unsafe {
287                b::BrotliEncoderCompressStream(
288                    encoder.0,
289                    b::BrotliEncoderOperation_BROTLI_OPERATION_FINISH,
290                    &raw mut available_in,
291                    &raw mut next_in,
292                    &raw mut available_out,
293                    &raw mut next_out,
294                    std::ptr::null_mut(),
295                )
296            };
297            if ok == 0 {
298                return Err(Error::Codec("brotli_compress(): failed to compress".into()));
299            }
300            // SAFETY: the encoder wrote `window - available_out` bytes into the room.
301            unsafe { out.set_len(len + (window - available_out)) };
302        }
303        Ok(())
304    }
305
306    /// `brotli_uncompress()`: a decoder that accepts large windows, run while it needs more
307    /// output; anything but success (truncated or corrupt input) is a failure. The output is
308    /// written in place, grown as [`GEOMETRIC`] says.
309    pub(super) fn decompress<S: Sink + ?Sized>(data: &[u8], out: &mut S) -> Result<(), Error> {
310        let failed = || Error::Codec("brotli_uncompress(): failed to uncompress".into());
311        // SAFETY: creates a decoder with brotli's default allocator, or returns null.
312        let decoder = Decoder(unsafe { b::BrotliDecoderCreateInstance(None, None, std::ptr::null_mut()) });
313        if decoder.0.is_null() {
314            return Err(Error::Codec("brotli_uncompress(): failed to prepare uncompression".into()));
315        }
316        // SAFETY: a live decoder.
317        if unsafe {
318            b::BrotliDecoderSetParameter(decoder.0, b::BrotliDecoderParameter_BROTLI_DECODER_PARAM_LARGE_WINDOW, 1)
319        } == 0
320        {
321            return Err(Error::Codec("brotli_uncompress(): failed to set uncompression parameters".into()));
322        }
323        let (mut available_in, mut next_in) = (data.len(), data.as_ptr());
324        let mut first = CHUNK.min(data.len().saturating_mul(4).max(1024));
325        loop {
326            let (len, capacity) = (out.len(), out.capacity());
327            // 512 KiB at a time, as PHP grows its output, up to 8 MiB; then by a quarter, so a
328            // large output is copied a bounded number of times when the block cannot be
329            // extended in place.
330            let wanted = if capacity < GEOMETRIC { len + first } else { (len + first).max(capacity + capacity / 4) };
331            if len + first > capacity && !out.grow(wanted) {
332                return Err(Error::Codec("brotli_uncompress(): insufficient memory".into()));
333            }
334            first = CHUNK;
335            let (at, room) = spare(out);
336            let (mut available_out, mut next_out) = (room, at);
337            // SAFETY: the decoder is live; the input covers what is left of `data` and the
338            // output the room in `out`.
339            let result = unsafe {
340                b::BrotliDecoderDecompressStream(
341                    decoder.0,
342                    &raw mut available_in,
343                    &raw mut next_in,
344                    &raw mut available_out,
345                    &raw mut next_out,
346                    std::ptr::null_mut(),
347                )
348            };
349            // SAFETY: the decoder wrote `room - available_out` bytes into the room.
350            unsafe { out.set_len(len + (room - available_out)) };
351            match result {
352                b::BrotliDecoderResult_BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT => {}
353                b::BrotliDecoderResult_BROTLI_DECODER_RESULT_SUCCESS => return Ok(()),
354                _ => return Err(failed()),
355            }
356        }
357    }
358}
359
360#[cfg(not(feature = "brotli"))]
361mod imp {
362    use crate::{Error, Sink};
363
364    pub(super) fn compress<S: Sink + ?Sized>(_: &[u8], _: i64, _: i64, _: &mut S) -> Result<(), Error> {
365        Err(Error::undefined("brotli_compress"))
366    }
367
368    pub(super) fn decompress<S: Sink + ?Sized>(_: &[u8], _: &mut S) -> Result<(), Error> {
369        Err(Error::undefined("brotli_uncompress"))
370    }
371}
372
373#[cfg(all(test, feature = "brotli"))]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn levels() {
379        let mut brotli = Brotli::new();
380        assert_eq!(brotli.set_level(-1), Err(Error::InvalidArgument("Level must be between 0 and 11".into())));
381        assert_eq!(brotli.set_level(12), Err(Error::InvalidArgument("Level must be between 0 and 11".into())));
382        let data = b"Lorem ipsum dolor sit amet ".repeat(500);
383        for level in 0..=11 {
384            brotli.set_level(level).unwrap();
385            assert_eq!(brotli.decompress(&brotli.compress(&data).unwrap()).unwrap(), data);
386        }
387    }
388
389    #[test]
390    fn modes_stay_generic() {
391        let mut brotli = Brotli::new();
392        brotli.use_text_mode();
393        assert_eq!(brotli.mode(), Mode::Generic);
394        brotli.use_font_mode();
395        assert_eq!(brotli.mode(), Mode::Generic);
396    }
397
398    #[test]
399    fn invalid_data() {
400        let failed = Err(Error::Codec("brotli_uncompress(): failed to uncompress".into()));
401        assert_eq!(Brotli::new().decompress(b""), failed);
402        assert_eq!(Brotli::new().decompress(b"garbage"), failed);
403        let body = Brotli::new().compress(&b"Lorem ipsum ".repeat(1000)).unwrap();
404        assert_eq!(Brotli::new().decompress(&body[..body.len() - 1]), failed);
405    }
406
407    #[test]
408    fn unchecked_parameters() {
409        let mut out = Vec::new();
410        assert_eq!(
411            Brotli::compress_with(b"x", 12, 0, &mut out),
412            Err(Error::Codec("brotli_compress(): failed to compression level (12): must be within 0..11".into()))
413        );
414        assert_eq!(
415            Brotli::compress_with(b"x", 4, 3, &mut out),
416            Err(Error::Codec(
417                "brotli_compress(): failed to compression mode (3): must be BROTLI_GENERIC(0)|BROTLI_TEXT(1)|BROTLI_FONT(2)"
418                    .into()
419            ))
420        );
421        Brotli::compress_with(b"text", 4, 1, &mut out).unwrap();
422        assert_eq!(Brotli::new().decompress(&out).unwrap(), b"text");
423    }
424
425    #[test]
426    fn large_output() {
427        // More than one 512 KiB chunk out of a small input.
428        let data = vec![b'a'; 3 << 20];
429        let body = Brotli::new().compress(&data).unwrap();
430        assert!(body.len() < 1000);
431        assert_eq!(Brotli::new().decompress(&body).unwrap(), data);
432    }
433}