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);
pub const DEFAULT_MAX_WINDOW_LOG: u32 = 21;
pub const LOW_LATENCY_WINDOW_LOG: u32 = 15;
const MIN_WINDOW_LOG: u32 = 10;
const ABS_MAX_WINDOW_LOG: u32 = 27;
pub(crate) const MIN_OBSERVE: usize = 8 * 1024;
const SLACK: usize = 16;
#[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 {
#[must_use]
#[inline]
pub const fn new(level: Level) -> Self {
Self {
level,
max_window_log: DEFAULT_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
}
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;
}
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
}
#[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();
}
}
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
}
#[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_opt(data: Vec<u8>, opt: EncodeOpt) -> Encoded {
encode_owned_with(data, &mut (), |_, _, _| Some(opt), false, noop_observe)
}
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)
}
#[must_use]
pub fn encode_opt(data: &[u8], opt: EncodeOpt) -> Vec<u8> {
encode_vec_with(data, &mut (), |_, _, _| Some(opt), false, noop_observe)
}
#[must_use]
pub fn encode_owned(data: Vec<u8>, level: Level) -> Encoded {
encode_owned_opt(data, EncodeOpt::new(level))
}
pub fn encode_into(data: &[u8], level: Level, out: &mut Vec<u8>) -> Type {
encode_into_opt(data, EncodeOpt::new(level), out)
}
#[must_use]
pub fn encode(data: &[u8], level: Level) -> Vec<u8> {
encode_opt(data, EncodeOpt::new(level))
}