diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 8adfb6f4bcf52..611f4ab38ab33 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -551,6 +551,29 @@ impl Option { matches!(*self, Some(_)) } + /// Returns `true` if the option is a [`Some`] wrapping a value matching the predicate. + /// + /// # Examples + /// + /// ``` + /// #![feature(is_some_with)] + /// + /// let x: Option = Some(2); + /// assert_eq!(x.is_some_with(|&x| x > 1), true); + /// + /// let x: Option = Some(0); + /// assert_eq!(x.is_some_with(|&x| x > 1), false); + /// + /// let x: Option = None; + /// assert_eq!(x.is_some_with(|&x| x > 1), false); + /// ``` + #[must_use] + #[inline] + #[unstable(feature = "is_some_with", issue = "93050")] + pub fn is_some_with(&self, f: impl FnOnce(&T) -> bool) -> bool { + matches!(self, Some(x) if f(x)) + } + /// Returns `true` if the option is a [`None`] value. /// /// # Examples diff --git a/library/core/src/result.rs b/library/core/src/result.rs index b8f0d84746cce..fbd6d419236ae 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -542,6 +542,29 @@ impl Result { matches!(*self, Ok(_)) } + /// Returns `true` if the result is [`Ok`] wrapping a value matching the predicate. + /// + /// # Examples + /// + /// ``` + /// #![feature(is_some_with)] + /// + /// let x: Result = Ok(2); + /// assert_eq!(x.is_ok_with(|&x| x > 1), true); + /// + /// let x: Result = Ok(0); + /// assert_eq!(x.is_ok_with(|&x| x > 1), false); + /// + /// let x: Result = Err("hey"); + /// assert_eq!(x.is_ok_with(|&x| x > 1), false); + /// ``` + #[must_use] + #[inline] + #[unstable(feature = "is_some_with", issue = "93050")] + 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 +586,30 @@ impl Result { !self.is_ok() } + /// Returns `true` if the result is [`Err`] wrapping a value matching the predicate. + /// + /// # Examples + /// + /// ``` + /// #![feature(is_some_with)] + /// use std::io::{Error, ErrorKind}; + /// + /// let x: Result = Err(Error::new(ErrorKind::NotFound, "!")); + /// assert_eq!(x.is_err_with(|x| x.kind() == ErrorKind::NotFound), true); + /// + /// let x: Result = Err(Error::new(ErrorKind::PermissionDenied, "!")); + /// assert_eq!(x.is_err_with(|x| x.kind() == ErrorKind::NotFound), false); + /// + /// let x: Result = Ok(123); + /// assert_eq!(x.is_err_with(|x| x.kind() == ErrorKind::NotFound), false); + /// ``` + #[must_use] + #[inline] + #[unstable(feature = "is_some_with", issue = "93050")] + pub fn is_err_with(&self, f: impl FnOnce(&E) -> bool) -> bool { + matches!(self, Err(x) if f(x)) + } + ///////////////////////////////////////////////////////////////////////// // Adapter for each variant /////////////////////////////////////////////////////////////////////////