autozstd 0.2.0

Zstd envelope compression with automatic raw fallback and magicless frames
Documentation

crates.io docs.rs license

English 简体中文 Français Deutsch Español 日本語 العربية Português Русский Italiano Nederlands 한국어 Türkçe Indonesia 正體中文 हिन्दी Polski தமிழ் Gaeilge Svenska বাংলা עברית ไทย Norsk Tiếng Việt मराठी Bahasa Melayu Dansk Română اردو Čeština فارسی తెలుగు ਪੰਜਾਬੀ ಕನ್ನಡ ગુજરાતી Ελληνικά Suomi Català Gàidhlig Қазақша Filipino Kiswahili ئۇيغۇرچە Magyar Українська Oʻzbekcha മലയാളം Slovenčina Afrikaans Hrvatski Српски Български Brezhoneg አማርኛ Cymraeg ଓଡ଼ିଆ සිංහල Hausa Euskara Ślōnskŏ Lietuvių Беларуская IsiZulu Galego မြန်မာ Slovenščina Azərbaycanca অসমীয়া ខ្មែរ नेपाली Kurdî IsiXhosa Latviešu Eesti Татарча Íslenska ქართული Bosanski Shqip Հայերեն Монгол Кыргызча Македонски ລາວ Тоҷикӣ Ikinyarwanda Esperanto Filipino Nynorsk سۆرانی Wolof Frysk

autozstd

A magicless Zstd envelope compression library with automatic raw-data fallback; compression level can optionally be chosen adaptively based on network speed.

For short text, protocol headers, and small JSON payloads, Zstd frame and block header overhead often makes the output larger than the input.

Already-compressed files and high-entropy data cannot be shrunk even with a full compression pass, yet still consume CPU time.

When the adaptive feature is enabled, Adaptive is available: pass in the current network speed, and it selects a level based on total compression and transfer time; if compression yields insufficient benefit, the raw data is sent as-is. The model learns from measured compression speed and ratio, so the same code adapts to LAN, broadband, and mobile networks.

autozstd uses a 1-byte marker to uniformly wrap raw data and magicless Zstd frames: if compression does not reduce size, the raw bytes are stored as-is; known compressed formats and incompressible large blocks skip full compression entirely.

Usage

use autozstd::{Level, decode, decode_limit, encode};

fn main() {
  let data = b"hello world ".repeat(100);
  let packed = encode(&data, Level::Balanced);
  assert_eq!(decode(&packed).unwrap(), data);
  assert_eq!(decode_limit(&packed, data.len()).unwrap(), data);
  println!("{} -> {}", data.len(), packed.len());
}

The example source is at examples/basic.rs; run command:

cargo run -p autozstd --example basic

API

Encoders, decoders, and sampling contexts are reused per thread; consecutive calls do not re-allocate working memory.

Encoding & Decoding

  • encode(data: &[u8], level: Level) -> Vec<u8>: compresses and returns the envelope; writes raw bytes if the result is not shorter than the input.
  • encode_owned(data: Vec<u8>, level: Level) -> Encoded: encodes an owned buffer; when the decision is to send raw data, the input allocation is returned directly without copying the payload. Encoded provides kind(), payload(), and into_parts(), allowing the tag and payload to be written out as two owned buffers.
  • encode_into(data: &[u8], level: Level, out: &mut Vec<u8>) -> Type: writes the full envelope into a reusable buffer, eliminating the per-call allocation of encode and allowing the compressed frame to be written directly into the target buffer.
  • decode(data: &[u8]) -> Result<Vec<u8>>: decodes the envelope as a single frame; returns an error if trailing data is present; intended for trusted input.
  • decode_limit(data: &[u8], max_len: usize) -> Result<Vec<u8>>: decoding entry point with a maximum decoded-output byte limit; intended for untrusted input.
  • decode_owned(data: Vec<u8>) -> Result<Vec<u8>>: decodes an owned envelope; for raw-data payloads, the input allocation is reused after stripping the tag.
  • decode_owned_limit(data: Vec<u8>, max_len: usize) -> Result<Vec<u8>>: owned-buffer decoding with a limit on the maximum decoded output bytes.

Buffer Ownership

Encoded separates the tag from the payload. encode_owned reuses the input allocation for the raw-data decision, and decode_owned avoids a new allocation when stripping the tag, making it suitable for owned-buffer runtimes like compio. encode_into writes into the caller's buffer and preserves capacity.

use autozstd::{Level, Type, decode_owned, encode_into, encode_owned};

