about summary refs log tree commit diff
diff options
context:
space:
mode:
authorOhad Ravid <ohad.rv@gmail.com>2020-11-18 07:48:03 +0200
committerOhad Ravid <ohad.rv@gmail.com>2020-12-17 18:42:19 +0200
commit1e9e30dc404edaec5bf5ef9c1d88157a883da374 (patch)
tree8cba3c982c2b4c42812e47cca8626c462d7e1951
parent3f671bc94450aff38d7fcd9243327a20cb553ee0 (diff)
downloadrust-1e9e30dc404edaec5bf5ef9c1d88157a883da374.tar.gz
rust-1e9e30dc404edaec5bf5ef9c1d88157a883da374.zip
Added `impl Rem<NonZeroU{0}> for u{0}` which cannot panic
-rw-r--r--library/core/src/num/nonzero.rs14
-rw-r--r--library/core/tests/nonzero.rs8
2 files changed, 21 insertions, 1 deletions
diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs
index 3355fb64ecf..e139facb6ea 100644
--- a/library/core/src/num/nonzero.rs
+++ b/library/core/src/num/nonzero.rs
@@ -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;
@@ -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()) }
+                }
+            }
         )+
     }
 }
diff --git a/library/core/tests/nonzero.rs b/library/core/tests/nonzero.rs
index 6ec3a04adc0..c2c08522d0c 100644
--- a/library/core/tests/nonzero.rs
+++ b/library/core/tests/nonzero.rs
@@ -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);
+}