use primase_foundations::compress::{Compressor, Decompressor, Error, Lz4, Result, Zlib, oodle::Oodle};
pub(crate) fn invalid(offset: usize, detail: impl ToString) -> Error {
Error::Invalid {
codec: "cas",
offset,
detail: detail.to_string(),
}
}
pub(crate) fn buffer(size: usize) -> Result<Vec<u8>> {
let mut out = Vec::new();
out.try_reserve_exact(size).map_err(|_| Error::Limit)?;
out.resize(size, 0);
Ok(out)
}
pub(crate) fn check_size(actual: usize, expected: usize) -> Result<()> {
if actual == expected {
Ok(())
} else {
Err(Error::Size { expected, actual })
}
}
#[derive(Debug, Clone, Copy)]
pub struct Block<'a> {
pub offset: usize,
pub kind: u8,
pub decoded_size: usize,
pub payload: &'a [u8],
}
pub fn blocks(input: &[u8]) -> Result<Vec<Block<'_>>> {
let mut out = Vec::new();
let mut pos = 0;
while pos < input.len() {
let start = pos;
let &[flag, d1, d2, d3, kind, s1, s2, s3] = input
.get(pos..)
.and_then(|rest| rest.first_chunk::<8>())
.ok_or_else(|| invalid(pos, "short header: expected 8 bytes"))?;
if flag != 0 || kind & 0x80 != 0 {
return Err(invalid(
pos,
"dictionary/reserved flag unsupported: expected byte 0 and the top bit of byte 4 clear",
));
}
if s1 >> 4 != 7 {
return Err(invalid(
pos,
"block flags unsupported: expected the high nibble of byte 5 to be 7",
));
}
let decoded_size = (usize::from(d1) << 16) | (usize::from(d2) << 8) | usize::from(d3);
let size = (usize::from(s1 & 15) << 16) | (usize::from(s2) << 8) | usize::from(s3);
pos = pos.saturating_add(8);
let payload = input
.get(pos..)
.and_then(|rest| rest.get(..size))
.ok_or_else(|| invalid(pos, format!("short payload: expected {size} bytes")))?;
out.push(Block {
offset: start,
kind,
decoded_size,
payload,
});
pos = pos.saturating_add(size);
}
Ok(out)
}
pub(crate) fn append(out: &mut Vec<u8>, decoded: usize, kind: u8, payload: &[u8]) {
out.extend_from_slice(&u32::try_from(decoded).unwrap_or(u32::MAX).to_be_bytes());
let [.., high, mid, low] = u64::try_from(payload.len()).unwrap_or(u64::MAX).to_be_bytes();
out.extend_from_slice(&[kind, 0x70 | (high & 0x0F)]);
out.extend_from_slice(&[mid, low]);
out.extend_from_slice(payload);
}
#[derive(Debug, Clone, Copy)]
pub struct CasRaw;
impl Compressor for CasRaw {
fn compress(&self, input: &[u8]) -> Result<Vec<u8>> {
let mut out = Vec::new();
if input.is_empty() {
append(&mut out, 0, 0, &[]);
}
for part in input.chunks(65536) {
append(&mut out, part.len(), 0, part);
}
Ok(out)
}
}
#[derive(Debug, Default)]
pub struct Cas<'a> {
pub oodle: Option<&'a Oodle>,
}
impl Decompressor for Cas<'_> {
fn decompress(&self, input: &[u8], expected: usize) -> Result<Vec<u8>> {
let blocks = blocks(input)?;
let total = blocks
.iter()
.try_fold(0usize, |s, b| s.checked_add(b.decoded_size).ok_or(Error::Limit))?;
check_size(total, expected)?;
if let Some(b) = blocks
.iter()
.find(|b| b.kind == 0 && b.payload.len() != b.decoded_size)
{
return Err(Error::Size {
expected: b.decoded_size,
actual: b.payload.len(),
});
}
let mut out = buffer(expected)?;
let mut rest = out.as_mut_slice();
for b in blocks {
let (dst, after) = std::mem::take(&mut rest)
.split_at_mut_checked(b.decoded_size)
.ok_or_else(|| invalid(b.offset, "block decodes past the stream's decoded size"))?;
rest = after;
match b.kind {
0 => {
check_size(b.payload.len(), b.decoded_size)?;
dst.copy_from_slice(b.payload);
}
2 => dst.copy_from_slice(
&Zlib
.decompress(b.payload, b.decoded_size)
.map_err(|e| invalid(b.offset, e))?,
),
9 => dst.copy_from_slice(
&Lz4.decompress(b.payload, b.decoded_size)
.map_err(|e| invalid(b.offset, e))?,
),
0x0f => {
return Err(invalid(
b.offset,
"codec 0x0f (Zstandard) is not read: a dictionary from the initfs may be needed to decode it",
));
}
0x11 | 0x15 | 0x19 => {
let oodle = self
.oodle
.ok_or_else(|| invalid(b.offset, "Oodle library required"))?;
dst.copy_from_slice(
&oodle
.decompress(b.payload, b.decoded_size)
.map_err(|e| invalid(b.offset, e))?,
);
}
_ => {
return Err(invalid(b.offset, format!("unsupported kind {:#x}", b.kind)));
}
}
}
Ok(out)
}
}
impl Compressor for Cas<'_> {
fn compress(&self, input: &[u8]) -> Result<Vec<u8>> {
let oodle = self
.oodle
.ok_or_else(|| invalid(0, "Oodle library required for encoding"))?;
let mut out = Vec::new();
if input.is_empty() {
append(&mut out, 0, 0, &[]);
}
for part in input.chunks(65536) {
let payload = oodle.compress(part)?;
if payload.len() < part.len() {
append(&mut out, part.len(), 0x11, &payload);
} else {
append(&mut out, part.len(), 0, part);
}
}
Ok(out)
}
}