use std::fmt;
use crate::error::{Error, ErrorKind};
const HEADER_LEN: usize = 8;
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Chunk<'a> {
pub id: [u8; 4],
pub offset: usize,
pub data: &'a [u8],
}
impl<'a> Chunk<'a> {
pub fn sub_chunks(&self) -> Chunks<'a> {
Chunks {
input: self.data,
offset: self.offset + HEADER_LEN,
nested: true,
}
}
}
impl fmt::Debug for Chunk<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Chunk")
.field("id", &String::from_utf8_lossy(&self.id))
.field("offset", &self.offset)
.field("len", &self.data.len())
.finish()
}
}
impl fmt::Debug for Chunks<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Chunks")
.field("offset", &self.offset)
.field("len", &self.input.len())
.field("nested", &self.nested)
.finish()
}
}
#[derive(Clone)]
pub struct Chunks<'a> {
input: &'a [u8],
offset: usize,
nested: bool,
}
impl<'a> Chunks<'a> {
pub fn new(data: &'a [u8]) -> Chunks<'a> {
Chunks::at(data, 0)
}
pub(crate) fn at(data: &'a [u8], offset: usize) -> Chunks<'a> {
Chunks {
input: data,
offset,
nested: false,
}
}
pub(crate) fn payload(data: &'a [u8]) -> Chunks<'a> {
Chunks {
input: data,
offset: 0,
nested: true,
}
}
fn next_chunk(&mut self) -> Result<Chunk<'a>, Error> {
let input = self.input;
if !is_chunk_id(&input[..input.len().min(4)]) {
return Err(Error::at(ErrorKind::InvalidChunk, None, self.offset));
}
let overrun = if self.nested {
ErrorKind::InvalidChunk
} else {
ErrorKind::Truncated
};
let Some((header, rest)) = input.split_first_chunk::<HEADER_LEN>() else {
let id = input.first_chunk::<4>().copied();
return Err(Error::at(overrun, id, self.offset));
};
let (id, size) = header.split_first_chunk::<4>().expect("eight bytes");
let size = u32::from_be_bytes(size.try_into().expect("four bytes"));
let Some(data) = usize::try_from(size).ok().and_then(|size| rest.get(..size)) else {
return Err(Error::at(overrun, Some(*id), self.offset));
};
let mut rest = &rest[data.len()..];
if data.len() % 2 == 1 && !rest.is_empty() {
rest = &rest[1..];
}
let chunk = Chunk {
id: *id,
offset: self.offset,
data,
};
self.offset += input.len() - rest.len();
self.input = rest;
Ok(chunk)
}
}
pub(crate) fn is_chunk_id(id: &[u8]) -> bool {
id.iter()
.all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
}
impl<'a> Iterator for Chunks<'a> {
type Item = Result<Chunk<'a>, Error>;
fn next(&mut self) -> Option<Self::Item> {
if self.input.is_empty() {
return None;
}
let chunk = self.next_chunk();
if chunk.is_err() {
self.input = &[];
}
Some(chunk)
}
}
#[cfg(test)]
mod tests {
use super::*;
type Walked<'a> = ([u8; 4], usize, &'a [u8]);
fn walk(input: &[u8]) -> Vec<Result<Walked<'_>, Error>> {
Chunks::new(input)
.map(|chunk| chunk.map(|c| (c.id, c.offset, c.data)))
.collect()
}
#[test]
fn walks_chunks_and_consumes_pad_bytes() {
let input = b"SND2\x00\x00\x00\x04abcdSND1\x00\x00\x00\x03abc\x00VQFR\x00\x00\x00\x00";
assert_eq!(
walk(input),
vec![
Ok((*b"SND2", 0, &b"abcd"[..])),
Ok((*b"SND1", 12, &b"abc"[..])),
Ok((*b"VQFR", 24, &b""[..])),
]
);
}
#[test]
fn odd_sized_chunk_at_end_of_input_needs_no_pad_byte() {
let chunks = walk(b"SND2\x00\x00\x00\x03abc");
assert_eq!(chunks, vec![Ok((*b"SND2", 0, &b"abc"[..]))]);
}
fn located(e: &Error) -> (ErrorKind, Option<[u8; 4]>, Option<usize>) {
(e.kind(), e.chunk(), e.offset())
}
fn failure(chunks: Chunks<'_>) -> (ErrorKind, Option<[u8; 4]>, Option<usize>) {
let errors: Vec<_> = chunks.filter_map(Result::err).collect();
assert_eq!(errors.len(), 1);
located(&errors[0])
}
#[test]
fn rejects_non_chunk_ids_and_stops() {
let invalid = (ErrorKind::InvalidChunk, None, Some(0));
assert_eq!(failure(Chunks::new(b"lin \x00\x00\x00\x00")), invalid);
assert_eq!(
failure(Chunks::new(b"\x00\x01\x02\x03\x00\x00\x00\x00")),
invalid
);
assert_eq!(failure(Chunks::new(b"SNd")), invalid);
assert_eq!(failure(Chunks::new(b"s")), invalid);
let chunks: Vec<_> = Chunks::new(b"SND2\x00\x00\x00\x00snd2").collect();
assert_eq!(chunks.len(), 2);
assert_eq!(
located(chunks[1].as_ref().unwrap_err()),
(ErrorKind::InvalidChunk, None, Some(8))
);
}
#[test]
fn a_chunk_running_past_the_input_is_a_cut_off_file() {
let cut = |id| (ErrorKind::Truncated, id, Some(0));
assert_eq!(
failure(Chunks::new(b"SND2\x00\x00\x00\x05abcd")),
cut(Some(*b"SND2"))
);
assert_eq!(
failure(Chunks::new(b"SND2\x00\x00\x00")),
cut(Some(*b"SND2"))
);
assert_eq!(
failure(Chunks::new(b"SND2\xff\xff\xff\xff")),
cut(Some(*b"SND2"))
);
assert_eq!(failure(Chunks::new(b"SND")), cut(None));
let chunks = walk(b"SND2\x00\x00\x00\x00SND");
assert_eq!(chunks[0], Ok((*b"SND2", 0, &b""[..])));
assert_eq!(
located(chunks[1].as_ref().unwrap_err()),
(ErrorKind::Truncated, None, Some(8))
);
assert_eq!(chunks.len(), 2);
}
#[test]
fn a_sub_chunk_running_past_its_container_is_corrupt() {
let input = b"VQFR\x00\x00\x00\x0aVPT0\x00\x00\x00\x10ab";
let vqfr = Chunks::new(input).next().unwrap().unwrap();
assert_eq!(
failure(vqfr.sub_chunks()),
(ErrorKind::InvalidChunk, Some(*b"VPT0"), Some(8))
);
assert_eq!(
failure(Chunks::payload(vqfr.data)),
(ErrorKind::InvalidChunk, Some(*b"VPT0"), Some(0))
);
assert_eq!(
failure(Chunks::new(vqfr.data)),
(ErrorKind::Truncated, Some(*b"VPT0"), Some(0))
);
for (payload, id) in [(&b"VPT0\x00\x00"[..], Some(*b"VPT0")), (b"VPT", None)] {
let mut input = b"VQFR".to_vec();
input.extend((payload.len() as u32).to_be_bytes());
input.extend(payload);
let vqfr = Chunks::new(&input).next().unwrap().unwrap();
let corrupt = (ErrorKind::InvalidChunk, id, Some(8));
assert_eq!(failure(vqfr.sub_chunks()), corrupt);
let cut = (ErrorKind::Truncated, id, Some(0));
assert_eq!(failure(Chunks::new(payload)), cut);
}
}
#[test]
fn sub_chunks_count_offsets_from_the_same_origin() {
let mut input = b"SND2\x00\x00\x00\x02abVQFR\x00\x00\x00\x12".to_vec();
input.extend(b"CBF0\x00\x00\x00\x01x\x00VPT0\x00\x00\x00\x00");
let chunks: Vec<_> = Chunks::at(&input, 100).map(Result::unwrap).collect();
assert_eq!(chunks[1].offset, 110);
let subs: Vec<_> = chunks[1].sub_chunks().map(Result::unwrap).collect();
assert_eq!(
(subs[0].id, subs[0].offset, subs[0].data),
(*b"CBF0", 118, &b"x"[..])
);
assert_eq!((subs[1].id, subs[1].offset), (*b"VPT0", 128));
for chunk in chunks.iter().chain(&subs) {
assert_eq!(&input[chunk.offset - 100..][..4], &chunk.id);
let payload = chunk.offset - 100 + HEADER_LEN;
assert_eq!(&input[payload..][..chunk.data.len()], chunk.data);
}
}
#[test]
fn debug_shows_the_length_rather_than_the_payload() {
let chunk = Chunks::new(b"SND2\x00\x00\x00\x04abcd")
.next()
.unwrap()
.unwrap();
assert_eq!(
format!("{chunk:?}"),
r#"Chunk { id: "SND2", offset: 0, len: 4 }"#
);
let mut chunks = Chunks::new(b"SND2\x00\x00\x00\x04abcdVQFR\x00\x00\x00\x00");
chunks.next();
assert_eq!(
format!("{chunks:?}"),
"Chunks { offset: 12, len: 8, nested: false }"
);
}
}