[](https://crates.io/crates/autozstd) [](https://docs.rs/autozstd) [](https://license.coscl.org.cn/MulanPSL2)
[](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/en/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/zh/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/fr/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/de/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/es/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ja/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ar/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/pt/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ru/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/it/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/nl/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ko/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/tr/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/id/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/zh-TW/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/hi/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/pl/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ta/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ga/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/sv/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/bn/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/he/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/th/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/no/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/vi/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/mr/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ms/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/da/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ro/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ur/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/cs/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/fa/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/te/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/pa/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/kn/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/gu/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/el/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/fi/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ca/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/gd/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/kk/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/tl/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/sw/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ug/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/hu/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/uk/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/uz/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ml/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/sk/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/af/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/hr/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/sr/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/bg/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/am/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/cy/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/or/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/si/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/eu/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/lt/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/be/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/gl/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/my/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/sl/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/az/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/as/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/km/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ne/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ku/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/lv/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/et/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/tt/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/is/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ka/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/sq/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/hy/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/mn/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ky/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/mk/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/lo/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/tg/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/eo/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/nn/README.md) [](https://atomgit.com/i18n-site/rs/blob/main/autozstd/i18n/ckb/README.md)
# 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` and `NetSignal` are provided to adaptively select a level or send the original data directly based on chunk content compressibility and link signals.
`autozstd` uses a 1-byte tag to uniformly wrap raw data and magic-less Zstd frames: short inputs, known compressed formats, and data classified as high-entropy in O(1) are stored verbatim, while the `windowLog` cap bounds per-thread working memory.
- [Usage](#usage)
- [API](#api)
- [Encoding & Decoding](#encoding-decoding)
- [Buffer Ownership](#buffer-ownership)
- [Levels, Windows, and Tags](#levels-windows-and-tags)
- [Errors](#errors)
- [Automatic Detection and O(1) Classification](#automatic-detection-and-o1-classification)
- [Envelope Format](#envelope-format)
- [Adaptive Compression](#adaptive-compression)
- [Dependencies](#dependencies)
## Usage
```rust
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`](https://atomgit.com/i18n-site/rs/blob/main/autozstd/examples/basic.rs); run command:
```bash
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 using the default `DEFAULT_MAX_WINDOW_LOG` and returns an envelope; writes the raw bytes if the compressed result is not smaller than the original.
- `encode_opt(data: &[u8], opt: EncodeOpt) -> Vec<u8>`: Encodes with the specified window cap and level and returns an envelope.
- `encode_owned(data: Vec<u8>, level: Level) -> Encoded` / `encode_owned_opt(data: Vec<u8>, opt: EncodeOpt) -> Encoded`: Encode owned buffers; when the data is determined to be raw, 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` / `encode_into_opt(data: &[u8], opt: EncodeOpt, out: &mut Vec<u8>) -> Type`: Write the complete envelope to a reusable buffer, eliminating per-call allocation.
- `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_payload_limit(kind: Type, payload: &[u8], max_len: usize) -> Result<Vec<u8>>`: A size-limited split-input decoding entry point that does not require a contiguous `[tag | payload]` buffer.
- `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.
```rust
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`](https://atomgit.com/i18n-site/rs/blob/main/autozstd/examples/buffer.rs); run command:
```bash
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, Windows, and Tags
- `Level`: Compression level presets, supporting `UltraFast = -4`, `SuperFast = -1`, `Fastest = 1`, `Fast = 3`, `Balanced = 6` (default), `Strong = 9`, `High = 12`, and `Best = 19`; `Level::ALL` lists all presets ordered from fastest to strongest, and `get()` returns the corresponding numeric level.
- `EncodeOpt`: Encapsulates `level` and `max_window_log`; used with `DEFAULT_MAX_WINDOW_LOG = 21` (2 MiB window cap) or `LOW_LATENCY_WINDOW_LOG = 15` (32 KiB window cap) to bound per-core working memory.
- `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).
## Automatic Detection and O(1) Classification
Inputs shorter than 7 bytes and inputs in known compressed formats are directly marked as `ContentBucket::Incompressible` and stored verbatim, bypassing the compression pipeline.
For inputs at least 4 KiB long, `classify(data)` samples fixed 512 B windows at `[0, tail / 3, tail / 2, tail]` (a constant 2 KiB scan and an approximately 544 B stack table), calculates byte cardinality and the 3-byte match rate, and classifies the input into four compressibility buckets—`Incompressible`, `Low`, `Medium`, and `High`—in strict $O(1)$ time and space.
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
```text
+--------+------------------------+
| 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
When the `adaptive` feature is enabled, `Adaptive` and `NetSignal` are provided to select the best option within `UltraFast..=High` or send the original data directly based on link bandwidth, concurrent core count, queue backlog, per-chunk latency cap, and memory budget.
The model combines total serial elapsed time with the multi-core pipeline overlap factor $\rho \in [0, 1]$, and maintains an EWMA of log time (time per byte) and a log-odds compression ratio for each of the `Low` / `Medium` / `High` compressibility buckets; it falls back to `Choice::Off` when the speedup over direct raw transmission is less than 5%, requires a gain greater than 3% to switch between adjacent compression levels, and rotates exploration through neighboring levels for each bucket every 64 observable encodes, while using the shared hardware multiplier `hw_scale` to transfer measured performance to unsampled levels.
```rust
use autozstd::{Adaptive, NetSignal};
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!("serial {speed} B/s -> {} bytes", packed.len());
}
let pipe_sig = NetSignal::pipeline(100_000_000, 4, 0);
let packed = codec.encode_signal(&data, &pipe_sig);
println!("pipeline 100 MB/s (4w) -> {} bytes", packed.len());
}
```
The example source is at [`examples/adaptive.rs`](https://atomgit.com/i18n-site/rs/blob/main/autozstd/examples/adaptive.rs); run command:
```bash
cargo run -p autozstd --features adaptive --example adaptive
```
- `NetSignal::{serial, pipeline, low_latency}`: Respectively construct signals for single-stream serial operation, a multi-core throughput pipeline ($\rho = 0.85$), and low-latency endpoints/RPC (32 KiB window and RTT budget).
- `Adaptive::new()`: creates an instance with built-in priors.
- `plan(data_len, bucket, sig)` / `plan_buckets(data_len, sig)`: Precompute the optimal choice under current conditions (or a choice matrix for the three buckets) for multithreaded dispatch and scheduling.
- `encode_signal(data, sig)` / `encode_owned_signal(data, sig)` / `encode_into_signal(data, sig, out)`: Make decisions and encode based on the full signal, then feed the results back into the model.
- `encode(data, net_speed)` / `encode_owned(data, net_speed)` / `encode_into(data, net_speed, out)` / `choice(net_speed)`: Convenience entry points based on `NetSignal::serial`; select `Level::Balanced` when `net_speed == 0`.
- `observe_bucket(level, bucket, raw_len, wire_len, elapsed_ns)` / `observe(level, speed, ratio)`: Inject measured elapsed time and the post-compression on-wire byte ratio to update the model and calibrate unobserved levels.
- `stats()` / `bucket_stats(bucket)`: Return a `[Stat; 8]` array ordered by `Level::ALL`, containing the speed, compression ratio, and sample count for each level.
## Dependencies
- [mzstd](https://docs.rs/mzstd): a pure-Rust Zstandard codec; single-threaded compression output is bit-identical to zstd 1.5.7.
- [thiserror](https://docs.rs/thiserror): derive macros for error-enum definitions.