From 9a25b48b49446cc42e3d43d352d4fdc0edabeeb6 Mon Sep 17 00:00:00 2001 From: rascul Date: Tue, 5 Sep 2023 17:31:00 -0500 Subject: [PATCH] init --- src/lib.rs | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/lib.rs diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..317a4e5 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,57 @@ +//! The Rear error wrapper + +use std::error::Error; +use std::fmt::{Display, Formatter, Result as FmtResult}; +use std::result::Result as StdResult; + +/// A `std::result::Result` wrapper that simply has a `Rear` as the error. +pub type Result = StdResult; + +/// A `Rear` is simply a message paired with the error. +#[derive(Debug)] +pub struct Rear { + error: Box, + message: String, +} + +impl Rear { + /// Return a reference to the error. + pub fn error(&self) -> &Box { + &self.error + } + + /// Return the message as a `&str`. + pub fn message(&self) -> &str { + &self.message + } + + /// Create a new `Rear` from an error implementing `std::error::Error` with + /// a message from anything that implementes `Into`. + pub fn new>(error: Box, message: S) -> Self { + let message = message.into(); + + Self { + error, + message, + } + } +} + +impl Display for Rear { + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + if ! self.message.is_empty() { + write!(f, "{}", self.error) + } else { + write!(f, "{}\n{}", &self.message, &self.error) + } + } +} + +impl From> for Rear { + fn from(error: Box) -> Self { + Self { + error: error, + message: String::new(), + } + } +}