File tree 2 files changed +37
-1
lines changed
2 files changed +37
-1
lines changed Original file line number Diff line number Diff line change 1
1
//! Definitions of integer that is known not to equal zero.
2
2
3
3
use crate :: fmt;
4
- use crate :: ops:: { BitOr , BitOrAssign } ;
4
+ use crate :: ops:: { BitOr , BitOrAssign , Div } ;
5
5
use crate :: str:: FromStr ;
6
6
7
7
use super :: from_str_radix;
@@ -263,3 +263,31 @@ nonzero_leading_trailing_zeros! {
263
263
NonZeroI128 ( u128 ) , -1i128 ;
264
264
NonZeroIsize ( usize ) , -1isize ;
265
265
}
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() {
312
312
const TRAILING_ZEROS : u32 = NonZeroU16 :: new ( 1 << 2 ) . unwrap ( ) . trailing_zeros ( ) ;
313
313
assert_eq ! ( TRAILING_ZEROS , 2 ) ;
314
314
}
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