pub(super) mod block;
pub(super) mod block_mode;
pub(crate) mod context;
pub(super) mod decimation;
pub(super) mod endpoint;
pub(crate) mod hdr;
pub(super) mod hdr_endpoint;
pub(super) mod ise;
pub(super) mod partition;
mod tables;
pub(crate) use block::ERROR;
pub(crate) use context::{Footprint, Tables};
pub(super) fn read_bits(data: &[u8], offset: usize, count: usize) -> Option<u32> {
if count > 16 || offset.checked_add(count)? > data.len().checked_mul(8)? {
return None;
}
let start = offset / 8;
let byte = |i: usize| u32::from(data.get(start + i).copied().unwrap_or(0));
let word = byte(0) | byte(1) << 8 | byte(2) << 16;
Some((word >> (offset % 8)) & ((1 << count) - 1))
}
pub(crate) fn decode_image(
tables: &mut Tables,
data: &[u8],
size: (usize, usize),
flip: bool,
error: [u8; 4],
out: &mut [u8],
) {
let image = match tables.footprint().width() {
4 => image::<16>,
5 => image::<20>,
6 => image::<24>,
8 => image::<32>,
10 => image::<40>,
12 => image::<48>,
_ => return,
};
image(tables, data, size, flip, error, out);
}
fn image<const ROW: usize>(
tables: &mut Tables,
data: &[u8],
(width, height): (usize, usize),
flip: bool,
error: [u8; 4],
out: &mut [u8],
) {
let fp = tables.footprint();
let (bw, bh) = (ROW / 4, usize::from(fp.height()));
let across = width.div_ceil(bw);
let blocks = across * height.div_ceil(bh);
let mut texels = [0; 4 * block::MAX_TEXELS];
for (i, bytes) in data.as_chunks::<16>().0.iter().take(blocks).enumerate() {
block::decode(tables, bytes, &mut texels, error);
let (x0, y0) = ((i % across) * bw, (i / across) * bh);
let n = bw.min(width - x0);
for (y, src) in texels.as_chunks::<ROW>().0.iter().take(bh).enumerate() {
let at = y0 + y;
if at >= height {
break;
}
let row = if flip { height - 1 - at } else { at };
let start = (row * width + x0) * 4;
if let Some(dst) = out.get_mut(start..start + 4 * n) {
match <&mut [u8; ROW]>::try_from(&mut *dst) {
Ok(dst) => *dst = *src,
Err(_) => edge(dst, src),
}
}
}
}
}
#[cold]
#[inline(never)]
fn edge(dst: &mut [u8], src: &[u8]) {
if let Some(src) = src.get(..dst.len()) {
dst.copy_from_slice(src);
}
}
pub(crate) fn error_blocks(tables: &mut Tables, data: &[u8]) -> Vec<bool> {
data.as_chunks::<16>()
.0
.iter()
.map(|b| block::is_error(tables, b))
.collect()
}
#[cfg(test)]
mod tests;