Skip to main content

num_primitive/
integer.rs

1use core::num::{NonZero, ParseIntError, TryFromIntError};
2
3use crate::{PrimitiveError, PrimitiveNumber, PrimitiveNumberRef};
4
5trait NonZeroSealed {}
6
7/// Trait for all primitive [integer types], including the supertrait [`PrimitiveNumber`].
8///
9/// This encapsulates trait implementations, constants, and inherent methods that are common among
10/// all of the primitive integer types: [`i8`], [`i16`], [`i32`], [`i64`], [`i128`], [`isize`],
11/// [`u8`], [`u16`], [`u32`], [`u64`], [`u128`], and [`usize`].
12///
13/// See the corresponding items on the individual types for more documentation and examples.
14///
15/// This trait is sealed with a private trait to prevent downstream implementations, so we may
16/// continue to expand along with the standard library without worrying about breaking changes for
17/// implementors.
18///
19/// [integer types]: https://doc.rust-lang.org/reference/types/numeric.html#r-type.numeric.int
20///
21/// # Examples
22///
23/// ```
24/// use num_primitive::PrimitiveInteger;
25///
26/// fn div_rem<T: PrimitiveInteger>(a: T, b: T) -> (T, T) {
27///     (a / b, a % b)
28/// }
29///
30/// fn div_rem_euclid<T: PrimitiveInteger>(a: T, b: T) -> (T, T) {
31///     (a.div_euclid(b), a.rem_euclid(b))
32/// }
33///
34/// assert_eq!(div_rem::<u8>(48, 18), (2, 12));
35/// assert_eq!(div_rem::<i8>(-48, 18), (-2, -12));
36///
37/// assert_eq!(div_rem_euclid::<u8>(48, 18), (2, 12));
38/// assert_eq!(div_rem_euclid::<i8>(-48, 18), (-3, 6));
39/// ```
40///
41pub trait PrimitiveInteger:
42    PrimitiveNumber
43    + core::cmp::Eq
44    + core::cmp::Ord
45    + core::convert::From<Self::NonZero>
46    + core::convert::TryFrom<i8, Error: PrimitiveError>
47    + core::convert::TryFrom<i16, Error: PrimitiveError>
48    + core::convert::TryFrom<i32, Error: PrimitiveError>
49    + core::convert::TryFrom<i64, Error: PrimitiveError>
50    + core::convert::TryFrom<i128, Error: PrimitiveError>
51    + core::convert::TryFrom<isize, Error: PrimitiveError>
52    + core::convert::TryFrom<u8, Error: PrimitiveError>
53    + core::convert::TryFrom<u16, Error: PrimitiveError>
54    + core::convert::TryFrom<u32, Error: PrimitiveError>
55    + core::convert::TryFrom<u64, Error: PrimitiveError>
56    + core::convert::TryFrom<u128, Error: PrimitiveError>
57    + core::convert::TryFrom<usize, Error: PrimitiveError>
58    + core::convert::TryInto<Self::NonZero, Error = TryFromIntError>
59    + core::convert::TryInto<i8, Error: PrimitiveError>
60    + core::convert::TryInto<i16, Error: PrimitiveError>
61    + core::convert::TryInto<i32, Error: PrimitiveError>
62    + core::convert::TryInto<i64, Error: PrimitiveError>
63    + core::convert::TryInto<i128, Error: PrimitiveError>
64    + core::convert::TryInto<isize, Error: PrimitiveError>
65    + core::convert::TryInto<u8, Error: PrimitiveError>
66    + core::convert::TryInto<u16, Error: PrimitiveError>
67    + core::convert::TryInto<u32, Error: PrimitiveError>
68    + core::convert::TryInto<u64, Error: PrimitiveError>
69    + core::convert::TryInto<u128, Error: PrimitiveError>
70    + core::convert::TryInto<usize, Error: PrimitiveError>
71    + core::fmt::Binary
72    + core::fmt::LowerHex
73    + core::fmt::Octal
74    + core::fmt::UpperHex
75    + core::hash::Hash
76    + core::ops::BitAnd<Self, Output = Self>
77    + core::ops::BitAndAssign<Self>
78    + core::ops::BitOr<Self, Output = Self>
79    + core::ops::BitOr<Self::NonZero, Output = Self::NonZero>
80    + core::ops::BitOrAssign<Self>
81    + core::ops::BitXor<Self, Output = Self>
82    + core::ops::BitXorAssign<Self>
83    + core::ops::Not<Output = Self>
84    + core::ops::Shl<Self, Output = Self>
85    + core::ops::Shl<i8, Output = Self>
86    + core::ops::Shl<i16, Output = Self>
87    + core::ops::Shl<i32, Output = Self>
88    + core::ops::Shl<i64, Output = Self>
89    + core::ops::Shl<i128, Output = Self>
90    + core::ops::Shl<isize, Output = Self>
91    + core::ops::Shl<u8, Output = Self>
92    + core::ops::Shl<u16, Output = Self>
93    + core::ops::Shl<u32, Output = Self>
94    + core::ops::Shl<u64, Output = Self>
95    + core::ops::Shl<u128, Output = Self>
96    + core::ops::Shl<usize, Output = Self>
97    + core::ops::ShlAssign<Self>
98    + core::ops::ShlAssign<i8>
99    + core::ops::ShlAssign<i16>
100    + core::ops::ShlAssign<i32>
101    + core::ops::ShlAssign<i64>
102    + core::ops::ShlAssign<i128>
103    + core::ops::ShlAssign<isize>
104    + core::ops::ShlAssign<u8>
105    + core::ops::ShlAssign<u16>
106    + core::ops::ShlAssign<u32>
107    + core::ops::ShlAssign<u64>
108    + core::ops::ShlAssign<u128>
109    + core::ops::ShlAssign<usize>
110    + core::ops::Shr<Self, Output = Self>
111    + core::ops::Shr<i8, Output = Self>
112    + core::ops::Shr<i16, Output = Self>
113    + core::ops::Shr<i32, Output = Self>
114    + core::ops::Shr<i64, Output = Self>
115    + core::ops::Shr<i128, Output = Self>
116    + core::ops::Shr<isize, Output = Self>
117    + core::ops::Shr<u8, Output = Self>
118    + core::ops::Shr<u16, Output = Self>
119    + core::ops::Shr<u32, Output = Self>
120    + core::ops::Shr<u64, Output = Self>
121    + core::ops::Shr<u128, Output = Self>
122    + core::ops::Shr<usize, Output = Self>
123    + core::ops::ShrAssign<Self>
124    + core::ops::ShrAssign<i8>
125    + core::ops::ShrAssign<i16>
126    + core::ops::ShrAssign<i32>
127    + core::ops::ShrAssign<i64>
128    + core::ops::ShrAssign<i128>
129    + core::ops::ShrAssign<isize>
130    + core::ops::ShrAssign<u8>
131    + core::ops::ShrAssign<u16>
132    + core::ops::ShrAssign<u32>
133    + core::ops::ShrAssign<u64>
134    + core::ops::ShrAssign<u128>
135    + core::ops::ShrAssign<usize>
136    + core::str::FromStr<Err = ParseIntError>
137    + for<'a> core::ops::BitAnd<&'a Self, Output = Self>
138    + for<'a> core::ops::BitAndAssign<&'a Self>
139    + for<'a> core::ops::BitOr<&'a Self, Output = Self>
140    + for<'a> core::ops::BitOrAssign<&'a Self>
141    + for<'a> core::ops::BitXor<&'a Self, Output = Self>
142    + for<'a> core::ops::BitXorAssign<&'a Self>
143    + for<'a> core::ops::Shl<&'a Self, Output = Self>
144    + for<'a> core::ops::Shl<&'a i8, Output = Self>
145    + for<'a> core::ops::Shl<&'a i16, Output = Self>
146    + for<'a> core::ops::Shl<&'a i32, Output = Self>
147    + for<'a> core::ops::Shl<&'a i64, Output = Self>
148    + for<'a> core::ops::Shl<&'a i128, Output = Self>
149    + for<'a> core::ops::Shl<&'a isize, Output = Self>
150    + for<'a> core::ops::Shl<&'a u8, Output = Self>
151    + for<'a> core::ops::Shl<&'a u16, Output = Self>
152    + for<'a> core::ops::Shl<&'a u32, Output = Self>
153    + for<'a> core::ops::Shl<&'a u64, Output = Self>
154    + for<'a> core::ops::Shl<&'a u128, Output = Self>
155    + for<'a> core::ops::Shl<&'a usize, Output = Self>
156    + for<'a> core::ops::ShlAssign<&'a Self>
157    + for<'a> core::ops::ShlAssign<&'a i8>
158    + for<'a> core::ops::ShlAssign<&'a i16>
159    + for<'a> core::ops::ShlAssign<&'a i32>
160    + for<'a> core::ops::ShlAssign<&'a i64>
161    + for<'a> core::ops::ShlAssign<&'a i128>
162    + for<'a> core::ops::ShlAssign<&'a isize>
163    + for<'a> core::ops::ShlAssign<&'a u8>
164    + for<'a> core::ops::ShlAssign<&'a u16>
165    + for<'a> core::ops::ShlAssign<&'a u32>
166    + for<'a> core::ops::ShlAssign<&'a u64>
167    + for<'a> core::ops::ShlAssign<&'a u128>
168    + for<'a> core::ops::ShlAssign<&'a usize>
169    + for<'a> core::ops::Shr<&'a Self, Output = Self>
170    + for<'a> core::ops::Shr<&'a i8, Output = Self>
171    + for<'a> core::ops::Shr<&'a i16, Output = Self>
172    + for<'a> core::ops::Shr<&'a i32, Output = Self>
173    + for<'a> core::ops::Shr<&'a i64, Output = Self>
174    + for<'a> core::ops::Shr<&'a i128, Output = Self>
175    + for<'a> core::ops::Shr<&'a isize, Output = Self>
176    + for<'a> core::ops::Shr<&'a u8, Output = Self>
177    + for<'a> core::ops::Shr<&'a u16, Output = Self>
178    + for<'a> core::ops::Shr<&'a u32, Output = Self>
179    + for<'a> core::ops::Shr<&'a u64, Output = Self>
180    + for<'a> core::ops::Shr<&'a u128, Output = Self>
181    + for<'a> core::ops::Shr<&'a usize, Output = Self>
182    + for<'a> core::ops::ShrAssign<&'a Self>
183    + for<'a> core::ops::ShrAssign<&'a i8>
184    + for<'a> core::ops::ShrAssign<&'a i16>
185    + for<'a> core::ops::ShrAssign<&'a i32>
186    + for<'a> core::ops::ShrAssign<&'a i64>
187    + for<'a> core::ops::ShrAssign<&'a i128>
188    + for<'a> core::ops::ShrAssign<&'a isize>
189    + for<'a> core::ops::ShrAssign<&'a u8>
190    + for<'a> core::ops::ShrAssign<&'a u16>
191    + for<'a> core::ops::ShrAssign<&'a u32>
192    + for<'a> core::ops::ShrAssign<&'a u64>
193    + for<'a> core::ops::ShrAssign<&'a u128>
194    + for<'a> core::ops::ShrAssign<&'a usize>
195{
196    /// The non-zero integer type wrapping this primitive integer.
197    ///
198    /// This is always `core::num::NonZero<Self>`.
199    type NonZero: NonZeroPrimitiveInteger<Integer = Self>;
200
201    /// The size of this integer type in bits.
202    const BITS: u32;
203
204    /// The largest value that can be represented by this integer type.
205    const MAX: Self;
206
207    /// The smallest value that can be represented by this integer type.
208    const MIN: Self;
209
210    /// Checked integer addition. Computes `self + rhs`, returning `None` if overflow occurred.
211    fn checked_add(self, rhs: Self) -> Option<Self>;
212
213    /// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0` or the
214    /// division results in overflow.
215    fn checked_div(self, rhs: Self) -> Option<Self>;
216
217    /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None` if `rhs == 0`
218    /// or the division results in overflow.
219    fn checked_div_euclid(self, rhs: Self) -> Option<Self>;
220
221    /// Returns the logarithm of the number with respect to an arbitrary base, rounded down.
222    /// Returns `None` if the number is negative or zero, or if the base is not at least 2.
223    fn checked_ilog(self, base: Self) -> Option<u32>;
224
225    /// Returns the base 10 logarithm of the number, rounded down. Returns `None` if the number is
226    /// negative or zero.
227    fn checked_ilog10(self) -> Option<u32>;
228
229    /// Returns the base 2 logarithm of the number, rounded down. Returns `None` if the number is
230    /// negative or zero.
231    fn checked_ilog2(self) -> Option<u32>;
232
233    /// Checked integer multiplication. Computes `self * rhs`, returning `None` if overflow
234    /// occurred.
235    fn checked_mul(self, rhs: Self) -> Option<Self>;
236
237    /// Checked negation. Computes -self, returning `None` if `self == MIN` for signed integers,
238    /// or for any non-zero unsigned integer.
239    fn checked_neg(self) -> Option<Self>;
240
241    /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if overflow occurred.
242    fn checked_pow(self, exp: u32) -> Option<Self>;
243
244    /// Checked integer remainder. Computes `self % rhs`, returning `None` if `rhs == 0` or the
245    /// division results in overflow.
246    fn checked_rem(self, rhs: Self) -> Option<Self>;
247
248    /// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None` if `rhs ==
249    /// 0` or the division results in overflow.
250    fn checked_rem_euclid(self, rhs: Self) -> Option<Self>;
251
252    /// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger than or
253    /// equal to the number of bits in `self`.
254    fn checked_shl(self, rhs: u32) -> Option<Self>;
255
256    /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is larger than or
257    /// equal to the number of bits in `self`.
258    fn checked_shr(self, rhs: u32) -> Option<Self>;
259
260    /// Checked integer subtraction. Computes `self - rhs`, returning `None` if overflow occurred.
261    fn checked_sub(self, rhs: Self) -> Option<Self>;
262
263    /// Returns the number of ones in the binary representation of `self`.
264    fn count_ones(self) -> u32;
265
266    /// Returns the number of zeros in the binary representation of `self`.
267    fn count_zeros(self) -> u32;
268
269    /// Calculates the quotient of Euclidean division of `self` by `rhs`. This computes the integer
270    /// `q` such that `self = q * rhs + r`, with `r = self.rem_euclid(rhs)` and `0 <= r <
271    /// abs(rhs)`.
272    fn div_euclid(self, rhs: Self) -> Self;
273
274    /// Converts an integer from big endian to the target's endianness.
275    fn from_be(value: Self) -> Self;
276
277    /// Converts an integer from little endian to the target's endianness.
278    fn from_le(value: Self) -> Self;
279
280    /// Parses an integer from a string slice with digits in a given base.
281    fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError>;
282
283    /// Returns the index of the highest bit set to one in `self`, or `None` if `self` is `0`.
284    fn highest_one(self) -> Option<u32>;
285
286    /// Returns the logarithm of the number with respect to an arbitrary base, rounded down.
287    fn ilog(self, base: Self) -> u32;
288
289    /// Returns the base 10 logarithm of the number, rounded down.
290    fn ilog10(self) -> u32;
291
292    /// Returns the base 2 logarithm of the number, rounded down.
293    fn ilog2(self) -> u32;
294
295    /// Returns `self` with only the most significant bit set, or `0` if the input is `0`.
296    fn isolate_highest_one(self) -> Self;
297
298    /// Returns `self` with only the least significant bit set, or `0` if the input is `0`.
299    fn isolate_lowest_one(self) -> Self;
300
301    /// Returns the square root of the number, rounded down.
302    fn isqrt(self) -> Self;
303
304    /// Returns the number of leading ones in the binary representation of `self`.
305    fn leading_ones(self) -> u32;
306
307    /// Returns the number of leading zeros in the binary representation of `self`.
308    fn leading_zeros(self) -> u32;
309
310    /// Returns the index of the lowest bit set to one in `self`, or `None` if `self` is `0`.
311    fn lowest_one(self) -> Option<u32>;
312
313    /// Calculates `self + rhs`. Returns a tuple of the addition along with a boolean indicating
314    /// whether an arithmetic overflow would occur.
315    fn overflowing_add(self, rhs: Self) -> (Self, bool);
316
317    /// Calculates the divisor when `self` is divided by `rhs`. Returns a tuple of the divisor
318    /// along with a boolean indicating whether an arithmetic overflow would occur.
319    fn overflowing_div(self, rhs: Self) -> (Self, bool);
320
321    /// Calculates the quotient of Euclidean division `self`.div_euclid(rhs). Returns a tuple of
322    /// the divisor along with a boolean indicating whether an arithmetic overflow would occur.
323    fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool);
324
325    /// Calculates the multiplication of `self` and `rhs`. Returns a tuple of the multiplication
326    /// along with a boolean indicating whether an arithmetic overflow would occur.
327    fn overflowing_mul(self, rhs: Self) -> (Self, bool);
328
329    /// Negates self, overflowing if this is equal to the minimum value. Returns a tuple of the
330    /// negated version of `self` along with a boolean indicating whether an overflow happened.
331    fn overflowing_neg(self) -> (Self, bool);
332
333    /// Raises `self` to the power of `exp`, using exponentiation by squaring. Returns a tuple of
334    /// the exponentiation along with a bool indicating whether an overflow happened.
335    fn overflowing_pow(self, exp: u32) -> (Self, bool);
336
337    /// Calculates the remainder when `self` is divided by `rhs`. Returns a tuple of the remainder
338    /// after dividing along with a boolean indicating whether an arithmetic overflow would occur.
339    fn overflowing_rem(self, rhs: Self) -> (Self, bool);
340
341    /// Overflowing Euclidean remainder. Calculates `self`.rem_euclid(rhs). Returns a tuple of the
342    /// remainder after dividing along with a boolean indicating whether an arithmetic overflow
343    /// would occur.
344    fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool);
345
346    /// Shifts `self` left by `rhs` bits. Returns a tuple of the shifted version of `self` along
347    /// with a boolean indicating whether the shift value was larger than or equal to the number of
348    /// bits.
349    fn overflowing_shl(self, rhs: u32) -> (Self, bool);
350
351    /// Shifts `self` right by `rhs` bits. Returns a tuple of the shifted version of `self` along
352    /// with a boolean indicating whether the shift value was larger than or equal to the number of
353    /// bits.
354    fn overflowing_shr(self, rhs: u32) -> (Self, bool);
355
356    /// Calculates `self - rhs`. Returns a tuple of the subtraction along with a boolean indicating
357    /// whether an arithmetic overflow would occur.
358    fn overflowing_sub(self, rhs: Self) -> (Self, bool);
359
360    /// Raises `self` to the power of `exp`, using exponentiation by squaring.
361    fn pow(self, exp: u32) -> Self;
362
363    /// Calculates the least nonnegative remainder of `self (mod rhs)`. This is done as if by the
364    /// Euclidean division algorithm – given `r = self.rem_euclid(rhs)`, the result satisfies `self
365    /// = rhs * self.div_euclid(rhs) + r` and `0 <= r < abs(rhs)`.
366    fn rem_euclid(self, rhs: Self) -> Self;
367
368    /// Reverses the order of bits in the integer.
369    fn reverse_bits(self) -> Self;
370
371    /// Shifts the bits to the left by a specified amount, n, wrapping the truncated bits to the
372    /// end of the resulting integer.
373    fn rotate_left(self, n: u32) -> Self;
374
375    /// Shifts the bits to the right by a specified amount, n, wrapping the truncated bits to the
376    /// beginning of the resulting integer.
377    fn rotate_right(self, n: u32) -> Self;
378
379    /// Saturating integer addition. Computes `self + rhs`, saturating at the numeric bounds
380    /// instead of overflowing.
381    fn saturating_add(self, rhs: Self) -> Self;
382
383    /// Saturating integer division. Computes `self / rhs`, saturating at the numeric bounds
384    /// instead of overflowing.
385    fn saturating_div(self, rhs: Self) -> Self;
386
387    /// Saturating integer multiplication. Computes `self * rhs`, saturating at the numeric bounds
388    /// instead of overflowing.
389    fn saturating_mul(self, rhs: Self) -> Self;
390
391    /// Saturating integer exponentiation. Computes `self.pow(exp)`, saturating at the numeric
392    /// bounds instead of overflowing.
393    fn saturating_pow(self, exp: u32) -> Self;
394
395    /// Saturating integer subtraction. Computes `self - rhs`, saturating at the numeric bounds
396    /// instead of overflowing.
397    fn saturating_sub(self, rhs: Self) -> Self;
398
399    /// Strict integer addition. Computes `self + rhs`, panicking if overflow occurred.
400    fn strict_add(self, rhs: Self) -> Self;
401
402    /// Strict integer division. Computes `self / rhs`, panicking if overflow occurred.
403    fn strict_div(self, rhs: Self) -> Self;
404
405    /// Strict Euclidean division. Computes `self.div_euclid(rhs)`, panicking if overflow occurred.
406    fn strict_div_euclid(self, rhs: Self) -> Self;
407
408    /// Strict integer multiplication. Computes `self * rhs`, panicking if overflow occurred.
409    fn strict_mul(self, rhs: Self) -> Self;
410
411    /// Strict negation. Computes `-self`, panicking if `self == MIN` for signed integers,
412    /// or for any non-zero unsigned integer.
413    fn strict_neg(self) -> Self;
414
415    /// Strict exponentiation. Computes `self.pow(exp)`, panicking if overflow occurred.
416    fn strict_pow(self, exp: u32) -> Self;
417
418    /// Strict integer remainder. Computes `self % rhs`, panicking if
419    /// the division results in overflow.
420    fn strict_rem(self, rhs: Self) -> Self;
421
422    /// Strict Euclidean remainder. Computes `self.rem_euclid(rhs)`, panicking if
423    /// the division results in overflow.
424    fn strict_rem_euclid(self, rhs: Self) -> Self;
425
426    /// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
427    /// than or equal to the number of bits in `self`.
428    fn strict_shl(self, rhs: u32) -> Self;
429
430    /// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
431    /// larger than or equal to the number of bits in `self`.
432    fn strict_shr(self, rhs: u32) -> Self;
433
434    /// Strict integer subtraction. Computes `self - rhs`, panicking if overflow occurred.
435    fn strict_sub(self, rhs: Self) -> Self;
436
437    /// Reverses the byte order of the integer.
438    fn swap_bytes(self) -> Self;
439
440    /// Converts `self` to big endian from the target's endianness.
441    fn to_be(self) -> Self;
442
443    /// Converts `self` to little endian from the target's endianness.
444    fn to_le(self) -> Self;
445
446    /// Returns the number of trailing ones in the binary representation of `self`.
447    fn trailing_ones(self) -> u32;
448
449    /// Returns the number of trailing zeros in the binary representation of `self`.
450    fn trailing_zeros(self) -> u32;
451
452    /// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
453    fn unbounded_shl(self, rhs: u32) -> Self;
454
455    /// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
456    fn unbounded_shr(self, rhs: u32) -> Self;
457
458    /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the boundary of the
459    /// type.
460    fn wrapping_add(self, rhs: Self) -> Self;
461
462    /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the boundary of the
463    /// type.
464    fn wrapping_div(self, rhs: Self) -> Self;
465
466    /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`, wrapping around at the
467    /// boundary of the type.
468    fn wrapping_div_euclid(self, rhs: Self) -> Self;
469
470    /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at the boundary
471    /// of the type.
472    fn wrapping_mul(self, rhs: Self) -> Self;
473
474    /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary of the type.
475    fn wrapping_neg(self) -> Self;
476
477    /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`, wrapping around at the
478    /// boundary of the type.
479    fn wrapping_pow(self, exp: u32) -> Self;
480
481    /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the boundary of the
482    /// type.
483    fn wrapping_rem(self, rhs: Self) -> Self;
484
485    /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around at the
486    /// boundary of the type.
487    fn wrapping_rem_euclid(self, rhs: Self) -> Self;
488
489    /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where mask removes any
490    /// high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
491    fn wrapping_shl(self, rhs: u32) -> Self;
492
493    /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where mask removes any
494    /// high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
495    fn wrapping_shr(self, rhs: u32) -> Self;
496
497    /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the boundary of
498    /// the type.
499    fn wrapping_sub(self, rhs: Self) -> Self;
500
501    /// Unchecked integer addition. Computes `self + rhs`, assuming overflow cannot occur.
502    ///
503    /// # Safety
504    ///
505    /// This results in undefined behavior when `self + rhs > Self::MAX` or `self + rhs <
506    /// Self::MIN`, i.e. when [`checked_add`][Self::checked_add] would return `None`.
507    unsafe fn unchecked_add(self, rhs: Self) -> Self;
508
509    /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow cannot occur.
510    ///
511    /// # Safety
512    ///
513    /// This results in undefined behavior when `self * rhs > Self::MAX` or `self * rhs <
514    /// Self::MIN`, i.e. when [`checked_mul`][Self::checked_mul] would return `None`.
515    unsafe fn unchecked_mul(self, rhs: Self) -> Self;
516
517    /// Unchecked shift left. Computes `self << rhs`, assuming that
518    /// `rhs` is less than the number of bits in `self`.
519    ///
520    /// # Safety
521    ///
522    /// This results in undefined behavior if `rhs` is larger than or equal to the number of bits
523    /// in `self`, i.e. when [`checked_shl`][Self::checked_shl] would return `None`.
524    unsafe fn unchecked_shl(self, rhs: u32) -> Self;
525
526    /// Unchecked shift right. Computes `self >> rhs`, assuming that
527    /// `rhs` is less than the number of bits in `self`.
528    ///
529    /// # Safety
530    ///
531    /// This results in undefined behavior if `rhs` is larger than or equal to the number of bits
532    /// in `self`, i.e. when [`checked_shr`][Self::checked_shr] would return `None`.
533    unsafe fn unchecked_shr(self, rhs: u32) -> Self;
534
535    /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow cannot occur.
536    ///
537    /// # Safety
538    ///
539    /// This results in undefined behavior when `self - rhs > Self::MAX` or `self - rhs <
540    /// Self::MIN`, i.e. when [`checked_sub`][Self::checked_sub] would return `None`.
541    unsafe fn unchecked_sub(self, rhs: Self) -> Self;
542}
543
544/// Trait for references to primitive integer types ([`PrimitiveInteger`]).
545///
546/// This enables traits like the standard operators in generic code,
547/// e.g. `where &T: PrimitiveIntegerRef<T>`.
548pub trait PrimitiveIntegerRef<T>:
549    PrimitiveNumberRef<T>
550    + core::cmp::Eq
551    + core::cmp::Ord
552    + core::fmt::Binary
553    + core::fmt::LowerHex
554    + core::fmt::Octal
555    + core::fmt::UpperHex
556    + core::hash::Hash
557    + core::ops::BitAnd<T, Output = T>
558    + core::ops::BitOr<T, Output = T>
559    + core::ops::BitXor<T, Output = T>
560    + core::ops::Not<Output = T>
561    + core::ops::Shl<T, Output = T>
562    + core::ops::Shl<i8, Output = T>
563    + core::ops::Shl<i16, Output = T>
564    + core::ops::Shl<i32, Output = T>
565    + core::ops::Shl<i64, Output = T>
566    + core::ops::Shl<i128, Output = T>
567    + core::ops::Shl<isize, Output = T>
568    + core::ops::Shl<u8, Output = T>
569    + core::ops::Shl<u16, Output = T>
570    + core::ops::Shl<u32, Output = T>
571    + core::ops::Shl<u64, Output = T>
572    + core::ops::Shl<u128, Output = T>
573    + core::ops::Shl<usize, Output = T>
574    + core::ops::Shr<T, Output = T>
575    + core::ops::Shr<i8, Output = T>
576    + core::ops::Shr<i16, Output = T>
577    + core::ops::Shr<i32, Output = T>
578    + core::ops::Shr<i64, Output = T>
579    + core::ops::Shr<i128, Output = T>
580    + core::ops::Shr<isize, Output = T>
581    + core::ops::Shr<u8, Output = T>
582    + core::ops::Shr<u16, Output = T>
583    + core::ops::Shr<u32, Output = T>
584    + core::ops::Shr<u64, Output = T>
585    + core::ops::Shr<u128, Output = T>
586    + core::ops::Shr<usize, Output = T>
587    + for<'a> core::ops::BitAnd<&'a T, Output = T>
588    + for<'a> core::ops::BitOr<&'a T, Output = T>
589    + for<'a> core::ops::BitXor<&'a T, Output = T>
590    + for<'a> core::ops::Shl<&'a T, Output = T>
591    + for<'a> core::ops::Shl<&'a i8, Output = T>
592    + for<'a> core::ops::Shl<&'a i16, Output = T>
593    + for<'a> core::ops::Shl<&'a i32, Output = T>
594    + for<'a> core::ops::Shl<&'a i64, Output = T>
595    + for<'a> core::ops::Shl<&'a i128, Output = T>
596    + for<'a> core::ops::Shl<&'a isize, Output = T>
597    + for<'a> core::ops::Shl<&'a u8, Output = T>
598    + for<'a> core::ops::Shl<&'a u16, Output = T>
599    + for<'a> core::ops::Shl<&'a u32, Output = T>
600    + for<'a> core::ops::Shl<&'a u64, Output = T>
601    + for<'a> core::ops::Shl<&'a u128, Output = T>
602    + for<'a> core::ops::Shl<&'a usize, Output = T>
603    + for<'a> core::ops::Shr<&'a T, Output = T>
604    + for<'a> core::ops::Shr<&'a i8, Output = T>
605    + for<'a> core::ops::Shr<&'a i16, Output = T>
606    + for<'a> core::ops::Shr<&'a i32, Output = T>
607    + for<'a> core::ops::Shr<&'a i64, Output = T>
608    + for<'a> core::ops::Shr<&'a i128, Output = T>
609    + for<'a> core::ops::Shr<&'a isize, Output = T>
610    + for<'a> core::ops::Shr<&'a u8, Output = T>
611    + for<'a> core::ops::Shr<&'a u16, Output = T>
612    + for<'a> core::ops::Shr<&'a u32, Output = T>
613    + for<'a> core::ops::Shr<&'a u64, Output = T>
614    + for<'a> core::ops::Shr<&'a u128, Output = T>
615    + for<'a> core::ops::Shr<&'a usize, Output = T>
616{
617}
618
619/// Trait for [`NonZero`] primitive integers.
620///
621/// This encapsulates trait implementations, constants, and inherent methods that are common among
622/// all of the implementations of `NonZero<T>`, where `T` is a [`PrimitiveInteger`].
623///
624/// See the corresponding items on the individual types for more documentation and examples.
625///
626/// This trait is sealed with a private trait to prevent downstream implementations, so we may
627/// continue to expand along with the standard library without worrying about breaking changes for
628/// implementors.
629///
630/// # Examples
631///
632/// ```
633/// use num_primitive::NonZeroPrimitiveInteger;
634/// use core::num::NonZero;
635///
636/// fn bits_and_zeros<T: NonZeroPrimitiveInteger>(n: T) -> (u32, u32, u32) {
637///     (T::BITS, n.leading_zeros(), n.trailing_zeros())
638/// }
639///
640/// assert_eq!(bits_and_zeros(NonZero::new(0b0010_1000u8).unwrap()), (8, 2, 3));
641/// assert_eq!(bits_and_zeros(NonZero::new(1i64).unwrap()), (64, 63, 0));
642/// ```
643#[expect(private_bounds)]
644pub trait NonZeroPrimitiveInteger:
645    'static
646    + NonZeroSealed
647    + core::cmp::Eq
648    + core::cmp::Ord
649    + core::convert::Into<Self::Integer>
650    + core::convert::TryFrom<Self::Integer, Error = TryFromIntError>
651    + core::convert::TryFrom<NonZero<i8>, Error: PrimitiveError>
652    + core::convert::TryFrom<NonZero<i16>, Error: PrimitiveError>
653    + core::convert::TryFrom<NonZero<i32>, Error: PrimitiveError>
654    + core::convert::TryFrom<NonZero<i64>, Error: PrimitiveError>
655    + core::convert::TryFrom<NonZero<i128>, Error: PrimitiveError>
656    + core::convert::TryFrom<NonZero<isize>, Error: PrimitiveError>
657    + core::convert::TryFrom<NonZero<u8>, Error: PrimitiveError>
658    + core::convert::TryFrom<NonZero<u16>, Error: PrimitiveError>
659    + core::convert::TryFrom<NonZero<u32>, Error: PrimitiveError>
660    + core::convert::TryFrom<NonZero<u64>, Error: PrimitiveError>
661    + core::convert::TryFrom<NonZero<u128>, Error: PrimitiveError>
662    + core::convert::TryFrom<NonZero<usize>, Error: PrimitiveError>
663    + core::convert::TryInto<NonZero<i8>, Error: PrimitiveError>
664    + core::convert::TryInto<NonZero<i16>, Error: PrimitiveError>
665    + core::convert::TryInto<NonZero<i32>, Error: PrimitiveError>
666    + core::convert::TryInto<NonZero<i64>, Error: PrimitiveError>
667    + core::convert::TryInto<NonZero<i128>, Error: PrimitiveError>
668    + core::convert::TryInto<NonZero<isize>, Error: PrimitiveError>
669    + core::convert::TryInto<NonZero<u8>, Error: PrimitiveError>
670    + core::convert::TryInto<NonZero<u16>, Error: PrimitiveError>
671    + core::convert::TryInto<NonZero<u32>, Error: PrimitiveError>
672    + core::convert::TryInto<NonZero<u64>, Error: PrimitiveError>
673    + core::convert::TryInto<NonZero<u128>, Error: PrimitiveError>
674    + core::convert::TryInto<NonZero<usize>, Error: PrimitiveError>
675    + core::fmt::Binary
676    + core::fmt::Debug
677    + core::fmt::Display
678    + core::fmt::LowerExp
679    + core::fmt::LowerHex
680    + core::fmt::Octal
681    + core::fmt::UpperExp
682    + core::fmt::UpperHex
683    + core::hash::Hash
684    + core::marker::Copy
685    + core::marker::Send
686    + core::marker::Sync
687    + core::marker::Unpin
688    + core::ops::BitOr<Self, Output = Self>
689    + core::ops::BitOr<Self::Integer, Output = Self>
690    + core::ops::BitOrAssign<Self>
691    + core::ops::BitOrAssign<Self::Integer>
692    + core::panic::RefUnwindSafe
693    + core::panic::UnwindSafe
694    + core::str::FromStr<Err = ParseIntError>
695{
696    /// The primitive integer type that this non-zero type wraps.
697    ///
698    /// For `core::num::NonZero<T>`, this is `T`.
699    type Integer: PrimitiveInteger<NonZero = Self>;
700
701    /// The size of this non-zero integer type in bits.
702    const BITS: u32;
703
704    /// The largest value that can be represented by this non-zero integer type.
705    const MAX: Self;
706
707    /// The smallest value that can be represented by this non-zero integer type.
708    const MIN: Self;
709
710    /// Multiplies two non-zero integers together. Returns [`None`] on overflow.
711    fn checked_mul(self, other: Self) -> Option<Self>;
712
713    /// Raises non-zero value to an integer power. Returns [`None`] on overflow.
714    fn checked_pow(self, other: u32) -> Option<Self>;
715
716    /// Returns the number of ones in the binary representation of `self`.
717    fn count_ones(self) -> NonZero<u32>;
718
719    /// Returns the contained value as a primitive type.
720    fn get(self) -> Self::Integer;
721
722    /// Returns the index of the highest bit set to one in `self`.
723    fn highest_one(self) -> u32;
724
725    /// Returns `self` with only the most significant bit set.
726    fn isolate_highest_one(self) -> Self;
727
728    /// Returns `self` with only the least significant bit set.
729    fn isolate_lowest_one(self) -> Self;
730
731    /// Returns the number of leading zeros in the binary representation of `self`.
732    fn leading_zeros(self) -> u32;
733
734    /// Returns the index of the lowest bit set to one in `self`.
735    fn lowest_one(self) -> u32;
736
737    /// Creates a non-zero if the given value is not zero.
738    fn new(n: Self::Integer) -> Option<Self>;
739
740    /// Multiplies two non-zero integers together, saturating at the numeric bounds
741    /// instead of overflowing.
742    fn saturating_mul(self, other: Self) -> Self;
743
744    /// Raise non-zero value to an integer power, saturating at the numeric bounds
745    /// instead of overflowing.
746    fn saturating_pow(self, other: u32) -> Self;
747
748    /// Returns the number of trailing zeros in the binary representation of `self`.
749    fn trailing_zeros(self) -> u32;
750
751    /// Creates a non-zero without checking whether the value is non-zero.
752    /// This results in undefined behavior if the value is zero.
753    ///
754    /// # Safety
755    ///
756    /// The value must not be zero.
757    unsafe fn new_unchecked(n: Self::Integer) -> Self;
758}
759
760macro_rules! impl_integer {
761    ($($Integer:ident),*) => {$(
762        impl PrimitiveInteger for $Integer {
763            type NonZero = NonZero<Self>;
764
765            use_consts!(Self::{
766                BITS: u32,
767                MAX: Self,
768                MIN: Self,
769            });
770
771            forward! {
772                fn from_be(value: Self) -> Self;
773                fn from_le(value: Self) -> Self;
774                fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError>;
775            }
776            forward! {
777                fn checked_add(self, rhs: Self) -> Option<Self>;
778                fn checked_div(self, rhs: Self) -> Option<Self>;
779                fn checked_div_euclid(self, rhs: Self) -> Option<Self>;
780                fn checked_ilog(self, base: Self) -> Option<u32>;
781                fn checked_ilog10(self) -> Option<u32>;
782                fn checked_ilog2(self) -> Option<u32>;
783                fn checked_mul(self, rhs: Self) -> Option<Self>;
784                fn checked_neg(self) -> Option<Self>;
785                fn checked_pow(self, exp: u32) -> Option<Self>;
786                fn checked_rem(self, rhs: Self) -> Option<Self>;
787                fn checked_rem_euclid(self, rhs: Self) -> Option<Self>;
788                fn checked_shl(self, rhs: u32) -> Option<Self>;
789                fn checked_shr(self, rhs: u32) -> Option<Self>;
790                fn checked_sub(self, rhs: Self) -> Option<Self>;
791                fn count_ones(self) -> u32;
792                fn count_zeros(self) -> u32;
793                fn div_euclid(self, rhs: Self) -> Self;
794                fn highest_one(self) -> Option<u32>;
795                fn ilog(self, base: Self) -> u32;
796                fn ilog10(self) -> u32;
797                fn ilog2(self) -> u32;
798                fn isolate_highest_one(self) -> Self;
799                fn isolate_lowest_one(self) -> Self;
800                fn isqrt(self) -> Self;
801                fn leading_ones(self) -> u32;
802                fn leading_zeros(self) -> u32;
803                fn lowest_one(self) -> Option<u32>;
804                fn overflowing_add(self, rhs: Self) -> (Self, bool);
805                fn overflowing_div(self, rhs: Self) -> (Self, bool);
806                fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool);
807                fn overflowing_mul(self, rhs: Self) -> (Self, bool);
808                fn overflowing_neg(self) -> (Self, bool);
809                fn overflowing_pow(self, exp: u32) -> (Self, bool);
810                fn overflowing_rem(self, rhs: Self) -> (Self, bool);
811                fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool);
812                fn overflowing_shl(self, rhs: u32) -> (Self, bool);
813                fn overflowing_shr(self, rhs: u32) -> (Self, bool);
814                fn overflowing_sub(self, rhs: Self) -> (Self, bool);
815                fn pow(self, exp: u32) -> Self;
816                fn rem_euclid(self, rhs: Self) -> Self;
817                fn reverse_bits(self) -> Self;
818                fn rotate_left(self, n: u32) -> Self;
819                fn rotate_right(self, n: u32) -> Self;
820                fn saturating_add(self, rhs: Self) -> Self;
821                fn saturating_div(self, rhs: Self) -> Self;
822                fn saturating_mul(self, rhs: Self) -> Self;
823                fn saturating_pow(self, exp: u32) -> Self;
824                fn saturating_sub(self, rhs: Self) -> Self;
825                fn strict_add(self, rhs: Self) -> Self;
826                fn strict_div(self, rhs: Self) -> Self;
827                fn strict_div_euclid(self, rhs: Self) -> Self;
828                fn strict_mul(self, rhs: Self) -> Self;
829                fn strict_neg(self) -> Self;
830                fn strict_pow(self, exp: u32) -> Self;
831                fn strict_rem(self, rhs: Self) -> Self;
832                fn strict_rem_euclid(self, rhs: Self) -> Self;
833                fn strict_shl(self, rhs: u32) -> Self;
834                fn strict_shr(self, rhs: u32) -> Self;
835                fn strict_sub(self, rhs: Self) -> Self;
836                fn swap_bytes(self) -> Self;
837                fn to_be(self) -> Self;
838                fn to_le(self) -> Self;
839                fn trailing_ones(self) -> u32;
840                fn trailing_zeros(self) -> u32;
841                fn unbounded_shl(self, rhs: u32) -> Self;
842                fn unbounded_shr(self, rhs: u32) -> Self;
843                fn wrapping_add(self, rhs: Self) -> Self;
844                fn wrapping_div(self, rhs: Self) -> Self;
845                fn wrapping_div_euclid(self, rhs: Self) -> Self;
846                fn wrapping_mul(self, rhs: Self) -> Self;
847                fn wrapping_neg(self) -> Self;
848                fn wrapping_pow(self, exp: u32) -> Self;
849                fn wrapping_rem(self, rhs: Self) -> Self;
850                fn wrapping_rem_euclid(self, rhs: Self) -> Self;
851                fn wrapping_shl(self, rhs: u32) -> Self;
852                fn wrapping_shr(self, rhs: u32) -> Self;
853                fn wrapping_sub(self, rhs: Self) -> Self;
854            }
855            forward! {
856                unsafe fn unchecked_add(self, rhs: Self) -> Self;
857                unsafe fn unchecked_mul(self, rhs: Self) -> Self;
858                unsafe fn unchecked_shl(self, rhs: u32) -> Self;
859                unsafe fn unchecked_shr(self, rhs: u32) -> Self;
860                unsafe fn unchecked_sub(self, rhs: Self) -> Self;
861            }
862        }
863
864        impl PrimitiveIntegerRef<$Integer> for &$Integer {}
865
866        impl NonZeroSealed for NonZero<$Integer> {}
867
868        impl NonZeroPrimitiveInteger for NonZero<$Integer> {
869            type Integer = $Integer;
870
871            use_consts!(Self::{
872                BITS: u32,
873                MAX: Self,
874                MIN: Self,
875            });
876
877            forward! {
878                fn new(n: Self::Integer) -> Option<Self>;
879            }
880            forward! {
881                fn checked_mul(self, other: Self) -> Option<Self>;
882                fn checked_pow(self, other: u32) -> Option<Self>;
883                fn count_ones(self) -> NonZero<u32>;
884                fn get(self) -> Self::Integer;
885                fn highest_one(self) -> u32;
886                fn isolate_highest_one(self) -> Self;
887                fn isolate_lowest_one(self) -> Self;
888                fn leading_zeros(self) -> u32;
889                fn lowest_one(self) -> u32;
890                fn saturating_mul(self, other: Self) -> Self;
891                fn saturating_pow(self, other: u32) -> Self;
892                fn trailing_zeros(self) -> u32;
893            }
894            forward! {
895                unsafe fn new_unchecked(n: Self::Integer) -> Self;
896            }
897        }
898    )*}
899}
900
901impl_integer!(i8, i16, i32, i64, i128, isize);
902impl_integer!(u8, u16, u32, u64, u128, usize);