File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff 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+
333355macro_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
340366impl_try_from_upper_bounded ! ( u16 => u8 ) ;
341367impl_try_from_upper_bounded ! ( u32 => u8 , u16 ) ;
You can’t perform that action at this time.
0 commit comments