Skip to content

Commit f12288e

Browse files
committed
TryFrom<integer> for bool
1 parent 163a4b4 commit f12288e

2 files changed

Lines changed: 37 additions & 1 deletion

File tree

library/core/src/convert/num.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,12 +327,48 @@ macro_rules! impl_try_from_both_bounded {
327327
)*}
328328
}
329329

330+
/// Implement `TryFrom<integer>` for `bool`
331+
macro_rules! impl_try_from_integer_for_bool {
332+
($($int:ty)+) => {$(
333+
#[stable(feature = "try_from", since = "1.34.0")]
334+
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
335+
impl const TryFrom<$int> for bool {
336+
type Error = TryFromIntError;
337+
338+
/// Tries to create a bool from an integer type.
339+
/// Returns an error if the integer is not 0 or 1.
340+
///
341+
/// # Examples
342+
///
343+
/// ```
344+
#[doc = concat!("assert_eq!(0_", stringify!($int), ".try_into(), Ok(false));")]
345+
///
346+
#[doc = concat!("assert_eq!(1_", stringify!($int), ".try_into(), Ok(true));")]
347+
///
348+
#[doc = concat!("assert!(<", stringify!($int), " as TryInto<bool>>::try_into(2).is_err());")]
349+
/// ```
350+
#[inline]
351+
fn try_from(i: $int) -> Result<Self, Self::Error> {
352+
match i {
353+
0 => Ok(false),
354+
1 => Ok(true),
355+
_ => Err(TryFromIntError(())),
356+
}
357+
}
358+
}
359+
)*}
360+
}
361+
330362
macro_rules! rev {
331363
($mac:ident, $source:ty => $($target:ty),+) => {$(
332364
$mac!($target => $source);
333365
)*}
334366
}
335367

368+
// integer -> bool
369+
impl_try_from_integer_for_bool!(u128 u64 u32 u16 u8);
370+
impl_try_from_integer_for_bool!(i128 i64 i32 i16 i8);
371+
336372
// unsigned integer -> unsigned integer
337373
impl_try_from_upper_bounded!(u16 => u8);
338374
impl_try_from_upper_bounded!(u32 => u8, u16);

tests/ui/try-trait/bad-interconversion.stderr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ help: the following other types implement trait `From<T>`
2222
::: $SRC_DIR/core/src/ascii/ascii_char.rs:LL:COL
2323
|
2424
= note: in this macro invocation
25-
= note: this error originates in the macro `impl_from` which comes from the expansion of the macro `into_int_impl` (in Nightly builds, run with -Z macro-backtrace for more info)
25+
= note: this error originates in the macro `impl_from_bool` which comes from the expansion of the macro `into_int_impl` (in Nightly builds, run with -Z macro-backtrace for more info)
2626

2727
error[E0277]: the `?` operator can only be used on `Result`s, not `Option`s, in a function that returns `Result`
2828
--> $DIR/bad-interconversion.rs:9:12

0 commit comments

Comments
 (0)