Skip to content

Commit

Permalink
Added impl Rem<NonZeroU{0}> for u{0} which cannot panic
Browse files Browse the repository at this point in the history
  • Loading branch information
ohadravid committed Dec 17, 2020
1 parent 3f671bc commit 1e9e30d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
14 changes: 13 additions & 1 deletion library/core/src/num/nonzero.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Definitions of integer that is known not to equal zero.

use crate::fmt;
use crate::ops::{BitOr, BitOrAssign, Div};
use crate::ops::{BitOr, BitOrAssign, Div, Rem};
use crate::str::FromStr;

use super::from_str_radix;
Expand Down Expand Up @@ -279,6 +279,18 @@ macro_rules! nonzero_integers_div {
unsafe { crate::intrinsics::unchecked_div(self, other.get()) }
}
}

#[stable(feature = "nonzero_div", since = "1.50.0")]
impl Rem<$Ty> for $Int {
type Output = $Int;
/// This operation satisfies `n % d == n - (n / d) * d`, and cannot panic.
#[inline]
fn rem(self, other: $Ty) -> $Int {
// SAFETY: rem by zero is checked because `other` is a nonzero,
// and MIN/-1 is checked because `self` is an unsigned int.
unsafe { crate::intrinsics::unchecked_rem(self, other.get()) }
}
}
)+
}
}
Expand Down
8 changes: 8 additions & 0 deletions library/core/tests/nonzero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,3 +320,11 @@ fn test_nonzero_uint_div() {
let x: u32 = 42u32 / nz;
assert_eq!(x, 42u32);
}

#[test]
fn test_nonzero_uint_rem() {
let nz = NonZeroU32::new(10).unwrap();

let x: u32 = 42u32 % nz;
assert_eq!(x, 2u32);
}

0 comments on commit 1e9e30d

Please sign in to comment.