Skip to content

Commit 2a70839

Browse files
Rollup merge of rust-lang#128103 - folkertdev:unsigned-int-is-multiple-of, r=Amanieu
add `is_multiple_of` for unsigned integer types tracking issue: rust-lang#128101 This adds the `.is_multiple_of` method on unsigned integers. Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise. This function is equivalent to `self % rhs == 0`, except that it will not panic for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`, `n.is_multiple_of(0) == false`.
2 parents 058f1d3 + 6cabb65 commit 2a70839

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

core/src/num/uint_macros.rs

+29
Original file line numberDiff line numberDiff line change
@@ -2853,6 +2853,35 @@ macro_rules! uint_impl {
28532853
}
28542854
}
28552855

2856+
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
2857+
///
2858+
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
2859+
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
2860+
/// `n.is_multiple_of(0) == false`.
2861+
///
2862+
/// # Examples
2863+
///
2864+
/// Basic usage:
2865+
///
2866+
/// ```
2867+
/// #![feature(unsigned_is_multiple_of)]
2868+
#[doc = concat!("assert!(6_", stringify!($SelfT), ".is_multiple_of(2));")]
2869+
#[doc = concat!("assert!(!5_", stringify!($SelfT), ".is_multiple_of(2));")]
2870+
///
2871+
#[doc = concat!("assert!(0_", stringify!($SelfT), ".is_multiple_of(0));")]
2872+
#[doc = concat!("assert!(!6_", stringify!($SelfT), ".is_multiple_of(0));")]
2873+
/// ```
2874+
#[unstable(feature = "unsigned_is_multiple_of", issue = "128101")]
2875+
#[must_use]
2876+
#[inline]
2877+
#[rustc_inherit_overflow_checks]
2878+
pub const fn is_multiple_of(self, rhs: Self) -> bool {
2879+
match rhs {
2880+
0 => self == 0,
2881+
_ => self % rhs == 0,
2882+
}
2883+
}
2884+
28562885
/// Returns `true` if and only if `self == 2^k` for some `k`.
28572886
///
28582887
/// # Examples

core/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
#![feature(num_midpoint)]
6060
#![feature(offset_of_nested)]
6161
#![feature(isqrt)]
62+
#![feature(unsigned_is_multiple_of)]
6263
#![feature(step_trait)]
6364
#![feature(str_internals)]
6465
#![feature(std_internals)]

core/tests/num/uint_macros.rs

+8
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,14 @@ macro_rules! uint_module {
260260
assert_eq!(MAX.checked_next_multiple_of(2), None);
261261
}
262262

263+
#[test]
264+
fn test_is_next_multiple_of() {
265+
assert!((12 as $T).is_multiple_of(4));
266+
assert!(!(12 as $T).is_multiple_of(5));
267+
assert!((0 as $T).is_multiple_of(0));
268+
assert!(!(12 as $T).is_multiple_of(0));
269+
}
270+
263271
#[test]
264272
fn test_carrying_add() {
265273
assert_eq!($T::MAX.carrying_add(1, false), (0, true));

0 commit comments

Comments
 (0)