Constify bool::then{,_some}

This commit is contained in:
Deadbeef 2021-12-15 00:11:23 +08:00
parent 404c8471ab
commit 4f4b2c7271
No known key found for this signature in database
GPG key ID: 6D017A96D8E6C2F9
3 changed files with 26 additions and 2 deletions

View file

@ -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 }
}
}

View file

@ -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));
}

View file

@ -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)]