Skip to content

Commit aaebae9

Browse files
committed
Add Result::{is_ok_with, is_err_with}.
1 parent 282224e commit aaebae9

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Diff for: library/core/src/result.rs

+42
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,27 @@ impl<T, E> Result<T, E> {
542542
matches!(*self, Ok(_))
543543
}
544544

545+
/// Returns `true` if the result is [`Ok`] wrapping a value matching the predicate.
546+
///
547+
/// # Examples
548+
///
549+
/// ```
550+
/// let x: Result<u32, &str> = Ok(2);
551+
/// assert_eq!(x.is_ok_with(|x| x > 1), true);
552+
///
553+
/// let x: Result<u32, &str> = Ok(0);
554+
/// assert_eq!(x.is_ok_with(|x| x > 1), false);
555+
///
556+
/// let x: Result<u32, &str> = Err("hey");
557+
/// assert_eq!(x.is_ok_with(|x| x > 1), false);
558+
/// ```
559+
#[must_use]
560+
#[inline]
561+
#[unstable(feature = "is_some_with", issue = "none")]
562+
pub fn is_ok_with(&self, f: impl FnOnce(&T) -> bool) -> bool {
563+
matches!(self, Ok(x) if f(x))
564+
}
565+
545566
/// Returns `true` if the result is [`Err`].
546567
///
547568
/// # Examples
@@ -563,6 +584,27 @@ impl<T, E> Result<T, E> {
563584
!self.is_ok()
564585
}
565586

587+
/// Returns `true` if the result is [`Err`] wrapping a value matching the predicate.
588+
///
589+
/// # Examples
590+
///
591+
/// ```
592+
/// let x: Result<u32, &str> = Err("abc");
593+
/// assert_eq!(x.is_err_with(|x| x.len() > 1), true);
594+
///
595+
/// let x: Result<u32, &str> = Err("");
596+
/// assert_eq!(x.is_ok_with(|x| x.len() > 1), false);
597+
///
598+
/// let x: Result<u32, &str> = Ok(123);
599+
/// assert_eq!(x.is_ok_with(|x| x.len() > 1), false);
600+
/// ```
601+
#[must_use]
602+
#[inline]
603+
#[unstable(feature = "is_some_with", issue = "none")]
604+
pub fn is_err_with(&self, f: impl FnOnce(&E) -> bool) -> bool {
605+
matches!(self, Err(x) if f(x))
606+
}
607+
566608
/////////////////////////////////////////////////////////////////////////
567609
// Adapter for each variant
568610
/////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)