Skip to content

Commit 2fab321

Browse files
committed
Auto merge of #79134 - ohadravid:nzint-div, r=dtolnay
Add `impl Div<NonZeroU{0}> for u{0}` which cannot panic Dividing an unsigned int by a `NonZeroUxx` requires a user to write (for example, in [this SO question](https://stackoverflow.com/questions/64855738/how-to-inform-the-optimizer-that-nonzerou32get-will-never-return-zero)): ``` pub fn safe_div(x: u32, y: std::num::NonZeroU32) -> u32 { x / y.get() } ``` which generates a panicking-checked-div [assembly](https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:rust,selection:(endColumn:2,endLineNumber:6,positionColumn:2,positionLineNumber:6,selectionStartColumn:2,selectionStartLineNumber:6,startColumn:2,startLineNumber:6),source:%27pub+fn+div(x:+u32,+y:+u32)+-%3E+u32+%7B%0A++++x+/+y%0A%7D%0Apub+fn+safe_div(x:+u32,+y:+std::num::NonZeroU32)+-%3E+u32+%7B%0A++++x+/+y.get()+//+an+unchecked+division+expected%0A%7D%27),l:%275%27,n:%270%27,o:%27Rust+source+%231%27,t:%270%27)),k:50,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:compiler,i:(compiler:r1470,filters:(b:%270%27,binary:%271%27,commentOnly:%270%27,demangle:%270%27,directives:%270%27,execute:%271%27,intel:%270%27,libraryCode:%271%27,trim:%271%27),fontScale:14,j:1,lang:rust,libs:!(),options:%27-O%27,selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:%275%27,n:%270%27,o:%27rustc+1.47.0+(Editor+%231,+Compiler+%231)+Rust%27,t:%270%27)),k:50,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27)),l:%272%27,n:%270%27,o:%27%27,t:%270%27)),version:4). Avoiding the `panic` currently requires `unsafe` code. This PR adds an `impl Div<NonZeroU{0}> for u{0}` (and `impl Rem<NonZeroU{0}> for u{0}`) which calls the `unchecked_div` (and `unchecked_rem`) intrinsic without any additional checks, making the following code compile: ``` pub fn safe_div(x: u32, y: std::num::NonZeroU32) -> u32 { x / y } pub fn safe_rem(x: u32, y: std::num::NonZeroU32) -> u32 { x % y } ``` The doc is set to match the regular div impl [docs](https://doc.rust-lang.org/beta/src/core/ops/arith.rs.html#460). I've marked these as stable because (as I understand it) trait impls are automatically stable. I'm happy to change it to unstable if needed. Following `@dtolnay` template from a similar issue: this adds the following **stable** impls, which rely on dividing unsigned integers by nonzero integers being well defined and previously would have involved unsafe code to encode that knowledge: ``` impl Div<NonZeroU8> for u8 { type Output = u8; } impl Rem<NonZeroU8> for u8 { type Output = u8; } ``` and equivalent for u16, u32, u64, u128, usize, but **not** for i8, i16, i32, i64, i128, isize (since -1/MIN is undefined). r? `@dtolnay`
2 parents dc6121c + 9586643 commit 2fab321

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-1
lines changed

library/core/src/num/nonzero.rs

+41-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, Rem};
55
use crate::str::FromStr;
66

77
use super::from_str_radix;
@@ -263,3 +263,43 @@ 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.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+
}

library/core/tests/nonzero.rs

+16
Original file line numberDiff line numberDiff line change
@@ -312,3 +312,19 @@ 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+
}
323+
324+
#[test]
325+
fn test_nonzero_uint_rem() {
326+
let nz = NonZeroU32::new(10).unwrap();
327+
328+
let x: u32 = 42u32 % nz;
329+
assert_eq!(x, 2u32);
330+
}

0 commit comments

Comments
 (0)