num_primitive/
unsigned.rs

1use crate::{PrimitiveInteger, PrimitiveIntegerRef, PrimitiveSigned};
2
3/// Trait for all primitive [unsigned integer types], including the supertraits
4/// [`PrimitiveInteger`] and [`PrimitiveNumber`][crate::PrimitiveNumber].
5///
6/// This encapsulates trait implementations and inherent methods that are common among all of the
7/// primitive unsigned integer types: [`u8`], [`u16`], [`u32`], [`u64`], [`u128`], and [`usize`].
8///
9/// See the corresponding items on the individual types for more documentation and examples.
10///
11/// This trait is sealed with a private trait to prevent downstream implementations, so we may
12/// continue to expand along with the standard library without worrying about breaking changes for
13/// implementors.
14///
15/// [unsigned integer types]: https://doc.rust-lang.org/reference/types/numeric.html#r-type.numeric.int.unsigned
16///
17/// # Examples
18///
19/// ```
20/// use num_primitive::PrimitiveUnsigned;
21///
22/// // Greatest Common Divisor (Euclidean algorithm)
23/// fn gcd<T: PrimitiveUnsigned>(mut a: T, mut b: T) -> T {
24///     let zero = T::from(0u8);
25///     while b != zero {
26///         (a, b) = (b, a % b);
27///     }
28///     a
29/// }
30///
31/// assert_eq!(gcd::<u8>(48, 18), 6);
32/// assert_eq!(gcd::<u16>(1071, 462), 21);
33/// assert_eq!(gcd::<u32>(6_700_417, 2_147_483_647), 1);
34/// ```
35pub trait PrimitiveUnsigned: PrimitiveInteger + From<u8> {
36    /// The signed integer type used by methods like
37    /// [`checked_add_signed`][Self::checked_add_signed].
38    type Signed: PrimitiveSigned;
39
40    /// Computes the absolute difference between `self` and `other`.
41    fn abs_diff(self, other: Self) -> Self;
42
43    /// Checked addition with a signed integer. Computes `self + rhs`, returning `None` if overflow
44    /// occurred.
45    fn checked_add_signed(self, rhs: Self::Signed) -> Option<Self>;
46
47    /// Calculates the smallest value greater than or equal to `self` that is a multiple of `rhs`.
48    /// Returns `None` if `rhs` is zero or the operation would result in overflow.
49    fn checked_next_multiple_of(self, rhs: Self) -> Option<Self>;
50
51    /// Returns the smallest power of two greater than or equal to `self`. If the next power of two
52    /// is greater than the type's maximum value, `None` is returned, otherwise the power of two is
53    /// wrapped in Some.
54    fn checked_next_power_of_two(self) -> Option<Self>;
55
56    /// Calculates the quotient of `self` and rhs, rounding the result towards positive infinity.
57    fn div_ceil(self, rhs: Self) -> Self;
58
59    /// Returns true if and only if `self == 2^k` for some `k`.
60    fn is_power_of_two(self) -> bool;
61
62    /// Calculates the middle point of `self` and `other`.
63    fn midpoint(self, other: Self) -> Self;
64
65    /// Calculates the smallest value greater than or equal to `self` that is a multiple of `rhs`.
66    fn next_multiple_of(self, rhs: Self) -> Self;
67
68    /// Returns the smallest power of two greater than or equal to `self`.
69    fn next_power_of_two(self) -> Self;
70
71    /// Calculates `self + rhs` with a signed `rhs`. Returns a tuple of the addition along with a
72    /// boolean indicating whether an arithmetic overflow would occur.
73    fn overflowing_add_signed(self, rhs: Self::Signed) -> (Self, bool);
74
75    /// Saturating addition with a signed integer. Computes `self + rhs`, saturating at the numeric
76    /// bounds instead of overflowing.
77    fn saturating_add_signed(self, rhs: Self::Signed) -> Self;
78
79    /// Wrapping (modular) addition with a signed integer. Computes `self + rhs`, wrapping around
80    /// at the boundary of the type.
81    fn wrapping_add_signed(self, rhs: Self::Signed) -> Self;
82}
83
84/// Trait for references to primitive unsigned integer types ([`PrimitiveUnsigned`]).
85///
86/// This enables traits like the standard operators in generic code,
87/// e.g. `where &T: PrimitiveUnsignedRef<T>`.
88pub trait PrimitiveUnsignedRef<T>: PrimitiveIntegerRef<T> {}
89
90macro_rules! impl_unsigned {
91    ($Unsigned:ident, $Signed:ty) => {
92        impl PrimitiveUnsigned for $Unsigned {
93            type Signed = $Signed;
94
95            forward! {
96                fn abs_diff(self, other: Self) -> Self;
97                fn checked_add_signed(self, rhs: Self::Signed) -> Option<Self>;
98                fn checked_next_multiple_of(self, rhs: Self) -> Option<Self>;
99                fn checked_next_power_of_two(self) -> Option<Self>;
100                fn div_ceil(self, rhs: Self) -> Self;
101                fn is_power_of_two(self) -> bool;
102                fn midpoint(self, other: Self) -> Self;
103                fn next_multiple_of(self, rhs: Self) -> Self;
104                fn next_power_of_two(self) -> Self;
105                fn overflowing_add_signed(self, rhs: Self::Signed) -> (Self, bool);
106                fn saturating_add_signed(self, rhs: Self::Signed) -> Self;
107                fn wrapping_add_signed(self, rhs: Self::Signed) -> Self;
108            }
109        }
110
111        impl PrimitiveUnsignedRef<$Unsigned> for &$Unsigned {}
112    };
113}
114
115impl_unsigned!(u8, i8);
116impl_unsigned!(u16, i16);
117impl_unsigned!(u32, i32);
118impl_unsigned!(u64, i64);
119impl_unsigned!(u128, i128);
120impl_unsigned!(usize, isize);