use std::fmt;
use std::ops::Range;
use std::sync::Arc;
use bytes::Bytes;
use crate::budget::DecodeBuf;
use crate::error::{Error, LimitError, LimitKind};
pub mod encode;
mod lz4;
mod lzma;
mod stored;
pub mod unitycn;
pub use lz4::Lz4;
pub use lzma::Lzma;
pub use stored::Stored;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Codec {
None,
Lzma,
Lz4,
Lz4Hc,
Lzham,
Other(u8),
}
impl Codec {
#[must_use]
pub fn from_flags(flags: u32) -> Self {
match flags & 0x3F {
0 => Self::None,
1 => Self::Lzma,
2 => Self::Lz4,
3 => Self::Lz4Hc,
4 => Self::Lzham,
n => Self::Other(u8::try_from(n).unwrap_or(u8::MAX)),
}
}
#[must_use]
pub fn is_canonical(self) -> bool {
match self {
Self::Other(n) => (5..64).contains(&n),
_ => true,
}
}
#[must_use]
pub fn id(self) -> u8 {
match self {
Self::None => 0,
Self::Lzma => 1,
Self::Lz4 => 2,
Self::Lz4Hc => 3,
Self::Lzham => 4,
Self::Other(n) => n,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Decoded {
Written,
Input(Range<usize>),
}
pub trait BlockCodec: Send + Sync {
fn compressor(
&self,
_which: Codec,
_meter: &Arc<crate::limits::Meter>,
) -> Result<Option<Arc<dyn BlockCodec>>, crate::files::SaveError> {
Ok(None)
}
fn decode_with_flags(
&self,
input: &Bytes,
uncompressed: u32,
_flags: u32,
out: &mut DecodeBuf,
) -> Result<Decoded, Error> {
self.decode(input, uncompressed, out)
}
fn compress(
&self,
data: &[u8],
which: Codec,
meter: &Arc<crate::limits::Meter>,
) -> Result<Bytes, crate::files::SaveError> {
encode::compress(data, which, meter)
}
fn chunk_size(
&self,
which: Codec,
_meter: &Arc<crate::limits::Meter>,
) -> Result<usize, crate::files::SaveError> {
match which {
Codec::None | Codec::Lzma => Ok(usize::try_from(u32::MAX).unwrap_or(usize::MAX)),
Codec::Lz4 | Codec::Lz4Hc => Ok(0x20000),
_ => Err(crate::files::SaveError::UnsupportedCodec(which)),
}
}
fn decode(
&self,
input: &Bytes,
uncompressed: u32,
out: &mut DecodeBuf,
) -> Result<Decoded, Error>;
}
pub fn decode_block(
which: Codec,
codec: &dyn BlockCodec,
input: &Bytes,
uncompressed: u32,
out: &mut DecodeBuf,
cap: u64,
) -> Result<Option<Bytes>, Error> {
decode_flagged(
which,
codec,
input,
uncompressed,
out,
cap,
u32::from(which.id()),
)
}
pub(crate) fn decode_flagged(
which: Codec,
codec: &dyn BlockCodec,
input: &Bytes,
uncompressed: u32,
out: &mut DecodeBuf,
cap: u64,
flags: u32,
) -> Result<Option<Bytes>, Error> {
out.begin_block(cap, LimitKind::BlockOutput, u64::from(uncompressed));
let epoch = out.segment_epoch();
let decoded = crate::env::registry::from_callers(codec.decode_with_flags(
input,
uncompressed,
flags,
out,
))?;
let bad = |detail: String| Error::Decompress {
codec: which,
detail: detail.into(),
};
if out.segment_epoch() != epoch {
return Err(bad(
"the codec began a segment of its own or cut the output below its block".to_owned(),
));
}
let range = match decoded {
Decoded::Written => return Ok(None),
Decoded::Input(range) => range,
};
if out.segment_len() != 0 {
return Err(bad(format!(
"the codec wrote {} bytes and returned a range of its input",
out.segment_len()
)));
}
if range.start > range.end || range.end > input.len() {
return Err(bad(format!(
"the codec returned the range {range:?} of a {}-byte input",
input.len()
)));
}
let n = u64::try_from(range.len()).unwrap_or(u64::MAX);
if n > cap {
return Err(Error::Limit(LimitError::refused(
LimitKind::BlockOutput,
n,
cap,
)));
}
Ok(Some(input.slice(range)))
}
pub trait BlockDecryptor: Send + Sync {
fn decrypt(&self, block: &mut [u8], index: usize) -> Result<(), Error>;
}
#[derive(Clone)]
pub struct Codecs {
slots: [Option<Arc<dyn BlockCodec>>; 64],
stored_builtin: bool,
}
impl Codecs {
#[must_use]
pub fn empty() -> Self {
Self {
slots: std::array::from_fn(|_| None),
stored_builtin: false,
}
}
#[must_use]
pub fn unitypy() -> Self {
let mut c = Self::empty();
let lz4: Arc<dyn BlockCodec> = Arc::new(Lz4);
for (which, codec) in [
(Codec::None, Arc::new(Stored) as Arc<dyn BlockCodec>),
(Codec::Lzma, Arc::new(Lzma)),
(Codec::Lz4, lz4.clone()),
(Codec::Lz4Hc, lz4),
] {
if let Some(slot) = c.slots.get_mut(usize::from(which.id())) {
*slot = Some(codec);
}
}
c.stored_builtin = true;
c
}
pub fn set(&mut self, which: Codec, codec: Arc<dyn BlockCodec>) -> Result<(), Codec> {
if !which.is_canonical() {
return Err(which);
}
match self.slots.get_mut(usize::from(which.id())) {
Some(slot) => {
*slot = Some(codec);
if which == Codec::None {
self.stored_builtin = false;
}
Ok(())
}
None => Err(which),
}
}
#[must_use]
pub fn stores_as_is(&self) -> bool {
self.stored_builtin
}
#[must_use]
pub fn get(&self, which: Codec) -> Option<&Arc<dyn BlockCodec>> {
if !which.is_canonical() {
return None;
}
self.slots.get(usize::from(which.id()))?.as_ref()
}
}
impl Default for Codecs {
fn default() -> Self {
Self::unitypy()
}
}
impl fmt::Debug for Codecs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let ids: Vec<usize> = (0..self.slots.len())
.filter(|i| self.slots.get(*i).is_some_and(Option::is_some))
.collect();
f.debug_struct("Codecs")
.field("registered", &ids)
.field("stored_builtin", &self.stored_builtin)
.finish()
}
}
#[cfg(test)]
mod tests;