Skip to content

Commit 2b85548

Browse files
committed
TryFrom<integer> for bool
1 parent d661299 commit 2b85548

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

358+
// integer -> bool
359+
impl_try_from_integer_for_bool!(u128 u64 u32 u16 u8);
360+
impl_try_from_integer_for_bool!(i128 i64 i32 i16 i8);
361+
336362
// unsigned integer -> unsigned integer
337363
impl_try_from_upper_bounded!(u16 => u8);
338364
impl_try_from_upper_bounded!(u32 => u8, u16);

0 commit comments

Comments
 (0)