Contents
use utopia_compression::Allocator;pub struct Allocator {
pub alloc: fn(*mut c_void, usize) -> *mut c_void,
pub free: fn(*mut c_void, *mut c_void),
pub opaque: *mut c_void,
}The allocator a codec's working state (zstd's contexts, brotli's encoder and decoder) comes
from during one call, in the C libraries' own shape: alloc(opaque, size) and
free(opaque, address). A block must be aligned as malloc() aligns one.
The state is created and freed within the call, as PHP's extensions create and free theirs, so no state outlives it: a codec behaves as on its first call, even on corrupt input.
use utopia_compression::Brotli;pub struct Brotli {
// private fields
}Brotli (RFC 7932): Content-Encoding: br.
Compresses at quality Brotli::DEFAULT_LEVEL (11) unless
Brotli::set_level says otherwise, with a 4 MiB window (lgwin 22).
Decompressing accepts what brotli_uncompress() accepts, including
trailing bytes after the stream.
The codec is C brotli 1.2.1, the library PHP's ext-brotli links, called the way
brotli_compress() calls it: the output is PHP's, byte for byte, at every quality.
Requires the brotli feature. PHP: Utopia\Compression\Algorithms\Brotli.
use utopia_compression::{Algorithm, Brotli};
let mut brotli = Brotli::new();
brotli.set_level(4)?;
let body = brotli.compress(b"This is a demo string")?;
assert_eq!(brotli.decompress(&body)?, b"This is a demo string");
assert_eq!(brotli.content_encoding(), "br");use Utopia\Compression\Algorithms\Brotli;
$brotli = new Brotli();
$brotli->setLevel(4);
$body = $brotli->compress('This is a demo string');
echo $brotli->decompress($body), "\n"; // This is a demo string
echo $brotli->getContentEncoding(), "\n"; // brDefault.use utopia_compression::Deflate;pub struct Deflate;Raw deflate (RFC 1951) at level 6: Content-Encoding: deflate.
Output is byte for byte PHP's gzdeflate($data, 6): the system's zlib (the one PHP links)
at memory level 9. Decompressing accepts what gzinflate() accepts, including trailing
bytes after the stream, which are ignored.
Requires the zlib feature. PHP: Utopia\Compression\Algorithms\Deflate.
use utopia_compression::{Algorithm, Deflate};
let deflate = Deflate::new();
assert_eq!(deflate.compress(b"a")?, b"\x4b\x04\x00");
assert_eq!(deflate.decompress(b"\x4b\x04\x00")?, b"a");use Utopia\Compression\Algorithms\Deflate;
$deflate = new Deflate();
echo bin2hex($deflate->compress('a')), "\n"; // 4b0400
echo $deflate->decompress("\x4b\x04\x00"), "\n"; // ause utopia_compression::Gzip;pub struct Gzip;Gzip (RFC 1952) at zlib's default level: Content-Encoding: gzip.
Output is byte for byte PHP's gzencode($data): a header with no name, a modification
time of 0 and the Unix OS byte (3), then the system zlib's deflate at level 6 and memory
level 9. Decompressing reads the first member, like gzdecode().
Requires the zlib feature. PHP: Utopia\Compression\Algorithms\GZIP.
use utopia_compression::{Algorithm, Gzip};
let gzip = Gzip::new();
let body = gzip.compress(b"a")?;
assert_eq!(&body[..10], b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03");
assert_eq!(gzip.decompress(&body)?, b"a");use Utopia\Compression\Algorithms\GZIP;
$gzip = new GZIP();
$body = $gzip->compress('a');
echo bin2hex(substr($body, 0, 10)), "\n"; // 1f8b0800000000000003
echo $gzip->decompress($body), "\n"; // ause utopia_compression::Lz4;pub struct Lz4 {
// private fields
}LZ4 blocks with ext-lz4's framing: the uncompressed size as a 4-byte little-endian prefix, then one LZ4 block.
Level 0 (the default) is LZ4's fast mode; levels 1 to 12 are its high
compression (HC) mode. Output is byte for byte PHP's lz4_compress()
(LZ4 1.10.0).
Requires the lz4 feature. PHP: Utopia\Compression\Algorithms\LZ4.
use utopia_compression::{Algorithm, Lz4};
let lz4 = Lz4::new();
let body = lz4.compress(b"This is a demo string")?;
assert_eq!(body.len(), 27);
assert_eq!(lz4.decompress(&body)?, b"This is a demo string");use Utopia\Compression\Algorithms\LZ4;
$lz4 = new LZ4();
$body = $lz4->compress('This is a demo string');
echo strlen($body), "\n"; // 27
echo $lz4->decompress($body), "\n"; // This is a demo stringuse utopia_compression::Snappy;pub struct Snappy;Snappy raw format: the uncompressed length as a varint, then literals and copies.
The compressor is a port of C++ snappy 1.2.1's level 1 (the library
PHP's ext-snappy links), with its portable hash: output is byte for byte
snappy_compress(). The decompressor is as strict as snappy's: any
malformed tag, out-of-range copy or length mismatch fails.
Pure Rust, always available. PHP: Utopia\Compression\Algorithms\Snappy.
use utopia_compression::{Algorithm, Snappy};
let snappy = Snappy::new();
let body = snappy.compress(b"This is a demo string")?;
assert_eq!(body.len(), 23);
assert_eq!(snappy.decompress(&body)?, b"This is a demo string");use Utopia\Compression\Algorithms\Snappy;
$snappy = new Snappy();
$body = $snappy->compress('This is a demo string');
echo strlen($body), "\n"; // 23
echo $snappy->decompress($body), "\n"; // This is a demo stringuse utopia_compression::Xz;pub struct Xz;XZ: LZMA2 at preset 5 in an .xz container with a CRC64 check.
The settings are those of PHP's ext-xz xzencode() (its default
xz.compression_level of 5); decompressing reads concatenated .xz
streams.
Requires the xz feature, which is off by default: without it, as in
PHP without ext-xz, compress() and decompress() fail with
Error::Unsupported. Output is not compared with PHP's: the PHP image
the conversion is checked against has no ext-xz.
PHP: Utopia\Compression\Algorithms\XZ.
use utopia_compression::{Algorithm, Xz};
let xz = Xz::new();
match xz.compress(b"This is a demo string") {
Ok(body) => assert_eq!(xz.decompress(&body)?, b"This is a demo string"),
// Built without the `xz` feature.
Err(e) => assert_eq!(e.php_class(), "Error"),
}use Utopia\Compression\Algorithms\XZ;
$xz = new XZ();
if (XZ::isSupported()) {
echo $xz->decompress($xz->compress('This is a demo string')), "\n"; // This is a demo string
}use utopia_compression::Zstd;pub struct Zstd {
// private fields
}Zstandard (RFC 8878): Content-Encoding: zstd.
Compresses at level 3 unless told otherwise, one frame with the content size in its
header. Output is byte for byte PHP's zstd_compress() (libzstd 1.5.7). Decompressing
reads the first frame, like zstd_uncompress().
Requires the zstd feature. PHP: Utopia\Compression\Algorithms\Zstd.
use utopia_compression::{Algorithm, Zstd};
let zstd = Zstd::new();
let body = zstd.compress(b"This is a demo string")?;
assert_eq!(body.len(), 30);
assert_eq!(zstd.decompress(&body)?, b"This is a demo string");use Utopia\Compression\Algorithms\Zstd;
$zstd = new Zstd();
$body = $zstd->compress('This is a demo string');
echo strlen($body), "\n"; // 30
echo $zstd->decompress($body), "\n"; // This is a demo stringDefault.use utopia_compression::Compression;pub enum Compression {
Brotli(Brotli),
Deflate(Deflate),
Gzip(Gzip),
Lz4(Lz4),
Snappy(Snappy),
Xz(Xz),
Zstd(Zstd),
}A built-in algorithm, as chosen by name or from an Accept-Encoding
header.
use utopia_compression::{Algorithm, Compression, Zstd};
assert_eq!(Compression::from_name("ZSTD"), Some(Compression::Zstd(Zstd::new())));
assert_eq!(Compression::from_name("br").unwrap().name(), "brotli");
assert_eq!(Compression::from_name("identity"), None);use Utopia\Compression\Compression;
var_dump(Compression::fromName('ZSTD') instanceof Utopia\Compression\Algorithms\Zstd); // bool(true)
echo Compression::fromName('br')->getName(), "\n"; // brotli
var_dump(Compression::fromName('identity')); // NULLuse utopia_compression::Error;pub enum Error {
InvalidArgument(String),
Codec(String),
Unsupported(String),
}Why compressing, decompressing or configuring an algorithm failed.
PHP: one variant per way utopia-php/compression fails (see
Error::php_class).
use utopia_compression::Mode;pub enum Mode {
Generic,
Text,
Font,
}The kind of data Brotli tunes its encoding for.
PHP: BROTLI_GENERIC, BROTLI_TEXT, BROTLI_FONT.
use utopia_compression::Algorithm;pub trait AlgorithmA compression algorithm: a name, a Content-Encoding token, and a pair
of inverse transformations.
Implement it to add an algorithm; Compression holds the built-in ones.
use utopia_compression::{Algorithm, Error};
/// Stores data as is.
struct Store;
impl Algorithm for Store {
fn name(&self) -> &str {
"Store"
}
fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
Ok(data.to_vec())
}
fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
Ok(data.to_vec())
}
fn supported(&self) -> bool {
true
}
}
assert_eq!(Store.content_encoding(), "store");use Utopia\Compression\Compression;
class Store extends Compression
{
public function getName(): string { return 'Store'; }
public function compress(string $data): string { return $data; }
public function decompress(string $data): string { return $data; }
public static function isSupported(): bool { return true; }
}
echo (new Store())->getContentEncoding(), "\n"; // storeuse utopia_compression::Sink;pub unsafe trait SinkA growable byte buffer an algorithm writes its output into, in place.
Vec<u8> is one. A caller with its own string type implements it so the output is written
once, where it ends up: the PHP extension writes straight into a PHP string, which a Vec
would cost a second copy of (and twice the memory, for a moment).
The *_into methods of each algorithm (Gzip::compress_into,
...) append to the sink; Algorithm::compress is
compress_into a new Vec. On an error, what the sink holds is unspecified.
Safety
Sink::as_mut_ptr points to Sink::capacity writable bytes, the first Sink::len of
them the output so far; Sink::grow and Sink::reserve keep those bytes (the pointer
may change).