Skip to main content

autozstd/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3//! Zstd envelope compression with automatic raw fallback and window-bounded memory.
4//!
5//! An envelope is `[type][payload]`: the first byte is a [`Type`], and the
6//! payload is either the input unchanged or a magicless Zstandard frame.
7//!
8//! Inputs shorter than 7 bytes, known compressed formats, and O(1)-sampled
9//! high-entropy payloads fall back directly to raw bytes without running Zstd.
10//! Encoder window size is clamped by both input length and [`EncodeOpt::max_window_log`]
11//! to bound per-thread memory (`O(min(len, 2^max_window_log))`).
12//!
13//! The optional `adaptive` feature adds `Adaptive` and `NetSignal`, modeling
14//! hybrid serial/pipeline overlap cost across content buckets (`Low`, `Medium`, `High`)
15//! and calibrating hardware speed across architectures.
16
17#[cfg(feature = "adaptive")]
18mod adaptive;
19mod decode;
20mod encode;
21mod error;
22mod probe;
23
24#[cfg(feature = "adaptive")]
25#[cfg_attr(docsrs, doc(cfg(feature = "adaptive")))]
26pub use adaptive::{Adaptive, Choice, NetSignal, Stat};
27pub use decode::{decode, decode_limit, decode_owned, decode_owned_limit, decode_payload_limit};
28pub use encode::{
29  DEFAULT_MAX_WINDOW_LOG, EncodeOpt, Encoded, LOW_LATENCY_WINDOW_LOG, encode, encode_into,
30  encode_into_opt, encode_opt, encode_owned, encode_owned_opt,
31};
32pub use error::{Error, Result};
33pub use probe::{ContentBucket, classify};
34
35/// Payload kind, stored in the first byte of an envelope.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37#[repr(u8)]
38pub enum Type {
39  /// Uncompressed bytes.
40  Raw = 0,
41  /// Magicless Zstandard frame.
42  Zstd = 1,
43}
44
45impl TryFrom<u8> for Type {
46  type Error = Error;
47
48  #[inline]
49  fn try_from(tag: u8) -> Result<Self> {
50    match tag {
51      0 => Ok(Self::Raw),
52      1 => Ok(Self::Zstd),
53      other => Err(Error::InvalidType(other)),
54    }
55  }
56}
57
58impl From<Type> for u8 {
59  #[inline]
60  fn from(value: Type) -> Self {
61    value as Self
62  }
63}
64
65/// Compression level presets spanning ultra-fast negative levels to level 19.
66#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
67#[repr(i32)]
68pub enum Level {
69  /// Level -4, Zstandard `--fast=4` skipping Huffman literals for maximum throughput.
70  UltraFast = -4,
71  /// Level -1, Zstandard `--fast=1`.
72  SuperFast = -1,
73  /// Level 1, fastest standard level.
74  Fastest = 1,
75  /// Level 3, Zstandard default.
76  Fast = 3,
77  /// Level 6, balanced speed and ratio.
78  #[default]
79  Balanced = 6,
80  /// Level 9, stronger compression.
81  Strong = 9,
82  /// Level 12, high compression for slow WAN links.
83  High = 12,
84  /// Level 19, strongest normal level (explicit use; excluded from online adaptive selection).
85  Best = 19,
86}
87
88impl Level {
89  /// All presets, ordered from fastest to strongest.
90  pub const ALL: [Self; 8] = [
91    Self::UltraFast,
92    Self::SuperFast,
93    Self::Fastest,
94    Self::Fast,
95    Self::Balanced,
96    Self::Strong,
97    Self::High,
98    Self::Best,
99  ];
100
101  /// Online transport presets (`UltraFast..=High`), excluding `Best` (19) to avoid
102  /// high memory footprint and tail-latency stalls.
103  #[cfg(feature = "adaptive")]
104  pub(crate) const ONLINE_CNT: usize = 7;
105
106  /// The preset as a Zstandard numeric level.
107  #[must_use]
108  #[inline]
109  pub const fn get(self) -> i32 {
110    self as i32
111  }
112
113  /// Zero-based index matching [`Self::ALL`].
114  #[cfg(feature = "adaptive")]
115  #[inline]
116  pub(crate) const fn index(self) -> usize {
117    match self {
118      Self::UltraFast => 0,
119      Self::SuperFast => 1,
120      Self::Fastest => 2,
121      Self::Fast => 3,
122      Self::Balanced => 4,
123      Self::Strong => 5,
124      Self::High => 6,
125      Self::Best => 7,
126    }
127  }
128}
129
130#[cfg(feature = "adaptive")]
131const _: () = {
132  let mut i = 0;
133  while i < Level::ALL.len() {
134    assert!(Level::ALL[i].index() == i);
135    i += 1;
136  }
137  assert!(Level::ALL[Level::ONLINE_CNT - 1].get() == Level::High.get());
138};
139
140impl From<Level> for i32 {
141  #[inline]
142  fn from(value: Level) -> Self {
143    value.get()
144  }
145}