Skip to content

Commit b73e32c

Browse files
committed
Add bool::then and bool::then_with
1 parent f0386a1 commit b73e32c

File tree

3 files changed

+50
-1
lines changed

3 files changed

+50
-1
lines changed

src/libcore/bool/mod.rs

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,44 @@
44

55
#[cfg(not(boostrap_stdarch_ignore_this))]
66
#[lang = "bool"]
7-
impl bool {}
7+
impl bool {
8+
/// Returns `Some(t)` if the `bool` is `true`, or `None` otherwise.
9+
///
10+
/// # Examples
11+
///
12+
/// ```
13+
/// #![feature(bool_to_option)]
14+
///
15+
/// assert_eq!(false.then(0), None);
16+
/// assert_eq!(true.then(0), Some(0));
17+
/// ```
18+
#[unstable(feature = "bool_to_option", issue = "0")]
19+
#[inline]
20+
pub fn then<T>(self, t: T) -> Option<T> {
21+
if self {
22+
Some(t)
23+
} else {
24+
None
25+
}
26+
}
27+
28+
/// Returns `Some(f())` if the `bool` is `true`, or `None` otherwise.
29+
///
30+
/// # Examples
31+
///
32+
/// ```
33+
/// #![feature(bool_to_option)]
34+
///
35+
/// assert_eq!(false.then_with(|| 0), None);
36+
/// assert_eq!(true.then_with(|| 0), Some(0));
37+
/// ```
38+
#[unstable(feature = "bool_to_option", issue = "0")]
39+
#[inline]
40+
pub fn then_with<T, F: FnOnce() -> T>(self, f: F) -> Option<T> {
41+
if self {
42+
Some(f())
43+
} else {
44+
None
45+
}
46+
}
47+
}

src/libcore/tests/bool.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#[test]
2+
fn test_bool_to_option() {
3+
assert_eq!(false.then(0), None);
4+
assert_eq!(true.then(0), Some(0));
5+
assert_eq!(false.then_with(|| 0), None);
6+
assert_eq!(true.then_with(|| 0), Some(0));
7+
}

src/libcore/tests/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#![feature(bool_to_option)]
12
#![feature(bound_cloned)]
23
#![feature(box_syntax)]
34
#![feature(cell_update)]
@@ -40,6 +41,7 @@ mod any;
4041
mod array;
4142
mod ascii;
4243
mod atomic;
44+
mod bool;
4345
mod cell;
4446
mod char;
4547
mod clone;

0 commit comments

Comments
 (0)