1*c3bf042aSAndrew Brown //! Defines an `Error` returned during source code generation.
2*c3bf042aSAndrew Brown 
3*c3bf042aSAndrew Brown use std::fmt;
4*c3bf042aSAndrew Brown use std::io;
5*c3bf042aSAndrew Brown 
6*c3bf042aSAndrew Brown /// An error that occurred when the cranelift_codegen_meta crate was generating
7*c3bf042aSAndrew Brown /// source files for the cranelift_codegen crate.
8*c3bf042aSAndrew Brown #[derive(Debug)]
9*c3bf042aSAndrew Brown pub struct Error {
10*c3bf042aSAndrew Brown     inner: Box<ErrorInner>,
11*c3bf042aSAndrew Brown }
12*c3bf042aSAndrew Brown 
13*c3bf042aSAndrew Brown impl Error {
14*c3bf042aSAndrew Brown     /// Create a new error object with the given message.
with_msg<S: Into<String>>(msg: S) -> Error15*c3bf042aSAndrew Brown     pub fn with_msg<S: Into<String>>(msg: S) -> Error {
16*c3bf042aSAndrew Brown         Error {
17*c3bf042aSAndrew Brown             inner: Box::new(ErrorInner::Msg(msg.into())),
18*c3bf042aSAndrew Brown         }
19*c3bf042aSAndrew Brown     }
20*c3bf042aSAndrew Brown }
21*c3bf042aSAndrew Brown 
22*c3bf042aSAndrew Brown impl std::error::Error for Error {}
23*c3bf042aSAndrew Brown 
24*c3bf042aSAndrew Brown impl fmt::Display for Error {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result25*c3bf042aSAndrew Brown     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
26*c3bf042aSAndrew Brown         write!(f, "{}", self.inner)
27*c3bf042aSAndrew Brown     }
28*c3bf042aSAndrew Brown }
29*c3bf042aSAndrew Brown 
30*c3bf042aSAndrew Brown impl From<io::Error> for Error {
from(e: io::Error) -> Self31*c3bf042aSAndrew Brown     fn from(e: io::Error) -> Self {
32*c3bf042aSAndrew Brown         Error {
33*c3bf042aSAndrew Brown             inner: Box::new(ErrorInner::IoError(e)),
34*c3bf042aSAndrew Brown         }
35*c3bf042aSAndrew Brown     }
36*c3bf042aSAndrew Brown }
37*c3bf042aSAndrew Brown 
38*c3bf042aSAndrew Brown #[derive(Debug)]
39*c3bf042aSAndrew Brown enum ErrorInner {
40*c3bf042aSAndrew Brown     Msg(String),
41*c3bf042aSAndrew Brown     IoError(io::Error),
42*c3bf042aSAndrew Brown }
43*c3bf042aSAndrew Brown 
44*c3bf042aSAndrew Brown impl fmt::Display for ErrorInner {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result45*c3bf042aSAndrew Brown     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46*c3bf042aSAndrew Brown         match *self {
47*c3bf042aSAndrew Brown             ErrorInner::Msg(ref s) => write!(f, "{s}"),
48*c3bf042aSAndrew Brown             ErrorInner::IoError(ref e) => write!(f, "{e}"),
49*c3bf042aSAndrew Brown         }
50*c3bf042aSAndrew Brown     }
51*c3bf042aSAndrew Brown }
52