autozstd 0.2.1

Zstd envelope compression with automatic raw fallback and magicless frames
Documentation
/// A non-empty magicless Zstd frame is at least 6 bytes (header + 3B block
/// header + 1B payload), so inputs under 7 bytes can never shrink.
pub(crate) const MIN_COMPRESS_LEN: usize = 7;

/// Inputs below this length skip statistical sampling and compress directly.
const CLASSIFY_MIN: usize = 4 * 1024;
/// Fixed per-window sample size (4 windows * 512 B = 2 KiB, strictly O(1)).
const WIN_LEN: usize = 512;
/// Trigram match per-mille ceiling to treat a high-entropy chunk as incompressible.
const INCOMP_MATCH_PM: usize = 25;
/// Distinct byte count floor to treat a low-match chunk as incompressible.
const INCOMP_UNIQUE_MIN: u32 = 242;

/// Coarse compressibility class estimated in O(1) time and stack space.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ContentBucket {
  /// Under minimum frame size, known compressed magic, or random/encrypted noise.
  Incompressible,
  /// Modest redundancy (weakly structured binary or dense logs).
  Low,
  /// Moderate redundancy (code, JSON, mixed archives).
  Medium,
  /// High redundancy (repetitive text, sparse tables, zero-padded blocks).
  High,
}

impl ContentBucket {
  /// Table index (`0..3`) for compressible buckets; `None` for [`Self::Incompressible`].
  #[cfg(feature = "adaptive")]
  #[must_use]
  #[inline]
  pub const fn index(self) -> Option<usize> {
    match self {
      Self::Incompressible => None,
      Self::Low => Some(0),
      Self::Medium => Some(1),
      Self::High => Some(2),
    }
  }
}

/// Returns `true` if `head` starts with a known compressed or container magic.
#[inline]
pub(crate) fn skip_magic(head: &[u8]) -> bool {
  let Some(&first) = head.first() else {
    return false;
  };
  match first {
    0x00 => {
      head.starts_with(b"\x00\x00\x00\x0cJXL \r\n\x87\n")
        || head.starts_with(b"\x00\x00\x00\x0cjP  \r\n\x87\n")
        || matches!(head, [0, 0, _, _, b'f', b't', b'y', b'p', _, _, _, _, ..])
    }
    0x04 => head.starts_with(b"\x04\x22\x4d\x18"),
    0x1a => head.starts_with(b"\x1aE\xdf\xa3"),
    0x1f => head.starts_with(b"\x1f\x8b\x08"),
    0x28 => head.starts_with(b"\x28\xb5\x2f\xfd"),
    b'7' => head.starts_with(b"7z\xbc\xaf\x27\x1c"),
    b'B' => matches!(head, [b'B', b'Z', b'h', b'1'..=b'9', ..]),
    b'G' => head.starts_with(b"GIF89a") || head.starts_with(b"GIF87a"),
    b'O' => head.starts_with(b"OggS"),
    b'P' => head.starts_with(b"PK\x03\x04"),
    b'R' => {
      head.starts_with(b"Rar!\x1a\x07")
        || matches!(
          head,
          [
            b'R',
            b'I',
            b'F',
            b'F',
            _,
            _,
            _,
            _,
            b'W',
            b'E',
            b'B',
            b'P',
            ..
          ]
        )
    }
    b'f' => head.starts_with(b"fLaC"),
    b'w' => head.starts_with(b"wOFF") || head.starts_with(b"wOF2"),
    0x89 => head.starts_with(b"\x89PNG\r\n\x1a\n"),
    0xfd => head.starts_with(b"\xfd7zXZ\x00"),
    0xff => {
      head.starts_with(b"\xff\xd8\xff")
        || head.starts_with(b"\xff\x0a")
        || head.starts_with(b"\xff\x4f\xff\x51")
    }
    _ => false,
  }
}

/// Scans one sample window into a stack 256-slot trigram table + 256-bit byte set.
fn scan_window(win: &[u8], seen: &mut [u64; 4]) -> usize {
  debug_assert!(win.len() >= 4);
  let mut ht = [0u16; 256];
  let mut hit_cnt = 0usize;
  // Separate byte-bitmap pass allows straightforward auto-vectorization on the 512 B window.
  for &b in win {
    seen[usize::from(b >> 6)] |= 1u64 << (b & 63);
  }
  for w in win.windows(3) {
    let v = u32::from_le_bytes([w[0], w[1], w[2], 0]);
    let slot = ((v.wrapping_mul(0x9E37_79B1)) >> 24) as usize;
    let tag = ((v ^ (v >> 11)) as u16) | 0x8000;
    if ht[slot] == tag {
      hit_cnt += 1;
    } else {
      ht[slot] = tag;
    }
  }
  let denom = (win.len() - 2).max(1);
  hit_cnt.saturating_mul(1000) / denom
}

/// Estimates data compressibility in strict O(1) time and stack memory (~544 B).
///
/// Short blocks (`< 4 KiB`) default to [`ContentBucket::Medium`] so tiny frames
/// still enter the encoder unless rejected by minimum length or magic header.
#[must_use]
pub fn classify(data: &[u8]) -> ContentBucket {
  if data.len() < MIN_COMPRESS_LEN || skip_magic(data) {
    return ContentBucket::Incompressible;
  }
  if data.len() < CLASSIFY_MIN {
    return ContentBucket::Medium;
  }

  let mut seen = [0u64; 4];
  let tail = data.len() - WIN_LEN;
  // Combine midpoint and non-dyadic offsets to catch centered patches and avoid power-of-2 stride resonance.
  let max_pm = [0, tail / 3, tail / 2, tail]
    .into_iter()
    .map(|start| scan_window(&data[start..start + WIN_LEN], &mut seen))
    .max()
    .unwrap_or(0);
  let unique: u32 = seen.iter().map(|w| w.count_ones()).sum();

  if max_pm < INCOMP_MATCH_PM && unique >= INCOMP_UNIQUE_MIN {
    ContentBucket::Incompressible
  } else if max_pm >= 350 || unique <= 80 {
    ContentBucket::High
  } else if max_pm >= 120 || unique <= 160 {
    ContentBucket::Medium
  } else {
    ContentBucket::Low
  }
}