use std::fmt; use std::io; pub type Result = std::result::Result; #[derive(Debug)] pub struct Error { message: String, } impl Error { pub fn new(message: impl Into) -> Self { Self { message: message.into(), } } pub fn io(message: impl Into) -> Self { Self::new(message) } pub fn usage(message: impl Into) -> Self { Self::new(message) } pub fn context(self, context: impl AsRef) -> Self { Self::new(format!("{}: {}", context.as_ref(), self.message)) } pub fn message(&self) -> &str { &self.message } } impl fmt::Display for Error { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str(&self.message) } } impl std::error::Error for Error {} impl From for Error { fn from(error: io::Error) -> Self { Self::new(error.to_string()) } } impl From for Error { fn from(message: String) -> Self { Self::new(message) } } impl From<&str> for Error { fn from(message: &str) -> Self { Self::new(message) } } pub trait OptionExt { fn or_error(self, message: impl Into) -> Result; } impl OptionExt for Option { fn or_error(self, message: impl Into) -> Result { self.ok_or_else(|| Error::new(message)) } }