From f27518b60bb697000dcb1f6363066ddbaf505368 Mon Sep 17 00:00:00 2001 From: Botahamec Date: Sun, 23 Oct 2022 15:57:23 -0400 Subject: Added more constructors --- src/unexpected.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 44 insertions(+), 4 deletions(-) (limited to 'src/unexpected.rs') diff --git a/src/unexpected.rs b/src/unexpected.rs index ed99e1f..321973f 100644 --- a/src/unexpected.rs +++ b/src/unexpected.rs @@ -60,9 +60,9 @@ impl RawUnexpected { /// let x = RawUnexpected::new(core::fmt::Error); /// ``` #[cfg(feature = "std")] - pub fn new(e: E) -> Self { + pub fn new(error: E) -> Self { Self { - internal: ErrorTy::Error(Box::new(e)), + internal: ErrorTy::Error(Box::new(error)), } } @@ -80,9 +80,9 @@ impl RawUnexpected { /// /// let x = RawUnexpected::msg("failed"); /// ``` - pub fn msg(e: E) -> Self { + pub fn msg(error: E) -> Self { Self { - internal: ErrorTy::Message(Box::new(e)), + internal: ErrorTy::Message(Box::new(error)), } } @@ -105,6 +105,7 @@ impl RawUnexpected { /// assert!(x.source().is_none()); /// ``` #[must_use] + #[cfg(feature = "std")] pub fn source(&self) -> Option<&(dyn Error + 'static)> { match &self.internal { ErrorTy::Message(_) => None, @@ -121,6 +122,45 @@ impl RawUnexpected { #[derive(Debug)] pub struct UnexpectedError(RawUnexpected); +impl UnexpectedError { + /// Create a new `UnexpectedError` from any [`Error`] type. + /// + /// The error must be thread-safe and `'static` so that the + /// `UnexpectedError` will be too. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// use exun::*; + /// + /// let x = UnexpectedError::new(core::fmt::Error); + /// ``` + #[cfg(feature = "std")] + pub fn new(error: E) -> Self { + Self(RawUnexpected::new(error)) + } + + /// Create a new `UnexpectedError` from a printable error message. + /// + /// If the argument implements [`Error`], prefer [`UnexpectedError::new`] + /// instead, which preserves the source. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// use exun::*; + /// + /// let x = UnexpectedError::msg("failed"); + /// ``` + pub fn msg(error: E) -> Self { + Self(RawUnexpected::msg(error)) + } +} + impl From for UnexpectedError { fn from(ru: RawUnexpected) -> Self { Self(ru) -- cgit v1.2.3