From 4e25a60d0f18aafab53a82a79e0ac10a0de2d6c4 Mon Sep 17 00:00:00 2001 From: Botahamec Date: Tue, 8 Aug 2023 21:24:57 -0400 Subject: Add From string conversions for UnexpectedError --- src/result.rs | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- src/unexpected.rs | 12 ++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/src/result.rs b/src/result.rs index 25392c8..6b3ad32 100644 --- a/src/result.rs +++ b/src/result.rs @@ -1,7 +1,9 @@ +use core::fmt::Debug; + #[cfg(feature = "std")] use std::error::Error; -use crate::{unexpected::Errorable, RawUnexpected}; +use crate::{unexpected::Errorable, Exun, RawUnexpected}; mod sealed { pub trait Sealed {} @@ -130,3 +132,71 @@ impl ResultMsgExt for Result { self.map_err(RawUnexpected::msg) } } + +trait ResultExunExt: Sealed { + fn expected_err(self) -> Option; + + fn unexpected_err(self) -> Option; + + fn map_expected_err(self, op: impl FnOnce(E) -> F) -> Result>; + + fn map_unexpected_err(self, op: impl FnOnce(U) -> F) -> Result>; + + fn unwrap_result(self) -> Result + where + U: Debug; + + fn unwrap_expected_err(self) -> E + where + T: Debug, + U: Debug; + + fn unwrap_unexpected_err(self) -> U + where + T: Debug, + E: Debug; +} + +impl ResultExunExt for Result> { + fn expected_err(self) -> Option { + self.err()?.expected() + } + + fn unexpected_err(self) -> Option { + self.err()?.unexpected() + } + + fn map_expected_err(self, op: impl FnOnce(E) -> F) -> Result> { + self.map_err(|e| e.map(op)) + } + + fn map_unexpected_err(self, op: impl FnOnce(U) -> F) -> Result> { + self.map_err(|e| e.map_unexpected(op)) + } + + fn unwrap_result(self) -> Result + where + U: Debug, + { + match self { + Ok(value) => Ok(value), + Err(error) => Err(error.unwrap()), + } + } + + fn unwrap_expected_err(self) -> E + where + T: Debug, + U: Debug, + { + self.unwrap_err().unwrap() + } + + fn unwrap_unexpected_err(self) -> U + where + T: Debug, + E: Debug, + { + self.unwrap_err().unwrap_unexpected() + } +} diff --git a/src/unexpected.rs b/src/unexpected.rs index 20a71c9..cc07728 100644 --- a/src/unexpected.rs +++ b/src/unexpected.rs @@ -214,6 +214,18 @@ impl From for UnexpectedError { } } +impl From<&'static str> for UnexpectedError { + fn from(value: &'static str) -> Self { + Self(RawUnexpected::msg(value)) + } +} + +impl From for UnexpectedError { + fn from(value: String) -> Self { + Self(RawUnexpected::msg(value)) + } +} + impl Display for UnexpectedError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Display::fmt(&self.0, f) -- cgit v1.2.3