use std::ops::Deref;
use std::sync::Arc;
use bytes::Bytes;
use crate::budget::DecodeBuf;
use crate::codec::unitycn::UnityCnDecryptor;
use crate::codec::{BlockDecryptor, Codec, decode_flagged};
use crate::error::{Error, LimitKind, Unsupported};
use crate::limits::Meter;
use crate::options::FileContext;
pub(super) struct BlockContext {
ctx: Arc<FileContext>,
encrypted: bool,
unitycn: Option<UnityCnDecryptor>,
}
impl BlockContext {
pub(super) fn new(
ctx: &Arc<FileContext>,
encrypted: bool,
unitycn: Option<UnityCnDecryptor>,
) -> Self {
Self {
ctx: ctx.clone(),
encrypted,
unitycn,
}
}
pub(super) fn file(&self) -> &Arc<FileContext> {
&self.ctx
}
}
impl Deref for BlockContext {
type Target = FileContext;
fn deref(&self) -> &FileContext {
&self.ctx
}
}
pub(super) fn decode_one(
ctx: &BlockContext,
meter: &Arc<Meter>,
input: Bytes,
uncompressed: u32,
flags: u32,
index: usize,
) -> Result<Bytes, Error> {
let mut out = DecodeBuf::new(meter, 0, u64::MAX, LimitKind::InputMemory)?;
let (which, codec) = codec_for(ctx, flags)?;
let decoded = reading(ctx, which, input.len(), &mut out, |out| {
let input = decrypted(ctx, meter, input, flags, which, index)?;
decode_flagged(
which,
codec.as_ref(),
&input,
uncompressed,
out,
ctx.limits.max_block_output,
flags,
)
.map_err(|e| with_codec(e, which))
})?;
match decoded {
Some(slice) => Ok(slice),
None => Ok(out.into_bytes()?),
}
}
pub(super) fn decode_block_into(
ctx: &BlockContext,
meter: &Arc<Meter>,
input: Bytes,
uncompressed: u32,
flags: u32,
index: usize,
out: &mut DecodeBuf,
) -> Result<(), Error> {
let (which, codec) = codec_for(ctx, flags)?;
reading(ctx, which, input.len(), out, |out| {
let input = decrypted(ctx, meter, input, flags, which, index)?;
if let Some(slice) = decode_flagged(
which,
codec.as_ref(),
&input,
uncompressed,
out,
ctx.limits.max_block_output,
flags,
)
.map_err(|e| with_codec(e, which))?
{
out.extend_from_slice(&slice)?;
}
Ok(())
})
}
fn reading<T>(
ctx: &BlockContext,
which: Codec,
input: usize,
out: &mut DecodeBuf,
decode: impl FnOnce(&mut DecodeBuf) -> Result<T, Error>,
) -> Result<T, Error> {
let n = if which == Codec::None && ctx.codecs.stores_as_is() {
0
} else {
u64::try_from(input).unwrap_or(u64::MAX)
};
out.prepay(n)?;
let got = decode(out);
let unused = out.end_prepaid();
if matches!(got, Err(Error::Budget(_) | Error::Allocator(_))) {
out.meter().uncount_decode(unused);
}
got
}
fn codec_for(
ctx: &FileContext,
flags: u32,
) -> Result<(Codec, Arc<dyn crate::codec::BlockCodec>), Error> {
let which = Codec::from_flags(flags);
match ctx.codecs.get(which) {
Some(c) => Ok((which, c.clone())),
None if which == Codec::Lzham => Err(Error::Unsupported(Unsupported::Lzham)),
None => Err(Error::Unsupported(Unsupported::Codec(which.id()))),
}
}
fn decrypted(
ctx: &BlockContext,
meter: &Arc<Meter>,
input: Bytes,
flags: u32,
which: Codec,
index: usize,
) -> Result<Bytes, Error> {
let decryptor = ctx
.decryptor
.as_deref()
.or_else(|| ctx.unitycn.as_ref().map(|d| d as &dyn BlockDecryptor));
let Some(d) = decryptor.filter(|_| ctx.encrypted) else {
return Ok(input);
};
if flags & 0x100 == 0 || which == Codec::None {
return Ok(input);
}
let mut copy = DecodeBuf::new(meter, 0, u64::MAX, LimitKind::InputMemory)?;
let block = copy.grow_zeroed(input.len())?;
block.copy_from_slice(&input);
crate::env::registry::from_callers(d.decrypt(block, index))?;
Ok(copy.into_bytes()?)
}
fn with_codec(e: Error, which: Codec) -> Error {
match e {
Error::Decompress { detail, .. } => Error::Decompress {
codec: which,
detail,
},
e => e,
}
}