Compression
RustIn Appwrite#
Appwrite runs the Rust crate: the PHP extension serves the library and none of its PHP is left.
Rust 2,862 lines (1,736 code)· PHP 0 lines (0 code)split
| Part | Code | Comments | Blank | Total | Files |
|---|---|---|---|---|---|
| Rust source | 1,736 | 857 | 269 | 2,862 | 10 |
| PHP source | 0 | 0 | 0 | 0 | 0 |
Comments include doc comments. Each side counts its src/; the PHP side is what the package still has in PHP.
Served from Rust (8)
Utopia\Compression\Algorithms\BrotliUtopia\Compression\Algorithms\DeflateUtopia\Compression\Algorithms\GZIPUtopia\Compression\Algorithms\LZ4Utopia\Compression\Algorithms\SnappyUtopia\Compression\Algorithms\XZUtopia\Compression\Algorithms\ZstdUtopia\Compression\CompressionInstall#
cargo add utopia-compressionGetting started#
Common tasks with Compression, each a complete program you can copy and run.
This library compresses and decompresses data with seven algorithms behind one Algorithm trait: Brotli, Deflate, Gzip, LZ4, Snappy, XZ and Zstd. It also picks the algorithm to answer an HTTP request with, from the client's Accept-Encoding header. The output matches what PHP's extensions write, so either runtime reads what the other wrote. This guide covers the common tasks.
Compress a response for the client
Compression::from_accept_encoding reads the header and returns the accepted algorithm with the highest q value, or None when the response should go out as is. Send the result with its content_encoding() as the Content-Encoding header.
use utopia_compression::{Algorithm, Compression};
let body = b"{\"users\": [], \"total\": 0}".repeat(100);
match Compression::from_accept_encoding("gzip;q=0.9, br, deflate;q=0.5", &[] as &[&str]) {
Some(algorithm) => {
let encoded = algorithm.compress(&body)?;
assert_eq!(algorithm.content_encoding(), "br");
assert!(encoded.len() < body.len());
}
None => unreachable!("Brotli is accepted"),
}use Utopia\Compression\Compression;
$body = str_repeat('{"users": [], "total": 0}', 100);
$algorithm = Compression::fromAcceptEncoding('gzip;q=0.9, br, deflate;q=0.5');
$encoded = $algorithm->compress($body);
echo $algorithm->getContentEncoding(), "\n"; // br
var_dump(strlen($encoded) < strlen($body)); // bool(true)Offer only some algorithms
Pass the names you offer. Clients' preferences decide among them, and the first one listed in the header wins a tie. none and identity mean no compression.
use utopia_compression::{Algorithm, Compression};
let chosen = Compression::from_accept_encoding("br;q=0.5, gzip;q=0.5", &["gzip", "brotli"]);
assert_eq!(chosen.unwrap().name(), "brotli");
assert!(Compression::from_accept_encoding("br", &["gzip"]).is_none());use Utopia\Compression\Compression;
echo Compression::fromAcceptEncoding('br;q=0.5, gzip;q=0.5', ['gzip', 'brotli'])->getName(), "\n"; // brotli
var_dump(Compression::fromAcceptEncoding('br', ['gzip'])); // NULLChoose an algorithm and its level
Each algorithm is a type you can build directly. Brotli, LZ4 and Zstd have levels: set_level checks the range and fails with Error::InvalidArgument outside it.
use utopia_compression::{Algorithm, Brotli, Error, Zstd};
let mut zstd = Zstd::new();
zstd.set_level(19)?;
let packed = zstd.compress(b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")?;
assert_eq!(zstd.decompress(&packed)?, b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
let mut brotli = Brotli::new();
assert_eq!(brotli.set_level(12), Err(Error::InvalidArgument("Level must be between 0 and 11".into())));use Utopia\Compression\Algorithms\Brotli;
use Utopia\Compression\Algorithms\Zstd;
$zstd = new Zstd();
$zstd->setLevel(19);
$packed = $zstd->compress(str_repeat('a', 40));
echo $zstd->decompress($packed), "\n"; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
try {
(new Brotli())->setLevel(12);
} catch (\InvalidArgumentException $e) {
echo $e->getMessage(), "\n"; // Level must be between 0 and 11
}Write into your own buffer
Each algorithm's compress_into and decompress_into append to a Sink: a Vec<u8>, or a buffer type of your own that implements it, so the output is written once, where it ends up. The PHP extension writes straight into the PHP string it returns this way.
use utopia_compression::{Algorithm, Zstd};
let mut out = b"header:".to_vec();
Zstd::new().compress_into(b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", &mut out)?;
assert_eq!(Zstd::new().decompress(&out[7..])?, b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");Handle data that is not compressed
Decompressing data that is not a valid stream fails with Error::Codec, whose message is the warning PHP's extension emits. PHP returns an empty string in that case.
use utopia_compression::{Algorithm, Error, Gzip};
assert_eq!(Gzip::new().decompress(b"plain text"), Err(Error::Codec("gzdecode(): data error".into())));use Utopia\Compression\Algorithms\GZIP;
var_dump(@(new GZIP())->decompress('plain text')); // string(0) ""
echo error_get_last()['message'], "\n"; // gzdecode(): data errorAdd your own algorithm
Implement Algorithm for a type. content_encoding() defaults to the name in lower case.
use utopia_compression::{Algorithm, Error};
/// Reverses the bytes: not compression, but an inverse pair.
struct Reverse;
impl Algorithm for Reverse {
fn name(&self) -> &str {
"Reverse"
}
fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
Ok(data.iter().rev().copied().collect())
}
fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
self.compress(data)
}
fn supported(&self) -> bool {
true
}
}
assert_eq!(Reverse.content_encoding(), "reverse");
assert_eq!(Reverse.decompress(&Reverse.compress(b"abc")?)?, b"abc");use Utopia\Compression\Compression;
class Reverse extends Compression
{
public function getName(): string { return 'Reverse'; }
public function compress(string $data): string { return strrev($data); }
public function decompress(string $data): string { return strrev($data); }
public static function isSupported(): bool { return true; }
}
echo (new Reverse())->getContentEncoding(), "\n"; // reverse
echo (new Reverse())->decompress((new Reverse())->compress('abc')), "\n"; // abcReference#
Compression algorithms behind one Algorithm trait: Brotli,
Deflate, Gzip, Lz4, Snappy, Xz and Zstd, and the
choice of one from a name or an HTTP Accept-Encoding header
(Compression::from_accept_encoding).
Every algorithm writes the bytes PHP's extension writes at the same level, on
the same C library (zlib, C brotli, libzstd, LZ4) or a port of it (snappy),
so data compressed by either runtime is read by the other, and responses
are identical. Each one can also write into a caller's buffer (Sink), so
the output is never copied.
Compressing is CPU work that grows with the input: in async code, run
large inputs on the blocking pool (utopia_async::spawn_blocking) so they
do not hold up a runtime thread.
Cargo features
Each algorithm that needs a codec library is behind a feature, as each
needs an extension in PHP: brotli, lz4, zlib (Deflate and GZIP),
zstd (all on by default) and xz (off). Without its feature an
algorithm reports Algorithm::supported false and fails with
Error::Unsupported, like PHP without the extension. Snappy is pure
Rust and always available.
PHP: ports utopia-php/compression.
| PHP | Rust |
|---|---|
Utopia\Compression\Compression (abstract class) | Algorithm (trait), and Compression for the built-in algorithms |
Compression::NONE, IDENTITY, BROTLI, ... | Compression::NONE, Compression::IDENTITY, Compression::BROTLI, ... |
Compression::fromName() | Compression::from_name |
Compression::fromAcceptEncoding() | Compression::from_accept_encoding, Compression::from_accept_encoding_with (a name => bool map) |
getName(), getContentEncoding() | Algorithm::name, Algorithm::content_encoding |
compress(), decompress() | Algorithm::compress, Algorithm::decompress |
isSupported() (static) | is_supported() on each algorithm, and Algorithm::supported |
getLevel(), setLevel() | level(), set_level() on Brotli, Lz4 and Zstd |
new LZ4($level), new Zstd($level) | Lz4::with_level, Zstd::with_level |
Brotli::useGenericMode(), useTextMode(), useFontMode() | Brotli::use_generic_mode, Brotli::use_text_mode, Brotli::use_font_mode |
Algorithms\Brotli, Deflate, GZIP, LZ4, Snappy, XZ, Zstd | Brotli, Deflate, Gzip, Lz4, Snappy, Xz, Zstd |
\InvalidArgumentException, a warning and "", \Error | Error::InvalidArgument, Error::Codec, Error::Unsupported |
PHP: where an extension emits a warning and returns false (invalid
data, a level the codec refuses), the PHP method returns an empty string;
Rust returns Error::Codec with the warning's text.
use utopia_compression::{Algorithm, Compression};
let algorithm = Compression::from_accept_encoding("gzip;q=0.8, br", &[] as &[&str]).unwrap();
assert_eq!(algorithm.content_encoding(), "br");
let body = algorithm.compress(b"Hello, Hello, Hello")?;
assert_eq!(algorithm.decompress(&body)?, b"Hello, Hello, Hello");use Utopia\Compression\Compression;
$algorithm = Compression::fromAcceptEncoding('gzip;q=0.8, br');
echo $algorithm->getContentEncoding(), "\n"; // br
$body = $algorithm->compress('Hello, Hello, Hello');
echo $algorithm->decompress($body), "\n"; // Hello, Hello, HelloAPI#
What utopia_compression exports at its root.