use std::fmt;
use crate::chunk::Chunk;
use crate::lcw::LcwError;
#[derive(Clone, PartialEq, Eq)]
pub struct Error {
kind: ErrorKind,
chunk: [u8; 4],
frame: u32,
offset: usize,
}
const NO_CHUNK: [u8; 4] = [0; 4];
const NO_FRAME: u32 = u32::MAX;
const NO_OFFSET: usize = usize::MAX;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorKind {
NotVqa,
InvalidHeader,
Truncated,
InvalidChunk,
Lcw(LcwError),
TooLarge(Limit),
Video(VideoError),
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Limit {
FrameSize,
Codebook,
Soundtrack,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VideoError {
MixedCodebookParts,
PaletteSize,
WrongPointerFormat,
PointerTableSize,
BlockIndexOutOfRange,
TruncatedPointerStream,
UnknownPointerCommand,
PointerStreamOverrun,
}
impl Error {
pub fn kind(&self) -> ErrorKind {
self.kind
}
pub fn chunk(&self) -> Option<[u8; 4]> {
(self.chunk != NO_CHUNK).then_some(self.chunk)
}
pub fn offset(&self) -> Option<usize> {
(self.offset != NO_OFFSET).then_some(self.offset)
}
pub fn frame(&self) -> Option<usize> {
(self.frame != NO_FRAME).then_some(self.frame as usize)
}
#[cold]
#[inline(never)]
pub(crate) fn at(kind: ErrorKind, chunk: Option<[u8; 4]>, offset: usize) -> Error {
Error {
kind,
chunk: chunk.unwrap_or(NO_CHUNK),
frame: NO_FRAME,
offset,
}
}
#[cold]
#[inline(never)]
pub(crate) fn in_chunk(kind: ErrorKind, chunk: &Chunk<'_>) -> Error {
Error::at(kind, Some(chunk.id), chunk.offset)
}
#[cold]
#[inline(never)]
pub(crate) fn or_in(mut self, chunk: &Chunk<'_>) -> Error {
if self.offset == NO_OFFSET {
self.chunk = chunk.id;
self.offset = chunk.offset;
}
self
}
#[cold]
#[inline(never)]
pub(crate) fn in_frame(mut self, frame: usize) -> Error {
self.frame = u32::try_from(frame).map_or(NO_FRAME - 1, |frame| frame.min(NO_FRAME - 1));
self
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Error {
Error {
kind,
chunk: NO_CHUNK,
frame: NO_FRAME,
offset: NO_OFFSET,
}
}
}
impl From<LcwError> for Error {
fn from(e: LcwError) -> Error {
Error::from(ErrorKind::Lcw(e))
}
}
impl From<LcwError> for ErrorKind {
fn from(e: LcwError) -> ErrorKind {
ErrorKind::Lcw(e)
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Error")
.field("kind", &self.kind)
.field(
"chunk",
&self
.chunk()
.map(|id| String::from_utf8_lossy(&id).into_owned()),
)
.field("offset", &self.offset())
.field("frame", &self.frame())
.finish()
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.kind)?;
let (frame, chunk, offset) = (self.frame(), self.chunk(), self.offset());
if frame.is_none() && offset.is_none() {
return Ok(());
}
f.write_str(" (")?;
if let Some(frame) = frame {
write!(f, "frame {frame}")?;
if offset.is_some() {
f.write_str(", ")?;
}
}
match (chunk, offset) {
(Some(id), Some(offset)) => {
write!(f, "{} chunk at offset {offset:#x}", id.escape_ascii())?
}
(None, Some(offset)) => write!(f, "at offset {offset:#x}")?,
_ => {}
}
f.write_str(")")
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ErrorKind::NotVqa => f.write_str("not a VQA file"),
ErrorKind::InvalidHeader => f.write_str("invalid VQHD header"),
ErrorKind::Truncated => f.write_str("unexpected end of data"),
ErrorKind::InvalidChunk => f.write_str("malformed chunk structure"),
ErrorKind::Lcw(e) => write!(f, "malformed LCW data: {e}"),
ErrorKind::TooLarge(limit) => write!(f, "{limit} exceeds sanity limits"),
ErrorKind::Video(e) => write!(f, "malformed video data: {e}"),
}
}
}
impl fmt::Display for Limit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Limit::FrameSize => "frame size",
Limit::Codebook => "codebook",
Limit::Soundtrack => "soundtrack",
})
}
}
impl fmt::Display for VideoError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
VideoError::MixedCodebookParts => "mixed CBP0/CBPZ parts",
VideoError::PaletteSize => "palette size",
VideoError::WrongPointerFormat => "pointer chunk for the other pixel format",
VideoError::PointerTableSize => "pointer table size mismatch",
VideoError::BlockIndexOutOfRange => "block index outside the codebook",
VideoError::TruncatedPointerStream => "truncated pointer stream",
VideoError::UnknownPointerCommand => "unknown pointer stream command",
VideoError::PointerStreamOverrun => "pointer stream writes past the frame",
})
}
}
impl std::error::Error for Error {}
#[cfg(test)]
mod tests {
use super::*;
fn every_kind() -> Vec<ErrorKind> {
let mut kinds = vec![
ErrorKind::NotVqa,
ErrorKind::InvalidHeader,
ErrorKind::Truncated,
ErrorKind::InvalidChunk,
];
for e in [LcwError::Truncated, LcwError::BadOffset, LcwError::TooLarge] {
kinds.push(ErrorKind::Lcw(e));
}
for limit in [Limit::FrameSize, Limit::Codebook, Limit::Soundtrack] {
kinds.push(ErrorKind::TooLarge(limit));
}
for e in [
VideoError::MixedCodebookParts,
VideoError::PaletteSize,
VideoError::WrongPointerFormat,
VideoError::PointerTableSize,
VideoError::BlockIndexOutOfRange,
VideoError::TruncatedPointerStream,
VideoError::UnknownPointerCommand,
VideoError::PointerStreamOverrun,
] {
kinds.push(ErrorKind::Video(e));
}
for kind in &kinds {
match kind {
ErrorKind::NotVqa
| ErrorKind::InvalidHeader
| ErrorKind::Truncated
| ErrorKind::InvalidChunk
| ErrorKind::Lcw(LcwError::Truncated | LcwError::BadOffset | LcwError::TooLarge)
| ErrorKind::TooLarge(Limit::FrameSize | Limit::Codebook | Limit::Soundtrack)
| ErrorKind::Video(
VideoError::MixedCodebookParts
| VideoError::PaletteSize
| VideoError::WrongPointerFormat
| VideoError::PointerTableSize
| VideoError::BlockIndexOutOfRange
| VideoError::TruncatedPointerStream
| VideoError::UnknownPointerCommand
| VideoError::PointerStreamOverrun,
) => {}
}
}
kinds
}
#[test]
fn every_kind_has_its_own_message() {
let kinds = every_kind();
let messages: std::collections::HashSet<_> =
kinds.iter().map(ToString::to_string).collect();
assert_eq!(messages.len(), kinds.len());
for message in &messages {
assert!(!message.ends_with('.'), "{message}");
}
}
#[test]
fn display_names_the_place_it_knows() {
let kind = ErrorKind::Video(VideoError::PointerTableSize);
let e = Error::at(kind, Some(*b"VPT0"), 0x28);
assert_eq!(
e.to_string(),
"malformed video data: pointer table size mismatch (VPT0 chunk at offset 0x28)"
);
assert_eq!(
e.clone().in_frame(1).to_string(),
"malformed video data: pointer table size mismatch \
(frame 1, VPT0 chunk at offset 0x28)"
);
let e = Error::at(ErrorKind::InvalidChunk, None, 0x5e);
assert_eq!(e.to_string(), "malformed chunk structure (at offset 0x5e)");
let e = Error::from(ErrorKind::TooLarge(Limit::Codebook)).in_frame(7);
assert_eq!(e.to_string(), "codebook exceeds sanity limits (frame 7)");
assert_eq!(Error::from(ErrorKind::NotVqa).to_string(), "not a VQA file");
}
#[test]
fn accessors_report_only_what_is_known() {
let e = Error::from(ErrorKind::Truncated);
assert_eq!((e.chunk(), e.offset(), e.frame()), (None, None, None));
let e = Error::at(ErrorKind::Truncated, Some(*b"SND2"), 0).in_frame(0);
assert_eq!(
(e.kind(), e.chunk(), e.offset(), e.frame()),
(ErrorKind::Truncated, Some(*b"SND2"), Some(0), Some(0))
);
assert_eq!(
format!("{e:?}"),
r#"Error { kind: Truncated, chunk: Some("SND2"), offset: Some(0), frame: Some(0) }"#
);
}
#[test]
fn or_in_places_only_errors_without_a_location() {
let vqfr = crate::Chunks::new(b"VQFR\0\0\0\0").next().unwrap().unwrap();
let e = Error::from(ErrorKind::TooLarge(Limit::Codebook))
.in_frame(3)
.or_in(&vqfr);
assert_eq!(
(e.chunk(), e.offset(), e.frame()),
(Some(*b"VQFR"), Some(0), Some(3))
);
let inner = Error::at(ErrorKind::InvalidChunk, None, 20);
assert_eq!(inner.clone().or_in(&vqfr), inner);
}
#[test]
fn stays_small() {
assert!(size_of::<Error>() <= 24);
assert_eq!(size_of::<ErrorKind>(), 2);
assert_eq!(size_of::<Result<(), ErrorKind>>(), 2);
}
}