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    /// Computes the absolute value of `self`. Returns a tuple of the absolute version of `self`
87    /// along with a boolean indicating whether an overflow happened.
88    fn overflowing_abs(self) -> (Self, bool);
89
90    /// Calculates `self + rhs` with an unsigned `rhs`. Returns a tuple of the addition along with
91    /// a boolean indicating whether an arithmetic overflow would occur.
92    fn overflowing_add_unsigned(self, rhs: Self::Unsigned) -> (Self, bool);
93
94    /// Calculates `self - rhs` with an unsigned `rhs`. Returns a tuple of the subtraction along
95    /// with a boolean indicating whether an arithmetic overflow would occur.
96    fn overflowing_sub_unsigned(self, rhs: Self::Unsigned) -> (Self, bool);
97
98    /// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self == MIN` instead
99    /// of overflowing.
100    fn saturating_abs(self) -> Self;
101
102    /// Saturating addition with an unsigned integer. Computes `self + rhs`, saturating at the
103    /// numeric bounds instead of overflowing.
104    fn saturating_add_unsigned(self, rhs: Self::Unsigned) -> Self;
105
106    /// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN` instead of
107    /// overflowing.
108    fn saturating_neg(self) -> Self;
109
110    /// Saturating subtraction with an unsigned integer. Computes `self - rhs`, saturating at the
111    /// numeric bounds instead of overflowing.
112    fn saturating_sub_unsigned(self, rhs: Self::Unsigned) -> Self;
113
114    /// Returns a number representing sign of `self`.
115    fn signum(self) -> Self;
116
117    /// Strict absolute value. Computes `self.abs()`, panicking if `self == MIN`.
118    fn strict_abs(self) -> Self;
119
120    /// Strict addition with an unsigned integer. Computes `self + rhs`,
121    /// panicking if overflow occurred.
122    fn strict_add_unsigned(self, rhs: Self::Unsigned) -> Self;
123
124    /// Strict subtraction with an unsigned integer. Computes `self - rhs`,
125    /// panicking if overflow occurred.
126    fn strict_sub_unsigned(self, rhs: Self::Unsigned) -> Self;
127
128    /// Computes the absolute value of `self` without any wrapping or panicking.
129    fn unsigned_abs(self) -> Self::Unsigned;
130
131    /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at the boundary
132    /// of the type.
133    fn wrapping_abs(self) -> Self;
134
135    /// Wrapping (modular) addition with an unsigned integer. Computes `self + rhs`, wrapping
136    /// around at the boundary of the type.
137    fn wrapping_add_unsigned(self, rhs: Self::Unsigned) -> Self;
138
139    /// Wrapping (modular) subtraction with an unsigned integer. Computes `self - rhs`, wrapping
140    /// around at the boundary of the type.
141    fn wrapping_sub_unsigned(self, rhs: Self::Unsigned) -> Self;
142}
143
144/// Trait for references to primitive signed integer types ([`PrimitiveSigned`]).
145///
146/// This enables traits like the standard operators in generic code,
147/// e.g. `where &T: PrimitiveSignedRef<T>`.
148pub trait PrimitiveSignedRef<T>: PrimitiveIntegerRef<T> + core::ops::Neg<Output = T> {}
149
150macro_rules! impl_signed {
151    ($Signed:ident, $Unsigned:ty) => {
152        impl PrimitiveSigned for $Signed {
153            type Unsigned = $Unsigned;
154
155            forward! {
156                fn abs(self) -> Self;
157                fn abs_diff(self, other: Self) -> Self::Unsigned;
158                fn cast_unsigned(self) -> Self::Unsigned;
159                fn checked_abs(self) -> Option<Self>;
160                fn checked_add_unsigned(self, rhs: Self::Unsigned) -> Option<Self>;
161                fn checked_isqrt(self) -> Option<Self>;
162                fn checked_sub_unsigned(self, rhs: Self::Unsigned) -> Option<Self>;
163                fn is_negative(self) -> bool;
164                fn is_positive(self) -> bool;
165                fn overflowing_abs(self) -> (Self, bool);
166                fn overflowing_add_unsigned(self, rhs: Self::Unsigned) -> (Self, bool);
167                fn overflowing_sub_unsigned(self, rhs: Self::Unsigned) -> (Self, bool);
168                fn saturating_abs(self) -> Self;
169                fn saturating_add_unsigned(self, rhs: Self::Unsigned) -> Self;
170                fn saturating_neg(self) -> Self;
171                fn saturating_sub_unsigned(self, rhs: Self::Unsigned) -> Self;
172                fn signum(self) -> Self;
173                fn strict_abs(self) -> Self;
174                fn strict_add_unsigned(self, rhs: Self::Unsigned) -> Self;
175                fn strict_sub_unsigned(self, rhs: Self::Unsigned) -> Self;
176                fn unsigned_abs(self) -> Self::Unsigned;
177                fn wrapping_abs(self) -> Self;
178                fn wrapping_add_unsigned(self, rhs: Self::Unsigned) -> Self;
179                fn wrapping_sub_unsigned(self, rhs: Self::Unsigned) -> Self;
180            }
181        }
182
183        impl PrimitiveSignedRef<$Signed> for &$Signed {}
184    };
185}
186
187impl_signed!(i8, u8);
188impl_signed!(i16, u16);
189impl_signed!(i32, u32);
190impl_signed!(i64, u64);
191impl_signed!(i128, u128);
192impl_signed!(isize, usize);