Skip to content

Commit 6cabb65

Browse files
committed
add is_multiple_of for unsigned integer types
1 parent 7ae76f0 commit 6cabb65

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
@@ -2764,6 +2764,35 @@ macro_rules! uint_impl {
27642764
}
27652765
}
27662766

2767+
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
2768+
///
2769+
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
2770+
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
2771+
/// `n.is_multiple_of(0) == false`.
2772+
///
2773+
/// # Examples
2774+
///
2775+
/// Basic usage:
2776+
///
2777+
/// ```
2778+
/// #![feature(unsigned_is_multiple_of)]
2779+
#[doc = concat!("assert!(6_", stringify!($SelfT), ".is_multiple_of(2));")]
2780+
#[doc = concat!("assert!(!5_", stringify!($SelfT), ".is_multiple_of(2));")]
2781+
///
2782+
#[doc = concat!("assert!(0_", stringify!($SelfT), ".is_multiple_of(0));")]
2783+
#[doc = concat!("assert!(!6_", stringify!($SelfT), ".is_multiple_of(0));")]
2784+
/// ```
2785+
#[unstable(feature = "unsigned_is_multiple_of", issue = "128101")]
2786+
#[must_use]
2787+
#[inline]
2788+
#[rustc_inherit_overflow_checks]
2789+
pub const fn is_multiple_of(self, rhs: Self) -> bool {
2790+
match rhs {
2791+
0 => self == 0,
2792+
_ => self % rhs == 0,
2793+
}
2794+
}
2795+
27672796
/// Returns `true` if and only if `self == 2^k` for some `k`.
27682797
///
27692798
/// # Examples

core/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
#![feature(num_midpoint)]
6262
#![feature(offset_of_nested)]
6363
#![feature(isqrt)]
64+
#![feature(unsigned_is_multiple_of)]
6465
#![feature(step_trait)]
6566
#![feature(str_internals)]
6667
#![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)