add Filter extension to Result

Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
Jason Volk 2024-10-31 07:33:16 +00:00
parent e49aee61c1
commit 6b0eb7608d
2 changed files with 24 additions and 2 deletions

View file

@ -1,4 +1,5 @@
mod debug_inspect; mod debug_inspect;
mod filter;
mod flat_ok; mod flat_ok;
mod into_is_ok; mod into_is_ok;
mod log_debug_err; mod log_debug_err;
@ -8,8 +9,8 @@ mod not_found;
mod unwrap_infallible; mod unwrap_infallible;
pub use self::{ pub use self::{
debug_inspect::DebugInspect, flat_ok::FlatOk, into_is_ok::IntoIsOk, log_debug_err::LogDebugErr, log_err::LogErr, debug_inspect::DebugInspect, filter::Filter, flat_ok::FlatOk, into_is_ok::IntoIsOk, log_debug_err::LogDebugErr,
map_expect::MapExpect, not_found::NotFound, unwrap_infallible::UnwrapInfallible, log_err::LogErr, map_expect::MapExpect, not_found::NotFound, unwrap_infallible::UnwrapInfallible,
}; };
pub type Result<T = (), E = crate::Error> = std::result::Result<T, E>; pub type Result<T = (), E = crate::Error> = std::result::Result<T, E>;

View file

@ -0,0 +1,21 @@
use super::Result;
pub trait Filter<T, E> {
/// Similar to Option::filter
#[must_use]
fn filter<P, U>(self, predicate: P) -> Self
where
P: FnOnce(&T) -> Result<(), U>,
E: From<U>;
}
impl<T, E> Filter<T, E> for Result<T, E> {
#[inline]
fn filter<P, U>(self, predicate: P) -> Self
where
P: FnOnce(&T) -> Result<(), U>,
E: From<U>,
{
self.and_then(move |t| predicate(&t).map(move |()| t).map_err(Into::into))
}
}