autozstd 0.2.1

Zstd envelope compression with automatic raw fallback and magicless frames
Documentation
#![cfg_attr(docsrs, feature(doc_cfg))]

//! Zstd envelope compression with automatic raw fallback and window-bounded memory.
//!
//! An envelope is `[type][payload]`: the first byte is a [`Type`], and the
//! payload is either the input unchanged or a magicless Zstandard frame.
//!
//! Inputs shorter than 7 bytes, known compressed formats, and O(1)-sampled
//! high-entropy payloads fall back directly to raw bytes without running Zstd.
//! Encoder window size is clamped by both input length and [`EncodeOpt::max_window_log`]
//! to bound per-thread memory (`O(min(len, 2^max_window_log))`).
//!
//! The optional `adaptive` feature adds `Adaptive` and `NetSignal`, modeling
//! hybrid serial/pipeline overlap cost across content buckets (`Low`, `Medium`, `High`)
//! and calibrating hardware speed across architectures.

#[cfg(feature = "adaptive")]
mod adaptive;
mod decode;
mod encode;
mod error;
mod probe;

#[cfg(feature = "adaptive")]
#[cfg_attr(docsrs, doc(cfg(feature = "adaptive")))]
pub use adaptive::{Adaptive, Choice, NetSignal, Stat};
pub use decode::{decode, decode_limit, decode_owned, decode_owned_limit, decode_payload_limit};
pub use encode::{
  DEFAULT_MAX_WINDOW_LOG, EncodeOpt, Encoded, LOW_LATENCY_WINDOW_LOG, encode, encode_into,
  encode_into_opt, encode_opt, encode_owned, encode_owned_opt,
};
pub use error::{Error, Result};
pub use probe::{ContentBucket, classify};

/// Payload kind, stored in the first byte of an envelope.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Type {
  /// Uncompressed bytes.
  Raw = 0,
  /// Magicless Zstandard frame.
  Zstd = 1,
}

impl TryFrom<u8> for Type {
  type Error = Error;

  #[inline]
  fn try_from(tag: u8) -> Result<Self> {
    match tag {
      0 => Ok(Self::Raw),
      1 => Ok(Self::Zstd),
      other => Err(Error::InvalidType(other)),
    }
  }
}

impl From<Type> for u8 {
  #[inline]
  fn from(value: Type) -> Self {
    value as Self
  }
}

/// Compression level presets spanning ultra-fast negative levels to level 19.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(i32)]
pub enum Level {
  /// Level -4, Zstandard `--fast=4` skipping Huffman literals for maximum throughput.
  UltraFast = -4,
  /// Level -1, Zstandard `--fast=1`.
  SuperFast = -1,
  /// Level 1, fastest standard level.
  Fastest = 1,
  /// Level 3, Zstandard default.
  Fast = 3,
  /// Level 6, balanced speed and ratio.
  #[default]
  Balanced = 6,
  /// Level 9, stronger compression.
  Strong = 9,
  /// Level 12, high compression for slow WAN links.
  High = 12,
  /// Level 19, strongest normal level (explicit use; excluded from online adaptive selection).
  Best = 19,
}

impl Level {
  /// All presets, ordered from fastest to strongest.
  pub const ALL: [Self; 8] = [
    Self::UltraFast,
    Self::SuperFast,
    Self::Fastest,
    Self::Fast,
    Self::Balanced,
    Self::Strong,
    Self::High,
    Self::Best,
  ];

  /// Online transport presets (`UltraFast..=High`), excluding `Best` (19) to avoid
  /// high memory footprint and tail-latency stalls.
  #[cfg(feature = "adaptive")]
  pub(crate) const ONLINE_CNT: usize = 7;

  /// The preset as a Zstandard numeric level.
  #[must_use]
  #[inline]
  pub const fn get(self) -> i32 {
    self as i32
  }

  /// Zero-based index matching [`Self::ALL`].
  #[cfg(feature = "adaptive")]
  #[inline]
  pub(crate) const fn index(self) -> usize {
    match self {
      Self::UltraFast => 0,
      Self::SuperFast => 1,
      Self::Fastest => 2,
      Self::Fast => 3,
      Self::Balanced => 4,
      Self::Strong => 5,
      Self::High => 6,
      Self::Best => 7,
    }
  }
}

#[cfg(feature = "adaptive")]
const _: () = {
  let mut i = 0;
  while i < Level::ALL.len() {
    assert!(Level::ALL[i].index() == i);
    i += 1;
  }
  assert!(Level::ALL[Level::ONLINE_CNT - 1].get() == Level::High.get());
};

impl From<Level> for i32 {
  #[inline]
  fn from(value: Level) -> Self {
    value.get()
  }
}