object_rewrite/
error.rs

1use object::build;
2use std::{error, fmt, io};
3
4/// An error that occurred while rewriting a file.
5#[derive(Debug)]
6pub struct Error {
7    inner: ErrorInner,
8}
9
10#[derive(Debug)]
11enum ErrorInner {
12    Io(io::Error),
13    Parse(build::Error),
14    Write(build::Error),
15    Modify(String),
16}
17
18/// The kind of error.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum ErrorKind {
21    /// A parse error occurred while reading the file.
22    Parse,
23    /// A validation error occurred while writing the file.
24    Write,
25    /// An I/O error occurred while writing the file.
26    Io(io::ErrorKind),
27    /// A validation error occurred while modifying the file.
28    Modify,
29}
30
31impl fmt::Display for Error {
32    #[inline]
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match &self.inner {
35            ErrorInner::Io(e) => e.fmt(f),
36            ErrorInner::Parse(e) => e.fmt(f),
37            ErrorInner::Write(e) => e.fmt(f),
38            ErrorInner::Modify(e) => e.fmt(f),
39        }
40    }
41}
42
43impl error::Error for Error {}
44
45impl Error {
46    /// Get the kind of error.
47    pub fn kind(&self) -> ErrorKind {
48        match &self.inner {
49            ErrorInner::Io(e) => ErrorKind::Io(e.kind()),
50            ErrorInner::Parse(_) => ErrorKind::Parse,
51            ErrorInner::Write(_) => ErrorKind::Write,
52            ErrorInner::Modify(_) => ErrorKind::Modify,
53        }
54    }
55
56    pub(crate) fn io(error: io::Error) -> Self {
57        Self {
58            inner: ErrorInner::Io(error),
59        }
60    }
61
62    pub(crate) fn parse(error: build::Error) -> Self {
63        Self {
64            inner: ErrorInner::Parse(error),
65        }
66    }
67
68    pub(crate) fn write(error: build::Error) -> Self {
69        Self {
70            inner: ErrorInner::Write(error),
71        }
72    }
73
74    pub(crate) fn modify(message: impl Into<String>) -> Self {
75        Self {
76            inner: ErrorInner::Modify(message.into()),
77        }
78    }
79}
80
81/// The  `Result` type for this library.
82pub type Result<T> = std::result::Result<T, Error>;