1
Fork 0

Add Result::{is_ok_with, is_err_with}.

This commit is contained in:
Mara Bos 2022-01-18 22:17:44 +01:00
parent 282224edf1
commit aaebae973f

View file

@ -542,6 +542,27 @@ impl<T, E> Result<T, E> {
matches!(*self, Ok(_))
}
/// Returns `true` if the result is [`Ok`] wrapping a value matching the predicate.
///
/// # Examples
///
/// ```
/// let x: Result<u32, &str> = Ok(2);
/// assert_eq!(x.is_ok_with(|x| x > 1), true);
///
/// let x: Result<u32, &str> = Ok(0);
/// assert_eq!(x.is_ok_with(|x| x > 1), false);
///
/// let x: Result<u32, &str> = Err("hey");
/// assert_eq!(x.is_ok_with(|x| x > 1), false);
/// ```
#[must_use]
#[inline]
#[unstable(feature = "is_some_with", issue = "none")]
pub fn is_ok_with(&self, f: impl FnOnce(&T) -> bool) -> bool {
matches!(self, Ok(x) if f(x))
}
/// Returns `true` if the result is [`Err`].
///
/// # Examples
@ -563,6 +584,27 @@ impl<T, E> Result<T, E> {
!self.is_ok()
}
/// Returns `true` if the result is [`Err`] wrapping a value matching the predicate.
///
/// # Examples
///
/// ```
/// let x: Result<u32, &str> = Err("abc");
/// assert_eq!(x.is_err_with(|x| x.len() > 1), true);
///
/// let x: Result<u32, &str> = Err("");
/// assert_eq!(x.is_ok_with(|x| x.len() > 1), false);
///
/// let x: Result<u32, &str> = Ok(123);
/// assert_eq!(x.is_ok_with(|x| x.len() > 1), false);
/// ```
#[must_use]
#[inline]
#[unstable(feature = "is_some_with", issue = "none")]
pub fn is_err_with(&self, f: impl FnOnce(&E) -> bool) -> bool {
matches!(self, Err(x) if f(x))
}
/////////////////////////////////////////////////////////////////////////
// Adapter for each variant
/////////////////////////////////////////////////////////////////////////