autozstd 0.2.1

Zstd envelope compression with automatic raw fallback and magicless frames
Documentation
use std::cell::RefCell;

use mzstd::{DecodeError, DecodeLimits, DecoderConfig, Decompressor, FrameFormat, FrameMode};

use crate::{Error, Result, Type};

const BASE_CONFIG: DecoderConfig = DecoderConfig::DEFAULT
  .with_format(FrameFormat::Magicless)
  .with_frame_mode(FrameMode::Single);

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

/// Returns an error when `len` exceeds `max_len`.
#[inline]
fn check_limit(len: usize, max_len: Option<usize>) -> Result<()> {
  match max_len {
    Some(limit) if len > limit => Err(Error::OutputLimit(limit)),
    _ => Ok(()),
  }
}

/// Decompresses a magicless frame, bounding the output when `max_len` is set.
fn decompress(payload: &[u8], max_len: Option<usize>) -> Result<Vec<u8>> {
  let config = max_len.map_or(BASE_CONFIG, |limit| {
    BASE_CONFIG.with_limits(DecodeLimits::DEFAULT.with_max_output_bytes(Some(limit as u64)))
  });
  DECOMPRESSOR.with_borrow_mut(|slot| {
    let decompressor = slot.get_or_insert_with(|| Decompressor::new(config));
    if *decompressor.config() != config {
      decompressor.reconfigure(config);
    }
    decompressor.decompress(payload).map_err(|err| match err {
      DecodeError::OutputLimitExceeded { .. } => Error::OutputLimit(max_len.unwrap_or(usize::MAX)),
      other => Error::Decode(other),
    })
  })
}

fn decode_with(data: &[u8], max_len: Option<usize>) -> Result<Vec<u8>> {
  let (&tag, payload) = data.split_first().ok_or(Error::Empty)?;

  match Type::try_from(tag)? {
    Type::Raw => {
      check_limit(payload.len(), max_len)?;
      Ok(payload.to_vec())
    }
    Type::Zstd => decompress(payload, max_len),
  }
}

fn decode_owned_with(mut data: Vec<u8>, max_len: Option<usize>) -> Result<Vec<u8>> {
  let Some(&tag) = data.first() else {
    return Err(Error::Empty);
  };
  match Type::try_from(tag)? {
    Type::Raw => {
      check_limit(data.len() - 1, max_len)?;
      // Shift the payload down over the tag inside the existing allocation.
      data.remove(0);
      Ok(data)
    }
    Type::Zstd => decompress(&data[1..], max_len),
  }
}

/// Decodes a payload whose [`Type`] tag was transmitted out of band, enforcing `max_len`.
///
/// Matches [`decode_limit`] semantics without requiring a contiguous `[tag | payload]`
/// envelope buffer on the caller side.
///
/// # Errors
///
/// Returns [`Error::OutputLimit`] when the payload exceeds `max_len`, or
/// [`Error::Decode`] on malformed frame data.
pub fn decode_payload_limit(kind: Type, payload: &[u8], max_len: usize) -> Result<Vec<u8>> {
  match kind {
    Type::Raw => {
      check_limit(payload.len(), Some(max_len))?;
      Ok(payload.to_vec())
    }
    Type::Zstd => decompress(payload, Some(max_len)),
  }
}

/// Decodes an envelope produced by [`encode`](crate::encode).
///
/// The input is expected to come from this crate; a Zstd payload from an
/// untrusted source can expand to a much larger output. Use [`decode_limit`] to
/// enforce an upper bound on decompressed bytes.
///
/// # Errors
///
/// Returns [`Error::Empty`] on empty input, [`Error::InvalidType`] on an
/// unknown type tag, or [`Error::Decode`] on malformed or trailing frame data.
pub fn decode(data: &[u8]) -> Result<Vec<u8>> {
  decode_with(data, None)
}

/// Decodes an envelope produced by [`encode`](crate::encode), rejecting any
/// payload whose decoded size exceeds `max_len` bytes.
///
/// # Errors
///
/// Returns [`Error::OutputLimit`] when the decoded payload exceeds `max_len`, or
/// the same errors as [`decode`].
pub fn decode_limit(data: &[u8], max_len: usize) -> Result<Vec<u8>> {
  decode_with(data, Some(max_len))
}

/// Decodes an owned envelope, reusing its buffer for raw payloads.
///
/// A raw payload is shifted down over the tag inside the input allocation: one
/// in-place move, no allocation, and the same pointer is returned. A Zstd
/// payload is decompressed into a new buffer and the input is dropped.
///
/// # Errors
///
/// Returns the same errors as [`decode`].
pub fn decode_owned(data: Vec<u8>) -> Result<Vec<u8>> {
  decode_owned_with(data, None)
}

/// Decodes an owned envelope, rejecting any payload whose decoded size exceeds
/// `max_len` bytes.
///
/// # Errors
///
/// Returns [`Error::OutputLimit`] when the decoded payload exceeds `max_len`, or
/// the same errors as [`decode`].
pub fn decode_owned_limit(data: Vec<u8>, max_len: usize) -> Result<Vec<u8>> {
  decode_owned_with(data, Some(max_len))
}