@@ -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+
330362macro_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
337373impl_try_from_upper_bounded ! ( u16 => u8 ) ;
338374impl_try_from_upper_bounded ! ( u32 => u8 , u16 ) ;
0 commit comments