autozstd 0.2.1

Zstd envelope compression with automatic raw fallback and magicless frames
Documentation
use std::cell::RefCell;
#[cfg(feature = "adaptive")]
use std::time::Instant;

use mzstd::{CompressionParams, Compressor, EncoderConfig, FrameFormat, Level as ZLevel};

use crate::{
  Level, Type,
  probe::{ContentBucket, classify},
};

const CONFIG: EncoderConfig = EncoderConfig::new().with_format(FrameFormat::Magicless);

/// Default `window_log` cap (`21` -> 2 MiB max window), keeping per-thread memory bounded.
pub const DEFAULT_MAX_WINDOW_LOG: u32 = 21;
/// Low-latency `window_log` cap (`15` -> 32 KiB max window) for terminal/RPC frames.
pub const LOW_LATENCY_WINDOW_LOG: u32 = 15;
const MIN_WINDOW_LOG: u32 = 10;
const ABS_MAX_WINDOW_LOG: u32 = 27;

/// Inputs below this size are not timed; clock noise dominates.
pub(crate) const MIN_OBSERVE: usize = 8 * 1024;
/// Extra tail room so frame/block header capacity checks never fail before raw fallback.
const SLACK: usize = 16;

/// Encoding parameters combining [`Level`] with an explicit window memory bound.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EncodeOpt {
  pub level: Level,
  pub max_window_log: u32,
}

impl Default for EncodeOpt {
  #[inline]
  fn default() -> Self {
    Self::new(Level::default())
  }
}

impl EncodeOpt {
  /// Builds options for `level` using [`DEFAULT_MAX_WINDOW_LOG`] (2 MiB window cap).
  #[must_use]
  #[inline]
  pub const fn new(level: Level) -> Self {
    Self {
      level,
      max_window_log: DEFAULT_MAX_WINDOW_LOG,
    }
  }

  /// Clamps Zstd `windowLog` to `10..=27`, capping per-context memory (`2^max_window_log`).
  #[must_use]
  #[inline]
  pub const fn with_max_window_log(mut self, max_window_log: u32) -> Self {
    self.max_window_log = if max_window_log < MIN_WINDOW_LOG {
      MIN_WINDOW_LOG
    } else if max_window_log > ABS_MAX_WINDOW_LOG {
      ABS_MAX_WINDOW_LOG
    } else {
      max_window_log
    };
    self
  }
}

thread_local! {
  static ENC: RefCell<Option<Compressor>> = const { RefCell::new(None) };
}

#[inline]
pub(crate) fn effective_window_log(data_len: usize, max_window_log: u32) -> u32 {
  let cap = max_window_log.clamp(MIN_WINDOW_LOG, ABS_MAX_WINDOW_LOG);
  if data_len <= (1usize << MIN_WINDOW_LOG) {
    return MIN_WINDOW_LOG;
  }
  let log = usize::BITS - (data_len - 1).leading_zeros();
  log.clamp(MIN_WINDOW_LOG, cap)
}

#[inline]
fn build_config(opt: EncodeOpt, data_len: usize) -> EncoderConfig {
  let zlevel = ZLevel::try_from(opt.level.get()).expect("preset zstd level is valid");
  let wlog = effective_window_log(data_len, opt.max_window_log);
  CONFIG
    .with_level(zlevel)
    .with_params(CompressionParams::default().with_window_log(wlog))
}

#[inline]
fn compressor_for(slot: &mut Option<Compressor>, cfg: EncoderConfig) -> &mut Compressor {
  let compressor = slot.get_or_insert_with(|| Compressor::new(cfg).expect("valid compressor cfg"));
  if *compressor.config() != cfg {
    compressor.reconfigure(cfg).expect("valid reconfigure cfg");
  }
  compressor
}