fn main() {
  let data = b"hello world ".repeat(10_000);
  let mut packed = Vec::new();
  assert_eq!(encode_into(&data, Level::Balanced, &mut packed), Type::Zstd);
  assert_eq!(decode_owned(packed).unwrap(), data);

  let mut raw = b"\x89PNG\r\n\x1a\n".to_vec();
  raw.resize(64 * 1024, 0);
  let ptr = raw.as_ptr();
  let encoded = encode_owned(raw, Level::Balanced);
  assert_eq!(encoded.kind(), Type::Raw);
  assert_eq!(encoded.payload().as_ptr(), ptr);

  let (kind, payload) = encoded.into_parts();
  println!("{kind:?}: {} payload bytes, tag {}", payload.len(), kind as u8);
}

A complete example is in examples/buffer.rs; run command:

cargo run -p autozstd --example buffer

Compressed output is always new bytes; zero-copy applies only to raw-data payloads. In async runtimes, offload encoding and decoding to a blocking thread pool and write the tag and payload as two owned buffers.

Levels & Markers

  • Level: compression-level presets; supports Fastest = 1, Fast = 3, Balanced = 6 (default), Strong = 9, Best = 19; Level::ALL lists all presets ordered from fastest to strongest, and get() returns the corresponding numeric level.
  • Type: the envelope's first-byte marker, with values Raw = 0 and Zstd = 1.

Errors

  • Error / Result<T>: Empty (empty input), InvalidType(u8) (unknown first-byte marker), OutputLimit(usize) (decoded output exceeds the limit), and Decode(mzstd::DecodeError) (transparently forwards the underlying decode error).

Auto-Detection

Inputs smaller than 7 bytes and known compressed formats are stored as raw data directly, bypassing the compression pipeline.

When the input reaches 128 KiB in length, a level-1 trial compression is first run on 16 KiB samples from the head, middle, and tail; if all three segments compress to at least 97% of the original size, the raw data is stored directly; otherwise, full compression at the target level is performed.

Recognized header formats include PNG, JPEG, ZIP, Gzip, Zstd, XZ, 7z, RAR, Bzip2, Ogg, FLAC, GIF, WebP (RIFF), Matroska, LZ4, JPEG XL, JPEG 2000, WOFF, WOFF2, and ftyp containers (MP4 / HEIC).

Envelope Format

+--------+------------------------+
| type   | payload                |
| 1 byte | raw bytes / zstd frame |
+--------+------------------------+

When type = 0, the payload is raw bytes; when type = 1, it is single-frame Zstd data with the 4-byte magic number 28 B5 2F FD omitted.

The decompression side does not need to record or supply the compression level.

Adaptive Compression

Enabling the adaptive feature provides Adaptive, which picks a compression level or sends raw data based on the current network speed.

Treating compression and transfer as a serial process, where s is the compression speed, q is the on-the-wire compression ratio including the first-byte marker, and W is the network speed, the normalized total time for each level is W / s + q.

choice selects the level with the lowest total time; returns Choice::Off when the speedup relative to raw-transmission time (1 / 1.05) is less than 5%.

Each time a compressed frame is retained and the input is at least 8 KiB, the speed and compression ratio for that level are updated; unobserved neighboring levels are calibrated in log-odds space according to prior ratios, preserving the global monotonic invariant that stronger levels are slower and yield lower compression ratios.

Every 64 observable encodings trigger a probe of a feasible neighboring level or Fastest, preventing occasional slowdowns or mixed content from locking the system into a no-compression state for extended periods.

use autozstd::Adaptive;

fn main() {
  let mut codec = Adaptive::new();
  let data = b"hello world ".repeat(10_000);
  for speed in [100_000, 1_000_000, 10_000_000, 1_000_000_000] {
    let packed = codec.encode(&data, speed);
    println!("{speed} B/s -> {} bytes", packed.len());
  }
}

The example source is at examples/adaptive.rs; run command:

cargo run -p autozstd --features adaptive --example adaptive
  • Adaptive::new(): creates an instance with built-in priors.
  • encode(data, net_speed): decides and encodes based on network speed (bytes/sec); 0 indicates unknown speed, in which case Level::Balanced is used and the model is updated as usual.
  • encode_owned(data: Vec<u8>, net_speed): owned-buffer version; the raw-data decision reuses the input allocation directly.
  • encode_into(data, net_speed, out): reusable-buffer version; writes the full envelope into out.
  • choice(net_speed): returns only Choice::Off or Choice::Level(Level) without performing encoding.
  • observe(level, speed, ratio): injects externally measured speed and compression ratio to update the table entry.
  • stats(): returns a [Stat; 5] ordered by Level::ALL, containing speed, compression ratio, and sample count for each level.

Dependencies

  • mzstd: a pure-Rust Zstandard codec; single-threaded compression output is bit-identical to zstd 1.5.7.
  • thiserror: derive macros for error-enum definitions.