From b482e06e29c3e92fa9b817a33c53de672115f30e Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 12 Jun 2024 15:19:40 +0200 Subject: [PATCH] add is_none_or --- core/src/option.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/core/src/option.rs b/core/src/option.rs index e253cfd2822be..d90b9cdb4b5c8 100644 --- a/core/src/option.rs +++ b/core/src/option.rs @@ -654,6 +654,32 @@ impl Option { !self.is_some() } + /// Returns `true` if the option is a [`None`] or the value inside of it matches a predicate. + /// + /// # Examples + /// + /// ``` + /// #![feature(is_none_or)] + /// + /// let x: Option = Some(2); + /// assert_eq!(x.is_none_or(|x| x > 1), true); + /// + /// let x: Option = Some(0); + /// assert_eq!(x.is_none_or(|x| x > 1), false); + /// + /// let x: Option = None; + /// assert_eq!(x.is_none_or(|x| x > 1), true); + /// ``` + #[must_use] + #[inline] + #[unstable(feature = "is_none_or", issue = "none")] + pub fn is_none_or(self, f: impl FnOnce(T) -> bool) -> bool { + match self { + None => true, + Some(x) => f(x), + } + } + ///////////////////////////////////////////////////////////////////////// // Adapter for working with references /////////////////////////////////////////////////////////////////////////