diff options
| -rw-r--r-- | library/core/src/bool.rs | 13 | ||||
| -rw-r--r-- | library/core/tests/bool.rs | 14 | ||||
| -rw-r--r-- | 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 f14c2a46416..d5119d0b7c3 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<T>(self, t: T) -> Option<T> { + pub const fn then_some<T>(self, t: T) -> Option<T> + 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, F: FnOnce() -> T>(self, f: F) -> Option<T> { + pub const fn then<T, F>(self, f: F) -> Option<T> + 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 e40f0482aee..4819ce911d6 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<i32> = false.then_some(0); + const B: Option<i32> = true.then_some(0); + const C: Option<i32> = false.then(zero); + const D: Option<i32> = 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 b41d3e09df8..dacb33619f8 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)] |
