File tree Expand file tree Collapse file tree 2 files changed +37
-1
lines changed Expand file tree Collapse file tree 2 files changed +37
-1
lines changed Original file line number Diff line number Diff line change 11//! Definitions of integer that is known not to equal zero.
22
33use crate :: fmt;
4- use crate :: ops:: { BitOr , BitOrAssign } ;
4+ use crate :: ops:: { BitOr , BitOrAssign , Div } ;
55use crate :: str:: FromStr ;
66
77use super :: from_str_radix;
@@ -263,3 +263,31 @@ nonzero_leading_trailing_zeros! {
263263 NonZeroI128 ( u128 ) , -1i128 ;
264264 NonZeroIsize ( usize ) , -1isize ;
265265}
266+
267+ macro_rules! nonzero_integers_div {
268+ ( $( $Ty: ident( $Int: ty) ; ) + ) => {
269+ $(
270+ #[ stable( feature = "nonzero_div" , since = "1.50.0" ) ]
271+ impl Div <$Ty> for $Int {
272+ type Output = $Int;
273+ /// This operation rounds towards zero,
274+ /// truncating any fractional part of the exact result, and cannot panic.
275+ #[ inline]
276+ fn div( self , other: $Ty) -> $Int {
277+ // SAFETY: div by zero is checked because `other` is a nonzero,
278+ // and MIN/-1 is checked because `self` is an unsigned int.
279+ unsafe { crate :: intrinsics:: unchecked_div( self , other. get( ) ) }
280+ }
281+ }
282+ ) +
283+ }
284+ }
285+
286+ nonzero_integers_div ! {
287+ NonZeroU8 ( u8 ) ;
288+ NonZeroU16 ( u16 ) ;
289+ NonZeroU32 ( u32 ) ;
290+ NonZeroU64 ( u64 ) ;
291+ NonZeroU128 ( u128 ) ;
292+ NonZeroUsize ( usize ) ;
293+ }
Original file line number Diff line number Diff line change @@ -312,3 +312,11 @@ fn nonzero_trailing_zeros() {
312312 const TRAILING_ZEROS : u32 = NonZeroU16 :: new ( 1 << 2 ) . unwrap ( ) . trailing_zeros ( ) ;
313313 assert_eq ! ( TRAILING_ZEROS , 2 ) ;
314314}
315+
316+ #[ test]
317+ fn test_nonzero_uint_div ( ) {
318+ let nz = NonZeroU32 :: new ( 1 ) . unwrap ( ) ;
319+
320+ let x: u32 = 42u32 / nz;
321+ assert_eq ! ( x, 42u32 ) ;
322+ }
You can’t perform that action at this time.
0 commit comments