Skip to main content

riff_chunks/
error.rs

1use core::fmt;
2
3use crate::Fourcc;
4
5/// A crate result with [`Error`] as its error type.
6pub type Result<T> = core::result::Result<T, Error>;
7
8/// An error from parsing, streaming, or writing a container.
9#[derive(Debug)]
10#[non_exhaustive]
11pub enum Error {
12    /// The underlying stream returned an error.
13    #[cfg(feature = "std")]
14    Io(std::io::Error),
15    /// The first four bytes do not identify a supported form.
16    NotRiff {
17        /// The form bytes found in the input.
18        found: [u8; 4],
19    },
20    /// Fewer than eight bytes remain for a chunk header, or fewer than twelve
21    /// bytes remain for the file header.
22    TruncatedHeader {
23        /// Absolute offset of the incomplete header.
24        offset: u64,
25        /// Bytes available from the offset.
26        available: u64,
27    },
28    /// A chunk payload ends before its declared size.
29    Truncated {
30        /// Identifier of the incomplete chunk.
31        id: Fourcc,
32        /// Declared payload size.
33        declared: u64,
34        /// Payload bytes available in the input.
35        available: u64,
36    },
37    /// A child chunk extends beyond its list.
38    ChildExceedsParent {
39        /// Identifier of the child chunk.
40        id: Fourcc,
41        /// Declared child payload size.
42        declared: u64,
43        /// Bytes left in the list from the child header.
44        remaining: u64,
45    },
46    /// An odd payload reaches the input end without a pad byte.
47    MissingPad {
48        /// Identifier of the unpadded chunk.
49        id: Fourcc,
50        /// Absolute offset where the pad byte belongs.
51        offset: u64,
52    },
53    /// A list payload has no complete four-byte list type.
54    ListTooShort {
55        /// Identifier of the list chunk.
56        id: Fourcc,
57        /// Declared list payload size.
58        size: u64,
59    },
60    /// List nesting reached the fixed limit.
61    TooDeep {
62        /// Maximum supported nesting depth.
63        max: usize,
64    },
65    /// An RF64 or BW64 file does not start with a size table.
66    MissingDs64 {
67        /// Identifier of the first chunk.
68        found: Fourcc,
69    },
70    /// The RF64 size table is too short for its declared entries.
71    BadDs64 {
72        /// Declared size of the table payload.
73        size: u64,
74    },
75    /// A sentinel size has no matching 64-bit value.
76    UnresolvedSize {
77        /// Identifier whose size could not be resolved.
78        id: Fourcc,
79    },
80    /// A list-only operation received another chunk type.
81    NotAList {
82        /// Identifier of the current chunk.
83        id: Fourcc,
84    },
85    /// A list-leave operation was requested at the top level.
86    NotInList,
87    /// A streaming write was requested without an open chunk.
88    NoOpenChunk,
89    /// The caller's payload buffer cannot hold the remaining bytes.
90    BufferTooSmall {
91        /// Required buffer length.
92        needed: u64,
93    },
94    /// A size cannot fit in a 32-bit container field.
95    TooLarge {
96        /// Size that exceeded the field.
97        size: u64,
98    },
99    /// The writer has open chunks or lists.
100    Unbalanced {
101        /// Number of open scopes.
102        open: usize,
103    },
104    /// The requested feature is unavailable.
105    Unsupported(Feature),
106}
107
108/// A format feature that a requested operation does not support.
109#[derive(Clone, Copy, PartialEq, Eq, Debug)]
110#[non_exhaustive]
111pub enum Feature {
112    /// Writing RF64 and BW64 containers.
113    Rf64Write,
114}
115
116impl fmt::Display for Error {
117    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
118        match self {
119            #[cfg(feature = "std")]
120            Self::Io(error) => write!(formatter, "stream error: {error}"),
121            Self::NotRiff { found } => write!(formatter, "unsupported form id: {}", Fourcc(*found)),
122            Self::TruncatedHeader { offset, available } => write!(
123                formatter,
124                "incomplete header at offset {offset}: {available} bytes available"
125            ),
126            Self::Truncated {
127                id,
128                declared,
129                available,
130            } => write!(
131                formatter,
132                "chunk {id} declares {declared} bytes with {available} available"
133            ),
134            Self::ChildExceedsParent {
135                id,
136                declared,
137                remaining,
138            } => write!(
139                formatter,
140                "chunk {id} declares {declared} bytes with {remaining} bytes left in its list"
141            ),
142            Self::MissingPad { id, offset } => {
143                write!(
144                    formatter,
145                    "chunk {id} is missing its pad byte at offset {offset}"
146                )
147            }
148            Self::ListTooShort { id, size } => {
149                write!(formatter, "list {id} has a {size}-byte payload")
150            }
151            Self::TooDeep { max } => write!(formatter, "list nesting exceeds {max} levels"),
152            Self::MissingDs64 { found } => {
153                write!(formatter, "64-bit form starts with {found} instead of ds64")
154            }
155            Self::BadDs64 { size } => write!(formatter, "invalid ds64 payload size {size}"),
156            Self::UnresolvedSize { id } => write!(formatter, "no 64-bit size for chunk {id}"),
157            Self::NotAList { id } => write!(formatter, "chunk {id} is not a list"),
158            Self::NotInList => formatter.write_str("the reader is at the top level"),
159            Self::NoOpenChunk => formatter.write_str("no writable chunk is open"),
160            Self::BufferTooSmall { needed } => {
161                write!(formatter, "payload buffer needs {needed} bytes")
162            }
163            Self::TooLarge { size } => write!(formatter, "size {size} exceeds a 32-bit field"),
164            Self::Unbalanced { open } => write!(formatter, "writer has {open} open scopes"),
165            Self::Unsupported(Feature::Rf64Write) => {
166                formatter.write_str("RF64 and BW64 writing is unsupported")
167            }
168        }
169    }
170}
171
172#[cfg(feature = "std")]
173impl std::error::Error for Error {
174    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
175        match self {
176            Self::Io(error) => Some(error),
177            _ => None,
178        }
179    }
180}
181
182#[cfg(feature = "std")]
183impl From<std::io::Error> for Error {
184    fn from(error: std::io::Error) -> Self {
185        Self::Io(error)
186    }
187}
188
189#[derive(Clone, Copy, Debug)]
190pub(crate) enum Failure {
191    #[cfg(feature = "std")]
192    Io(std::io::ErrorKind),
193    TruncatedHeader(u64, u64),
194    Truncated(Fourcc, u64, u64),
195    ChildExceedsParent(Fourcc, u64, u64),
196    MissingPad(Fourcc, u64),
197    ListTooShort(Fourcc, u64),
198    #[cfg(feature = "std")]
199    TooDeep,
200    #[cfg(feature = "std")]
201    UnresolvedSize(Fourcc),
202}
203
204impl Failure {
205    pub(crate) fn into_error(self) -> Error {
206        match self {
207            #[cfg(feature = "std")]
208            Self::Io(kind) => Error::Io(std::io::Error::from(kind)),
209            Self::TruncatedHeader(offset, available) => {
210                Error::TruncatedHeader { offset, available }
211            }
212            Self::Truncated(id, declared, available) => Error::Truncated {
213                id,
214                declared,
215                available,
216            },
217            Self::ChildExceedsParent(id, declared, remaining) => Error::ChildExceedsParent {
218                id,
219                declared,
220                remaining,
221            },
222            Self::MissingPad(id, offset) => Error::MissingPad { id, offset },
223            Self::ListTooShort(id, size) => Error::ListTooShort { id, size },
224            #[cfg(feature = "std")]
225            Self::TooDeep => Error::TooDeep {
226                max: crate::MAX_DEPTH,
227            },
228            #[cfg(feature = "std")]
229            Self::UnresolvedSize(id) => Error::UnresolvedSize { id },
230        }
231    }
232}