Skip to content

Commit fb0bc9f

Browse files
committed
TryFrom<integer> for bool
1 parent 7318d1a commit fb0bc9f

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
@@ -326,12 +326,38 @@ macro_rules! impl_try_from_both_bounded {
326326
)*}
327327
}
328328

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

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

0 commit comments

Comments
 (0)