autozstd 0.2.0

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

//! Zstd envelope compression with automatic raw fallback.
//!
//! An envelope is `[type][payload]`: the first byte is a [`Type`], and the
//! payload is either the input unchanged or a magicless Zstandard frame.
//!
//! [`encode`] skips inputs shorter than 7 bytes and known compressed formats
//! directly, and probes inputs of 128 KiB and up before a full compression
//! pass. Whenever the compressed frame is not smaller than the input, raw bytes
//! are stored instead.
//!
//! Encoder and decoder contexts are reused per thread across calls. Use
//! [`decode_limit`] when decoding untrusted inputs to bound the decompressed
//! size.
//!
//! [`encode_owned`] keeps the input allocation for raw payloads and returns the
//! tag separately as [`Encoded`], while [`encode_into`] writes into a
//! caller-provided buffer. [`decode_owned`] shifts a raw payload over its tag
//! without allocating.
//!
//! The optional `adaptive` feature adds [`Adaptive`], which folds measured
//! compression speed and ratio into a network-aware level choice.
//!
//! ```
//! use autozstd::{Level, decode, encode};
//!
//! let data = b"hello world ".repeat(100);
//! let packed = encode(&data, Level::Balanced);
//! assert_eq!(decode(&packed)?, data);
//! # Ok::<(), autozstd::Error>(())
//! ```

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

#[cfg(feature = "adaptive")]
#[cfg_attr(docsrs, doc(cfg(feature = "adaptive")))]
pub use adaptive::{Adaptive, Choice, Stat};
pub use decode::{decode, decode_limit, decode_owned, decode_owned_limit};
pub use encode::{Encoded, encode, encode_into, encode_owned};
pub use error::{Error, Result};

/// 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.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(i32)]
pub enum Level {
  /// Level 1, fastest.
  Fastest = 1,
  /// Level 3, Zstandard default.
  Fast = 3,
  /// Level 6, balanced speed and ratio.
  #[default]
  Balanced = 6,
  /// Level 9, stronger compression.
  Strong = 9,
  /// Level 19, strongest normal level.
  Best = 19,
}

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

  /// 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::Fastest => 0,
      Self::Fast => 1,
      Self::Balanced => 2,
      Self::Strong => 3,
      Self::Best => 4,
    }
  }
}

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

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