Skip to main content

goblin/
error.rs

1//! A custom Goblin error
2//!
3
4use alloc::string::String;
5use core::error;
6use core::fmt;
7use core::num::TryFromIntError;
8use core::result;
9#[non_exhaustive]
10#[derive(Debug)]
11/// A custom Goblin error
12pub enum Error {
13    /// The binary is malformed somehow
14    Malformed(String),
15    /// The binary's magic is unknown or bad
16    BadMagic(u64),
17    /// An error emanating from reading and interpreting bytes
18    Scroll(scroll::Error),
19    /// An IO based error
20    #[cfg(feature = "std")]
21    IO(std::io::Error),
22    /// Buffer is too short to hold N items
23    BufferTooShort(usize, &'static str),
24}
25
26impl error::Error for Error {
27    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
28        match *self {
29            #[cfg(feature = "std")]
30            Error::IO(ref io) => Some(io),
31            Error::Scroll(ref scroll) => Some(scroll),
32            _ => None,
33        }
34    }
35}
36
37#[cfg(feature = "std")]
38impl From<std::io::Error> for Error {
39    fn from(err: std::io::Error) -> Error {
40        Error::IO(err)
41    }
42}
43
44impl From<TryFromIntError> for Error {
45    fn from(err: TryFromIntError) -> Error {
46        Error::Malformed(format!("Integer do not fit: {err}"))
47    }
48}
49
50impl From<scroll::Error> for Error {
51    fn from(err: scroll::Error) -> Error {
52        Error::Scroll(err)
53    }
54}
55
56impl fmt::Display for Error {
57    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
58        match *self {
59            #[cfg(feature = "std")]
60            Error::IO(ref err) => write!(fmt, "{}", err),
61            Error::Scroll(ref err) => write!(fmt, "{}", err),
62            Error::BadMagic(magic) => write!(fmt, "Invalid magic number: 0x{:x}", magic),
63            Error::Malformed(ref msg) => write!(fmt, "Malformed entity: {}", msg),
64            Error::BufferTooShort(n, item) => write!(fmt, "Buffer is too short for {} {}", n, item),
65        }
66    }
67}
68
69/// An impish result
70pub type Result<T> = result::Result<T, Error>;