about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMara Bos <m-ou.se@m-ou.se>2022-01-18 22:17:44 +0100
committerMara Bos <m-ou.se@m-ou.se>2022-01-18 22:17:44 +0100
commitaaebae973f7a4fafd24cb6c9fad7a6beba205b74 (patch)
treeeb7cb061ee9a6bf8e956e9439787122c7d59956c
parent282224edf19fb8a511c5a9e279f18b804ff61b25 (diff)
downloadrust-aaebae973f7a4fafd24cb6c9fad7a6beba205b74.tar.gz
rust-aaebae973f7a4fafd24cb6c9fad7a6beba205b74.zip
Add Result::{is_ok_with, is_err_with}.
-rw-r--r--library/core/src/result.rs42
1 files changed, 42 insertions, 0 deletions
diff --git a/library/core/src/result.rs b/library/core/src/result.rs
index b8f0d84746c..f4f3d84e62b 100644
--- a/library/core/src/result.rs
+++ b/library/core/src/result.rs
@@ -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
     /////////////////////////////////////////////////////////////////////////