|
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, Rem}; |
5 | 5 | use crate::str::FromStr;
|
6 | 6 |
|
7 | 7 | use super::from_str_radix;
|
@@ -263,3 +263,43 @@ 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.51.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 | + #[stable(feature = "nonzero_div", since = "1.51.0")] |
| 284 | + impl Rem<$Ty> for $Int { |
| 285 | + type Output = $Int; |
| 286 | + /// This operation satisfies `n % d == n - (n / d) * d`, and cannot panic. |
| 287 | + #[inline] |
| 288 | + fn rem(self, other: $Ty) -> $Int { |
| 289 | + // SAFETY: rem by zero is checked because `other` is a nonzero, |
| 290 | + // and MIN/-1 is checked because `self` is an unsigned int. |
| 291 | + unsafe { crate::intrinsics::unchecked_rem(self, other.get()) } |
| 292 | + } |
| 293 | + } |
| 294 | + )+ |
| 295 | + } |
| 296 | +} |
| 297 | + |
| 298 | +nonzero_integers_div! { |
| 299 | + NonZeroU8(u8); |
| 300 | + NonZeroU16(u16); |
| 301 | + NonZeroU32(u32); |
| 302 | + NonZeroU64(u64); |
| 303 | + NonZeroU128(u128); |
| 304 | + NonZeroUsize(usize); |
| 305 | +} |
0 commit comments