/// Attempts to write a compressed frame into `out`, reusing its capacity.
fn compress_at(
  slot: &mut Option<Compressor>,
  data: &[u8],
  opt: EncodeOpt,
  out: &mut Vec<u8>,
  with_tag: bool,
) -> bool {
  out.clear();
  if data.len() > isize::MAX as usize - SLACK - 1 {
    return false;
  }
  let cfg = build_config(opt, data.len());
  let compressor = compressor_for(slot, cfg);
  let limit = data.len() + SLACK;
  let offset = usize::from(with_tag);

  if out.capacity() < limit + offset {
    out.reserve_exact(limit + offset);
  }
  if with_tag {
    out.push(Type::Zstd.into());
  }
  let Ok(written) = compressor.compress_to_uninit(data, &mut out.spare_capacity_mut()[..limit])
  else {
    out.clear();
    return false;
  };
  if written >= data.len() || written > limit {
    out.clear();
    return false;
  }
  // SAFETY: `compress_to_uninit` initialized `out[len..len + written]` on `Ok(written)`.
  unsafe { out.set_len(offset + written) };
  true
}

#[inline]
pub(crate) fn raw(data: &[u8]) -> Vec<u8> {
  let mut out = Vec::with_capacity(data.len() + 1);
  out.push(Type::Raw.into());
  out.extend_from_slice(data);
  out
}

/// Writes `[Raw tag][data]` into `out`, reusing its capacity.
#[inline]
pub(crate) fn raw_into(out: &mut Vec<u8>, data: &[u8]) {
  out.clear();
  out.reserve(data.len() + 1);
  out.push(Type::Raw.into());
  out.extend_from_slice(data);
}

/// Releases excess capacity after a fresh output buffer has been filled.
#[inline]
pub(crate) fn shrink(out: &mut Vec<u8>) {
  if out.len() * 2 < out.capacity() {
    out.shrink_to_fit();
  }
}

/// Compresses `data` into `out`, optionally timing calls at or above `MIN_OBSERVE`.
fn compress_run(
  data: &[u8],
  opt: EncodeOpt,
  out: &mut Vec<u8>,
  with_tag: bool,
  timed: bool,
) -> (bool, Option<u64>) {
  #[cfg(feature = "adaptive")]
  let start = (timed && data.len() >= MIN_OBSERVE).then(Instant::now);
  #[cfg(not(feature = "adaptive"))]
  let _ = (timed, MIN_OBSERVE);
  let compressed = ENC.with_borrow_mut(|slot| compress_at(slot, data, opt, out, with_tag));
  #[cfg(feature = "adaptive")]
  let ns = start.map(|t| {
    u64::try_from(t.elapsed().as_nanos())
      .unwrap_or(u64::MAX)
      .max(1)
  });
  #[cfg(not(feature = "adaptive"))]
  let ns = None;
  (compressed, ns)
}

#[inline]
fn noop_observe(_: &mut (), _: EncodeOpt, _: ContentBucket, _: usize, _: u64) {}

fn prepare_bucket<Ctx>(
  data: &[u8],
  ctx: &mut Ctx,
  decide: impl FnOnce(&mut Ctx, ContentBucket, bool) -> Option<EncodeOpt>,
) -> Option<(EncodeOpt, ContentBucket)> {
  let bucket = classify(data);
  if bucket == ContentBucket::Incompressible {
    return None;
  }
  let opt = decide(ctx, bucket, data.len() >= MIN_OBSERVE)?;
  Some((opt, bucket))
}

pub(crate) fn encode_owned_with<Ctx>(
  data: Vec<u8>,
  ctx: &mut Ctx,
  decide: impl FnOnce(&mut Ctx, ContentBucket, bool) -> Option<EncodeOpt>,
  timed: bool,
  on_observe: impl FnOnce(&mut Ctx, EncodeOpt, ContentBucket, usize, u64),
) -> Encoded {
  let Some((opt, bucket)) = prepare_bucket(&data, ctx, decide) else {
    return Encoded::raw(data);
  };
  let mut out = Vec::new();
  let (compressed, ns_opt) = compress_run(&data, opt, &mut out, false, timed);
  if compressed {
    if let Some(ns) = ns_opt {
      on_observe(ctx, opt, bucket, out.len() + 1, ns);
    }
    shrink(&mut out);
    Encoded::zstd(out)
  } else {
    Encoded::raw(data)
  }
}

