constify boolean methods
This commit is contained in:
parent
081c4c6abb
commit
207dcbbe7c
2 changed files with 17 additions and 8 deletions
|
|
@ -1,5 +1,7 @@
|
|||
//! impl bool {}
|
||||
|
||||
use crate::marker::Destruct;
|
||||
|
||||
impl bool {
|
||||
/// Returns `Some(t)` if the `bool` is [`true`](../std/keyword.true.html),
|
||||
/// or `None` otherwise.
|
||||
|
|
@ -29,8 +31,9 @@ impl bool {
|
|||
/// assert_eq!(a, 2);
|
||||
/// ```
|
||||
#[stable(feature = "bool_to_option", since = "1.62.0")]
|
||||
#[rustc_const_unstable(feature = "const_bool", issue = "151531")]
|
||||
#[inline]
|
||||
pub fn then_some<T>(self, t: T) -> Option<T> {
|
||||
pub const fn then_some<T: [const] Destruct>(self, t: T) -> Option<T> {
|
||||
if self { Some(t) } else { None }
|
||||
}
|
||||
|
||||
|
|
@ -57,8 +60,9 @@ impl bool {
|
|||
#[doc(alias = "then_with")]
|
||||
#[stable(feature = "lazy_bool_to_option", since = "1.50.0")]
|
||||
#[rustc_diagnostic_item = "bool_then"]
|
||||
#[rustc_const_unstable(feature = "const_bool", issue = "151531")]
|
||||
#[inline]
|
||||
pub fn then<T, F: FnOnce() -> T>(self, f: F) -> Option<T> {
|
||||
pub const fn then<T, F: [const] FnOnce() -> T + [const] Destruct>(self, f: F) -> Option<T> {
|
||||
if self { Some(f()) } else { None }
|
||||
}
|
||||
|
||||
|
|
@ -94,8 +98,9 @@ impl bool {
|
|||
/// assert_eq!(a, 2);
|
||||
/// ```
|
||||
#[unstable(feature = "bool_to_result", issue = "142748")]
|
||||
#[rustc_const_unstable(feature = "const_bool", issue = "151531")]
|
||||
#[inline]
|
||||
pub fn ok_or<E>(self, err: E) -> Result<(), E> {
|
||||
pub const fn ok_or<E: [const] Destruct>(self, err: E) -> Result<(), E> {
|
||||
if self { Ok(()) } else { Err(err) }
|
||||
}
|
||||
|
||||
|
|
@ -124,8 +129,12 @@ impl bool {
|
|||
/// assert_eq!(a, 1);
|
||||
/// ```
|
||||
#[unstable(feature = "bool_to_result", issue = "142748")]
|
||||
#[rustc_const_unstable(feature = "const_bool", issue = "151531")]
|
||||
#[inline]
|
||||
pub fn ok_or_else<E, F: FnOnce() -> E>(self, f: F) -> Result<(), E> {
|
||||
pub const fn ok_or_else<E, F: [const] FnOnce() -> E + [const] Destruct>(
|
||||
self,
|
||||
f: F,
|
||||
) -> Result<(), E> {
|
||||
if self { Ok(()) } else { Err(f()) }
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -82,6 +82,10 @@ pub fn test_bool_not() {
|
|||
}
|
||||
}
|
||||
|
||||
const fn zero() -> i32 {
|
||||
0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bool_to_option() {
|
||||
assert_eq!(false.then_some(0), None);
|
||||
|
|
@ -89,10 +93,6 @@ fn test_bool_to_option() {
|
|||
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);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue