From 4f4b2c7271d3090b6b63bf1ce8373a47b5b30d86 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Wed, 15 Dec 2021 00:11:23 +0800 Subject: [PATCH] Constify `bool::then{,_some}` --- library/core/src/bool.rs | 13 +++++++++++-- library/core/tests/bool.rs | 14 ++++++++++++++ library/core/tests/lib.rs | 1 + 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/library/core/src/bool.rs b/library/core/src/bool.rs index f14c2a4641627..d5119d0b7c328 100644 --- a/library/core/src/bool.rs +++ b/library/core/src/bool.rs @@ -14,8 +14,12 @@ impl bool { /// assert_eq!(true.then_some(0), Some(0)); /// ``` #[unstable(feature = "bool_to_option", issue = "80967")] + #[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")] #[inline] - pub fn then_some(self, t: T) -> Option { + pub const fn then_some(self, t: T) -> Option + where + T: ~const Drop, + { if self { Some(t) } else { None } } @@ -29,8 +33,13 @@ impl bool { /// assert_eq!(true.then(|| 0), Some(0)); /// ``` #[stable(feature = "lazy_bool_to_option", since = "1.50.0")] + #[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")] #[inline] - pub fn then T>(self, f: F) -> Option { + pub const fn then(self, f: F) -> Option + where + F: ~const FnOnce() -> T, + F: ~const Drop, + { if self { Some(f()) } else { None } } } diff --git a/library/core/tests/bool.rs b/library/core/tests/bool.rs index e40f0482aee3e..4819ce911d618 100644 --- a/library/core/tests/bool.rs +++ b/library/core/tests/bool.rs @@ -88,4 +88,18 @@ fn test_bool_to_option() { assert_eq!(true.then_some(0), Some(0)); assert_eq!(false.then(|| 0), None); assert_eq!(true.then(|| 0), Some(0)); + + const fn zero() -> i32 { + 0 + } + + const A: Option = false.then_some(0); + const B: Option = true.then_some(0); + const C: Option = false.then(zero); + const D: Option = true.then(zero); + + assert_eq!(A, None); + assert_eq!(B, Some(0)); + assert_eq!(C, None); + assert_eq!(D, Some(0)); } diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index b41d3e09df876..dacb33619f8c3 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -8,6 +8,7 @@ #![feature(cfg_panic)] #![feature(cfg_target_has_atomic)] #![feature(const_assume)] +#![feature(const_bool_to_option)] #![feature(const_cell_into_inner)] #![feature(const_convert)] #![feature(const_maybe_uninit_as_mut_ptr)]