pub(crate) fn encode_into_with<Ctx>(
  data: &[u8],
  ctx: &mut Ctx,
  decide: impl FnOnce(&mut Ctx, ContentBucket, bool) -> Option<EncodeOpt>,
  out: &mut Vec<u8>,
  timed: bool,
  on_observe: impl FnOnce(&mut Ctx, EncodeOpt, ContentBucket, usize, u64),
) -> Type {
  let Some((opt, bucket)) = prepare_bucket(data, ctx, decide) else {
    raw_into(out, data);
    return Type::Raw;
  };
  let (compressed, ns_opt) = compress_run(data, opt, out, true, timed);
  if compressed {
    if let Some(ns) = ns_opt {
      on_observe(ctx, opt, bucket, out.len(), ns);
    }
    Type::Zstd
  } else {
    raw_into(out, data);
    Type::Raw
  }
}

pub(crate) fn encode_vec_with<Ctx>(
  data: &[u8],
  ctx: &mut Ctx,
  decide: impl FnOnce(&mut Ctx, ContentBucket, bool) -> Option<EncodeOpt>,
  timed: bool,
  on_observe: impl FnOnce(&mut Ctx, EncodeOpt, ContentBucket, usize, u64),
) -> Vec<u8> {
  let Some((opt, bucket)) = prepare_bucket(data, ctx, decide) else {
    return raw(data);
  };
  let mut out = Vec::new();
  let (compressed, ns_opt) = compress_run(data, opt, &mut out, true, timed);
  if compressed {
    if let Some(ns) = ns_opt {
      on_observe(ctx, opt, bucket, out.len(), ns);
    }
  } else {
    raw_into(&mut out, data);
  }
  shrink(&mut out);
  out
}

/// Encoded payload with the type tag kept separate from the payload buffer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Encoded {
  kind: Type,
  payload: Vec<u8>,
}

impl Encoded {
  #[inline]
  pub(crate) fn raw(payload: Vec<u8>) -> Self {
    Self {
      kind: Type::Raw,
      payload,
    }
  }

  #[inline]
  pub(crate) fn zstd(payload: Vec<u8>) -> Self {
    Self {
      kind: Type::Zstd,
      payload,
    }
  }

  /// Returns the payload kind.
  #[must_use]
  #[inline]
  pub fn kind(&self) -> Type {
    self.kind
  }

  /// Returns the payload bytes without the tag.
  #[must_use]
  #[inline]
  pub fn payload(&self) -> &[u8] {
    &self.payload
  }

  /// Consumes the value into its kind and payload buffer.
  #[must_use]
  #[inline]
  pub fn into_parts(self) -> (Type, Vec<u8>) {
    (self.kind, self.payload)
  }
}

/// Encodes an owned buffer with explicit [`EncodeOpt`], keeping it untouched on raw fallback.
#[must_use]
pub fn encode_owned_opt(data: Vec<u8>, opt: EncodeOpt) -> Encoded {
  encode_owned_with(data, &mut (), |_, _, _| Some(opt), false, noop_observe)
}

/// Encodes into `out` with explicit [`EncodeOpt`], reusing its capacity.
pub fn encode_into_opt(data: &[u8], opt: EncodeOpt, out: &mut Vec<u8>) -> Type {
  encode_into_with(data, &mut (), |_, _, _| Some(opt), out, false, noop_observe)
}

/// Compresses `data` into an envelope with explicit [`EncodeOpt`].
#[must_use]
pub fn encode_opt(data: &[u8], opt: EncodeOpt) -> Vec<u8> {
  encode_vec_with(data, &mut (), |_, _, _| Some(opt), false, noop_observe)
}

/// Encodes an owned buffer with default [`DEFAULT_MAX_WINDOW_LOG`].
#[must_use]
pub fn encode_owned(data: Vec<u8>, level: Level) -> Encoded {
  encode_owned_opt(data, EncodeOpt::new(level))
}

/// Encodes into `out` reusing capacity with default [`DEFAULT_MAX_WINDOW_LOG`].
pub fn encode_into(data: &[u8], level: Level, out: &mut Vec<u8>) -> Type {
  encode_into_opt(data, EncodeOpt::new(level), out)
}

/// Compresses `data` into an envelope with default [`DEFAULT_MAX_WINDOW_LOG`].
#[must_use]
pub fn encode(data: &[u8], level: Level) -> Vec<u8> {
  encode_opt(data, EncodeOpt::new(level))
}