TryFrom<integer> for bool

This commit is contained in:
Marijn Schouten 2025-10-06 16:27:02 +00:00
parent 163a4b4caf
commit f12288ec26
2 changed files with 37 additions and 1 deletions

View file

@ -327,12 +327,48 @@ macro_rules! impl_try_from_both_bounded {
)*}
}
/// Implement `TryFrom<integer>` for `bool`
macro_rules! impl_try_from_integer_for_bool {
($($int:ty)+) => {$(
#[stable(feature = "try_from", since = "1.34.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
impl const TryFrom<$int> for bool {
type Error = TryFromIntError;
/// Tries to create a bool from an integer type.
/// Returns an error if the integer is not 0 or 1.
///
/// # Examples
///
/// ```
#[doc = concat!("assert_eq!(0_", stringify!($int), ".try_into(), Ok(false));")]
///
#[doc = concat!("assert_eq!(1_", stringify!($int), ".try_into(), Ok(true));")]
///
#[doc = concat!("assert!(<", stringify!($int), " as TryInto<bool>>::try_into(2).is_err());")]
/// ```
#[inline]
fn try_from(i: $int) -> Result<Self, Self::Error> {
match i {
0 => Ok(false),
1 => Ok(true),
_ => Err(TryFromIntError(())),
}
}
}
)*}
}
macro_rules! rev {
($mac:ident, $source:ty => $($target:ty),+) => {$(
$mac!($target => $source);
)*}
}
// integer -> bool
impl_try_from_integer_for_bool!(u128 u64 u32 u16 u8);
impl_try_from_integer_for_bool!(i128 i64 i32 i16 i8);
// unsigned integer -> unsigned integer
impl_try_from_upper_bounded!(u16 => u8);
impl_try_from_upper_bounded!(u32 => u8, u16);

View file

@ -22,7 +22,7 @@ help: the following other types implement trait `From<T>`
::: $SRC_DIR/core/src/ascii/ascii_char.rs:LL:COL
|
= note: in this macro invocation
= 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)
= 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)
error[E0277]: the `?` operator can only be used on `Result`s, not `Option`s, in a function that returns `Result`
--> $DIR/bad-interconversion.rs:9:12