Skip to main content

Algorithm

Trait Algorithm 

Source
pub trait Algorithm {
    // Required methods
    fn name(&self) -> &str;
    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error>;
    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error>;
    fn supported(&self) -> bool;

    // Provided method
    fn content_encoding(&self) -> Cow<'_, str> { ... }
}
Expand description

A 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"; // store

Required Methods§

Source

fn name(&self) -> &str

The algorithm’s name, such as gzip.

PHP: getName().

Source

fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error>

Compresses data.

PHP: compress($data).

Source

fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error>

Decompresses data. Fails with Error::Codec when data is not a valid stream of the algorithm.

PHP: decompress($data).

Source

fn supported(&self) -> bool

Whether this build can run the algorithm.

PHP: static::isSupported(), whether the extension is loaded.

Provided Methods§

Source

fn content_encoding(&self) -> Cow<'_, str>

The token of the algorithm in Content-Encoding and Accept-Encoding headers: by default the name in lower case (ASCII only); br for Brotli.

PHP: getContentEncoding(), strtolower($this->getName()) by default.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§