Skip to content

Commit 13fb051

Browse files
authored
Rollup merge of #91918 - fee1-dead:constification0-the-great-constification-begins, r=oli-obk
Constify `bool::then{,_some}` Note on `~const Drop`: it has no effect when called from runtime functions, when called from const contexts, the trait system ensures that the type can be dropped in const contexts.
2 parents 99f4458 + 4f4b2c7 commit 13fb051

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

library/core/src/bool.rs

+11-2
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,12 @@ impl bool {
1414
/// assert_eq!(true.then_some(0), Some(0));
1515
/// ```
1616
#[unstable(feature = "bool_to_option", issue = "80967")]
17+
#[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")]
1718
#[inline]
18-
pub fn then_some<T>(self, t: T) -> Option<T> {
19+
pub const fn then_some<T>(self, t: T) -> Option<T>
20+
where
21+
T: ~const Drop,
22+
{
1923
if self { Some(t) } else { None }
2024
}
2125

@@ -29,8 +33,13 @@ impl bool {
2933
/// assert_eq!(true.then(|| 0), Some(0));
3034
/// ```
3135
#[stable(feature = "lazy_bool_to_option", since = "1.50.0")]
36+
#[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")]
3237
#[inline]
33-
pub fn then<T, F: FnOnce() -> T>(self, f: F) -> Option<T> {
38+
pub const fn then<T, F>(self, f: F) -> Option<T>
39+
where
40+
F: ~const FnOnce() -> T,
41+
F: ~const Drop,
42+
{
3443
if self { Some(f()) } else { None }
3544
}
3645
}

library/core/tests/bool.rs

+14
Original file line numberDiff line numberDiff line change
@@ -88,4 +88,18 @@ fn test_bool_to_option() {
8888
assert_eq!(true.then_some(0), Some(0));
8989
assert_eq!(false.then(|| 0), None);
9090
assert_eq!(true.then(|| 0), Some(0));
91+
92+
const fn zero() -> i32 {
93+
0
94+
}
95+
96+
const A: Option<i32> = false.then_some(0);
97+
const B: Option<i32> = true.then_some(0);
98+
const C: Option<i32> = false.then(zero);
99+
const D: Option<i32> = true.then(zero);
100+
101+
assert_eq!(A, None);
102+
assert_eq!(B, Some(0));
103+
assert_eq!(C, None);
104+
assert_eq!(D, Some(0));
91105
}

library/core/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#![feature(cfg_panic)]
99
#![feature(cfg_target_has_atomic)]
1010
#![feature(const_assume)]
11+
#![feature(const_bool_to_option)]
1112
#![feature(const_cell_into_inner)]
1213
#![feature(const_convert)]
1314
#![feature(const_maybe_uninit_as_mut_ptr)]

0 commit comments

Comments
 (0)