Skip to content

Commit 4c3b591

Browse files
committed
TryFrom<integer> for bool
1 parent 0f38395 commit 4c3b591

File tree

1 file changed

+26
-0
lines changed
  • library/core/src/convert

1 file changed

+26
-0
lines changed

library/core/src/convert/num.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,12 +330,38 @@ macro_rules! impl_try_from_both_bounded {
330330
)*}
331331
}
332332

333+
/// Implement `TryFrom<integer>` for `bool`
334+
macro_rules! impl_try_from_integer_for_bool {
335+
($($source:ty)+) => {$(
336+
#[stable(feature = "try_from", since = "1.34.0")]
337+
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
338+
impl const TryFrom<$source> for bool {
339+
type Error = TryFromIntError;
340+
341+
/// Tries to create a bool from a source number type.
342+
/// Returns an error if the source value is not 0 or 1.
343+
#[inline]
344+
fn try_from(i: $source) -> Result<Self, Self::Error> {
345+
match i {
346+
0 => Ok(false),
347+
1 => Ok(true),
348+
_ => Err(TryFromIntError(())),
349+
}
350+
}
351+
}
352+
)*}
353+
}
354+
333355
macro_rules! rev {
334356
($mac:ident, $source:ty => $($target:ty),+) => {$(
335357
$mac!($target => $source);
336358
)*}
337359
}
338360

361+
// integer -> bool
362+
impl_try_from_integer_for_bool!(u128 u64 u32 u16 u8);
363+
impl_try_from_integer_for_bool!(i128 i64 i32 i16 i8);
364+
339365
// unsigned integer -> unsigned integer
340366
impl_try_from_upper_bounded!(u16 => u8);
341367
impl_try_from_upper_bounded!(u32 => u8, u16);

0 commit comments

Comments
 (0)