Skip to content

Commit

Permalink
Constify bool::then{,_some}
Browse files Browse the repository at this point in the history
  • Loading branch information
fee1-dead committed Dec 14, 2021
1 parent 404c847 commit 4f4b2c7
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
13 changes: 11 additions & 2 deletions library/core/src/bool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}

Expand All @@ -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 }
}
}
14 changes: 14 additions & 0 deletions library/core/tests/bool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
1 change: 1 addition & 0 deletions library/core/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down

0 comments on commit 4f4b2c7

Please sign in to comment.