Added impl Div<NonZeroU{0}> for u{0} which cannot panic

This commit is contained in:
Ohad Ravid 2020-11-16 15:38:22 +02:00
parent caeb3335c0
commit 3f671bc944
2 changed files with 37 additions and 1 deletions

View File

@ -1,7 +1,7 @@
//! Definitions of integer that is known not to equal zero.
use crate::fmt;
use crate::ops::{BitOr, BitOrAssign};
use crate::ops::{BitOr, BitOrAssign, Div};
use crate::str::FromStr;
use super::from_str_radix;
@ -263,3 +263,31 @@ nonzero_leading_trailing_zeros! {
NonZeroI128(u128), -1i128;
NonZeroIsize(usize), -1isize;
}
macro_rules! nonzero_integers_div {
( $( $Ty: ident($Int: ty); )+ ) => {
$(
#[stable(feature = "nonzero_div", since = "1.50.0")]
impl Div<$Ty> for $Int {
type Output = $Int;
/// This operation rounds towards zero,
/// truncating any fractional part of the exact result, and cannot panic.
#[inline]
fn div(self, other: $Ty) -> $Int {
// SAFETY: div by zero is checked because `other` is a nonzero,
// and MIN/-1 is checked because `self` is an unsigned int.
unsafe { crate::intrinsics::unchecked_div(self, other.get()) }
}
}
)+
}
}
nonzero_integers_div! {
NonZeroU8(u8);
NonZeroU16(u16);
NonZeroU32(u32);
NonZeroU64(u64);
NonZeroU128(u128);
NonZeroUsize(usize);
}

View File

@ -312,3 +312,11 @@ fn nonzero_trailing_zeros() {
const TRAILING_ZEROS: u32 = NonZeroU16::new(1 << 2).unwrap().trailing_zeros();
assert_eq!(TRAILING_ZEROS, 2);
}
#[test]
fn test_nonzero_uint_div() {
let nz = NonZeroU32::new(1).unwrap();
let x: u32 = 42u32 / nz;
assert_eq!(x, 42u32);
}