Skip to main content

vsd_mp4/
error.rs

1/// A specialized [`Result`] type for operations that can fail in `vsd-mp4`.
2pub type Result<T> = std::result::Result<T, Error>;
3
4/// The error type returned by functions in `vsd-mp4`.
5#[derive(Debug)]
6pub enum Error {
7    /// The decryption key size is invalid (expected 16 bytes).
8    InvalidKeySize(usize),
9    /// An I/O error occurred during reading or writing.
10    Io(std::io::Error),
11    /// A generic or custom error accompanied by a message.
12    Other(String),
13}
14
15impl std::error::Error for Error {}
16
17impl std::fmt::Display for Error {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        match self {
20            Error::InvalidKeySize(x) => {
21                write!(f, "invalid key size: expected 16 bytes got {0} bytes.", x)
22            }
23            Error::Io(x) => write!(f, "i/o error: {}", x),
24            Error::Other(x) => write!(f, "{}", x),
25        }
26    }
27}
28
29impl From<std::io::Error> for Error {
30    fn from(e: std::io::Error) -> Self {
31        Self::Io(e)
32    }
33}
34
35impl From<std::string::FromUtf8Error> for Error {
36    fn from(e: std::string::FromUtf8Error) -> Self {
37        Self::Other(e.to_string())
38    }
39}
40
41impl From<std::string::FromUtf16Error> for Error {
42    fn from(e: std::string::FromUtf16Error) -> Self {
43        Self::Other(e.to_string())
44    }
45}
46
47#[cfg(any(feature = "decrypt-cenc", feature = "pssh"))]
48impl From<hex::FromHexError> for Error {
49    fn from(e: hex::FromHexError) -> Self {
50        Self::Other(format!("hex decode error: {e}"))
51    }
52}
53
54#[cfg(feature = "pssh")]
55impl From<prost::DecodeError> for Error {
56    fn from(e: prost::DecodeError) -> Self {
57        Self::Other(format!("protobuf decode error: {e}"))
58    }
59}
60
61#[cfg(feature = "pssh")]
62impl From<quick_xml::de::DeError> for Error {
63    fn from(e: quick_xml::de::DeError) -> Self {
64        Self::Other(format!("xml parse error: {e}"))
65    }
66}
67
68/// Early-returns with an [`Error::Other`] variant.
69///
70/// This macro accepts the same format arguments as [`format!`].
71#[macro_export]
72macro_rules! bail {
73    ($($arg:tt)*) => {
74        return Err($crate::Error::Other(format!($($arg)*)))
75    };
76}