goblin_experimental/
error.rs

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