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 @@ -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+
330352macro_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
337363impl_try_from_upper_bounded ! ( u16 => u8 ) ;
338364impl_try_from_upper_bounded ! ( u32 => u8 , u16 ) ;
You can’t perform that action at this time.
0 commit comments