summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBotahamec <botahamec@outlook.com>2023-08-08 21:24:57 -0400
committerBotahamec <botahamec@outlook.com>2023-08-08 21:24:57 -0400
commit4e25a60d0f18aafab53a82a79e0ac10a0de2d6c4 (patch)
treeb0239aa992c7e5a801ee5d8b659b4bc6a9c76ff0
parentdb8110aa743c2cd85f4dee2abdd6856312bdd523 (diff)
Add From string conversions for UnexpectedError
-rw-r--r--src/result.rs72
-rw-r--r--src/unexpected.rs12
2 files changed, 83 insertions, 1 deletions
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<T, E: Errorable + 'static> ResultMsgExt<T> for Result<T, E> {
self.map_err(RawUnexpected::msg)
}
}
+
+trait ResultExunExt<T, E, U>: Sealed {
+ fn expected_err(self) -> Option<E>;
+
+ fn unexpected_err(self) -> Option<U>;
+
+ fn map_expected_err<F>(self, op: impl FnOnce(E) -> F) -> Result<T, Exun<F, U>>;
+
+ fn map_unexpected_err<F>(self, op: impl FnOnce(U) -> F) -> Result<T, Exun<E, F>>;
+
+ fn unwrap_result(self) -> Result<T, E>
+ 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<T, E, U> ResultExunExt<T, E, U> for Result<T, Exun<E, U>> {
+ fn expected_err(self) -> Option<E> {
+ self.err()?.expected()
+ }
+
+ fn unexpected_err(self) -> Option<U> {
+ self.err()?.unexpected()
+ }
+
+ fn map_expected_err<F>(self, op: impl FnOnce(E) -> F) -> Result<T, Exun<F, U>> {
+ self.map_err(|e| e.map(op))
+ }
+
+ fn map_unexpected_err<F>(self, op: impl FnOnce(U) -> F) -> Result<T, Exun<E, F>> {
+ self.map_err(|e| e.map_unexpected(op))
+ }
+
+ fn unwrap_result(self) -> Result<T, E>
+ 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<RawUnexpected> for UnexpectedError {
}
}
+impl From<&'static str> for UnexpectedError {
+ fn from(value: &'static str) -> Self {
+ Self(RawUnexpected::msg(value))
+ }
+}
+
+impl From<String> 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)