num_primitive/
signed.rs

1use crate::{PrimitiveInteger, PrimitiveIntegerRef, PrimitiveUnsigned};
2
3/// Trait for all primitive [signed integer types], including the supertraits [`PrimitiveInteger`]
4/// and [`PrimitiveNumber`][crate::PrimitiveNumber].
5///
6/// This encapsulates trait implementations and inherent methods that are common among all of the
7/// primitive signed integer types: [`i8`], [`i16`], [`i32`], [`i64`], [`i128`], and [`isize`].
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/// [signed integer types]: https://doc.rust-lang.org/reference/types/numeric.html#r-type.numeric.int.signed
16///
17/// # Examples
18///
19/// ```
20/// use num_primitive::PrimitiveSigned;
21///
22/// // GCD with Bézout coefficients (extended Euclidean algorithm)
23/// fn extended_gcd<T: PrimitiveSigned>(a: T, b: T) -> (T, T, T) {
24///     let zero = T::from(0i8);
25///     let one = T::from(1i8);
26///
27///     let (mut old_r, mut r) = (a, b);
28///     let (mut old_s, mut s) = (one, zero);
29///     let (mut old_t, mut t) = (zero, one);
30///
31///     while r != zero {
32///         let quotient = old_r.div_euclid(r);
33///         (old_r, r) = (r, old_r - quotient * r);
34///         (old_s, s) = (s, old_s - quotient * s);
35///         (old_t, t) = (t, old_t - quotient * t);
36///     }
37///
38///     let (gcd, x, y) = if old_r.is_negative() {
39///         (-old_r, -old_s, -old_t)
40///     } else {
41///         (old_r, old_s, old_t)
42///     };
43///     assert_eq!(gcd, a * x + b * y);
44///     (gcd, x, y)
45/// }
46///
47/// assert_eq!(extended_gcd::<i8>(0, -42), (42, 0, -1));
48/// assert_eq!(extended_gcd::<i8>(48, 18), (6, -1, 3));
49/// assert_eq!(extended_gcd::<i16>(1071, -462), (21, -3, -7));
50/// assert_eq!(extended_gcd::<i64>(6_700_417, 2_147_483_647), (1, 715_828_096, -2_233_473));
51/// ```
52pub trait PrimitiveSigned: PrimitiveInteger + From<i8> + core::ops::Neg<Output = Self> {
53    /// The unsigned integer type used by methods like [`abs_diff`][Self::abs_diff] and
54    /// [`checked_add_unsigned`][Self::checked_add_unsigned].
55    type Unsigned: PrimitiveUnsigned;
56
57    /// Computes the absolute value of `self`.
58    fn abs(self) -> Self;
59
60    /// Computes the absolute difference between `self` and `other`.
61    fn abs_diff(self, other: Self) -> Self::Unsigned;
62
63    /// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
64    fn cast_unsigned(self) -> Self::Unsigned;
65
66    /// Checked absolute value. Computes `self.abs()`, returning `None` if `self == MIN`.
67    fn checked_abs(self) -> Option<Self>;
68
69    /// Checked addition with an unsigned integer. Computes `self + rhs`, returning `None` if
70    /// overflow occurred.
71    fn checked_add_unsigned(self, rhs: Self::Unsigned) -> Option<Self>;
72
73    /// Returns the square root of the number, rounded down. Returns `None` if `self` is negative.
74    fn checked_isqrt(self) -> Option<Self>;
75
76    /// Checked subtraction with an unsigned integer. Computes `self - rhs`, returning `None` if
77    /// overflow occurred.
78    fn checked_sub_unsigned(self, rhs: Self::Unsigned) -> Option<Self>;
79
80    /// Returns true if `self` is negative and false if the number is zero or positive.
81    fn is_negative(self) -> bool;
82
83    /// Returns true if `self` is positive and false if the number is zero or negative.
84    fn is_positive(self) -> bool;
85
86    /// Calculates the middle point of `self` and `other`.
87    fn midpoint(self, other: Self) -> Self;
88
89    /// Computes the absolute value of `self`. Returns a tuple of the absolute version of `self`
90    /// along with a boolean indicating whether an overflow happened.
91    fn overflowing_abs(self) -> (Self, bool);
92
93    /// Calculates `self + rhs` with an unsigned `rhs`. Returns a tuple of the addition along with
94    /// a boolean indicating whether an arithmetic overflow would occur.
95    fn overflowing_add_unsigned(self, rhs: Self::Unsigned) -> (Self, bool);
96
97    /// Calculates `self - rhs` with an unsigned `rhs`. Returns a tuple of the subtraction along
98    /// with a boolean indicating whether an arithmetic overflow would occur.
99    fn overflowing_sub_unsigned(self, rhs: Self::Unsigned) -> (Self, bool);
100
101    /// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self == MIN` instead
102    /// of overflowing.
103    fn saturating_abs(self) -> Self;
104
105    /// Saturating addition with an unsigned integer. Computes `self + rhs`, saturating at the
106    /// numeric bounds instead of overflowing.
107    fn saturating_add_unsigned(self, rhs: Self::Unsigned) -> Self;
108
109    /// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN` instead of
110    /// overflowing.
111    fn saturating_neg(self) -> Self;
112
113    /// Saturating subtraction with an unsigned integer. Computes `self - rhs`, saturating at the
114    /// numeric bounds instead of overflowing.
115    fn saturating_sub_unsigned(self, rhs: Self::Unsigned) -> Self;
116
117    /// Returns a number representing sign of `self`.
118    fn signum(self) -> Self;
119
120    /// Computes the absolute value of `self` without any wrapping or panicking.
121    fn unsigned_abs(self) -> Self::Unsigned;
122
123    /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at the boundary
124    /// of the type.
125    fn wrapping_abs(self) -> Self;
126
127    /// Wrapping (modular) addition with an unsigned integer. Computes `self + rhs`, wrapping
128    /// around at the boundary of the type.
129    fn wrapping_add_unsigned(self, rhs: Self::Unsigned) -> Self;
130
131    /// Wrapping (modular) subtraction with an unsigned integer. Computes `self - rhs`, wrapping
132    /// around at the boundary of the type.
133    fn wrapping_sub_unsigned(self, rhs: Self::Unsigned) -> Self;
134}
135
136/// Trait for references to primitive signed integer types ([`PrimitiveSigned`]).
137///
138/// This enables traits like the standard operators in generic code,
139/// e.g. `where &T: PrimitiveSignedRef<T>`.
140pub trait PrimitiveSignedRef<T>: PrimitiveIntegerRef<T> + core::ops::Neg<Output = T> {}
141
142macro_rules! impl_signed {
143    ($Signed:ident, $Unsigned:ty) => {
144        impl PrimitiveSigned for $Signed {
145            type Unsigned = $Unsigned;
146
147            forward! {
148                fn abs(self) -> Self;
149                fn abs_diff(self, other: Self) -> Self::Unsigned;
150                fn cast_unsigned(self) -> Self::Unsigned;
151                fn checked_abs(self) -> Option<Self>;
152                fn checked_add_unsigned(self, rhs: Self::Unsigned) -> Option<Self>;
153                fn checked_isqrt(self) -> Option<Self>;
154                fn checked_sub_unsigned(self, rhs: Self::Unsigned) -> Option<Self>;
155                fn is_negative(self) -> bool;
156                fn is_positive(self) -> bool;
157                fn midpoint(self, other: Self) -> Self;
158                fn overflowing_abs(self) -> (Self, bool);
159                fn overflowing_add_unsigned(self, rhs: Self::Unsigned) -> (Self, bool);
160                fn overflowing_sub_unsigned(self, rhs: Self::Unsigned) -> (Self, bool);
161                fn saturating_abs(self) -> Self;
162                fn saturating_add_unsigned(self, rhs: Self::Unsigned) -> Self;
163                fn saturating_neg(self) -> Self;
164                fn saturating_sub_unsigned(self, rhs: Self::Unsigned) -> Self;
165                fn signum(self) -> Self;
166                fn unsigned_abs(self) -> Self::Unsigned;
167                fn wrapping_abs(self) -> Self;
168                fn wrapping_add_unsigned(self, rhs: Self::Unsigned) -> Self;
169                fn wrapping_sub_unsigned(self, rhs: Self::Unsigned) -> Self;
170            }
171        }
172
173        impl PrimitiveSignedRef<$Signed> for &$Signed {}
174    };
175}
176
177impl_signed!(i8, u8);
178impl_signed!(i16, u16);
179impl_signed!(i32, u32);
180impl_signed!(i64, u64);
181impl_signed!(i128, u128);
182impl_signed!(isize, usize);