Skip to content

Commit 3f671bc

Browse files
committed
Added impl Div<NonZeroU{0}> for u{0} which cannot panic
1 parent caeb333 commit 3f671bc

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

Diff for: library/core/src/num/nonzero.rs

+29-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Definitions of integer that is known not to equal zero.
22
33
use crate::fmt;
4-
use crate::ops::{BitOr, BitOrAssign};
4+
use crate::ops::{BitOr, BitOrAssign, Div};
55
use crate::str::FromStr;
66

77
use 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+
}

Diff for: library/core/tests/nonzero.rs

+8
Original file line numberDiff line numberDiff 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+
}

0 commit comments

Comments
 (0)