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 logarithm of the number with respect to an arbitrary base, rounded down.
284    fn ilog(self, base: Self) -> u32;
285
286    /// Returns the base 10 logarithm of the number, rounded down.
287    fn ilog10(self) -> u32;
288
289    /// Returns the base 2 logarithm of the number, rounded down.
290    fn ilog2(self) -> u32;
291
292    /// Returns the square root of the number, rounded down.
293    fn isqrt(self) -> Self;
294
295    /// Returns the number of leading ones in the binary representation of `self`.
296    fn leading_ones(self) -> u32;
297
298    /// Returns the number of leading zeros in the binary representation of `self`.
299    fn leading_zeros(self) -> u32;
300
301    /// Calculates `self + rhs`. Returns a tuple of the addition along with a boolean indicating
302    /// whether an arithmetic overflow would occur.
303    fn overflowing_add(self, rhs: Self) -> (Self, bool);
304
305    /// Calculates the divisor when `self` is divided by `rhs`. Returns a tuple of the divisor
306    /// along with a boolean indicating whether an arithmetic overflow would occur.
307    fn overflowing_div(self, rhs: Self) -> (Self, bool);
308
309    /// Calculates the quotient of Euclidean division `self`.div_euclid(rhs). Returns a tuple of
310    /// the divisor along with a boolean indicating whether an arithmetic overflow would occur.
311    fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool);
312
313    /// Calculates the multiplication of `self` and `rhs`. Returns a tuple of the multiplication
314    /// along with a boolean indicating whether an arithmetic overflow would occur.
315    fn overflowing_mul(self, rhs: Self) -> (Self, bool);
316
317    /// Negates self, overflowing if this is equal to the minimum value. Returns a tuple of the
318    /// negated version of `self` along with a boolean indicating whether an overflow happened.
319    fn overflowing_neg(self) -> (Self, bool);
320
321    /// Raises `self` to the power of `exp`, using exponentiation by squaring. Returns a tuple of
322    /// the exponentiation along with a bool indicating whether an overflow happened.
323    fn overflowing_pow(self, exp: u32) -> (Self, bool);
324
325    /// Calculates the remainder when `self` is divided by `rhs`. Returns a tuple of the remainder
326    /// after dividing along with a boolean indicating whether an arithmetic overflow would occur.
327    fn overflowing_rem(self, rhs: Self) -> (Self, bool);
328
329    /// Overflowing Euclidean remainder. Calculates `self`.rem_euclid(rhs). Returns a tuple of the
330    /// remainder after dividing along with a boolean indicating whether an arithmetic overflow
331    /// would occur.
332    fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool);
333
334    /// Shifts `self` left by `rhs` bits. Returns a tuple of the shifted version of `self` along
335    /// with a boolean indicating whether the shift value was larger than or equal to the number of
336    /// bits.
337    fn overflowing_shl(self, rhs: u32) -> (Self, bool);
338
339    /// Shifts `self` right by `rhs` bits. Returns a tuple of the shifted version of `self` along
340    /// with a boolean indicating whether the shift value was larger than or equal to the number of
341    /// bits.
342    fn overflowing_shr(self, rhs: u32) -> (Self, bool);
343
344    /// Calculates `self - rhs`. Returns a tuple of the subtraction along with a boolean indicating
345    /// whether an arithmetic overflow would occur.
346    fn overflowing_sub(self, rhs: Self) -> (Self, bool);
347
348    /// Raises `self` to the power of `exp`, using exponentiation by squaring.
349    fn pow(self, exp: u32) -> Self;
350
351    /// Calculates the least nonnegative remainder of `self (mod rhs)`. This is done as if by the
352    /// Euclidean division algorithm – given `r = self.rem_euclid(rhs)`, the result satisfies `self
353    /// = rhs * self.div_euclid(rhs) + r` and `0 <= r < abs(rhs)`.
354    fn rem_euclid(self, rhs: Self) -> Self;
355
356    /// Reverses the order of bits in the integer.
357    fn reverse_bits(self) -> Self;
358
359    /// Shifts the bits to the left by a specified amount, n, wrapping the truncated bits to the
360    /// end of the resulting integer.
361    fn rotate_left(self, n: u32) -> Self;
362
363    /// Shifts the bits to the right by a specified amount, n, wrapping the truncated bits to the
364    /// beginning of the resulting integer.
365    fn rotate_right(self, n: u32) -> Self;
366
367    /// Saturating integer addition. Computes `self + rhs`, saturating at the numeric bounds
368    /// instead of overflowing.
369    fn saturating_add(self, rhs: Self) -> Self;
370
371    /// Saturating integer division. Computes `self / rhs`, saturating at the numeric bounds
372    /// instead of overflowing.
373    fn saturating_div(self, rhs: Self) -> Self;
374
375    /// Saturating integer multiplication. Computes `self * rhs`, saturating at the numeric bounds
376    /// instead of overflowing.
377    fn saturating_mul(self, rhs: Self) -> Self;
378
379    /// Saturating integer exponentiation. Computes `self.pow(exp)`, saturating at the numeric
380    /// bounds instead of overflowing.
381    fn saturating_pow(self, exp: u32) -> Self;
382
383    /// Saturating integer subtraction. Computes `self - rhs`, saturating at the numeric bounds
384    /// instead of overflowing.
385    fn saturating_sub(self, rhs: Self) -> Self;
386
387    /// Strict integer addition. Computes `self + rhs`, panicking if overflow occurred.
388    fn strict_add(self, rhs: Self) -> Self;
389
390    /// Strict integer division. Computes `self / rhs`, panicking if overflow occurred.
391    fn strict_div(self, rhs: Self) -> Self;
392
393    /// Strict Euclidean division. Computes `self.div_euclid(rhs)`, panicking if overflow occurred.
394    fn strict_div_euclid(self, rhs: Self) -> Self;
395
396    /// Strict integer multiplication. Computes `self * rhs`, panicking if overflow occurred.
397    fn strict_mul(self, rhs: Self) -> Self;
398
399    /// Strict negation. Computes `-self`, panicking if `self == MIN` for signed integers,
400    /// or for any non-zero unsigned integer.
401    fn strict_neg(self) -> Self;
402
403    /// Strict exponentiation. Computes `self.pow(exp)`, panicking if overflow occurred.
404    fn strict_pow(self, exp: u32) -> Self;
405
406    /// Strict integer remainder. Computes `self % rhs`, panicking if
407    /// the division results in overflow.
408    fn strict_rem(self, rhs: Self) -> Self;
409
410    /// Strict Euclidean remainder. Computes `self.rem_euclid(rhs)`, panicking if
411    /// the division results in overflow.
412    fn strict_rem_euclid(self, rhs: Self) -> Self;
413
414    /// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
415    /// than or equal to the number of bits in `self`.
416    fn strict_shl(self, rhs: u32) -> Self;
417
418    /// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
419    /// larger than or equal to the number of bits in `self`.
420    fn strict_shr(self, rhs: u32) -> Self;
421
422    /// Strict integer subtraction. Computes `self - rhs`, panicking if overflow occurred.
423    fn strict_sub(self, rhs: Self) -> Self;
424
425    /// Reverses the byte order of the integer.
426    fn swap_bytes(self) -> Self;
427
428    /// Converts `self` to big endian from the target's endianness.
429    fn to_be(self) -> Self;
430
431    /// Converts `self` to little endian from the target's endianness.
432    fn to_le(self) -> Self;
433
434    /// Returns the number of trailing ones in the binary representation of `self`.
435    fn trailing_ones(self) -> u32;
436
437    /// Returns the number of trailing zeros in the binary representation of `self`.
438    fn trailing_zeros(self) -> u32;
439
440    /// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
441    fn unbounded_shl(self, rhs: u32) -> Self;
442
443    /// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
444    fn unbounded_shr(self, rhs: u32) -> Self;
445
446    /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the boundary of the
447    /// type.
448    fn wrapping_add(self, rhs: Self) -> Self;
449
450    /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the boundary of the
451    /// type.
452    fn wrapping_div(self, rhs: Self) -> Self;
453
454    /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`, wrapping around at the
455    /// boundary of the type.
456    fn wrapping_div_euclid(self, rhs: Self) -> Self;
457
458    /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at the boundary
459    /// of the type.
460    fn wrapping_mul(self, rhs: Self) -> Self;
461
462    /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary of the type.
463    fn wrapping_neg(self) -> Self;
464
465    /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`, wrapping around at the
466    /// boundary of the type.
467    fn wrapping_pow(self, exp: u32) -> Self;
468
469    /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the boundary of the
470    /// type.
471    fn wrapping_rem(self, rhs: Self) -> Self;
472
473    /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around at the
474    /// boundary of the type.
475    fn wrapping_rem_euclid(self, rhs: Self) -> Self;
476
477    /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where mask removes any
478    /// high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
479    fn wrapping_shl(self, rhs: u32) -> Self;
480
481    /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where mask removes any
482    /// high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
483    fn wrapping_shr(self, rhs: u32) -> Self;
484
485    /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the boundary of
486    /// the type.
487    fn wrapping_sub(self, rhs: Self) -> Self;
488
489    /// Unchecked integer addition. Computes `self + rhs`, assuming overflow cannot occur.
490    ///
491    /// # Safety
492    ///
493    /// This results in undefined behavior when `self + rhs > Self::MAX` or `self + rhs <
494    /// Self::MIN`, i.e. when [`checked_add`][Self::checked_add] would return `None`.
495    unsafe fn unchecked_add(self, rhs: Self) -> Self;
496
497    /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow cannot occur.
498    ///
499    /// # Safety
500    ///
501    /// This results in undefined behavior when `self * rhs > Self::MAX` or `self * rhs <
502    /// Self::MIN`, i.e. when [`checked_mul`][Self::checked_mul] would return `None`.
503    unsafe fn unchecked_mul(self, rhs: Self) -> Self;
504
505    /// Unchecked shift left. Computes `self << rhs`, assuming that
506    /// `rhs` is less than the number of bits in `self`.
507    ///
508    /// # Safety
509    ///
510    /// This results in undefined behavior if `rhs` is larger than or equal to the number of bits
511    /// in `self`, i.e. when [`checked_shl`][Self::checked_shl] would return `None`.
512    unsafe fn unchecked_shl(self, rhs: u32) -> Self;
513
514    /// Unchecked shift right. Computes `self >> rhs`, assuming that
515    /// `rhs` is less than the number of bits in `self`.
516    ///
517    /// # Safety
518    ///
519    /// This results in undefined behavior if `rhs` is larger than or equal to the number of bits
520    /// in `self`, i.e. when [`checked_shr`][Self::checked_shr] would return `None`.
521    unsafe fn unchecked_shr(self, rhs: u32) -> Self;
522
523    /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow cannot occur.
524    ///
525    /// # Safety
526    ///
527    /// This results in undefined behavior when `self - rhs > Self::MAX` or `self - rhs <
528    /// Self::MIN`, i.e. when [`checked_sub`][Self::checked_sub] would return `None`.
529    unsafe fn unchecked_sub(self, rhs: Self) -> Self;
530}
531
532/// Trait for references to primitive integer types ([`PrimitiveInteger`]).
533///
534/// This enables traits like the standard operators in generic code,
535/// e.g. `where &T: PrimitiveIntegerRef<T>`.
536pub trait PrimitiveIntegerRef<T>:
537    PrimitiveNumberRef<T>
538    + core::cmp::Eq
539    + core::cmp::Ord
540    + core::fmt::Binary
541    + core::fmt::LowerHex
542    + core::fmt::Octal
543    + core::fmt::UpperHex
544    + core::hash::Hash
545    + core::ops::BitAnd<T, Output = T>
546    + core::ops::BitOr<T, Output = T>
547    + core::ops::BitXor<T, Output = T>
548    + core::ops::Not<Output = T>
549    + core::ops::Shl<T, Output = T>
550    + core::ops::Shl<i8, Output = T>
551    + core::ops::Shl<i16, Output = T>
552    + core::ops::Shl<i32, Output = T>
553    + core::ops::Shl<i64, Output = T>
554    + core::ops::Shl<i128, Output = T>
555    + core::ops::Shl<isize, Output = T>
556    + core::ops::Shl<u8, Output = T>
557    + core::ops::Shl<u16, Output = T>
558    + core::ops::Shl<u32, Output = T>
559    + core::ops::Shl<u64, Output = T>
560    + core::ops::Shl<u128, Output = T>
561    + core::ops::Shl<usize, Output = T>
562    + core::ops::Shr<T, Output = T>
563    + core::ops::Shr<i8, Output = T>
564    + core::ops::Shr<i16, Output = T>
565    + core::ops::Shr<i32, Output = T>
566    + core::ops::Shr<i64, Output = T>
567    + core::ops::Shr<i128, Output = T>
568    + core::ops::Shr<isize, Output = T>
569    + core::ops::Shr<u8, Output = T>
570    + core::ops::Shr<u16, Output = T>
571    + core::ops::Shr<u32, Output = T>
572    + core::ops::Shr<u64, Output = T>
573    + core::ops::Shr<u128, Output = T>
574    + core::ops::Shr<usize, Output = T>
575    + for<'a> core::ops::BitAnd<&'a T, Output = T>
576    + for<'a> core::ops::BitOr<&'a T, Output = T>
577    + for<'a> core::ops::BitXor<&'a T, Output = T>
578    + for<'a> core::ops::Shl<&'a T, Output = T>
579    + for<'a> core::ops::Shl<&'a i8, Output = T>
580    + for<'a> core::ops::Shl<&'a i16, Output = T>
581    + for<'a> core::ops::Shl<&'a i32, Output = T>
582    + for<'a> core::ops::Shl<&'a i64, Output = T>
583    + for<'a> core::ops::Shl<&'a i128, Output = T>
584    + for<'a> core::ops::Shl<&'a isize, Output = T>
585    + for<'a> core::ops::Shl<&'a u8, Output = T>
586    + for<'a> core::ops::Shl<&'a u16, Output = T>
587    + for<'a> core::ops::Shl<&'a u32, Output = T>
588    + for<'a> core::ops::Shl<&'a u64, Output = T>
589    + for<'a> core::ops::Shl<&'a u128, Output = T>
590    + for<'a> core::ops::Shl<&'a usize, Output = T>
591    + for<'a> core::ops::Shr<&'a T, Output = T>
592    + for<'a> core::ops::Shr<&'a i8, Output = T>
593    + for<'a> core::ops::Shr<&'a i16, Output = T>
594    + for<'a> core::ops::Shr<&'a i32, Output = T>
595    + for<'a> core::ops::Shr<&'a i64, Output = T>
596    + for<'a> core::ops::Shr<&'a i128, Output = T>
597    + for<'a> core::ops::Shr<&'a isize, Output = T>
598    + for<'a> core::ops::Shr<&'a u8, Output = T>
599    + for<'a> core::ops::Shr<&'a u16, Output = T>
600    + for<'a> core::ops::Shr<&'a u32, Output = T>
601    + for<'a> core::ops::Shr<&'a u64, Output = T>
602    + for<'a> core::ops::Shr<&'a u128, Output = T>
603    + for<'a> core::ops::Shr<&'a usize, Output = T>
604{
605}
606
607/// Trait for [`NonZero`] primitive integers.
608///
609/// This encapsulates trait implementations, constants, and inherent methods that are common among
610/// all of the implementations of `NonZero<T>`, where `T` is a [`PrimitiveInteger`].
611///
612/// See the corresponding items on the individual types for more documentation and examples.
613///
614/// This trait is sealed with a private trait to prevent downstream implementations, so we may
615/// continue to expand along with the standard library without worrying about breaking changes for
616/// implementors.
617///
618/// # Examples
619///
620/// ```
621/// use num_primitive::NonZeroPrimitiveInteger;
622/// use core::num::NonZero;
623///
624/// fn bits_and_zeros<T: NonZeroPrimitiveInteger>(n: T) -> (u32, u32, u32) {
625///     (T::BITS, n.leading_zeros(), n.trailing_zeros())
626/// }
627///
628/// assert_eq!(bits_and_zeros(NonZero::new(0b0010_1000u8).unwrap()), (8, 2, 3));
629/// assert_eq!(bits_and_zeros(NonZero::new(1i64).unwrap()), (64, 63, 0));
630/// ```
631#[expect(private_bounds)]
632pub trait NonZeroPrimitiveInteger:
633    'static
634    + NonZeroSealed
635    + core::cmp::Eq
636    + core::cmp::Ord
637    + core::convert::Into<Self::Integer>
638    + core::convert::TryFrom<Self::Integer, Error = TryFromIntError>
639    + core::convert::TryFrom<NonZero<i8>, Error: PrimitiveError>
640    + core::convert::TryFrom<NonZero<i16>, Error: PrimitiveError>
641    + core::convert::TryFrom<NonZero<i32>, Error: PrimitiveError>
642    + core::convert::TryFrom<NonZero<i64>, Error: PrimitiveError>
643    + core::convert::TryFrom<NonZero<i128>, Error: PrimitiveError>
644    + core::convert::TryFrom<NonZero<isize>, Error: PrimitiveError>
645    + core::convert::TryFrom<NonZero<u8>, Error: PrimitiveError>
646    + core::convert::TryFrom<NonZero<u16>, Error: PrimitiveError>
647    + core::convert::TryFrom<NonZero<u32>, Error: PrimitiveError>
648    + core::convert::TryFrom<NonZero<u64>, Error: PrimitiveError>
649    + core::convert::TryFrom<NonZero<u128>, Error: PrimitiveError>
650    + core::convert::TryFrom<NonZero<usize>, Error: PrimitiveError>
651    + core::convert::TryInto<NonZero<i8>, Error: PrimitiveError>
652    + core::convert::TryInto<NonZero<i16>, Error: PrimitiveError>
653    + core::convert::TryInto<NonZero<i32>, Error: PrimitiveError>
654    + core::convert::TryInto<NonZero<i64>, Error: PrimitiveError>
655    + core::convert::TryInto<NonZero<i128>, Error: PrimitiveError>
656    + core::convert::TryInto<NonZero<isize>, Error: PrimitiveError>
657    + core::convert::TryInto<NonZero<u8>, Error: PrimitiveError>
658    + core::convert::TryInto<NonZero<u16>, Error: PrimitiveError>
659    + core::convert::TryInto<NonZero<u32>, Error: PrimitiveError>
660    + core::convert::TryInto<NonZero<u64>, Error: PrimitiveError>
661    + core::convert::TryInto<NonZero<u128>, Error: PrimitiveError>
662    + core::convert::TryInto<NonZero<usize>, Error: PrimitiveError>
663    + core::fmt::Binary
664    + core::fmt::Debug
665    + core::fmt::Display
666    + core::fmt::LowerExp
667    + core::fmt::LowerHex
668    + core::fmt::Octal
669    + core::fmt::UpperExp
670    + core::fmt::UpperHex
671    + core::hash::Hash
672    + core::marker::Copy
673    + core::marker::Send
674    + core::marker::Sync
675    + core::marker::Unpin
676    + core::ops::BitOr<Self, Output = Self>
677    + core::ops::BitOr<Self::Integer, Output = Self>
678    + core::ops::BitOrAssign<Self>
679    + core::ops::BitOrAssign<Self::Integer>
680    + core::panic::RefUnwindSafe
681    + core::panic::UnwindSafe
682    + core::str::FromStr<Err = ParseIntError>
683{
684    /// The primitive integer type that this non-zero type wraps.
685    ///
686    /// For `core::num::NonZero<T>`, this is `T`.
687    type Integer: PrimitiveInteger<NonZero = Self>;
688
689    /// The size of this non-zero integer type in bits.
690    const BITS: u32;
691
692    /// The largest value that can be represented by this non-zero integer type.
693    const MAX: Self;
694
695    /// The smallest value that can be represented by this non-zero integer type.
696    const MIN: Self;
697
698    /// Multiplies two non-zero integers together. Returns [`None`] on overflow.
699    fn checked_mul(self, other: Self) -> Option<Self>;
700
701    /// Raises non-zero value to an integer power. Returns [`None`] on overflow.
702    fn checked_pow(self, other: u32) -> Option<Self>;
703
704    /// Returns the number of ones in the binary representation of `self`.
705    fn count_ones(self) -> NonZero<u32>;
706
707    /// Returns the contained value as a primitive type.
708    fn get(self) -> Self::Integer;
709
710    /// Returns the number of leading zeros in the binary representation of `self`.
711    fn leading_zeros(self) -> u32;
712
713    /// Creates a non-zero if the given value is not zero.
714    fn new(n: Self::Integer) -> Option<Self>;
715
716    /// Multiplies two non-zero integers together, saturating at the numeric bounds
717    /// instead of overflowing.
718    fn saturating_mul(self, other: Self) -> Self;
719
720    /// Raise non-zero value to an integer power, saturating at the numeric bounds
721    /// instead of overflowing.
722    fn saturating_pow(self, other: u32) -> Self;
723
724    /// Returns the number of trailing zeros in the binary representation of `self`.
725    fn trailing_zeros(self) -> u32;
726
727    /// Creates a non-zero without checking whether the value is non-zero.
728    /// This results in undefined behavior if the value is zero.
729    ///
730    /// # Safety
731    ///
732    /// The value must not be zero.
733    unsafe fn new_unchecked(n: Self::Integer) -> Self;
734}
735
736macro_rules! impl_integer {
737    ($($Integer:ident),*) => {$(
738        impl PrimitiveInteger for $Integer {
739            type NonZero = NonZero<Self>;
740
741            use_consts!(Self::{
742                BITS: u32,
743                MAX: Self,
744                MIN: Self,
745            });
746
747            forward! {
748                fn from_be(value: Self) -> Self;
749                fn from_le(value: Self) -> Self;
750                fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError>;
751            }
752            forward! {
753                fn checked_add(self, rhs: Self) -> Option<Self>;
754                fn checked_div(self, rhs: Self) -> Option<Self>;
755                fn checked_div_euclid(self, rhs: Self) -> Option<Self>;
756                fn checked_ilog(self, base: Self) -> Option<u32>;
757                fn checked_ilog10(self) -> Option<u32>;
758                fn checked_ilog2(self) -> Option<u32>;
759                fn checked_mul(self, rhs: Self) -> Option<Self>;
760                fn checked_neg(self) -> Option<Self>;
761                fn checked_pow(self, exp: u32) -> Option<Self>;
762                fn checked_rem(self, rhs: Self) -> Option<Self>;
763                fn checked_rem_euclid(self, rhs: Self) -> Option<Self>;
764                fn checked_shl(self, rhs: u32) -> Option<Self>;
765                fn checked_shr(self, rhs: u32) -> Option<Self>;
766                fn checked_sub(self, rhs: Self) -> Option<Self>;
767                fn count_ones(self) -> u32;
768                fn count_zeros(self) -> u32;
769                fn div_euclid(self, rhs: Self) -> Self;
770                fn ilog(self, base: Self) -> u32;
771                fn ilog10(self) -> u32;
772                fn ilog2(self) -> u32;
773                fn isqrt(self) -> Self;
774                fn leading_ones(self) -> u32;
775                fn leading_zeros(self) -> u32;
776                fn overflowing_add(self, rhs: Self) -> (Self, bool);
777                fn overflowing_div(self, rhs: Self) -> (Self, bool);
778                fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool);
779                fn overflowing_mul(self, rhs: Self) -> (Self, bool);
780                fn overflowing_neg(self) -> (Self, bool);
781                fn overflowing_pow(self, exp: u32) -> (Self, bool);
782                fn overflowing_rem(self, rhs: Self) -> (Self, bool);
783                fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool);
784                fn overflowing_shl(self, rhs: u32) -> (Self, bool);
785                fn overflowing_shr(self, rhs: u32) -> (Self, bool);
786                fn overflowing_sub(self, rhs: Self) -> (Self, bool);
787                fn pow(self, exp: u32) -> Self;
788                fn rem_euclid(self, rhs: Self) -> Self;
789                fn reverse_bits(self) -> Self;
790                fn rotate_left(self, n: u32) -> Self;
791                fn rotate_right(self, n: u32) -> Self;
792                fn saturating_add(self, rhs: Self) -> Self;
793                fn saturating_div(self, rhs: Self) -> Self;
794                fn saturating_mul(self, rhs: Self) -> Self;
795                fn saturating_pow(self, exp: u32) -> Self;
796                fn saturating_sub(self, rhs: Self) -> Self;
797                fn strict_add(self, rhs: Self) -> Self;
798                fn strict_div(self, rhs: Self) -> Self;
799                fn strict_div_euclid(self, rhs: Self) -> Self;
800                fn strict_mul(self, rhs: Self) -> Self;
801                fn strict_neg(self) -> Self;
802                fn strict_pow(self, exp: u32) -> Self;
803                fn strict_rem(self, rhs: Self) -> Self;
804                fn strict_rem_euclid(self, rhs: Self) -> Self;
805                fn strict_shl(self, rhs: u32) -> Self;
806                fn strict_shr(self, rhs: u32) -> Self;
807                fn strict_sub(self, rhs: Self) -> Self;
808                fn swap_bytes(self) -> Self;
809                fn to_be(self) -> Self;
810                fn to_le(self) -> Self;
811                fn trailing_ones(self) -> u32;
812                fn trailing_zeros(self) -> u32;
813                fn unbounded_shl(self, rhs: u32) -> Self;
814                fn unbounded_shr(self, rhs: u32) -> Self;
815                fn wrapping_add(self, rhs: Self) -> Self;
816                fn wrapping_div(self, rhs: Self) -> Self;
817                fn wrapping_div_euclid(self, rhs: Self) -> Self;
818                fn wrapping_mul(self, rhs: Self) -> Self;
819                fn wrapping_neg(self) -> Self;
820                fn wrapping_pow(self, exp: u32) -> Self;
821                fn wrapping_rem(self, rhs: Self) -> Self;
822                fn wrapping_rem_euclid(self, rhs: Self) -> Self;
823                fn wrapping_shl(self, rhs: u32) -> Self;
824                fn wrapping_shr(self, rhs: u32) -> Self;
825                fn wrapping_sub(self, rhs: Self) -> Self;
826            }
827            forward! {
828                unsafe fn unchecked_add(self, rhs: Self) -> Self;
829                unsafe fn unchecked_mul(self, rhs: Self) -> Self;
830                unsafe fn unchecked_shl(self, rhs: u32) -> Self;
831                unsafe fn unchecked_shr(self, rhs: u32) -> Self;
832                unsafe fn unchecked_sub(self, rhs: Self) -> Self;
833            }
834        }
835
836        impl PrimitiveIntegerRef<$Integer> for &$Integer {}
837
838        impl NonZeroSealed for NonZero<$Integer> {}
839
840        impl NonZeroPrimitiveInteger for NonZero<$Integer> {
841            type Integer = $Integer;
842
843            use_consts!(Self::{
844                BITS: u32,
845                MAX: Self,
846                MIN: Self,
847            });
848
849            forward! {
850                fn new(n: Self::Integer) -> Option<Self>;
851            }
852            forward! {
853                fn checked_mul(self, other: Self) -> Option<Self>;
854                fn checked_pow(self, other: u32) -> Option<Self>;
855                fn count_ones(self) -> NonZero<u32>;
856                fn get(self) -> Self::Integer;
857                fn leading_zeros(self) -> u32;
858                fn saturating_mul(self, other: Self) -> Self;
859                fn saturating_pow(self, other: u32) -> Self;
860                fn trailing_zeros(self) -> u32;
861            }
862            forward! {
863                unsafe fn new_unchecked(n: Self::Integer) -> Self;
864            }
865        }
866    )*}
867}
868
869impl_integer!(i8, i16, i32, i64, i128, isize);
870impl_integer!(u8, u16, u32, u64, u128, usize);