y4m_codec/error.rs
1//! Error type for stream parsing, limits, and writer validation.
2
3use std::fmt;
4use std::io;
5
6/// Errors reported by the decoder and encoder.
7///
8/// Every malformed, truncated, or over-budget input maps to a typed variant,
9/// so callers can branch on truncation versus clean end of stream.
10#[non_exhaustive]
11#[derive(Debug)]
12pub enum Error {
13 /// Clean end of stream: EOF exactly where a `FRAME` header would start,
14 /// or EOF while reading the stream header before any frame was decoded.
15 EndOfStream,
16 /// EOF inside a frame header or frame payload: the stream was cut off
17 /// mid-frame.
18 Truncated,
19 /// A header byte sequence violates the YUV4MPEG2 grammar. The payload
20 /// names the offending location or rule.
21 Parse(&'static str),
22 /// A `C` (colorspace) tag with a value this crate does not recognize.
23 /// The payload holds the tag value as read from the wire.
24 Unsupported(String),
25 /// A header line or frame byte budget was exceeded, or plane size
26 /// arithmetic overflowed.
27 Limits,
28 /// An I/O error other than `UnexpectedEof` from the underlying reader or
29 /// writer.
30 Io(io::Error),
31 /// Writer input validation failure: plane length mismatch, invalid
32 /// extension bytes, or an out-of-range sample.
33 BadInput,
34}
35
36impl fmt::Display for Error {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 match self {
39 Error::EndOfStream => write!(f, "end of stream"),
40 Error::Truncated => write!(f, "unexpected EOF inside a frame"),
41 Error::Parse(detail) => write!(f, "parse error: {detail}"),
42 Error::Unsupported(tag) => write!(f, "unsupported colorspace tag: C{tag}"),
43 Error::Limits => write!(f, "header or frame size limit exceeded"),
44 Error::Io(e) => write!(f, "i/o error: {e}"),
45 Error::BadInput => write!(f, "writer input does not match the stream header"),
46 }
47 }
48}
49
50impl std::error::Error for Error {
51 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
52 match self {
53 Error::Io(e) => Some(e),
54 _ => None,
55 }
56 }
57}
58
59impl From<io::Error> for Error {
60 /// `UnexpectedEof` maps to [`Error::Truncated`]. The decoder reports
61 /// [`Error::EndOfStream`] itself when EOF falls on a frame boundary.
62 fn from(e: io::Error) -> Self {
63 if e.kind() == io::ErrorKind::UnexpectedEof {
64 Error::Truncated
65 } else {
66 Error::Io(e)
67 }
68 }
69}