utopia_compression/lib.rs
1//! Compression algorithms behind one [`Algorithm`] trait: [`Brotli`],
2//! [`Deflate`], [`Gzip`], [`Lz4`], [`Snappy`], [`Xz`] and [`Zstd`], and the
3//! choice of one from a name or an HTTP `Accept-Encoding` header
4//! ([`Compression::from_accept_encoding`]).
5//!
6//! Every algorithm writes the bytes PHP's extension writes at the same level, on
7//! the same C library (zlib, C brotli, libzstd, LZ4) or a port of it (snappy),
8//! so data compressed by either runtime is read by the other, and responses
9//! are identical. Each one can also write into a caller's buffer ([`Sink`]), so
10//! the output is never copied.
11//!
12//! ```
13//! use utopia_compression::{Algorithm, Compression};
14//!
15//! let algorithm = Compression::from_accept_encoding("gzip;q=0.8, br", &[] as &[&str]).unwrap();
16//! assert_eq!(algorithm.content_encoding(), "br");
17//!
18//! let body = algorithm.compress(b"Hello, Hello, Hello")?;
19//! assert_eq!(algorithm.decompress(&body)?, b"Hello, Hello, Hello");
20//! # Ok::<(), utopia_compression::Error>(())
21//! ```
22//!
23//! ```php
24//! use Utopia\Compression\Compression;
25//!
26//! $algorithm = Compression::fromAcceptEncoding('gzip;q=0.8, br');
27//! echo $algorithm->getContentEncoding(), "\n"; // br
28//!
29//! $body = $algorithm->compress('Hello, Hello, Hello');
30//! echo $algorithm->decompress($body), "\n"; // Hello, Hello, Hello
31//! ```
32//!
33//! Compressing is CPU work that grows with the input: in async code, run
34//! large inputs on the blocking pool (`utopia_async::spawn_blocking`) so they
35//! do not hold up a runtime thread.
36//!
37//! ## Cargo features
38//!
39//! Each algorithm that needs a codec library is behind a feature, as each
40//! needs an extension in PHP: `brotli`, `lz4`, `zlib` (Deflate and GZIP),
41//! `zstd` (all on by default) and `xz` (off). Without its feature an
42//! algorithm reports [`Algorithm::supported`] `false` and fails with
43//! [`Error::Unsupported`], like PHP without the extension. [`Snappy`] is pure
44//! Rust and always available.
45//!
46//! PHP: ports `utopia-php/compression`.
47//!
48//! | PHP | Rust |
49//! |---|---|
50//! | `Utopia\Compression\Compression` (abstract class) | [`Algorithm`] (trait), and [`Compression`] for the built-in algorithms |
51//! | `Compression::NONE`, `IDENTITY`, `BROTLI`, ... | [`Compression::NONE`], [`Compression::IDENTITY`], [`Compression::BROTLI`], ... |
52//! | `Compression::fromName()` | [`Compression::from_name`] |
53//! | `Compression::fromAcceptEncoding()` | [`Compression::from_accept_encoding`], [`Compression::from_accept_encoding_with`] (a `name => bool` map) |
54//! | `getName()`, `getContentEncoding()` | [`Algorithm::name`], [`Algorithm::content_encoding`] |
55//! | `compress()`, `decompress()` | [`Algorithm::compress`], [`Algorithm::decompress`] |
56//! | `isSupported()` (static) | `is_supported()` on each algorithm, and [`Algorithm::supported`] |
57//! | `getLevel()`, `setLevel()` | `level()`, `set_level()` on [`Brotli`], [`Lz4`] and [`Zstd`] |
58//! | `new LZ4($level)`, `new Zstd($level)` | [`Lz4::with_level`], [`Zstd::with_level`] |
59//! | `Brotli::useGenericMode()`, `useTextMode()`, `useFontMode()` | [`Brotli::use_generic_mode`], [`Brotli::use_text_mode`], [`Brotli::use_font_mode`] |
60//! | `Algorithms\Brotli`, `Deflate`, `GZIP`, `LZ4`, `Snappy`, `XZ`, `Zstd` | [`Brotli`], [`Deflate`], [`Gzip`], [`Lz4`], [`Snappy`], [`Xz`], [`Zstd`] |
61//! | `\InvalidArgumentException`, a warning and `""`, `\Error` | [`Error::InvalidArgument`], [`Error::Codec`], [`Error::Unsupported`] |
62//!
63//! PHP: where an extension emits a warning and returns `false` (invalid
64//! data, a level the codec refuses), the PHP method returns an empty string;
65//! Rust returns [`Error::Codec`] with the warning's text.
66
67#![warn(missing_docs)]
68
69mod brotli;
70mod error;
71mod lz4;
72mod negotiate;
73mod sink;
74mod snappy;
75mod xz;
76mod zlib;
77mod zstd;
78
79use std::borrow::Cow;
80
81pub use brotli::{Brotli, Mode};
82pub use error::Error;
83pub use lz4::Lz4;
84pub use sink::{Allocator, Sink};
85pub use snappy::Snappy;
86pub use xz::Xz;
87pub use zlib::{Deflate, Gzip};
88pub use zstd::Zstd;
89
90/// The getting started guide (`guide.md`), compiled and run with the doctests.
91#[cfg(doctest)]
92#[doc = include_str!("../guide.md")]
93pub struct GettingStarted;
94
95/// A compression algorithm: a name, a `Content-Encoding` token, and a pair
96/// of inverse transformations.
97///
98/// Implement it to add an algorithm; [`Compression`] holds the built-in ones.
99///
100/// ```
101/// use utopia_compression::{Algorithm, Error};
102///
103/// /// Stores data as is.
104/// struct Store;
105///
106/// impl Algorithm for Store {
107/// fn name(&self) -> &str {
108/// "Store"
109/// }
110/// fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
111/// Ok(data.to_vec())
112/// }
113/// fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
114/// Ok(data.to_vec())
115/// }
116/// fn supported(&self) -> bool {
117/// true
118/// }
119/// }
120///
121/// assert_eq!(Store.content_encoding(), "store");
122/// ```
123///
124/// ```php
125/// use Utopia\Compression\Compression;
126///
127/// class Store extends Compression
128/// {
129/// public function getName(): string { return 'Store'; }
130/// public function compress(string $data): string { return $data; }
131/// public function decompress(string $data): string { return $data; }
132/// public static function isSupported(): bool { return true; }
133/// }
134///
135/// echo (new Store())->getContentEncoding(), "\n"; // store
136/// ```
137pub trait Algorithm {
138 /// The algorithm's name, such as `gzip`.
139 ///
140 /// PHP: `getName()`.
141 fn name(&self) -> &str;
142
143 /// The token of the algorithm in `Content-Encoding` and
144 /// `Accept-Encoding` headers: by default the name in lower case (ASCII
145 /// only); `br` for Brotli.
146 ///
147 /// PHP: `getContentEncoding()`, `strtolower($this->getName())` by default.
148 fn content_encoding(&self) -> Cow<'_, str> {
149 let name = self.name();
150 match php_std::string::strtolower(name.as_bytes()) {
151 Cow::Borrowed(_) => Cow::Borrowed(name),
152 // ASCII case mapping keeps UTF-8 valid.
153 Cow::Owned(lower) => Cow::Owned(String::from_utf8_lossy(&lower).into_owned()),
154 }
155 }
156
157 /// Compresses `data`.
158 ///
159 /// PHP: `compress($data)`.
160 fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error>;
161
162 /// Decompresses `data`. Fails with [`Error::Codec`] when `data` is not a
163 /// valid stream of the algorithm.
164 ///
165 /// PHP: `decompress($data)`.
166 fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error>;
167
168 /// Whether this build can run the algorithm.
169 ///
170 /// PHP: `static::isSupported()`, whether the extension is loaded.
171 fn supported(&self) -> bool;
172}
173
174/// A built-in algorithm, as chosen by name or from an `Accept-Encoding`
175/// header.
176///
177/// ```
178/// use utopia_compression::{Algorithm, Compression, Zstd};
179///
180/// assert_eq!(Compression::from_name("ZSTD"), Some(Compression::Zstd(Zstd::new())));
181/// assert_eq!(Compression::from_name("br").unwrap().name(), "brotli");
182/// assert_eq!(Compression::from_name("identity"), None);
183/// ```
184///
185/// ```php
186/// use Utopia\Compression\Compression;
187///
188/// var_dump(Compression::fromName('ZSTD') instanceof Utopia\Compression\Algorithms\Zstd); // bool(true)
189/// echo Compression::fromName('br')->getName(), "\n"; // brotli
190/// var_dump(Compression::fromName('identity')); // NULL
191/// ```
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub enum Compression {
194 /// Brotli (`br`).
195 Brotli(Brotli),
196 /// Raw deflate (`deflate`).
197 Deflate(Deflate),
198 /// Gzip (`gzip`).
199 Gzip(Gzip),
200 /// LZ4 (`lz4`).
201 Lz4(Lz4),
202 /// Snappy (`snappy`).
203 Snappy(Snappy),
204 /// XZ (`xz`).
205 Xz(Xz),
206 /// Zstandard (`zstd`).
207 Zstd(Zstd),
208}
209
210impl Compression {
211 /// No compression. PHP: `Compression::NONE`.
212 pub const NONE: &'static str = "none";
213 /// No compression, the HTTP token. PHP: `Compression::IDENTITY` (deprecated there).
214 pub const IDENTITY: &'static str = "identity";
215 /// PHP: `Compression::BROTLI`.
216 pub const BROTLI: &'static str = "brotli";
217 /// PHP: `Compression::DEFLATE`.
218 pub const DEFLATE: &'static str = "deflate";
219 /// PHP: `Compression::GZIP`.
220 pub const GZIP: &'static str = "gzip";
221 /// PHP: `Compression::LZ4`.
222 pub const LZ4: &'static str = "lz4";
223 /// PHP: `Compression::SNAPPY`.
224 pub const SNAPPY: &'static str = "snappy";
225 /// PHP: `Compression::XZ`.
226 pub const XZ: &'static str = "xz";
227 /// PHP: `Compression::ZSTD`.
228 pub const ZSTD: &'static str = "zstd";
229
230 /// The algorithm named `name` (ASCII case-insensitive; `br` is Brotli),
231 /// at its default level. `None` for `none`, `identity` and unknown names.
232 ///
233 /// PHP: `Compression::fromName($name)`.
234 pub fn from_name(name: &str) -> Option<Self> {
235 Self::from_name_bytes(name.as_bytes())
236 }
237
238 /// [`Compression::from_name`] for a name in bytes, as PHP's strings are.
239 pub fn from_name_bytes(name: &[u8]) -> Option<Self> {
240 Some(match php_std::string::strtolower(name).as_ref() {
241 b"brotli" | b"br" => Compression::Brotli(Brotli::new()),
242 b"deflate" => Compression::Deflate(Deflate::new()),
243 b"gzip" => Compression::Gzip(Gzip::new()),
244 b"lz4" => Compression::Lz4(Lz4::new()),
245 b"snappy" => Compression::Snappy(Snappy::new()),
246 b"xz" => Compression::Xz(Xz::new()),
247 b"zstd" => Compression::Zstd(Zstd::new()),
248 _ => return None,
249 })
250 }
251
252 /// The algorithm to answer an `Accept-Encoding` header with: of the
253 /// encodings the header lists that are in `supported`, the one with the
254 /// highest `q` (the first listed on a tie), or `None` when there is
255 /// none, or when it is `none` or `identity` (no compression).
256 ///
257 /// An empty `supported` means [`Compression::is_default_supported`]:
258 /// `zstd`, `brotli`, `gzip` and `deflate` when this build supports them,
259 /// plus `none` and `identity`. Names in `supported` are canonical (`brotli`,
260 /// not `br`).
261 ///
262 /// ```
263 /// use utopia_compression::{Algorithm, Compression};
264 ///
265 /// let chosen = Compression::from_accept_encoding("gzip;q=0.5, br;q=0.5", &["gzip", "brotli"]);
266 /// assert_eq!(chosen.unwrap().name(), "gzip");
267 ///
268 /// let chosen = Compression::from_accept_encoding("snappy;q=0.6, br;q=0.4", &["snappy"]);
269 /// assert_eq!(chosen.unwrap().name(), "snappy");
270 ///
271 /// assert_eq!(Compression::from_accept_encoding("identity, gzip", &[] as &[&str]), None);
272 /// ```
273 ///
274 /// ```php
275 /// use Utopia\Compression\Compression;
276 ///
277 /// echo Compression::fromAcceptEncoding('gzip;q=0.5, br;q=0.5', ['gzip', 'brotli'])->getName(), "\n"; // gzip
278 /// echo Compression::fromAcceptEncoding('snappy;q=0.6, br;q=0.4', ['snappy'])->getName(), "\n"; // snappy
279 /// var_dump(Compression::fromAcceptEncoding('identity, gzip')); // NULL
280 /// ```
281 ///
282 /// PHP: `Compression::fromAcceptEncoding($acceptEncoding, $supported)` with
283 /// a list of names.
284 pub fn from_accept_encoding<S: AsRef<str>>(accept: &str, supported: &[S]) -> Option<Self> {
285 if supported.is_empty() {
286 Self::from_accept_encoding_with(accept, Self::is_default_supported)
287 } else {
288 Self::from_accept_encoding_with(accept, |name| supported.iter().any(|s| s.as_ref() == name))
289 }
290 }
291
292 /// [`Compression::from_accept_encoding`] with the supported encodings
293 /// given by a predicate on their canonical name.
294 ///
295 /// PHP: `Compression::fromAcceptEncoding($acceptEncoding, $supported)`
296 /// with a `name => bool` map (`fn(name) => $supported[$name] ?? false`).
297 pub fn from_accept_encoding_with(accept: &str, supported: impl Fn(&str) -> bool) -> Option<Self> {
298 negotiate::choose(accept.as_bytes(), |name| std::str::from_utf8(name).is_ok_and(&supported))
299 }
300
301 /// [`Compression::from_accept_encoding_with`] for a header and names in bytes, as PHP's
302 /// strings are: a name that is not UTF-8 can still be supported, and chosen (it names no
303 /// algorithm, so the answer is then `None`).
304 pub fn from_accept_encoding_bytes(accept: &[u8], supported: impl Fn(&[u8]) -> bool) -> Option<Self> {
305 negotiate::choose(accept, supported)
306 }
307
308 /// Whether `name` is offered when no supported list is given: `zstd`,
309 /// `brotli`, `gzip` and `deflate` when this build supports them, and
310 /// `none` and `identity`.
311 ///
312 /// PHP: the default `$supported` of `fromAcceptEncoding()`.
313 pub fn is_default_supported(name: &str) -> bool {
314 match name {
315 Self::ZSTD => Zstd::is_supported(),
316 Self::BROTLI => Brotli::is_supported(),
317 Self::GZIP => Gzip::is_supported(),
318 Self::DEFLATE => Deflate::is_supported(),
319 Self::NONE | Self::IDENTITY => true,
320 _ => false,
321 }
322 }
323
324 fn algorithm(&self) -> &dyn Algorithm {
325 match self {
326 Compression::Brotli(a) => a,
327 Compression::Deflate(a) => a,
328 Compression::Gzip(a) => a,
329 Compression::Lz4(a) => a,
330 Compression::Snappy(a) => a,
331 Compression::Xz(a) => a,
332 Compression::Zstd(a) => a,
333 }
334 }
335}
336
337impl Algorithm for Compression {
338 fn name(&self) -> &str {
339 self.algorithm().name()
340 }
341
342 fn content_encoding(&self) -> Cow<'_, str> {
343 self.algorithm().content_encoding()
344 }
345
346 fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
347 match self {
348 Compression::Brotli(a) => a.compress(data),
349 Compression::Deflate(a) => a.compress(data),
350 Compression::Gzip(a) => a.compress(data),
351 Compression::Lz4(a) => a.compress(data),
352 Compression::Snappy(a) => a.compress(data),
353 Compression::Xz(a) => a.compress(data),
354 Compression::Zstd(a) => a.compress(data),
355 }
356 }
357
358 fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
359 match self {
360 Compression::Brotli(a) => a.decompress(data),
361 Compression::Deflate(a) => a.decompress(data),
362 Compression::Gzip(a) => a.decompress(data),
363 Compression::Lz4(a) => a.decompress(data),
364 Compression::Snappy(a) => a.decompress(data),
365 Compression::Xz(a) => a.decompress(data),
366 Compression::Zstd(a) => a.decompress(data),
367 }
368 }
369
370 fn supported(&self) -> bool {
371 self.algorithm().supported()
372 }
373}