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) };
}
#[inline]
fn check_limit(len: usize, max_len: Option<usize>) -> Result<()> {
match max_len {
Some(limit) if len > limit => Err(Error::OutputLimit(limit)),
_ => Ok(()),
}
}
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)?;
data.remove(0);
Ok(data)
}
Type::Zstd => decompress(&data[1..], max_len),
}
}
pub fn decode(data: &[u8]) -> Result<Vec<u8>> {
decode_with(data, None)
}
pub fn decode_limit(data: &[u8], max_len: usize) -> Result<Vec<u8>> {
decode_with(data, Some(max_len))
}
pub fn decode_owned(data: Vec<u8>) -> Result<Vec<u8>> {
decode_owned_with(data, None)
}
pub fn decode_owned_limit(data: Vec<u8>, max_len: usize) -> Result<Vec<u8>> {
decode_owned_with(data, Some(max_len))
}