From 9790a6edc992d24490e19161394c3041e137331d Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Mon, 11 Nov 2024 20:33:56 +0000 Subject: [PATCH] add unwrap_or_err to result Signed-off-by: Jason Volk --- src/core/utils/result.rs | 2 ++ src/core/utils/result/unwrap_or_err.rs | 15 +++++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 src/core/utils/result/unwrap_or_err.rs diff --git a/src/core/utils/result.rs b/src/core/utils/result.rs index fb1b7b95..6b11ea66 100644 --- a/src/core/utils/result.rs +++ b/src/core/utils/result.rs @@ -7,10 +7,12 @@ mod log_err; mod map_expect; mod not_found; mod unwrap_infallible; +mod unwrap_or_err; pub use self::{ debug_inspect::DebugInspect, filter::Filter, flat_ok::FlatOk, into_is_ok::IntoIsOk, log_debug_err::LogDebugErr, log_err::LogErr, map_expect::MapExpect, not_found::NotFound, unwrap_infallible::UnwrapInfallible, + unwrap_or_err::UnwrapOrErr, }; pub type Result = std::result::Result; diff --git a/src/core/utils/result/unwrap_or_err.rs b/src/core/utils/result/unwrap_or_err.rs new file mode 100644 index 00000000..69901958 --- /dev/null +++ b/src/core/utils/result/unwrap_or_err.rs @@ -0,0 +1,15 @@ +use std::convert::identity; + +use super::Result; + +/// Returns the Ok value or the Err value. Available when the Ok and Err types +/// are the same. This is a way to default the result using the specific Err +/// value rather than unwrap_or_default() using Ok's default. +pub trait UnwrapOrErr { + fn unwrap_or_err(self) -> T; +} + +impl UnwrapOrErr for Result { + #[inline] + fn unwrap_or_err(self) -> T { self.unwrap_or_else(identity::) } +}