use std::cell::RefCell;
#[cfg(feature = "adaptive")]
use std::time::Instant;
use mzstd::{Compressor, EncoderConfig, FrameFormat, Level as ZLevel};
use crate::{Level, Type};
const CONFIG: EncoderConfig = EncoderConfig::new().with_format(FrameFormat::Magicless);
pub(crate) const MIN_COMPRESS_LEN: usize = 7;
const PROBE_LEN: usize = 16 * 1024;
const PROBE_MIN: usize = 8 * PROBE_LEN;
const PROBE_PCT: usize = 97;
const PROBE_MAX: usize = (PROBE_LEN * PROBE_PCT).div_ceil(100) - 1;
const MIN_OBSERVE: usize = 8 * 1024;
const SLACK: usize = 16;
thread_local! {
static ENC: RefCell<EncState> = const {
RefCell::new(EncState {
compressor: None,
probe: None,
})
};
}
struct EncState {
compressor: Option<Compressor>,
probe: Option<Probe>,
}
struct Probe {
compressor: Compressor,
buf: Box<[u8]>,
}
impl Probe {
fn new() -> Self {
let zlevel = ZLevel::try_from(Level::Fastest.get()).unwrap();
Self {
compressor: Compressor::new(CONFIG.with_level(zlevel)).unwrap(),
buf: vec![0u8; PROBE_MAX + SLACK].into_boxed_slice(),
}
}
fn can_compress(&mut self, data: &[u8]) -> bool {
let tail = data.len() - PROBE_LEN;
[0, tail / 2, tail].into_iter().any(|start| {
let sample = &data[start..start + PROBE_LEN];
matches!(
self.compressor.compress_to_slice(sample, &mut self.buf),
Ok(written) if written <= PROBE_MAX
)
})
}
}
#[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,
}
}
#[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
}
#[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);
}
#[inline]
pub(crate) fn shrink(out: &mut Vec<u8>) {
if out.len() * 2 < out.capacity() {
out.shrink_to_fit();
}
}
#[inline]
fn compressor_for(slot: &mut Option<Compressor>, level: Level) -> &mut Compressor {
let zlevel = ZLevel::try_from(level.get()).unwrap();
let compressor = slot.get_or_insert_with(|| Compressor::new(CONFIG.with_level(zlevel)).unwrap());
if compressor.config().level() != zlevel {
compressor.reconfigure(CONFIG.with_level(zlevel)).unwrap();
}
compressor
}
fn compress_at(
state: &mut EncState,
data: &[u8],
level: Level,
out: &mut Vec<u8>,
with_tag: bool,
) -> bool {
out.clear();
if data.len() > isize::MAX as usize - SLACK - 1 {
return false;
}
let compressor = compressor_for(&mut state.compressor, level);
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;
}
unsafe { out.set_len(offset + written) };
true
}
#[inline]
fn compress_into(state: &mut EncState, data: &[u8], level: Level, out: &mut Vec<u8>) -> bool {
compress_at(state, data, level, out, true)
}
#[inline]
fn compress_payload_into(
state: &mut EncState,
data: &[u8],
level: Level,
out: &mut Vec<u8>,
) -> bool {
compress_at(state, data, level, out, false)
}
fn encode_with(state: &mut EncState, data: &[u8], level: Level) -> Vec<u8> {
let mut out = Vec::new();
if !compress_into(state, data, level, &mut out) {
raw_into(&mut out, data);
}
shrink(&mut out);
out
}
pub(crate) enum Plan {
Raw,
Zstd(Level),
}
pub(crate) fn plan(data: &[u8], decide: impl FnOnce(bool) -> Option<Level>) -> Plan {
if data.len() < MIN_COMPRESS_LEN || skip_magic(data) {
return Plan::Raw;
}
let Some(level) = decide(data.len() >= MIN_OBSERVE) else {
return Plan::Raw;
};
if data.len() >= PROBE_MIN {
let compressible = ENC.with_borrow_mut(|state| {
state
.probe
.get_or_insert_with(Probe::new)
.can_compress(data)
});
if !compressible {
return Plan::Raw;
}
}
Plan::Zstd(level)
}
#[cfg(feature = "adaptive")]
fn compress_timed(
data: &[u8],
level: Level,
out: &mut Vec<u8>,
with_tag: bool,
) -> (bool, Option<f64>) {
let start = (data.len() >= MIN_OBSERVE).then(Instant::now);
let compressed = ENC.with_borrow_mut(|state| compress_at(state, data, level, out, with_tag));
(compressed, start.map(|t| t.elapsed().as_secs_f64()))
}
#[cfg(feature = "adaptive")]
#[inline]
pub(crate) fn compress_into_timed(
data: &[u8],
level: Level,
out: &mut Vec<u8>,
) -> (bool, Option<f64>) {
compress_timed(data, level, out, true)
}
#[cfg(feature = "adaptive")]
#[inline]
pub(crate) fn compress_payload_into_timed(
data: &[u8],
level: Level,
out: &mut Vec<u8>,
) -> (bool, Option<f64>) {
compress_timed(data, level, out, false)
}
#[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,
}
}
#[must_use]
#[inline]
pub fn kind(&self) -> Type {
self.kind
}
#[must_use]
#[inline]
pub fn payload(&self) -> &[u8] {
&self.payload
}
#[must_use]
#[inline]
pub fn into_parts(self) -> (Type, Vec<u8>) {
(self.kind, self.payload)
}
}
#[must_use]
pub fn encode_owned(data: Vec<u8>, level: Level) -> Encoded {
match plan(&data, |_| Some(level)) {
Plan::Raw => Encoded::raw(data),
Plan::Zstd(level) => {
let mut out = Vec::new();
let compressed =
ENC.with_borrow_mut(|state| compress_payload_into(state, &data, level, &mut out));
if compressed {
shrink(&mut out);
Encoded::zstd(out)
} else {
Encoded::raw(data)
}
}
}
}
pub fn encode_into(data: &[u8], level: Level, out: &mut Vec<u8>) -> Type {
match plan(data, |_| Some(level)) {
Plan::Raw => {
raw_into(out, data);
Type::Raw
}
Plan::Zstd(level) => {
let compressed = ENC.with_borrow_mut(|state| compress_into(state, data, level, out));
if compressed {
Type::Zstd
} else {
raw_into(out, data);
Type::Raw
}
}
}
}
#[must_use]
pub fn encode(data: &[u8], level: Level) -> Vec<u8> {
match plan(data, |_| Some(level)) {
Plan::Raw => raw(data),
Plan::Zstd(level) => ENC.with_borrow_mut(|state| encode_with(state, data, level)),
}
}