Skip to main content

core/num/
uint_macros.rs

1macro_rules! uint_impl {
2    (
3        Self = $SelfT:ty,
4        ActualT = $ActualT:ident,
5        SignedT = $SignedT:ident,
6
7        // These are all for use *only* in doc comments.
8        // As such, they're all passed as literals -- passing them as a string
9        // literal is fine if they need to be multiple code tokens.
10        // In non-comments, use the associated constants rather than these.
11        BITS = $BITS:literal,
12        BITS_MINUS_ONE = $BITS_MINUS_ONE:literal,
13        MAX = $MaxV:literal,
14        rot = $rot:literal,
15        rot_op = $rot_op:literal,
16        rot_result = $rot_result:literal,
17        fsh_op = $fsh_op:literal,
18        fshl_result = $fshl_result:literal,
19        fshr_result = $fshr_result:literal,
20        clmul_lhs = $clmul_lhs:literal,
21        clmul_rhs = $clmul_rhs:literal,
22        clmul_result = $clmul_result:literal,
23        swap_op = $swap_op:literal,
24        swapped = $swapped:literal,
25        reversed = $reversed:literal,
26        le_bytes = $le_bytes:literal,
27        be_bytes = $be_bytes:literal,
28        to_xe_bytes_doc = $to_xe_bytes_doc:expr,
29        from_xe_bytes_doc = $from_xe_bytes_doc:expr,
30        bound_condition = $bound_condition:literal,
31    ) => {
32        /// The smallest value that can be represented by this integer type.
33        ///
34        /// # Examples
35        ///
36        /// ```
37        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, 0);")]
38        /// ```
39        #[stable(feature = "assoc_int_consts", since = "1.43.0")]
40        pub const MIN: Self = 0;
41
42        /// The largest value that can be represented by this integer type
43        #[doc = concat!("(2<sup>", $BITS, "</sup> &minus; 1", $bound_condition, ").")]
44        ///
45        /// # Examples
46        ///
47        /// ```
48        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");")]
49        /// ```
50        #[stable(feature = "assoc_int_consts", since = "1.43.0")]
51        pub const MAX: Self = !0;
52
53        /// The size of this integer type in bits.
54        ///
55        /// # Examples
56        ///
57        /// ```
58        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
59        /// ```
60        #[stable(feature = "int_bits_const", since = "1.53.0")]
61        pub const BITS: u32 = Self::MAX.count_ones();
62
63        /// Returns the number of ones in the binary representation of `self`.
64        ///
65        /// # Examples
66        ///
67        /// ```
68        #[doc = concat!("let n = 0b01001100", stringify!($SelfT), ";")]
69        /// assert_eq!(n.count_ones(), 3);
70        ///
71        #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
72        #[doc = concat!("assert_eq!(max.count_ones(), ", stringify!($BITS), ");")]
73        ///
74        #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
75        /// assert_eq!(zero.count_ones(), 0);
76        /// ```
77        #[stable(feature = "rust1", since = "1.0.0")]
78        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
79        #[doc(alias = "popcount")]
80        #[doc(alias = "popcnt")]
81        #[must_use = "this returns the result of the operation, \
82                      without modifying the original"]
83        #[inline(always)]
84        pub const fn count_ones(self) -> u32 {
85            return intrinsics::ctpop(self);
86        }
87
88        /// Returns the number of zeros in the binary representation of `self`.
89        ///
90        /// # Examples
91        ///
92        /// ```
93        #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
94        #[doc = concat!("assert_eq!(zero.count_zeros(), ", stringify!($BITS), ");")]
95        ///
96        #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
97        /// assert_eq!(max.count_zeros(), 0);
98        /// ```
99        ///
100        /// This is heavily dependent on the width of the type, and thus
101        /// might give surprising results depending on type inference:
102        /// ```
103        /// # fn foo(_: u8) {}
104        /// # fn bar(_: u16) {}
105        /// let lucky = 7;
106        /// foo(lucky);
107        /// assert_eq!(lucky.count_zeros(), 5);
108        /// assert_eq!(lucky.count_ones(), 3);
109        ///
110        /// let lucky = 7;
111        /// bar(lucky);
112        /// assert_eq!(lucky.count_zeros(), 13);
113        /// assert_eq!(lucky.count_ones(), 3);
114        /// ```
115        /// You might want to use [`Self::count_ones`] instead, or emphasize
116        /// the type you're using in the call rather than method syntax:
117        /// ```
118        /// let small = 1;
119        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::count_zeros(small), ", stringify!($BITS_MINUS_ONE) ,");")]
120        /// ```
121        #[stable(feature = "rust1", since = "1.0.0")]
122        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
123        #[must_use = "this returns the result of the operation, \
124                      without modifying the original"]
125        #[inline(always)]
126        pub const fn count_zeros(self) -> u32 {
127            (!self).count_ones()
128        }
129
130        /// Returns the number of leading zeros in the binary representation of `self`.
131        ///
132        /// Depending on what you're doing with the value, you might also be interested in the
133        /// [`ilog2`] function which returns a consistent number, even if the type widens.
134        ///
135        /// # Examples
136        ///
137        /// ```
138        #[doc = concat!("let n = ", stringify!($SelfT), "::MAX >> 2;")]
139        /// assert_eq!(n.leading_zeros(), 2);
140        ///
141        #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
142        #[doc = concat!("assert_eq!(zero.leading_zeros(), ", stringify!($BITS), ");")]
143        ///
144        #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
145        /// assert_eq!(max.leading_zeros(), 0);
146        /// ```
147        #[doc = concat!("[`ilog2`]: ", stringify!($SelfT), "::ilog2")]
148        #[stable(feature = "rust1", since = "1.0.0")]
149        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
150        #[must_use = "this returns the result of the operation, \
151                      without modifying the original"]
152        #[inline(always)]
153        pub const fn leading_zeros(self) -> u32 {
154            return intrinsics::ctlz(self as $ActualT);
155        }
156
157        /// Returns the number of trailing zeros in the binary representation
158        /// of `self`.
159        ///
160        /// # Examples
161        ///
162        /// ```
163        #[doc = concat!("let n = 0b0101000", stringify!($SelfT), ";")]
164        /// assert_eq!(n.trailing_zeros(), 3);
165        ///
166        #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
167        #[doc = concat!("assert_eq!(zero.trailing_zeros(), ", stringify!($BITS), ");")]
168        ///
169        #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
170        #[doc = concat!("assert_eq!(max.trailing_zeros(), 0);")]
171        /// ```
172        #[stable(feature = "rust1", since = "1.0.0")]
173        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
174        #[must_use = "this returns the result of the operation, \
175                      without modifying the original"]
176        #[inline(always)]
177        pub const fn trailing_zeros(self) -> u32 {
178            return intrinsics::cttz(self);
179        }
180
181        /// Returns the number of leading ones in the binary representation of `self`.
182        ///
183        /// # Examples
184        ///
185        /// ```
186        #[doc = concat!("let n = !(", stringify!($SelfT), "::MAX >> 2);")]
187        /// assert_eq!(n.leading_ones(), 2);
188        ///
189        #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
190        /// assert_eq!(zero.leading_ones(), 0);
191        ///
192        #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
193        #[doc = concat!("assert_eq!(max.leading_ones(), ", stringify!($BITS), ");")]
194        /// ```
195        #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
196        #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
197        #[must_use = "this returns the result of the operation, \
198                      without modifying the original"]
199        #[inline(always)]
200        pub const fn leading_ones(self) -> u32 {
201            (!self).leading_zeros()
202        }
203
204        /// Returns the number of trailing ones in the binary representation
205        /// of `self`.
206        ///
207        /// # Examples
208        ///
209        /// ```
210        #[doc = concat!("let n = 0b1010111", stringify!($SelfT), ";")]
211        /// assert_eq!(n.trailing_ones(), 3);
212        ///
213        #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
214        /// assert_eq!(zero.trailing_ones(), 0);
215        ///
216        #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
217        #[doc = concat!("assert_eq!(max.trailing_ones(), ", stringify!($BITS), ");")]
218        /// ```
219        #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
220        #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
221        #[must_use = "this returns the result of the operation, \
222                      without modifying the original"]
223        #[inline(always)]
224        pub const fn trailing_ones(self) -> u32 {
225            (!self).trailing_zeros()
226        }
227
228        /// Returns the minimum number of bits required to represent `self`.
229        ///
230        /// This method returns zero if `self` is zero.
231        ///
232        /// # Examples
233        ///
234        /// ```
235        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".bit_width(), 0);")]
236        #[doc = concat!("assert_eq!(0b111_", stringify!($SelfT), ".bit_width(), 3);")]
237        #[doc = concat!("assert_eq!(0b1110_", stringify!($SelfT), ".bit_width(), 4);")]
238        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.bit_width(), ", stringify!($BITS), ");")]
239        /// ```
240        #[stable(feature = "uint_bit_width", since = "CURRENT_RUSTC_VERSION")]
241        #[rustc_const_stable(feature = "uint_bit_width", since = "CURRENT_RUSTC_VERSION")]
242        #[must_use = "this returns the result of the operation, \
243                      without modifying the original"]
244        #[inline(always)]
245        pub const fn bit_width(self) -> u32 {
246            Self::BITS - self.leading_zeros()
247        }
248
249        /// Returns `self` with only the most significant bit set, or `0` if
250        /// the input is `0`.
251        ///
252        /// # Examples
253        ///
254        /// ```
255        #[doc = concat!("let n: ", stringify!($SelfT), " = 0b_01100100;")]
256        ///
257        /// assert_eq!(n.isolate_highest_one(), 0b_01000000);
258        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".isolate_highest_one(), 0);")]
259        /// ```
260        #[stable(feature = "isolate_most_least_significant_one", since = "CURRENT_RUSTC_VERSION")]
261        #[rustc_const_stable(feature = "isolate_most_least_significant_one", since = "CURRENT_RUSTC_VERSION")]
262        #[must_use = "this returns the result of the operation, \
263                      without modifying the original"]
264        #[inline(always)]
265        pub const fn isolate_highest_one(self) -> Self {
266            self & (((1 as $SelfT) << (<$SelfT>::BITS - 1)).wrapping_shr(self.leading_zeros()))
267        }
268
269        /// Returns `self` with only the least significant bit set, or `0` if
270        /// the input is `0`.
271        ///
272        /// # Examples
273        ///
274        /// ```
275        #[doc = concat!("let n: ", stringify!($SelfT), " = 0b_01100100;")]
276        ///
277        /// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
278        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".isolate_lowest_one(), 0);")]
279        /// ```
280        #[stable(feature = "isolate_most_least_significant_one", since = "CURRENT_RUSTC_VERSION")]
281        #[rustc_const_stable(feature = "isolate_most_least_significant_one", since = "CURRENT_RUSTC_VERSION")]
282        #[must_use = "this returns the result of the operation, \
283                      without modifying the original"]
284        #[inline(always)]
285        pub const fn isolate_lowest_one(self) -> Self {
286            self & self.wrapping_neg()
287        }
288
289        /// Returns the index of the highest bit set to one in `self`, or `None`
290        /// if `self` is `0`.
291        ///
292        /// # Examples
293        ///
294        /// ```
295        #[doc = concat!("assert_eq!(0b0_", stringify!($SelfT), ".highest_one(), None);")]
296        #[doc = concat!("assert_eq!(0b1_", stringify!($SelfT), ".highest_one(), Some(0));")]
297        #[doc = concat!("assert_eq!(0b1_0000_", stringify!($SelfT), ".highest_one(), Some(4));")]
298        #[doc = concat!("assert_eq!(0b1_1111_", stringify!($SelfT), ".highest_one(), Some(4));")]
299        /// ```
300        #[stable(feature = "int_lowest_highest_one", since = "CURRENT_RUSTC_VERSION")]
301        #[rustc_const_stable(feature = "int_lowest_highest_one", since = "CURRENT_RUSTC_VERSION")]
302        #[must_use = "this returns the result of the operation, \
303                      without modifying the original"]
304        #[inline(always)]
305        pub const fn highest_one(self) -> Option<u32> {
306            match NonZero::new(self) {
307                Some(v) => Some(v.highest_one()),
308                None => None,
309            }
310        }
311
312        /// Returns the index of the lowest bit set to one in `self`, or `None`
313        /// if `self` is `0`.
314        ///
315        /// # Examples
316        ///
317        /// ```
318        #[doc = concat!("assert_eq!(0b0_", stringify!($SelfT), ".lowest_one(), None);")]
319        #[doc = concat!("assert_eq!(0b1_", stringify!($SelfT), ".lowest_one(), Some(0));")]
320        #[doc = concat!("assert_eq!(0b1_0000_", stringify!($SelfT), ".lowest_one(), Some(4));")]
321        #[doc = concat!("assert_eq!(0b1_1111_", stringify!($SelfT), ".lowest_one(), Some(0));")]
322        /// ```
323        #[stable(feature = "int_lowest_highest_one", since = "CURRENT_RUSTC_VERSION")]
324        #[rustc_const_stable(feature = "int_lowest_highest_one", since = "CURRENT_RUSTC_VERSION")]
325        #[must_use = "this returns the result of the operation, \
326                      without modifying the original"]
327        #[inline(always)]
328        pub const fn lowest_one(self) -> Option<u32> {
329            match NonZero::new(self) {
330                Some(v) => Some(v.lowest_one()),
331                None => None,
332            }
333        }
334
335        /// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
336        ///
337        /// This produces the same result as an `as` cast, but ensures that the bit-width remains
338        /// the same.
339        ///
340        /// # Examples
341        ///
342        /// ```
343        #[doc = concat!("let n = ", stringify!($SelfT), "::MAX;")]
344        ///
345        #[doc = concat!("assert_eq!(n.cast_signed(), -1", stringify!($SignedT), ");")]
346        /// ```
347        #[stable(feature = "integer_sign_cast", since = "1.87.0")]
348        #[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
349        #[must_use = "this returns the result of the operation, \
350                      without modifying the original"]
351        #[inline(always)]
352        pub const fn cast_signed(self) -> $SignedT {
353            self as $SignedT
354        }
355
356        /// Saturating conversion of `self` to a signed integer of the same size.
357        ///
358        /// The signed integer's maximum value is returned if `self` is larger
359        /// than the maximum positive value representable by the signed integer.
360        ///
361        /// For other kinds of signed integer casts, see
362        /// [`cast_signed`](Self::cast_signed),
363        /// [`checked_cast_signed`](Self::checked_cast_signed),
364        /// or [`strict_cast_signed`](Self::strict_cast_signed).
365        ///
366        /// # Examples
367        ///
368        /// ```
369        /// #![feature(integer_cast_extras)]
370        #[doc = concat!("let n = ", stringify!($SelfT), "::MAX;")]
371        ///
372        #[doc = concat!("assert_eq!(n.saturating_cast_signed(), ", stringify!($SignedT), "::MAX);")]
373        #[doc = concat!("assert_eq!(64", stringify!($SelfT), ".saturating_cast_signed(), 64", stringify!($SignedT), ");")]
374        /// ```
375        #[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
376        #[unstable(feature = "integer_cast_extras", issue = "154650")]
377        #[must_use = "this returns the result of the operation, \
378                      without modifying the original"]
379        #[inline(always)]
380        pub const fn saturating_cast_signed(self) -> $SignedT {
381            // Clamp to the signed integer max size, which is ActualT::MAX >> 1.
382            if self <= <$SignedT>::MAX.cast_unsigned() {
383                self.cast_signed()
384            } else {
385                <$SignedT>::MAX
386            }
387        }
388
389        /// Checked conversion of `self` to a signed integer of the same size,
390        /// returning `None` if `self` is larger than the signed integer's
391        /// maximum value.
392        ///
393        /// For other kinds of signed integer casts, see
394        /// [`cast_signed`](Self::cast_signed),
395        /// [`saturating_cast_signed`](Self::saturating_cast_signed),
396        /// or [`strict_cast_signed`](Self::strict_cast_signed).
397        ///
398        /// # Examples
399        ///
400        /// ```
401        /// #![feature(integer_cast_extras)]
402        #[doc = concat!("let n = ", stringify!($SelfT), "::MAX;")]
403        ///
404        #[doc = concat!("assert_eq!(n.checked_cast_signed(), None);")]
405        #[doc = concat!("assert_eq!(64", stringify!($SelfT), ".checked_cast_signed(), Some(64", stringify!($SignedT), "));")]
406        /// ```
407        #[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
408        #[unstable(feature = "integer_cast_extras", issue = "154650")]
409        #[must_use = "this returns the result of the operation, \
410                      without modifying the original"]
411        #[inline(always)]
412        pub const fn checked_cast_signed(self) -> Option<$SignedT> {
413            if self <= <$SignedT>::MAX.cast_unsigned() {
414                Some(self.cast_signed())
415            } else {
416                None
417            }
418        }
419
420        /// Strict conversion of `self` to a signed integer of the same size,
421        /// which panics if `self` is larger than the signed integer's maximum
422        /// value.
423        ///
424        /// For other kinds of signed integer casts, see
425        /// [`cast_signed`](Self::cast_signed),
426        /// [`checked_cast_signed`](Self::checked_cast_signed),
427        /// or [`saturating_cast_signed`](Self::saturating_cast_signed).
428        ///
429        /// # Examples
430        ///
431        /// ```should_panic
432        /// #![feature(integer_cast_extras)]
433        #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_cast_signed();")]
434        /// ```
435        #[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
436        #[unstable(feature = "integer_cast_extras", issue = "154650")]
437        #[must_use = "this returns the result of the operation, \
438                      without modifying the original"]
439        #[inline]
440        #[track_caller]
441        pub const fn strict_cast_signed(self) -> $SignedT {
442            match self.checked_cast_signed() {
443                Some(n) => n,
444                None => imp::overflow_panic::cast_integer(),
445            }
446        }
447
448        /// Shifts the bits to the left by a specified amount, `n`,
449        /// wrapping the truncated bits to the end of the resulting integer.
450        ///
451        /// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
452        /// particular, a rotation by the number of bits in `self` returns the input value
453        /// unchanged.
454        ///
455        /// Please note this isn't the same operation as the `<<` shifting operator!
456        ///
457        /// # Examples
458        ///
459        /// ```
460        #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
461        #[doc = concat!("let m = ", $rot_result, ";")]
462        ///
463        #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
464        #[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
465        /// ```
466        #[stable(feature = "rust1", since = "1.0.0")]
467        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
468        #[must_use = "this returns the result of the operation, \
469                      without modifying the original"]
470        #[inline(always)]
471        #[rustc_allow_const_fn_unstable(const_trait_impl)] // for the intrinsic fallback
472        pub const fn rotate_left(self, n: u32) -> Self {
473            return intrinsics::rotate_left(self, n);
474        }
475
476        /// Shifts the bits to the right by a specified amount, `n`,
477        /// wrapping the truncated bits to the beginning of the resulting
478        /// integer.
479        ///
480        /// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
481        /// particular, a rotation by the number of bits in `self` returns the input value
482        /// unchanged.
483        ///
484        /// Please note this isn't the same operation as the `>>` shifting operator!
485        ///
486        /// # Examples
487        ///
488        /// ```
489        #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
490        #[doc = concat!("let m = ", $rot_op, ";")]
491        ///
492        #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
493        #[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
494        /// ```
495        #[stable(feature = "rust1", since = "1.0.0")]
496        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
497        #[must_use = "this returns the result of the operation, \
498                      without modifying the original"]
499        #[inline(always)]
500        #[rustc_allow_const_fn_unstable(const_trait_impl)] // for the intrinsic fallback
501        pub const fn rotate_right(self, n: u32) -> Self {
502            return intrinsics::rotate_right(self, n);
503        }
504
505        /// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
506        /// making up the most significant half, then shifts the combined value left
507        /// by `n`, and most significant half is extracted to produce the result).
508        ///
509        /// Please note this isn't the same operation as the `<<` shifting operator or
510        /// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
511        /// to `a.rotate_left(n)`.
512        ///
513        /// # Panics
514        ///
515        /// If `n` is greater than or equal to the number of bits in `self`
516        ///
517        /// # Examples
518        ///
519        /// Basic usage:
520        ///
521        /// ```
522        /// #![feature(funnel_shifts)]
523        #[doc = concat!("let a = ", $rot_op, stringify!($SelfT), ";")]
524        #[doc = concat!("let b = ", $fsh_op, stringify!($SelfT), ";")]
525        #[doc = concat!("let m = ", $fshl_result, ";")]
526        ///
527        #[doc = concat!("assert_eq!(a.funnel_shl(b, ", $rot, "), m);")]
528        /// ```
529        #[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
530        #[unstable(feature = "funnel_shifts", issue = "145686")]
531        #[must_use = "this returns the result of the operation, \
532                      without modifying the original"]
533        #[inline(always)]
534        pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
535            assert!(n < Self::BITS, "attempt to funnel shift left with overflow");
536            // SAFETY: just checked that `shift` is in-range
537            unsafe { self.unchecked_funnel_shl(rhs, n) }
538        }
539
540        /// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
541        /// making up the most significant half, then shifts the combined value right
542        /// by `n`, and least significant half is extracted to produce the result).
543        ///
544        /// Please note this isn't the same operation as the `>>` shifting operator or
545        /// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
546        /// to `a.rotate_right(n)`.
547        ///
548        /// # Panics
549        ///
550        /// If `n` is greater than or equal to the number of bits in `self`
551        ///
552        /// # Examples
553        ///
554        /// Basic usage:
555        ///
556        /// ```
557        /// #![feature(funnel_shifts)]
558        #[doc = concat!("let a = ", $rot_op, stringify!($SelfT), ";")]
559        #[doc = concat!("let b = ", $fsh_op, stringify!($SelfT), ";")]
560        #[doc = concat!("let m = ", $fshr_result, ";")]
561        ///
562        #[doc = concat!("assert_eq!(a.funnel_shr(b, ", $rot, "), m);")]
563        /// ```
564        #[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
565        #[unstable(feature = "funnel_shifts", issue = "145686")]
566        #[must_use = "this returns the result of the operation, \
567                      without modifying the original"]
568        #[inline(always)]
569        pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
570            assert!(n < Self::BITS, "attempt to funnel shift right with overflow");
571            // SAFETY: just checked that `shift` is in-range
572            unsafe { self.unchecked_funnel_shr(rhs, n) }
573        }
574
575        /// Unchecked funnel shift left.
576        ///
577        /// # Safety
578        ///
579        /// This results in undefined behavior if `n` is greater than or equal to
580        #[doc = concat!("`", stringify!($SelfT) , "::BITS`,")]
581        /// i.e. when [`funnel_shl`](Self::funnel_shl) would panic.
582        ///
583        #[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
584        #[unstable(feature = "funnel_shifts", issue = "145686")]
585        #[must_use = "this returns the result of the operation, \
586                      without modifying the original"]
587        #[inline(always)]
588        #[track_caller]
589        pub const unsafe fn unchecked_funnel_shl(self, low: Self, n: u32) -> Self {
590            assert_unsafe_precondition!(
591                check_language_ub,
592                concat!(stringify!($SelfT), "::unchecked_funnel_shl cannot overflow"),
593                (n: u32 = n) => n < <$ActualT>::BITS,
594            );
595
596            // SAFETY: this is guaranteed to be safe by the caller.
597            unsafe {
598                intrinsics::unchecked_funnel_shl(self, low, n)
599            }
600        }
601
602        /// Unchecked funnel shift right.
603        ///
604        /// # Safety
605        ///
606        /// This results in undefined behavior if `n` is greater than or equal to
607        #[doc = concat!("`", stringify!($SelfT) , "::BITS`,")]
608        /// i.e. when [`funnel_shr`](Self::funnel_shr) would panic.
609        ///
610        #[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
611        #[unstable(feature = "funnel_shifts", issue = "145686")]
612        #[must_use = "this returns the result of the operation, \
613                      without modifying the original"]
614        #[inline(always)]
615        #[track_caller]
616        pub const unsafe fn unchecked_funnel_shr(self, low: Self, n: u32) -> Self {
617            assert_unsafe_precondition!(
618                check_language_ub,
619                concat!(stringify!($SelfT), "::unchecked_funnel_shr cannot overflow"),
620                (n: u32 = n) => n < <$ActualT>::BITS,
621            );
622
623            // SAFETY: this is guaranteed to be safe by the caller.
624            unsafe {
625                intrinsics::unchecked_funnel_shr(self, low, n)
626            }
627        }
628
629        /// Performs a carry-less multiplication, returning the lower bits.
630        ///
631        /// This operation is similar to long multiplication in base 2, except that exclusive or is
632        /// used instead of addition. The implementation is equivalent to:
633        ///
634        /// ```no_run
635        #[doc = concat!("pub fn carryless_mul(lhs: ", stringify!($SelfT), ", rhs: ", stringify!($SelfT), ") -> ", stringify!($SelfT), "{")]
636        ///     let mut retval = 0;
637        #[doc = concat!("    for i in 0..",  stringify!($SelfT), "::BITS {")]
638        ///         if (rhs >> i) & 1 != 0 {
639        ///             // long multiplication would use +=
640        ///             retval ^= lhs << i;
641        ///         }
642        ///     }
643        ///     retval
644        /// }
645        /// ```
646        ///
647        /// The actual implementation is more efficient, and on some platforms lowers directly to a
648        /// dedicated instruction.
649        ///
650        /// # Uses
651        ///
652        /// Carryless multiplication can be used to turn a bitmask of quote characters into a
653        /// bit mask of characters surrounded by quotes:
654        ///
655        /// ```no_run
656        /// r#"abc xxx "foobar" zzz "a"!"#; // input string
657        ///  0b0000000010000001000001010; // quote_mask
658        ///  0b0000000001111110000000100; // quote_mask.carryless_mul(!0) & !quote_mask
659        /// ```
660        ///
661        /// Another use is in cryptography, where carryless multiplication allows for efficient
662        /// implementations of polynomial multiplication in `GF(2)[X]`, the polynomial ring
663        /// over `GF(2)`.
664        ///
665        /// # Examples
666        ///
667        /// ```
668        /// #![feature(uint_carryless_mul)]
669        ///
670        #[doc = concat!("let a = ", $clmul_lhs, stringify!($SelfT), ";")]
671        #[doc = concat!("let b = ", $clmul_rhs, stringify!($SelfT), ";")]
672        ///
673        #[doc = concat!("assert_eq!(a.carryless_mul(b), ", $clmul_result, ");")]
674        /// ```
675        #[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
676        #[doc(alias = "clmul")]
677        #[unstable(feature = "uint_carryless_mul", issue = "152080")]
678        #[must_use = "this returns the result of the operation, \
679                      without modifying the original"]
680        #[inline(always)]
681        pub const fn carryless_mul(self, rhs: Self) -> Self {
682            intrinsics::carryless_mul(self, rhs)
683        }
684
685        /// Reverses the byte order of the integer.
686        ///
687        /// # Examples
688        ///
689        /// ```
690        #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
691        /// let m = n.swap_bytes();
692        ///
693        #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
694        /// ```
695        #[stable(feature = "rust1", since = "1.0.0")]
696        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
697        #[must_use = "this returns the result of the operation, \
698                      without modifying the original"]
699        #[inline(always)]
700        pub const fn swap_bytes(self) -> Self {
701            intrinsics::bswap(self as $ActualT) as Self
702        }
703
704        /// Returns an integer with the bit locations specified by `mask` packed
705        /// contiguously into the least significant bits of the result.
706        /// ```
707        /// #![feature(uint_gather_scatter_bits)]
708        #[doc = concat!("let n: ", stringify!($SelfT), " = 0b1011_1100;")]
709        ///
710        /// assert_eq!(n.extract_bits(0b0010_0100), 0b0000_0011);
711        /// assert_eq!(n.extract_bits(0xF0), 0b0000_1011);
712        /// ```
713        #[doc(alias = "pext")]
714        #[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
715        #[must_use = "this returns the result of the operation, \
716                      without modifying the original"]
717        #[inline]
718        pub const fn extract_bits(self, mask: Self) -> Self {
719            imp::int_bits::$ActualT::extract_impl(self as $ActualT, mask as $ActualT) as $SelfT
720        }
721
722        /// Returns an integer with the least significant bits of `self`
723        /// distributed to the bit locations specified by `mask`.
724        /// ```
725        /// #![feature(uint_gather_scatter_bits)]
726        #[doc = concat!("let n: ", stringify!($SelfT), " = 0b1010_1101;")]
727        ///
728        /// assert_eq!(n.deposit_bits(0b0101_0101), 0b0101_0001);
729        /// assert_eq!(n.deposit_bits(0xF0), 0b1101_0000);
730        /// ```
731        #[doc(alias = "pdep")]
732        #[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
733        #[must_use = "this returns the result of the operation, \
734                      without modifying the original"]
735        #[inline]
736        pub const fn deposit_bits(self, mask: Self) -> Self {
737            imp::int_bits::$ActualT::deposit_impl(self as $ActualT, mask as $ActualT) as $SelfT
738        }
739
740        /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
741        ///                 second least-significant bit becomes second most-significant bit, etc.
742        ///
743        /// # Examples
744        ///
745        /// ```
746        #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
747        /// let m = n.reverse_bits();
748        ///
749        #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
750        #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
751        /// ```
752        #[stable(feature = "reverse_bits", since = "1.37.0")]
753        #[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
754        #[must_use = "this returns the result of the operation, \
755                      without modifying the original"]
756        #[inline(always)]
757        pub const fn reverse_bits(self) -> Self {
758            intrinsics::bitreverse(self as $ActualT) as Self
759        }
760
761        /// Converts an integer from big endian to the target's endianness.
762        ///
763        /// On big endian this is a no-op. On little endian the bytes are
764        /// swapped.
765        ///
766        /// # Examples
767        ///
768        /// ```
769        #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
770        ///
771        /// if cfg!(target_endian = "big") {
772        #[doc = concat!("    assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
773        /// } else {
774        #[doc = concat!("    assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
775        /// }
776        /// ```
777        #[stable(feature = "rust1", since = "1.0.0")]
778        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
779        #[must_use]
780        #[inline(always)]
781        pub const fn from_be(x: Self) -> Self {
782            cfg_select! {
783                target_endian = "big" => x,
784                _ => x.swap_bytes(),
785            }
786        }
787
788        /// Converts an integer from little endian to the target's endianness.
789        ///
790        /// On little endian this is a no-op. On big endian the bytes are
791        /// swapped.
792        ///
793        /// # Examples
794        ///
795        /// ```
796        #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
797        ///
798        /// if cfg!(target_endian = "little") {
799        #[doc = concat!("    assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
800        /// } else {
801        #[doc = concat!("    assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
802        /// }
803        /// ```
804        #[stable(feature = "rust1", since = "1.0.0")]
805        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
806        #[must_use]
807        #[inline(always)]
808        pub const fn from_le(x: Self) -> Self {
809            cfg_select! {
810                target_endian = "little" => x,
811                _ => x.swap_bytes(),
812            }
813        }
814
815        /// Converts `self` to big endian from the target's endianness.
816        ///
817        /// On big endian this is a no-op. On little endian the bytes are
818        /// swapped.
819        ///
820        /// # Examples
821        ///
822        /// ```
823        #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
824        ///
825        /// if cfg!(target_endian = "big") {
826        ///     assert_eq!(n.to_be(), n)
827        /// } else {
828        ///     assert_eq!(n.to_be(), n.swap_bytes())
829        /// }
830        /// ```
831        #[stable(feature = "rust1", since = "1.0.0")]
832        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
833        #[must_use = "this returns the result of the operation, \
834                      without modifying the original"]
835        #[inline(always)]
836        pub const fn to_be(self) -> Self { // or not to be?
837            cfg_select! {
838                target_endian = "big" => self,
839                _ => self.swap_bytes(),
840            }
841        }
842
843        /// Converts `self` to little endian from the target's endianness.
844        ///
845        /// On little endian this is a no-op. On big endian the bytes are
846        /// swapped.
847        ///
848        /// # Examples
849        ///
850        /// ```
851        #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
852        ///
853        /// if cfg!(target_endian = "little") {
854        ///     assert_eq!(n.to_le(), n)
855        /// } else {
856        ///     assert_eq!(n.to_le(), n.swap_bytes())
857        /// }
858        /// ```
859        #[stable(feature = "rust1", since = "1.0.0")]
860        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
861        #[must_use = "this returns the result of the operation, \
862                      without modifying the original"]
863        #[inline(always)]
864        pub const fn to_le(self) -> Self {
865            cfg_select! {
866                target_endian = "little" => self,
867                _ => self.swap_bytes(),
868            }
869        }
870
871        /// Checked integer addition. Computes `self + rhs`, returning `None`
872        /// if overflow occurred.
873        ///
874        /// # Examples
875        ///
876        /// ```
877        #[doc = concat!(
878            "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
879            "Some(", stringify!($SelfT), "::MAX - 1));"
880        )]
881        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
882        /// ```
883        #[stable(feature = "rust1", since = "1.0.0")]
884        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
885        #[must_use = "this returns the result of the operation, \
886                      without modifying the original"]
887        #[inline]
888        pub const fn checked_add(self, rhs: Self) -> Option<Self> {
889            // This used to use `overflowing_add`, but that means it ends up being
890            // a `wrapping_add`, losing some optimization opportunities. Notably,
891            // phrasing it this way helps `.checked_add(1)` optimize to a check
892            // against `MAX` and a `add nuw`.
893            // Per <https://github.com/rust-lang/rust/pull/124114#issuecomment-2066173305>,
894            // LLVM is happy to re-form the intrinsic later if useful.
895
896            if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
897                None
898            } else {
899                // SAFETY: Just checked it doesn't overflow
900                Some(unsafe { intrinsics::unchecked_add(self, rhs) })
901            }
902        }
903
904        /// Strict integer addition. Computes `self + rhs`, panicking
905        /// if overflow occurred.
906        ///
907        /// # Panics
908        ///
909        /// ## Overflow behavior
910        ///
911        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
912        ///
913        /// # Examples
914        ///
915        /// ```
916        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).strict_add(1), ", stringify!($SelfT), "::MAX - 1);")]
917        /// ```
918        ///
919        /// The following panics because of overflow:
920        ///
921        /// ```should_panic
922        #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX - 2).strict_add(3);")]
923        /// ```
924        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
925        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
926        #[must_use = "this returns the result of the operation, \
927                      without modifying the original"]
928        #[inline]
929        #[track_caller]
930        pub const fn strict_add(self, rhs: Self) -> Self {
931            let (a, b) = self.overflowing_add(rhs);
932            if b { imp::overflow_panic::add() } else { a }
933        }
934
935        /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
936        /// cannot occur.
937        ///
938        /// Calling `x.unchecked_add(y)` is semantically equivalent to calling
939        /// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
940        ///
941        /// If you're just trying to avoid the panic in debug mode, then **do not**
942        /// use this.  Instead, you're looking for [`wrapping_add`].
943        ///
944        /// # Safety
945        ///
946        /// This results in undefined behavior when
947        #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX`,")]
948        /// i.e. when [`checked_add`] would return `None`.
949        ///
950        /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
951        #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
952        #[doc = concat!("[`wrapping_add`]: ", stringify!($SelfT), "::wrapping_add")]
953        #[stable(feature = "unchecked_math", since = "1.79.0")]
954        #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
955        #[must_use = "this returns the result of the operation, \
956                      without modifying the original"]
957        #[inline(always)]
958        #[track_caller]
959        pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
960            assert_unsafe_precondition!(
961                check_language_ub,
962                concat!(stringify!($SelfT), "::unchecked_add cannot overflow"),
963                (
964                    lhs: $SelfT = self,
965                    rhs: $SelfT = rhs,
966                ) => !lhs.overflowing_add(rhs).1,
967            );
968
969            // SAFETY: this is guaranteed to be safe by the caller.
970            unsafe {
971                intrinsics::unchecked_add(self, rhs)
972            }
973        }
974
975        /// Checked addition with a signed integer. Computes `self + rhs`,
976        /// returning `None` if overflow occurred.
977        ///
978        /// # Examples
979        ///
980        /// ```
981        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(2), Some(3));")]
982        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(-2), None);")]
983        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_signed(3), None);")]
984        /// ```
985        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
986        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
987        #[must_use = "this returns the result of the operation, \
988                      without modifying the original"]
989        #[inline]
990        pub const fn checked_add_signed(self, rhs: $SignedT) -> Option<Self> {
991            let (a, b) = self.overflowing_add_signed(rhs);
992            if intrinsics::unlikely(b) { None } else { Some(a) }
993        }
994
995        /// Strict addition with a signed integer. Computes `self + rhs`,
996        /// panicking if overflow occurred.
997        ///
998        /// # Panics
999        ///
1000        /// ## Overflow behavior
1001        ///
1002        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1003        ///
1004        /// # Examples
1005        ///
1006        /// ```
1007        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".strict_add_signed(2), 3);")]
1008        /// ```
1009        ///
1010        /// The following panic because of overflow:
1011        ///
1012        /// ```should_panic
1013        #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_add_signed(-2);")]
1014        /// ```
1015        ///
1016        /// ```should_panic
1017        #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX - 2).strict_add_signed(3);")]
1018        /// ```
1019        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1020        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1021        #[must_use = "this returns the result of the operation, \
1022                      without modifying the original"]
1023        #[inline]
1024        #[track_caller]
1025        pub const fn strict_add_signed(self, rhs: $SignedT) -> Self {
1026            let (a, b) = self.overflowing_add_signed(rhs);
1027            if b { imp::overflow_panic::add() } else { a }
1028        }
1029
1030        /// Checked integer subtraction. Computes `self - rhs`, returning
1031        /// `None` if overflow occurred.
1032        ///
1033        /// # Examples
1034        ///
1035        /// ```
1036        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));")]
1037        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);")]
1038        /// ```
1039        #[stable(feature = "rust1", since = "1.0.0")]
1040        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1041        #[must_use = "this returns the result of the operation, \
1042                      without modifying the original"]
1043        #[inline]
1044        pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
1045            // Per PR#103299, there's no advantage to the `overflowing` intrinsic
1046            // for *unsigned* subtraction and we just emit the manual check anyway.
1047            // Thus, rather than using `overflowing_sub` that produces a wrapping
1048            // subtraction, check it ourself so we can use an unchecked one.
1049
1050            if self < rhs {
1051                None
1052            } else {
1053                // SAFETY: just checked this can't overflow
1054                Some(unsafe { intrinsics::unchecked_sub(self, rhs) })
1055            }
1056        }
1057
1058        /// Strict integer subtraction. Computes `self - rhs`, panicking if
1059        /// overflow occurred.
1060        ///
1061        /// # Panics
1062        ///
1063        /// ## Overflow behavior
1064        ///
1065        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1066        ///
1067        /// # Examples
1068        ///
1069        /// ```
1070        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".strict_sub(1), 0);")]
1071        /// ```
1072        ///
1073        /// The following panics because of overflow:
1074        ///
1075        /// ```should_panic
1076        #[doc = concat!("let _ = 0", stringify!($SelfT), ".strict_sub(1);")]
1077        /// ```
1078        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1079        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1080        #[must_use = "this returns the result of the operation, \
1081                      without modifying the original"]
1082        #[inline]
1083        #[track_caller]
1084        pub const fn strict_sub(self, rhs: Self) -> Self {
1085            let (a, b) = self.overflowing_sub(rhs);
1086            if b { imp::overflow_panic::sub() } else { a }
1087        }
1088
1089        /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
1090        /// cannot occur.
1091        ///
1092        /// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
1093        /// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
1094        ///
1095        /// If you're just trying to avoid the panic in debug mode, then **do not**
1096        /// use this.  Instead, you're looking for [`wrapping_sub`].
1097        ///
1098        /// If you find yourself writing code like this:
1099        ///
1100        /// ```
1101        /// # let foo = 30_u32;
1102        /// # let bar = 20;
1103        /// if foo >= bar {
1104        ///     // SAFETY: just checked it will not overflow
1105        ///     let diff = unsafe { foo.unchecked_sub(bar) };
1106        ///     // ... use diff ...
1107        /// }
1108        /// ```
1109        ///
1110        /// Consider changing it to
1111        ///
1112        /// ```
1113        /// # let foo = 30_u32;
1114        /// # let bar = 20;
1115        /// if let Some(diff) = foo.checked_sub(bar) {
1116        ///     // ... use diff ...
1117        /// }
1118        /// ```
1119        ///
1120        /// As that does exactly the same thing -- including telling the optimizer
1121        /// that the subtraction cannot overflow -- but avoids needing `unsafe`.
1122        ///
1123        /// # Safety
1124        ///
1125        /// This results in undefined behavior when
1126        #[doc = concat!("`self - rhs < ", stringify!($SelfT), "::MIN`,")]
1127        /// i.e. when [`checked_sub`] would return `None`.
1128        ///
1129        /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
1130        #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
1131        #[doc = concat!("[`wrapping_sub`]: ", stringify!($SelfT), "::wrapping_sub")]
1132        #[stable(feature = "unchecked_math", since = "1.79.0")]
1133        #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
1134        #[must_use = "this returns the result of the operation, \
1135                      without modifying the original"]
1136        #[inline(always)]
1137        #[track_caller]
1138        pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
1139            assert_unsafe_precondition!(
1140                check_language_ub,
1141                concat!(stringify!($SelfT), "::unchecked_sub cannot overflow"),
1142                (
1143                    lhs: $SelfT = self,
1144                    rhs: $SelfT = rhs,
1145                ) => !lhs.overflowing_sub(rhs).1,
1146            );
1147
1148            // SAFETY: this is guaranteed to be safe by the caller.
1149            unsafe {
1150                intrinsics::unchecked_sub(self, rhs)
1151            }
1152        }
1153
1154        /// Checked subtraction with a signed integer. Computes `self - rhs`,
1155        /// returning `None` if overflow occurred.
1156        ///
1157        /// # Examples
1158        ///
1159        /// ```
1160        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_signed(2), None);")]
1161        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_signed(-2), Some(3));")]
1162        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_sub_signed(-4), None);")]
1163        /// ```
1164        #[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
1165        #[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
1166        #[must_use = "this returns the result of the operation, \
1167                      without modifying the original"]
1168        #[inline]
1169        pub const fn checked_sub_signed(self, rhs: $SignedT) -> Option<Self> {
1170            let (res, overflow) = self.overflowing_sub_signed(rhs);
1171
1172            if !overflow {
1173                Some(res)
1174            } else {
1175                None
1176            }
1177        }
1178
1179        /// Strict subtraction with a signed integer. Computes `self - rhs`,
1180        /// panicking if overflow occurred.
1181        ///
1182        /// # Panics
1183        ///
1184        /// ## Overflow behavior
1185        ///
1186        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1187        ///
1188        /// # Examples
1189        ///
1190        /// ```
1191        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".strict_sub_signed(2), 1);")]
1192        /// ```
1193        ///
1194        /// The following panic because of overflow:
1195        ///
1196        /// ```should_panic
1197        #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_sub_signed(2);")]
1198        /// ```
1199        ///
1200        /// ```should_panic
1201        #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX).strict_sub_signed(-1);")]
1202        /// ```
1203        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1204        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1205        #[must_use = "this returns the result of the operation, \
1206                      without modifying the original"]
1207        #[inline]
1208        #[track_caller]
1209        pub const fn strict_sub_signed(self, rhs: $SignedT) -> Self {
1210            let (a, b) = self.overflowing_sub_signed(rhs);
1211            if b { imp::overflow_panic::sub() } else { a }
1212        }
1213
1214        #[doc = concat!(
1215            "Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`",
1216            stringify!($SignedT), "`], returning `None` if overflow occurred."
1217        )]
1218        ///
1219        /// # Examples
1220        ///
1221        /// ```
1222        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_signed_diff(2), Some(8));")]
1223        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_signed_diff(10), Some(-8));")]
1224        #[doc = concat!(
1225            "assert_eq!(",
1226            stringify!($SelfT),
1227            "::MAX.checked_signed_diff(",
1228            stringify!($SignedT),
1229            "::MAX as ",
1230            stringify!($SelfT),
1231            "), None);"
1232        )]
1233        #[doc = concat!(
1234            "assert_eq!((",
1235            stringify!($SignedT),
1236            "::MAX as ",
1237            stringify!($SelfT),
1238            ").checked_signed_diff(",
1239            stringify!($SelfT),
1240            "::MAX), Some(",
1241            stringify!($SignedT),
1242            "::MIN));"
1243        )]
1244        #[doc = concat!(
1245            "assert_eq!((",
1246            stringify!($SignedT),
1247            "::MAX as ",
1248            stringify!($SelfT),
1249            " + 1).checked_signed_diff(0), None);"
1250        )]
1251        #[doc = concat!(
1252            "assert_eq!(",
1253            stringify!($SelfT),
1254            "::MAX.checked_signed_diff(",
1255            stringify!($SelfT),
1256            "::MAX), Some(0));"
1257        )]
1258        /// ```
1259        #[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
1260        #[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
1261        #[inline]
1262        pub const fn checked_signed_diff(self, rhs: Self) -> Option<$SignedT> {
1263            let res = self.wrapping_sub(rhs) as $SignedT;
1264            let overflow = (self >= rhs) == (res < 0);
1265
1266            if !overflow {
1267                Some(res)
1268            } else {
1269                None
1270            }
1271        }
1272
1273        /// Checked integer multiplication. Computes `self * rhs`, returning
1274        /// `None` if overflow occurred.
1275        ///
1276        /// # Examples
1277        ///
1278        /// ```
1279        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));")]
1280        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
1281        /// ```
1282        #[stable(feature = "rust1", since = "1.0.0")]
1283        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1284        #[must_use = "this returns the result of the operation, \
1285                      without modifying the original"]
1286        #[inline]
1287        pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
1288            let (a, b) = self.overflowing_mul(rhs);
1289            if intrinsics::unlikely(b) { None } else { Some(a) }
1290        }
1291
1292        /// Strict integer multiplication. Computes `self * rhs`, panicking if
1293        /// overflow occurred.
1294        ///
1295        /// # Panics
1296        ///
1297        /// ## Overflow behavior
1298        ///
1299        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1300        ///
1301        /// # Examples
1302        ///
1303        /// ```
1304        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".strict_mul(1), 5);")]
1305        /// ```
1306        ///
1307        /// The following panics because of overflow:
1308        ///
1309        /// ``` should_panic
1310        #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_mul(2);")]
1311        /// ```
1312        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1313        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1314        #[must_use = "this returns the result of the operation, \
1315                      without modifying the original"]
1316        #[inline]
1317        #[track_caller]
1318        pub const fn strict_mul(self, rhs: Self) -> Self {
1319            let (a, b) = self.overflowing_mul(rhs);
1320            if b { imp::overflow_panic::mul() } else { a }
1321        }
1322
1323        /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
1324        /// cannot occur.
1325        ///
1326        /// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
1327        /// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
1328        ///
1329        /// If you're just trying to avoid the panic in debug mode, then **do not**
1330        /// use this.  Instead, you're looking for [`wrapping_mul`].
1331        ///
1332        /// # Safety
1333        ///
1334        /// This results in undefined behavior when
1335        #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX`,")]
1336        /// i.e. when [`checked_mul`] would return `None`.
1337        ///
1338        /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
1339        #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
1340        #[doc = concat!("[`wrapping_mul`]: ", stringify!($SelfT), "::wrapping_mul")]
1341        #[stable(feature = "unchecked_math", since = "1.79.0")]
1342        #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
1343        #[must_use = "this returns the result of the operation, \
1344                      without modifying the original"]
1345        #[inline(always)]
1346        #[track_caller]
1347        pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
1348            assert_unsafe_precondition!(
1349                check_language_ub,
1350                concat!(stringify!($SelfT), "::unchecked_mul cannot overflow"),
1351                (
1352                    lhs: $SelfT = self,
1353                    rhs: $SelfT = rhs,
1354                ) => !lhs.overflowing_mul(rhs).1,
1355            );
1356
1357            // SAFETY: this is guaranteed to be safe by the caller.
1358            unsafe {
1359                intrinsics::unchecked_mul(self, rhs)
1360            }
1361        }
1362
1363        /// Checked integer division. Computes `self / rhs`, returning `None`
1364        /// if `rhs == 0`.
1365        ///
1366        /// # Examples
1367        ///
1368        /// ```
1369        #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));")]
1370        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);")]
1371        /// ```
1372        #[stable(feature = "rust1", since = "1.0.0")]
1373        #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
1374        #[must_use = "this returns the result of the operation, \
1375                      without modifying the original"]
1376        #[inline]
1377        pub const fn checked_div(self, rhs: Self) -> Option<Self> {
1378            if intrinsics::unlikely(rhs == 0) {
1379                None
1380            } else {
1381                // SAFETY: div by zero has been checked above and unsigned types have no other
1382                // failure modes for division
1383                Some(unsafe { intrinsics::unchecked_div(self, rhs) })
1384            }
1385        }
1386
1387        /// Strict integer division. Computes `self / rhs`.
1388        ///
1389        /// Strict division on unsigned types is just normal division. There's no
1390        /// way overflow could ever happen. This function exists so that all
1391        /// operations are accounted for in the strict operations.
1392        ///
1393        /// # Panics
1394        ///
1395        /// This function will panic if `rhs` is zero.
1396        ///
1397        /// # Examples
1398        ///
1399        /// ```
1400        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_div(10), 10);")]
1401        /// ```
1402        ///
1403        /// The following panics because of division by zero:
1404        ///
1405        /// ```should_panic
1406        #[doc = concat!("let _ = (1", stringify!($SelfT), ").strict_div(0);")]
1407        /// ```
1408        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1409        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1410        #[must_use = "this returns the result of the operation, \
1411                      without modifying the original"]
1412        #[inline(always)]
1413        #[track_caller]
1414        pub const fn strict_div(self, rhs: Self) -> Self {
1415            self / rhs
1416        }
1417
1418        /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
1419        /// if `rhs == 0`.
1420        ///
1421        /// # Examples
1422        ///
1423        /// ```
1424        #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));")]
1425        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);")]
1426        /// ```
1427        #[stable(feature = "euclidean_division", since = "1.38.0")]
1428        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1429        #[must_use = "this returns the result of the operation, \
1430                      without modifying the original"]
1431        #[inline]
1432        pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
1433            if intrinsics::unlikely(rhs == 0) {
1434                None
1435            } else {
1436                Some(self.div_euclid(rhs))
1437            }
1438        }
1439
1440        /// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
1441        ///
1442        /// Strict division on unsigned types is just normal division. There's no
1443        /// way overflow could ever happen. This function exists so that all
1444        /// operations are accounted for in the strict operations. Since, for the
1445        /// positive integers, all common definitions of division are equal, this
1446        /// is exactly equal to `self.strict_div(rhs)`.
1447        ///
1448        /// # Panics
1449        ///
1450        /// This function will panic if `rhs` is zero.
1451        ///
1452        /// # Examples
1453        ///
1454        /// ```
1455        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_div_euclid(10), 10);")]
1456        /// ```
1457        /// The following panics because of division by zero:
1458        ///
1459        /// ```should_panic
1460        #[doc = concat!("let _ = (1", stringify!($SelfT), ").strict_div_euclid(0);")]
1461        /// ```
1462        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1463        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1464        #[must_use = "this returns the result of the operation, \
1465                      without modifying the original"]
1466        #[inline(always)]
1467        #[track_caller]
1468        pub const fn strict_div_euclid(self, rhs: Self) -> Self {
1469            self / rhs
1470        }
1471
1472        /// Checked integer division without remainder. Computes `self / rhs`,
1473        /// returning `None` if `rhs == 0` or if `self % rhs != 0`.
1474        ///
1475        /// # Examples
1476        ///
1477        /// ```
1478        /// #![feature(exact_div)]
1479        #[doc = concat!("assert_eq!(64", stringify!($SelfT), ".checked_div_exact(2), Some(32));")]
1480        #[doc = concat!("assert_eq!(64", stringify!($SelfT), ".checked_div_exact(32), Some(2));")]
1481        #[doc = concat!("assert_eq!(64", stringify!($SelfT), ".checked_div_exact(0), None);")]
1482        #[doc = concat!("assert_eq!(65", stringify!($SelfT), ".checked_div_exact(2), None);")]
1483        /// ```
1484        #[unstable(
1485            feature = "exact_div",
1486            issue = "139911",
1487        )]
1488        #[must_use = "this returns the result of the operation, \
1489                      without modifying the original"]
1490        #[inline]
1491        pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
1492            if intrinsics::unlikely(rhs == 0) {
1493                None
1494            } else {
1495                // SAFETY: division by zero is checked above
1496                unsafe {
1497                    if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0) {
1498                        None
1499                    } else {
1500                        Some(intrinsics::exact_div(self, rhs))
1501                    }
1502                }
1503            }
1504        }
1505
1506        /// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
1507        ///
1508        /// # Panics
1509        ///
1510        /// This function will panic  if `rhs == 0`.
1511        ///
1512        /// # Examples
1513        ///
1514        /// ```
1515        /// #![feature(exact_div)]
1516        #[doc = concat!("assert_eq!(64", stringify!($SelfT), ".div_exact(2), Some(32));")]
1517        #[doc = concat!("assert_eq!(64", stringify!($SelfT), ".div_exact(32), Some(2));")]
1518        #[doc = concat!("assert_eq!(65", stringify!($SelfT), ".div_exact(2), None);")]
1519        /// ```
1520        #[unstable(
1521            feature = "exact_div",
1522            issue = "139911",
1523        )]
1524        #[must_use = "this returns the result of the operation, \
1525                      without modifying the original"]
1526        #[inline]
1527        #[rustc_inherit_overflow_checks]
1528        pub const fn div_exact(self, rhs: Self) -> Option<Self> {
1529            if self % rhs != 0 {
1530                None
1531            } else {
1532                Some(self / rhs)
1533            }
1534        }
1535
1536        /// Unchecked integer division without remainder. Computes `self / rhs`.
1537        ///
1538        /// # Safety
1539        ///
1540        /// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
1541        /// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
1542        #[unstable(
1543            feature = "exact_div",
1544            issue = "139911",
1545        )]
1546        #[must_use = "this returns the result of the operation, \
1547                      without modifying the original"]
1548        #[inline]
1549        pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
1550            assert_unsafe_precondition!(
1551                check_language_ub,
1552                concat!(stringify!($SelfT), "::unchecked_div_exact divide by zero or leave a remainder"),
1553                (
1554                    lhs: $SelfT = self,
1555                    rhs: $SelfT = rhs,
1556                ) => rhs > 0 && lhs % rhs == 0,
1557            );
1558            // SAFETY: Same precondition
1559            unsafe { intrinsics::exact_div(self, rhs) }
1560        }
1561
1562        /// Checked integer remainder. Computes `self % rhs`, returning `None`
1563        /// if `rhs == 0`.
1564        ///
1565        /// # Examples
1566        ///
1567        /// ```
1568        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
1569        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
1570        /// ```
1571        #[stable(feature = "wrapping", since = "1.7.0")]
1572        #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
1573        #[must_use = "this returns the result of the operation, \
1574                      without modifying the original"]
1575        #[inline]
1576        pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
1577            if intrinsics::unlikely(rhs == 0) {
1578                None
1579            } else {
1580                // SAFETY: div by zero has been checked above and unsigned types have no other
1581                // failure modes for division
1582                Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
1583            }
1584        }
1585
1586        /// Strict integer remainder. Computes `self % rhs`.
1587        ///
1588        /// Strict remainder calculation on unsigned types is just the regular
1589        /// remainder calculation. There's no way overflow could ever happen.
1590        /// This function exists so that all operations are accounted for in the
1591        /// strict operations.
1592        ///
1593        /// # Panics
1594        ///
1595        /// This function will panic if `rhs` is zero.
1596        ///
1597        /// # Examples
1598        ///
1599        /// ```
1600        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_rem(10), 0);")]
1601        /// ```
1602        ///
1603        /// The following panics because of division by zero:
1604        ///
1605        /// ```should_panic
1606        #[doc = concat!("let _ = 5", stringify!($SelfT), ".strict_rem(0);")]
1607        /// ```
1608        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1609        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1610        #[must_use = "this returns the result of the operation, \
1611                      without modifying the original"]
1612        #[inline(always)]
1613        #[track_caller]
1614        pub const fn strict_rem(self, rhs: Self) -> Self {
1615            self % rhs
1616        }
1617
1618        /// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
1619        /// if `rhs == 0`.
1620        ///
1621        /// # Examples
1622        ///
1623        /// ```
1624        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
1625        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
1626        /// ```
1627        #[stable(feature = "euclidean_division", since = "1.38.0")]
1628        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1629        #[must_use = "this returns the result of the operation, \
1630                      without modifying the original"]
1631        #[inline]
1632        pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
1633            if intrinsics::unlikely(rhs == 0) {
1634                None
1635            } else {
1636                Some(self.rem_euclid(rhs))
1637            }
1638        }
1639
1640        /// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1641        ///
1642        /// Strict modulo calculation on unsigned types is just the regular
1643        /// remainder calculation. There's no way overflow could ever happen.
1644        /// This function exists so that all operations are accounted for in the
1645        /// strict operations. Since, for the positive integers, all common
1646        /// definitions of division are equal, this is exactly equal to
1647        /// `self.strict_rem(rhs)`.
1648        ///
1649        /// # Panics
1650        ///
1651        /// This function will panic if `rhs` is zero.
1652        ///
1653        /// # Examples
1654        ///
1655        /// ```
1656        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_rem_euclid(10), 0);")]
1657        /// ```
1658        ///
1659        /// The following panics because of division by zero:
1660        ///
1661        /// ```should_panic
1662        #[doc = concat!("let _ = 5", stringify!($SelfT), ".strict_rem_euclid(0);")]
1663        /// ```
1664        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1665        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1666        #[must_use = "this returns the result of the operation, \
1667                      without modifying the original"]
1668        #[inline(always)]
1669        #[track_caller]
1670        pub const fn strict_rem_euclid(self, rhs: Self) -> Self {
1671            self % rhs
1672        }
1673
1674        /// Same value as `self | other`, but UB if any bit position is set in both inputs.
1675        ///
1676        /// This is a situational micro-optimization for places where you'd rather
1677        /// use addition on some platforms and bitwise or on other platforms, based
1678        /// on exactly which instructions combine better with whatever else you're
1679        /// doing.  Note that there's no reason to bother using this for places
1680        /// where it's clear from the operations involved that they can't overlap.
1681        /// For example, if you're combining `u16`s into a `u32` with
1682        /// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
1683        /// know those sides of the `|` are disjoint without needing help.
1684        ///
1685        /// # Examples
1686        ///
1687        /// ```
1688        /// #![feature(disjoint_bitor)]
1689        ///
1690        /// // SAFETY: `1` and `4` have no bits in common.
1691        /// unsafe {
1692        #[doc = concat!("    assert_eq!(1_", stringify!($SelfT), ".unchecked_disjoint_bitor(4), 5);")]
1693        /// }
1694        /// ```
1695        ///
1696        /// # Safety
1697        ///
1698        /// Requires that `(self & other) == 0`, otherwise it's immediate UB.
1699        ///
1700        /// Equivalently, requires that `(self | other) == (self + other)`.
1701        #[unstable(feature = "disjoint_bitor", issue = "135758")]
1702        #[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
1703        #[inline]
1704        pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
1705            assert_unsafe_precondition!(
1706                check_language_ub,
1707                concat!(stringify!($SelfT), "::unchecked_disjoint_bitor cannot have overlapping bits"),
1708                (
1709                    lhs: $SelfT = self,
1710                    rhs: $SelfT = other,
1711                ) => (lhs & rhs) == 0,
1712            );
1713
1714            // SAFETY: Same precondition
1715            unsafe { intrinsics::disjoint_bitor(self, other) }
1716        }
1717
1718        /// Returns the logarithm of the number with respect to an arbitrary base,
1719        /// rounded down.
1720        ///
1721        /// This method might not be optimized owing to implementation details;
1722        /// `ilog2` can produce results more efficiently for base 2, and `ilog10`
1723        /// can produce results more efficiently for base 10.
1724        ///
1725        /// # Panics
1726        ///
1727        /// This function will panic if `self` is zero, or if `base` is less than 2.
1728        ///
1729        /// # Examples
1730        ///
1731        /// ```
1732        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".ilog(5), 1);")]
1733        /// ```
1734        #[stable(feature = "int_log", since = "1.67.0")]
1735        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1736        #[must_use = "this returns the result of the operation, \
1737                      without modifying the original"]
1738        #[inline]
1739        #[track_caller]
1740        pub const fn ilog(self, base: Self) -> u32 {
1741            assert!(base >= 2, "base of integer logarithm must be at least 2");
1742            if let Some(log) = self.checked_ilog(base) {
1743                log
1744            } else {
1745                imp::int_log10::panic_for_nonpositive_argument()
1746            }
1747        }
1748
1749        /// Returns the base 2 logarithm of the number, rounded down.
1750        ///
1751        /// # Panics
1752        ///
1753        /// This function will panic if `self` is zero.
1754        ///
1755        /// # Examples
1756        ///
1757        /// ```
1758        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".ilog2(), 1);")]
1759        /// ```
1760        #[stable(feature = "int_log", since = "1.67.0")]
1761        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1762        #[must_use = "this returns the result of the operation, \
1763                      without modifying the original"]
1764        #[inline]
1765        #[track_caller]
1766        pub const fn ilog2(self) -> u32 {
1767            if let Some(log) = self.checked_ilog2() {
1768                log
1769            } else {
1770                imp::int_log10::panic_for_nonpositive_argument()
1771            }
1772        }
1773
1774        /// Returns the base 10 logarithm of the number, rounded down.
1775        ///
1776        /// # Panics
1777        ///
1778        /// This function will panic if `self` is zero.
1779        ///
1780        /// # Example
1781        ///
1782        /// ```
1783        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".ilog10(), 1);")]
1784        /// ```
1785        #[stable(feature = "int_log", since = "1.67.0")]
1786        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1787        #[must_use = "this returns the result of the operation, \
1788                      without modifying the original"]
1789        #[inline]
1790        #[track_caller]
1791        pub const fn ilog10(self) -> u32 {
1792            if let Some(log) = self.checked_ilog10() {
1793                log
1794            } else {
1795                imp::int_log10::panic_for_nonpositive_argument()
1796            }
1797        }
1798
1799        /// Returns the logarithm of the number with respect to an arbitrary base,
1800        /// rounded down.
1801        ///
1802        /// Returns `None` if the number is zero, or if the base is not at least 2.
1803        ///
1804        /// This method might not be optimized owing to implementation details;
1805        /// `checked_ilog2` can produce results more efficiently for base 2, and
1806        /// `checked_ilog10` can produce results more efficiently for base 10.
1807        ///
1808        /// # Examples
1809        ///
1810        /// ```
1811        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_ilog(5), Some(1));")]
1812        /// ```
1813        #[stable(feature = "int_log", since = "1.67.0")]
1814        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1815        #[must_use = "this returns the result of the operation, \
1816                      without modifying the original"]
1817        #[inline]
1818        pub const fn checked_ilog(self, base: Self) -> Option<u32> {
1819            // Inform compiler of optimizations when the base is known at
1820            // compile time and there's a cheaper method available.
1821            //
1822            // Note: Like all optimizations, this is not guaranteed to be
1823            // applied by the compiler. If you want those specific bases,
1824            // use `.checked_ilog2()` or `.checked_ilog10()` directly.
1825            if core::intrinsics::is_val_statically_known(base) {
1826                if base == 2 {
1827                    return self.checked_ilog2();
1828                } else if base == 10 {
1829                    return self.checked_ilog10();
1830                }
1831            }
1832
1833            if self <= 0 || base <= 1 {
1834                None
1835            } else if self < base {
1836                Some(0)
1837            } else {
1838                // Since base >= self, n >= 1
1839                let mut n = 1;
1840                let mut r = base;
1841
1842                // Optimization for 128 bit wide integers.
1843                if Self::BITS == 128 {
1844                    // The following is a correct lower bound for ⌊log(base,self)⌋ because
1845                    //
1846                    // log(base,self) = log(2,self) / log(2,base)
1847                    //                ≥ ⌊log(2,self)⌋ / (⌊log(2,base)⌋ + 1)
1848                    //
1849                    // hence
1850                    //
1851                    // ⌊log(base,self)⌋ ≥ ⌊ ⌊log(2,self)⌋ / (⌊log(2,base)⌋ + 1) ⌋ .
1852                    n = self.ilog2() / (base.ilog2() + 1);
1853                    r = base.pow(n);
1854                }
1855
1856                while r <= self / base {
1857                    n += 1;
1858                    r *= base;
1859                }
1860                Some(n)
1861            }
1862        }
1863
1864        /// Returns the base 2 logarithm of the number, rounded down.
1865        ///
1866        /// Returns `None` if the number is zero.
1867        ///
1868        /// # Examples
1869        ///
1870        /// ```
1871        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_ilog2(), Some(1));")]
1872        /// ```
1873        #[stable(feature = "int_log", since = "1.67.0")]
1874        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1875        #[must_use = "this returns the result of the operation, \
1876                      without modifying the original"]
1877        #[inline]
1878        pub const fn checked_ilog2(self) -> Option<u32> {
1879            match NonZero::new(self) {
1880                Some(x) => Some(x.ilog2()),
1881                None => None,
1882            }
1883        }
1884
1885        /// Returns the base 10 logarithm of the number, rounded down.
1886        ///
1887        /// Returns `None` if the number is zero.
1888        ///
1889        /// # Examples
1890        ///
1891        /// ```
1892        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_ilog10(), Some(1));")]
1893        /// ```
1894        #[stable(feature = "int_log", since = "1.67.0")]
1895        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1896        #[must_use = "this returns the result of the operation, \
1897                      without modifying the original"]
1898        #[inline]
1899        pub const fn checked_ilog10(self) -> Option<u32> {
1900            match NonZero::new(self) {
1901                Some(x) => Some(x.ilog10()),
1902                None => None,
1903            }
1904        }
1905
1906        /// Checked negation. Computes `-self`, returning `None` unless `self ==
1907        /// 0`.
1908        ///
1909        /// Note that negating any positive integer will overflow.
1910        ///
1911        /// # Examples
1912        ///
1913        /// ```
1914        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));")]
1915        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);")]
1916        /// ```
1917        #[stable(feature = "wrapping", since = "1.7.0")]
1918        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1919        #[must_use = "this returns the result of the operation, \
1920                      without modifying the original"]
1921        #[inline]
1922        pub const fn checked_neg(self) -> Option<Self> {
1923            let (a, b) = self.overflowing_neg();
1924            if intrinsics::unlikely(b) { None } else { Some(a) }
1925        }
1926
1927        /// Strict negation. Computes `-self`, panicking unless `self ==
1928        /// 0`.
1929        ///
1930        /// Note that negating any positive integer will overflow.
1931        ///
1932        /// # Panics
1933        ///
1934        /// ## Overflow behavior
1935        ///
1936        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1937        ///
1938        /// # Examples
1939        ///
1940        /// ```
1941        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".strict_neg(), 0);")]
1942        /// ```
1943        ///
1944        /// The following panics because of overflow:
1945        ///
1946        /// ```should_panic
1947        #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_neg();")]
1948        /// ```
1949        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1950        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1951        #[must_use = "this returns the result of the operation, \
1952                      without modifying the original"]
1953        #[inline]
1954        #[track_caller]
1955        pub const fn strict_neg(self) -> Self {
1956            let (a, b) = self.overflowing_neg();
1957            if b { imp::overflow_panic::neg() } else { a }
1958        }
1959
1960        /// Checked shift left. Computes `self << rhs`, returning `None`
1961        /// if `rhs` is larger than or equal to the number of bits in `self`.
1962        ///
1963        /// # Examples
1964        ///
1965        /// ```
1966        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
1967        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")]
1968        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(", stringify!($BITS_MINUS_ONE), "), Some(0));")]
1969        /// ```
1970        #[stable(feature = "wrapping", since = "1.7.0")]
1971        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1972        #[must_use = "this returns the result of the operation, \
1973                      without modifying the original"]
1974        #[inline]
1975        pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
1976            // Not using overflowing_shl as that's a wrapping shift
1977            if rhs < Self::BITS {
1978                // SAFETY: just checked the RHS is in-range
1979                Some(unsafe { self.unchecked_shl(rhs) })
1980            } else {
1981                None
1982            }
1983        }
1984
1985        /// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
1986        /// than or equal to the number of bits in `self`.
1987        ///
1988        /// # Panics
1989        ///
1990        /// ## Overflow behavior
1991        ///
1992        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1993        ///
1994        /// # Examples
1995        ///
1996        /// ```
1997        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".strict_shl(4), 0x10);")]
1998        /// ```
1999        ///
2000        /// The following panics because of overflow:
2001        ///
2002        /// ```should_panic
2003        #[doc = concat!("let _ = 0x10", stringify!($SelfT), ".strict_shl(129);")]
2004        /// ```
2005        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
2006        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
2007        #[must_use = "this returns the result of the operation, \
2008                      without modifying the original"]
2009        #[inline]
2010        #[track_caller]
2011        pub const fn strict_shl(self, rhs: u32) -> Self {
2012            let (a, b) = self.overflowing_shl(rhs);
2013            if b { imp::overflow_panic::shl() } else { a }
2014        }
2015
2016        /// Unchecked shift left. Computes `self << rhs`, assuming that
2017        /// `rhs` is less than the number of bits in `self`.
2018        ///
2019        /// # Safety
2020        ///
2021        /// This results in undefined behavior if `rhs` is larger than
2022        /// or equal to the number of bits in `self`,
2023        /// i.e. when [`checked_shl`] would return `None`.
2024        ///
2025        #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
2026        #[stable(feature = "unchecked_shifts", since = "1.93.0")]
2027        #[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
2028        #[must_use = "this returns the result of the operation, \
2029                      without modifying the original"]
2030        #[inline(always)]
2031        #[track_caller]
2032        pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
2033            assert_unsafe_precondition!(
2034                check_language_ub,
2035                concat!(stringify!($SelfT), "::unchecked_shl cannot overflow"),
2036                (
2037                    rhs: u32 = rhs,
2038                ) => rhs < <$ActualT>::BITS,
2039            );
2040
2041            // SAFETY: this is guaranteed to be safe by the caller.
2042            unsafe {
2043                intrinsics::unchecked_shl(self, rhs)
2044            }
2045        }
2046
2047        /// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
2048        ///
2049        /// If `rhs` is larger or equal to the number of bits in `self`,
2050        /// the entire value is shifted out, and `0` is returned.
2051        ///
2052        /// # Examples
2053        ///
2054        /// ```
2055        #[doc = concat!("assert_eq!(0x1_", stringify!($SelfT), ".unbounded_shl(4), 0x10);")]
2056        #[doc = concat!("assert_eq!(0x1_", stringify!($SelfT), ".unbounded_shl(129), 0);")]
2057        #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".unbounded_shl(0), 0b101);")]
2058        #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".unbounded_shl(1), 0b1010);")]
2059        #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".unbounded_shl(2), 0b10100);")]
2060        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".unbounded_shl(", stringify!($BITS), "), 0);")]
2061        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".unbounded_shl(1).unbounded_shl(", stringify!($BITS_MINUS_ONE), "), 0);")]
2062        ///
2063        #[doc = concat!("let start : ", stringify!($SelfT), " = 13;")]
2064        /// let mut running = start;
2065        /// for i in 0..160 {
2066        ///     // The unbounded shift left by i is the same as `<< 1` i times
2067        ///     assert_eq!(running, start.unbounded_shl(i));
2068        ///     // Which is not always the case for a wrapping shift
2069        #[doc = concat!("    assert_eq!(running == start.wrapping_shl(i), i < ", stringify!($BITS), ");")]
2070        ///
2071        ///     running <<= 1;
2072        /// }
2073        /// ```
2074        #[stable(feature = "unbounded_shifts", since = "1.87.0")]
2075        #[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
2076        #[must_use = "this returns the result of the operation, \
2077                      without modifying the original"]
2078        #[inline]
2079        pub const fn unbounded_shl(self, rhs: u32) -> $SelfT{
2080            if rhs < Self::BITS {
2081                // SAFETY:
2082                // rhs is just checked to be in-range above
2083                unsafe { self.unchecked_shl(rhs) }
2084            } else {
2085                0
2086            }
2087        }
2088
2089        /// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
2090        ///
2091        /// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
2092        #[doc = concat!("`", stringify!($SelfT), "::BITS`.")]
2093        /// Otherwise, returns `Some(self << rhs)`.
2094        ///
2095        /// # Examples
2096        ///
2097        /// ```
2098        /// #![feature(exact_bitshifts)]
2099        ///
2100        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".shl_exact(4), Some(0x10));")]
2101        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".shl_exact(129), None);")]
2102        /// ```
2103        #[unstable(feature = "exact_bitshifts", issue = "144336")]
2104        #[must_use = "this returns the result of the operation, \
2105                      without modifying the original"]
2106        #[inline]
2107        pub const fn shl_exact(self, rhs: u32) -> Option<$SelfT> {
2108            if rhs <= self.leading_zeros() && rhs < <$SelfT>::BITS {
2109                // SAFETY: rhs is checked above
2110                Some(unsafe { self.unchecked_shl(rhs) })
2111            } else {
2112                None
2113            }
2114        }
2115
2116        /// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
2117        /// losslessly reversed `rhs` cannot be larger than
2118        #[doc = concat!("`", stringify!($SelfT), "::BITS`.")]
2119        ///
2120        /// # Safety
2121        ///
2122        /// This results in undefined behavior when `rhs > self.leading_zeros() || rhs >=
2123        #[doc = concat!(stringify!($SelfT), "::BITS`")]
2124        /// i.e. when
2125        #[doc = concat!("[`", stringify!($SelfT), "::shl_exact`]")]
2126        /// would return `None`.
2127        #[unstable(feature = "exact_bitshifts", issue = "144336")]
2128        #[must_use = "this returns the result of the operation, \
2129                      without modifying the original"]
2130        #[inline]
2131        pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> $SelfT {
2132            assert_unsafe_precondition!(
2133                check_library_ub,
2134                concat!(stringify!($SelfT), "::unchecked_shl_exact cannot shift out non-zero bits"),
2135                (
2136                    zeros: u32 = self.leading_zeros(),
2137                    bits: u32 =  <$SelfT>::BITS,
2138                    rhs: u32 = rhs,
2139                ) => rhs <= zeros && rhs < bits,
2140            );
2141
2142            // SAFETY: this is guaranteed to be safe by the caller
2143            unsafe { self.unchecked_shl(rhs) }
2144        }
2145
2146        /// Checked shift right. Computes `self >> rhs`, returning `None`
2147        /// if `rhs` is larger than or equal to the number of bits in `self`.
2148        ///
2149        /// # Examples
2150        ///
2151        /// ```
2152        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
2153        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);")]
2154        /// ```
2155        #[stable(feature = "wrapping", since = "1.7.0")]
2156        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
2157        #[must_use = "this returns the result of the operation, \
2158                      without modifying the original"]
2159        #[inline]
2160        pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
2161            // Not using overflowing_shr as that's a wrapping shift
2162            if rhs < Self::BITS {
2163                // SAFETY: just checked the RHS is in-range
2164                Some(unsafe { self.unchecked_shr(rhs) })
2165            } else {
2166                None
2167            }
2168        }
2169
2170        /// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
2171        /// larger than or equal to the number of bits in `self`.
2172        ///
2173        /// # Panics
2174        ///
2175        /// ## Overflow behavior
2176        ///
2177        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
2178        ///
2179        /// # Examples
2180        ///
2181        /// ```
2182        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".strict_shr(4), 0x1);")]
2183        /// ```
2184        ///
2185        /// The following panics because of overflow:
2186        ///
2187        /// ```should_panic
2188        #[doc = concat!("let _ = 0x10", stringify!($SelfT), ".strict_shr(129);")]
2189        /// ```
2190        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
2191        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
2192        #[must_use = "this returns the result of the operation, \
2193                      without modifying the original"]
2194        #[inline]
2195        #[track_caller]
2196        pub const fn strict_shr(self, rhs: u32) -> Self {
2197            let (a, b) = self.overflowing_shr(rhs);
2198            if b { imp::overflow_panic::shr() } else { a }
2199        }
2200
2201        /// Unchecked shift right. Computes `self >> rhs`, assuming that
2202        /// `rhs` is less than the number of bits in `self`.
2203        ///
2204        /// # Safety
2205        ///
2206        /// This results in undefined behavior if `rhs` is larger than
2207        /// or equal to the number of bits in `self`,
2208        /// i.e. when [`checked_shr`] would return `None`.
2209        ///
2210        #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
2211        #[stable(feature = "unchecked_shifts", since = "1.93.0")]
2212        #[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
2213        #[must_use = "this returns the result of the operation, \
2214                      without modifying the original"]
2215        #[inline(always)]
2216        #[track_caller]
2217        pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
2218            assert_unsafe_precondition!(
2219                check_language_ub,
2220                concat!(stringify!($SelfT), "::unchecked_shr cannot overflow"),
2221                (
2222                    rhs: u32 = rhs,
2223                ) => rhs < <$ActualT>::BITS,
2224            );
2225
2226            // SAFETY: this is guaranteed to be safe by the caller.
2227            unsafe {
2228                intrinsics::unchecked_shr(self, rhs)
2229            }
2230        }
2231
2232        /// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
2233        ///
2234        /// If `rhs` is larger or equal to the number of bits in `self`,
2235        /// the entire value is shifted out, and `0` is returned.
2236        ///
2237        /// # Examples
2238        ///
2239        /// ```
2240        #[doc = concat!("assert_eq!(0x10_", stringify!($SelfT), ".unbounded_shr(4), 0x1);")]
2241        #[doc = concat!("assert_eq!(0x10_", stringify!($SelfT), ".unbounded_shr(129), 0);")]
2242        #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".unbounded_shr(0), 0b1010);")]
2243        #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".unbounded_shr(1), 0b101);")]
2244        #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".unbounded_shr(2), 0b10);")]
2245        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".unbounded_shr(", stringify!($BITS), "), 0);")]
2246        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".unbounded_shr(1).unbounded_shr(", stringify!($BITS_MINUS_ONE), "), 0);")]
2247        ///
2248        #[doc = concat!("let start = ", stringify!($SelfT), "::rotate_right(13, 4);")]
2249        /// let mut running = start;
2250        /// for i in 0..160 {
2251        ///     // The unbounded shift right by i is the same as `>> 1` i times
2252        ///     assert_eq!(running, start.unbounded_shr(i));
2253        ///     // Which is not always the case for a wrapping shift
2254        #[doc = concat!("    assert_eq!(running == start.wrapping_shr(i), i < ", stringify!($BITS), ");")]
2255        ///
2256        ///     running >>= 1;
2257        /// }
2258        /// ```
2259        #[stable(feature = "unbounded_shifts", since = "1.87.0")]
2260        #[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
2261        #[must_use = "this returns the result of the operation, \
2262                      without modifying the original"]
2263        #[inline]
2264        pub const fn unbounded_shr(self, rhs: u32) -> $SelfT{
2265            if rhs < Self::BITS {
2266                // SAFETY:
2267                // rhs is just checked to be in-range above
2268                unsafe { self.unchecked_shr(rhs) }
2269            } else {
2270                0
2271            }
2272        }
2273
2274        /// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
2275        ///
2276        /// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
2277        #[doc = concat!("`", stringify!($SelfT), "::BITS`.")]
2278        /// Otherwise, returns `Some(self >> rhs)`.
2279        ///
2280        /// # Examples
2281        ///
2282        /// ```
2283        /// #![feature(exact_bitshifts)]
2284        ///
2285        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".shr_exact(4), Some(0x1));")]
2286        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".shr_exact(5), None);")]
2287        /// ```
2288        #[unstable(feature = "exact_bitshifts", issue = "144336")]
2289        #[must_use = "this returns the result of the operation, \
2290                      without modifying the original"]
2291        #[inline]
2292        pub const fn shr_exact(self, rhs: u32) -> Option<$SelfT> {
2293            if rhs <= self.trailing_zeros() && rhs < <$SelfT>::BITS {
2294                // SAFETY: rhs is checked above
2295                Some(unsafe { self.unchecked_shr(rhs) })
2296            } else {
2297                None
2298            }
2299        }
2300
2301        /// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
2302        /// losslessly reversed and `rhs` cannot be larger than
2303        #[doc = concat!("`", stringify!($SelfT), "::BITS`.")]
2304        ///
2305        /// # Safety
2306        ///
2307        /// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
2308        #[doc = concat!(stringify!($SelfT), "::BITS`")]
2309        /// i.e. when
2310        #[doc = concat!("[`", stringify!($SelfT), "::shr_exact`]")]
2311        /// would return `None`.
2312        #[unstable(feature = "exact_bitshifts", issue = "144336")]
2313        #[must_use = "this returns the result of the operation, \
2314                      without modifying the original"]
2315        #[inline]
2316        pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> $SelfT {
2317            assert_unsafe_precondition!(
2318                check_library_ub,
2319                concat!(stringify!($SelfT), "::unchecked_shr_exact cannot shift out non-zero bits"),
2320                (
2321                    zeros: u32 = self.trailing_zeros(),
2322                    bits: u32 =  <$SelfT>::BITS,
2323                    rhs: u32 = rhs,
2324                ) => rhs <= zeros && rhs < bits,
2325            );
2326
2327            // SAFETY: this is guaranteed to be safe by the caller
2328            unsafe { self.unchecked_shr(rhs) }
2329        }
2330
2331        /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2332        /// overflow occurred.
2333        ///
2334        /// # Examples
2335        ///
2336        /// ```
2337        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));")]
2338        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".checked_pow(0), Some(1));")]
2339        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
2340        /// ```
2341        #[stable(feature = "no_panic_pow", since = "1.34.0")]
2342        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2343        #[must_use = "this returns the result of the operation, \
2344                      without modifying the original"]
2345        #[inline]
2346        pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
2347            if exp == 0 {
2348                return Some(1);
2349            }
2350            let mut base = self;
2351            let mut acc: Self = 1;
2352
2353            loop {
2354                if (exp & 1) == 1 {
2355                    acc = try_opt!(acc.checked_mul(base));
2356                    // since exp!=0, finally the exp must be 1.
2357                    if exp == 1 {
2358                        return Some(acc);
2359                    }
2360                }
2361                exp /= 2;
2362                base = try_opt!(base.checked_mul(base));
2363            }
2364        }
2365
2366        /// Strict exponentiation. Computes `self.pow(exp)`, panicking if
2367        /// overflow occurred.
2368        ///
2369        /// # Panics
2370        ///
2371        /// ## Overflow behavior
2372        ///
2373        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
2374        ///
2375        /// # Examples
2376        ///
2377        /// ```
2378        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".strict_pow(5), 32);")]
2379        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".strict_pow(0), 1);")]
2380        /// ```
2381        ///
2382        /// The following panics because of overflow:
2383        ///
2384        /// ```should_panic
2385        #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_pow(2);")]
2386        /// ```
2387        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
2388        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
2389        #[must_use = "this returns the result of the operation, \
2390                      without modifying the original"]
2391        #[inline]
2392        #[track_caller]
2393        pub const fn strict_pow(self, mut exp: u32) -> Self {
2394            if exp == 0 {
2395                return 1;
2396            }
2397            let mut base = self;
2398            let mut acc: Self = 1;
2399
2400            loop {
2401                if (exp & 1) == 1 {
2402                    acc = acc.strict_mul(base);
2403                    // since exp!=0, finally the exp must be 1.
2404                    if exp == 1 {
2405                        return acc;
2406                    }
2407                }
2408                exp /= 2;
2409                base = base.strict_mul(base);
2410            }
2411        }
2412
2413        /// Saturating integer addition. Computes `self + rhs`, saturating at
2414        /// the numeric bounds instead of overflowing.
2415        ///
2416        /// # Examples
2417        ///
2418        /// ```
2419        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
2420        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")]
2421        /// ```
2422        #[stable(feature = "rust1", since = "1.0.0")]
2423        #[must_use = "this returns the result of the operation, \
2424                      without modifying the original"]
2425        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
2426        #[inline(always)]
2427        pub const fn saturating_add(self, rhs: Self) -> Self {
2428            intrinsics::saturating_add(self, rhs)
2429        }
2430
2431        /// Saturating addition with a signed integer. Computes `self + rhs`,
2432        /// saturating at the numeric bounds instead of overflowing.
2433        ///
2434        /// # Examples
2435        ///
2436        /// ```
2437        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(2), 3);")]
2438        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(-2), 0);")]
2439        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_add_signed(4), ", stringify!($SelfT), "::MAX);")]
2440        /// ```
2441        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2442        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2443        #[must_use = "this returns the result of the operation, \
2444                      without modifying the original"]
2445        #[inline]
2446        pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self {
2447            let (res, overflow) = self.overflowing_add(rhs as Self);
2448            if overflow == (rhs < 0) {
2449                res
2450            } else if overflow {
2451                Self::MAX
2452            } else {
2453                0
2454            }
2455        }
2456
2457        /// Saturating integer subtraction. Computes `self - rhs`, saturating
2458        /// at the numeric bounds instead of overflowing.
2459        ///
2460        /// # Examples
2461        ///
2462        /// ```
2463        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);")]
2464        #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")]
2465        /// ```
2466        #[stable(feature = "rust1", since = "1.0.0")]
2467        #[must_use = "this returns the result of the operation, \
2468                      without modifying the original"]
2469        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
2470        #[inline(always)]
2471        pub const fn saturating_sub(self, rhs: Self) -> Self {
2472            intrinsics::saturating_sub(self, rhs)
2473        }
2474
2475        /// Saturating integer subtraction. Computes `self` - `rhs`, saturating at
2476        /// the numeric bounds instead of overflowing.
2477        ///
2478        /// # Examples
2479        ///
2480        /// ```
2481        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_sub_signed(2), 0);")]
2482        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_sub_signed(-2), 3);")]
2483        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_sub_signed(-4), ", stringify!($SelfT), "::MAX);")]
2484        /// ```
2485        #[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
2486        #[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
2487        #[must_use = "this returns the result of the operation, \
2488                      without modifying the original"]
2489        #[inline]
2490        pub const fn saturating_sub_signed(self, rhs: $SignedT) -> Self {
2491            let (res, overflow) = self.overflowing_sub_signed(rhs);
2492
2493            if !overflow {
2494                res
2495            } else if rhs < 0 {
2496                Self::MAX
2497            } else {
2498                0
2499            }
2500        }
2501
2502        /// Saturating integer multiplication. Computes `self * rhs`,
2503        /// saturating at the numeric bounds instead of overflowing.
2504        ///
2505        /// # Examples
2506        ///
2507        /// ```
2508        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);")]
2509        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")]
2510        /// ```
2511        #[stable(feature = "wrapping", since = "1.7.0")]
2512        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
2513        #[must_use = "this returns the result of the operation, \
2514                      without modifying the original"]
2515        #[inline]
2516        pub const fn saturating_mul(self, rhs: Self) -> Self {
2517            match self.checked_mul(rhs) {
2518                Some(x) => x,
2519                None => Self::MAX,
2520            }
2521        }
2522
2523        /// Saturating integer division. Computes `self / rhs`, saturating at the
2524        /// numeric bounds instead of overflowing.
2525        ///
2526        /// # Panics
2527        ///
2528        /// This function will panic if `rhs` is zero.
2529        ///
2530        /// # Examples
2531        ///
2532        /// ```
2533        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
2534        ///
2535        /// ```
2536        #[stable(feature = "saturating_div", since = "1.58.0")]
2537        #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
2538        #[must_use = "this returns the result of the operation, \
2539                      without modifying the original"]
2540        #[inline]
2541        #[track_caller]
2542        pub const fn saturating_div(self, rhs: Self) -> Self {
2543            // on unsigned types, there is no overflow in integer division
2544            self.wrapping_div(rhs)
2545        }
2546
2547        /// Saturating integer exponentiation. Computes `self.pow(exp)`,
2548        /// saturating at the numeric bounds instead of overflowing.
2549        ///
2550        /// # Examples
2551        ///
2552        /// ```
2553        #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")]
2554        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".saturating_pow(0), 1);")]
2555        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
2556        /// ```
2557        #[stable(feature = "no_panic_pow", since = "1.34.0")]
2558        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2559        #[must_use = "this returns the result of the operation, \
2560                      without modifying the original"]
2561        #[inline]
2562        pub const fn saturating_pow(self, exp: u32) -> Self {
2563            match self.checked_pow(exp) {
2564                Some(x) => x,
2565                None => Self::MAX,
2566            }
2567        }
2568
2569        /// Wrapping (modular) addition. Computes `self + rhs`,
2570        /// wrapping around at the boundary of the type.
2571        ///
2572        /// # Examples
2573        ///
2574        /// ```
2575        #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")]
2576        #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")]
2577        /// ```
2578        #[stable(feature = "rust1", since = "1.0.0")]
2579        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2580        #[must_use = "this returns the result of the operation, \
2581                      without modifying the original"]
2582        #[inline(always)]
2583        pub const fn wrapping_add(self, rhs: Self) -> Self {
2584            intrinsics::wrapping_add(self, rhs)
2585        }
2586
2587        /// Wrapping (modular) addition with a signed integer. Computes
2588        /// `self + rhs`, wrapping around at the boundary of the type.
2589        ///
2590        /// # Examples
2591        ///
2592        /// ```
2593        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(2), 3);")]
2594        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(-2), ", stringify!($SelfT), "::MAX);")]
2595        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);")]
2596        /// ```
2597        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2598        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2599        #[must_use = "this returns the result of the operation, \
2600                      without modifying the original"]
2601        #[inline]
2602        pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self {
2603            self.wrapping_add(rhs as Self)
2604        }
2605
2606        /// Wrapping (modular) subtraction. Computes `self - rhs`,
2607        /// wrapping around at the boundary of the type.
2608        ///
2609        /// # Examples
2610        ///
2611        /// ```
2612        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")]
2613        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")]
2614        /// ```
2615        #[stable(feature = "rust1", since = "1.0.0")]
2616        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2617        #[must_use = "this returns the result of the operation, \
2618                      without modifying the original"]
2619        #[inline(always)]
2620        pub const fn wrapping_sub(self, rhs: Self) -> Self {
2621            intrinsics::wrapping_sub(self, rhs)
2622        }
2623
2624        /// Wrapping (modular) subtraction with a signed integer. Computes
2625        /// `self - rhs`, wrapping around at the boundary of the type.
2626        ///
2627        /// # Examples
2628        ///
2629        /// ```
2630        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_sub_signed(2), ", stringify!($SelfT), "::MAX);")]
2631        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_sub_signed(-2), 3);")]
2632        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_sub_signed(-4), 1);")]
2633        /// ```
2634        #[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
2635        #[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
2636        #[must_use = "this returns the result of the operation, \
2637                      without modifying the original"]
2638        #[inline]
2639        pub const fn wrapping_sub_signed(self, rhs: $SignedT) -> Self {
2640            self.wrapping_sub(rhs as Self)
2641        }
2642
2643        /// Wrapping (modular) multiplication. Computes `self *
2644        /// rhs`, wrapping around at the boundary of the type.
2645        ///
2646        /// # Examples
2647        ///
2648        /// Please note that this example is shared among integer types, which is why `u8` is used.
2649        ///
2650        /// ```
2651        /// assert_eq!(10u8.wrapping_mul(12), 120);
2652        /// assert_eq!(25u8.wrapping_mul(12), 44);
2653        /// ```
2654        #[stable(feature = "rust1", since = "1.0.0")]
2655        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2656        #[must_use = "this returns the result of the operation, \
2657                      without modifying the original"]
2658        #[inline(always)]
2659        pub const fn wrapping_mul(self, rhs: Self) -> Self {
2660            intrinsics::wrapping_mul(self, rhs)
2661        }
2662
2663        /// Wrapping (modular) division. Computes `self / rhs`.
2664        ///
2665        /// Wrapped division on unsigned types is just normal division. There's
2666        /// no way wrapping could ever happen. This function exists so that all
2667        /// operations are accounted for in the wrapping operations.
2668        ///
2669        /// # Panics
2670        ///
2671        /// This function will panic if `rhs` is zero.
2672        ///
2673        /// # Examples
2674        ///
2675        /// ```
2676        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
2677        /// ```
2678        #[stable(feature = "num_wrapping", since = "1.2.0")]
2679        #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
2680        #[must_use = "this returns the result of the operation, \
2681                      without modifying the original"]
2682        #[inline(always)]
2683        #[track_caller]
2684        pub const fn wrapping_div(self, rhs: Self) -> Self {
2685            self / rhs
2686        }
2687
2688        /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
2689        ///
2690        /// Wrapped division on unsigned types is just normal division. There's
2691        /// no way wrapping could ever happen. This function exists so that all
2692        /// operations are accounted for in the wrapping operations. Since, for
2693        /// the positive integers, all common definitions of division are equal,
2694        /// this is exactly equal to `self.wrapping_div(rhs)`.
2695        ///
2696        /// # Panics
2697        ///
2698        /// This function will panic if `rhs` is zero.
2699        ///
2700        /// # Examples
2701        ///
2702        /// ```
2703        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
2704        /// ```
2705        #[stable(feature = "euclidean_division", since = "1.38.0")]
2706        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2707        #[must_use = "this returns the result of the operation, \
2708                      without modifying the original"]
2709        #[inline(always)]
2710        #[track_caller]
2711        pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
2712            self / rhs
2713        }
2714
2715        /// Wrapping (modular) remainder. Computes `self % rhs`.
2716        ///
2717        /// Wrapped remainder calculation on unsigned types is just the regular
2718        /// remainder calculation. There's no way wrapping could ever happen.
2719        /// This function exists so that all operations are accounted for in the
2720        /// wrapping operations.
2721        ///
2722        /// # Panics
2723        ///
2724        /// This function will panic if `rhs` is zero.
2725        ///
2726        /// # Examples
2727        ///
2728        /// ```
2729        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
2730        /// ```
2731        #[stable(feature = "num_wrapping", since = "1.2.0")]
2732        #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
2733        #[must_use = "this returns the result of the operation, \
2734                      without modifying the original"]
2735        #[inline(always)]
2736        #[track_caller]
2737        pub const fn wrapping_rem(self, rhs: Self) -> Self {
2738            self % rhs
2739        }
2740
2741        /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
2742        ///
2743        /// Wrapped modulo calculation on unsigned types is just the regular
2744        /// remainder calculation. There's no way wrapping could ever happen.
2745        /// This function exists so that all operations are accounted for in the
2746        /// wrapping operations. Since, for the positive integers, all common
2747        /// definitions of division are equal, this is exactly equal to
2748        /// `self.wrapping_rem(rhs)`.
2749        ///
2750        /// # Panics
2751        ///
2752        /// This function will panic if `rhs` is zero.
2753        ///
2754        /// # Examples
2755        ///
2756        /// ```
2757        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
2758        /// ```
2759        #[stable(feature = "euclidean_division", since = "1.38.0")]
2760        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2761        #[must_use = "this returns the result of the operation, \
2762                      without modifying the original"]
2763        #[inline(always)]
2764        #[track_caller]
2765        pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
2766            self % rhs
2767        }
2768
2769        /// Wrapping (modular) negation. Computes `-self`,
2770        /// wrapping around at the boundary of the type.
2771        ///
2772        /// Since unsigned types do not have negative equivalents
2773        /// all applications of this function will wrap (except for `-0`).
2774        /// For values smaller than the corresponding signed type's maximum
2775        /// the result is the same as casting the corresponding signed value.
2776        /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2777        /// `MAX` is the corresponding signed type's maximum.
2778        ///
2779        /// # Examples
2780        ///
2781        /// ```
2782        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".wrapping_neg(), 0);")]
2783        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_neg(), 1);")]
2784        #[doc = concat!("assert_eq!(13_", stringify!($SelfT), ".wrapping_neg(), (!13) + 1);")]
2785        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_neg(), !(42 - 1));")]
2786        /// ```
2787        #[stable(feature = "num_wrapping", since = "1.2.0")]
2788        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2789        #[must_use = "this returns the result of the operation, \
2790                      without modifying the original"]
2791        #[inline(always)]
2792        pub const fn wrapping_neg(self) -> Self {
2793            (0 as $SelfT).wrapping_sub(self)
2794        }
2795
2796        /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2797        /// where `mask` removes any high-order bits of `rhs` that
2798        /// would cause the shift to exceed the bitwidth of the type.
2799        ///
2800        /// Beware that, unlike most other `wrapping_*` methods on integers, this
2801        /// does *not* give the same result as doing the shift in infinite precision
2802        /// then truncating as needed.  The behaviour matches what shift instructions
2803        /// do on many processors, and is what the `<<` operator does when overflow
2804        /// checks are disabled, but numerically it's weird.  Consider, instead,
2805        /// using [`Self::unbounded_shl`] which has nicer behaviour.
2806        ///
2807        /// Note that this is *not* the same as a rotate-left; the
2808        /// RHS of a wrapping shift-left is restricted to the range
2809        /// of the type, rather than the bits shifted out of the LHS
2810        /// being returned to the other end. The primitive integer
2811        /// types all implement a [`rotate_left`](Self::rotate_left) function,
2812        /// which may be what you want instead.
2813        ///
2814        /// # Examples
2815        ///
2816        /// ```
2817        #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".wrapping_shl(7), 128);")]
2818        #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".wrapping_shl(0), 0b101);")]
2819        #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".wrapping_shl(1), 0b1010);")]
2820        #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".wrapping_shl(2), 0b10100);")]
2821        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_shl(2), ", stringify!($SelfT), "::MAX - 3);")]
2822        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shl(", stringify!($BITS), "), 42);")]
2823        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shl(1).wrapping_shl(", stringify!($BITS_MINUS_ONE), "), 0);")]
2824        #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".wrapping_shl(128), 1);")]
2825        #[doc = concat!("assert_eq!(5_", stringify!($SelfT), ".wrapping_shl(1025), 10);")]
2826        /// ```
2827        #[stable(feature = "num_wrapping", since = "1.2.0")]
2828        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2829        #[must_use = "this returns the result of the operation, \
2830                      without modifying the original"]
2831        #[inline(always)]
2832        pub const fn wrapping_shl(self, rhs: u32) -> Self {
2833            // SAFETY: the masking by the bitsize of the type ensures that we do not shift
2834            // out of bounds
2835            unsafe {
2836                self.unchecked_shl(rhs & (Self::BITS - 1))
2837            }
2838        }
2839
2840        /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2841        /// where `mask` removes any high-order bits of `rhs` that
2842        /// would cause the shift to exceed the bitwidth of the type.
2843        ///
2844        /// Beware that, unlike most other `wrapping_*` methods on integers, this
2845        /// does *not* give the same result as doing the shift in infinite precision
2846        /// then truncating as needed.  The behaviour matches what shift instructions
2847        /// do on many processors, and is what the `>>` operator does when overflow
2848        /// checks are disabled, but numerically it's weird.  Consider, instead,
2849        /// using [`Self::unbounded_shr`] which has nicer behaviour.
2850        ///
2851        /// Note that this is *not* the same as a rotate-right; the
2852        /// RHS of a wrapping shift-right is restricted to the range
2853        /// of the type, rather than the bits shifted out of the LHS
2854        /// being returned to the other end. The primitive integer
2855        /// types all implement a [`rotate_right`](Self::rotate_right) function,
2856        /// which may be what you want instead.
2857        ///
2858        /// # Examples
2859        ///
2860        /// ```
2861        #[doc = concat!("assert_eq!(128_", stringify!($SelfT), ".wrapping_shr(7), 1);")]
2862        #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".wrapping_shr(0), 0b1010);")]
2863        #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".wrapping_shr(1), 0b101);")]
2864        #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".wrapping_shr(2), 0b10);")]
2865        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_shr(1), ", stringify!($SignedT), "::MAX.cast_unsigned());")]
2866        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shr(", stringify!($BITS), "), 42);")]
2867        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shr(1).wrapping_shr(", stringify!($BITS_MINUS_ONE), "), 0);")]
2868        #[doc = concat!("assert_eq!(128_", stringify!($SelfT), ".wrapping_shr(128), 128);")]
2869        #[doc = concat!("assert_eq!(10_", stringify!($SelfT), ".wrapping_shr(1025), 5);")]
2870        /// ```
2871        #[stable(feature = "num_wrapping", since = "1.2.0")]
2872        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2873        #[must_use = "this returns the result of the operation, \
2874                      without modifying the original"]
2875        #[inline(always)]
2876        pub const fn wrapping_shr(self, rhs: u32) -> Self {
2877            // SAFETY: the masking by the bitsize of the type ensures that we do not shift
2878            // out of bounds
2879            unsafe {
2880                self.unchecked_shr(rhs & (Self::BITS - 1))
2881            }
2882        }
2883
2884        /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2885        /// wrapping around at the boundary of the type.
2886        ///
2887        /// # Examples
2888        ///
2889        /// ```
2890        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")]
2891        /// assert_eq!(3u8.wrapping_pow(6), 217);
2892        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".wrapping_pow(0), 1);")]
2893        /// ```
2894        #[stable(feature = "no_panic_pow", since = "1.34.0")]
2895        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2896        #[must_use = "this returns the result of the operation, \
2897                      without modifying the original"]
2898        #[inline]
2899        pub const fn wrapping_pow(self, mut exp: u32) -> Self {
2900            if exp == 0 {
2901                return 1;
2902            }
2903            let mut base = self;
2904            let mut acc: Self = 1;
2905
2906            if intrinsics::is_val_statically_known(exp) {
2907                while exp > 1 {
2908                    if (exp & 1) == 1 {
2909                        acc = acc.wrapping_mul(base);
2910                    }
2911                    exp /= 2;
2912                    base = base.wrapping_mul(base);
2913                }
2914
2915                // since exp!=0, finally the exp must be 1.
2916                // Deal with the final bit of the exponent separately, since
2917                // squaring the base afterwards is not necessary.
2918                acc.wrapping_mul(base)
2919            } else {
2920                // This is faster than the above when the exponent is not known
2921                // at compile time. We can't use the same code for the constant
2922                // exponent case because LLVM is currently unable to unroll
2923                // this loop.
2924                loop {
2925                    if (exp & 1) == 1 {
2926                        acc = acc.wrapping_mul(base);
2927                        // since exp!=0, finally the exp must be 1.
2928                        if exp == 1 {
2929                            return acc;
2930                        }
2931                    }
2932                    exp /= 2;
2933                    base = base.wrapping_mul(base);
2934                }
2935            }
2936        }
2937
2938        /// Calculates `self` + `rhs`.
2939        ///
2940        /// Returns a tuple of the addition along with a boolean indicating
2941        /// whether an arithmetic overflow would occur. If an overflow would
2942        /// have occurred then the wrapped value is returned.
2943        ///
2944        /// # Examples
2945        ///
2946        /// ```
2947        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
2948        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")]
2949        /// ```
2950        #[stable(feature = "wrapping", since = "1.7.0")]
2951        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2952        #[must_use = "this returns the result of the operation, \
2953                      without modifying the original"]
2954        #[inline(always)]
2955        pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2956            let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
2957            (a as Self, b)
2958        }
2959
2960        /// Calculates `self` + `rhs` + `carry` and returns a tuple containing
2961        /// the sum and the output carry (in that order).
2962        ///
2963        /// Performs "ternary addition" of two integer operands and a carry-in
2964        /// bit, and returns an output integer and a carry-out bit. This allows
2965        /// chaining together multiple additions to create a wider addition, and
2966        /// can be useful for bignum addition.
2967        ///
2968        #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")]
2969        ///
2970        /// If the input carry is false, this method is equivalent to
2971        /// [`overflowing_add`](Self::overflowing_add), and the output carry is
2972        /// equal to the overflow flag. Note that although carry and overflow
2973        /// flags are similar for unsigned integers, they are different for
2974        /// signed integers.
2975        ///
2976        /// # Examples
2977        ///
2978        /// ```
2979        #[doc = concat!("//    3  MAX    (a = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
2980        #[doc = concat!("// +  5    7    (b = 5 × 2^", stringify!($BITS), " + 7)")]
2981        /// // ---------
2982        #[doc = concat!("//    9    6    (sum = 9 × 2^", stringify!($BITS), " + 6)")]
2983        ///
2984        #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (3, ", stringify!($SelfT), "::MAX);")]
2985        #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
2986        /// let carry0 = false;
2987        ///
2988        /// let (sum0, carry1) = a0.carrying_add(b0, carry0);
2989        /// assert_eq!(carry1, true);
2990        /// let (sum1, carry2) = a1.carrying_add(b1, carry1);
2991        /// assert_eq!(carry2, false);
2992        ///
2993        /// assert_eq!((sum1, sum0), (9, 6));
2994        /// ```
2995        #[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
2996        #[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue = "152015")]
2997        #[must_use = "this returns the result of the operation, \
2998                      without modifying the original"]
2999        #[inline]
3000        pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
3001            // note: longer-term this should be done via an intrinsic, but this has been shown
3002            //   to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
3003            let (a, c1) = self.overflowing_add(rhs);
3004            let (b, c2) = a.overflowing_add(carry as $SelfT);
3005            // Ideally LLVM would know this is disjoint without us telling them,
3006            // but it doesn't <https://github.com/llvm/llvm-project/issues/118162>
3007            // SAFETY: Only one of `c1` and `c2` can be set.
3008            // For c1 to be set we need to have overflowed, but if we did then
3009            // `a` is at most `MAX-1`, which means that `c2` cannot possibly
3010            // overflow because it's adding at most `1` (since it came from `bool`)
3011            (b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
3012        }
3013
3014        /// Calculates `self` + `rhs` with a signed `rhs`.
3015        ///
3016        /// Returns a tuple of the addition along with a boolean indicating
3017        /// whether an arithmetic overflow would occur. If an overflow would
3018        /// have occurred then the wrapped value is returned.
3019        ///
3020        /// # Examples
3021        ///
3022        /// ```
3023        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(2), (3, false));")]
3024        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(-2), (", stringify!($SelfT), "::MAX, true));")]
3025        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));")]
3026        /// ```
3027        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
3028        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
3029        #[must_use = "this returns the result of the operation, \
3030                      without modifying the original"]
3031        #[inline]
3032        pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) {
3033            let (res, overflowed) = self.overflowing_add(rhs as Self);
3034            (res, overflowed ^ (rhs < 0))
3035        }
3036
3037        /// Calculates `self` - `rhs`.
3038        ///
3039        /// Returns a tuple of the subtraction along with a boolean indicating
3040        /// whether an arithmetic overflow would occur. If an overflow would
3041        /// have occurred then the wrapped value is returned.
3042        ///
3043        /// # Examples
3044        ///
3045        /// ```
3046        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
3047        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
3048        /// ```
3049        #[stable(feature = "wrapping", since = "1.7.0")]
3050        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3051        #[must_use = "this returns the result of the operation, \
3052                      without modifying the original"]
3053        #[inline(always)]
3054        pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3055            let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3056            (a as Self, b)
3057        }
3058
3059        /// Calculates `self` &minus; `rhs` &minus; `borrow` and returns a tuple
3060        /// containing the difference and the output borrow.
3061        ///
3062        /// Performs "ternary subtraction" by subtracting both an integer
3063        /// operand and a borrow-in bit from `self`, and returns an output
3064        /// integer and a borrow-out bit. This allows chaining together multiple
3065        /// subtractions to create a wider subtraction, and can be useful for
3066        /// bignum subtraction.
3067        ///
3068        /// # Examples
3069        ///
3070        /// ```
3071        #[doc = concat!("//    9    6    (a = 9 × 2^", stringify!($BITS), " + 6)")]
3072        #[doc = concat!("// -  5    7    (b = 5 × 2^", stringify!($BITS), " + 7)")]
3073        /// // ---------
3074        #[doc = concat!("//    3  MAX    (diff = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
3075        ///
3076        #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (9, 6);")]
3077        #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
3078        /// let borrow0 = false;
3079        ///
3080        /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
3081        /// assert_eq!(borrow1, true);
3082        /// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
3083        /// assert_eq!(borrow2, false);
3084        ///
3085        #[doc = concat!("assert_eq!((diff1, diff0), (3, ", stringify!($SelfT), "::MAX));")]
3086        /// ```
3087        #[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
3088        #[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue = "152015")]
3089        #[must_use = "this returns the result of the operation, \
3090                      without modifying the original"]
3091        #[inline]
3092        pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
3093            // note: longer-term this should be done via an intrinsic, but this has been shown
3094            //   to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
3095            let (a, c1) = self.overflowing_sub(rhs);
3096            let (b, c2) = a.overflowing_sub(borrow as $SelfT);
3097            // SAFETY: Only one of `c1` and `c2` can be set.
3098            // For c1 to be set we need to have underflowed, but if we did then
3099            // `a` is nonzero, which means that `c2` cannot possibly
3100            // underflow because it's subtracting at most `1` (since it came from `bool`)
3101            (b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
3102        }
3103
3104        /// Calculates `self` - `rhs` with a signed `rhs`
3105        ///
3106        /// Returns a tuple of the subtraction along with a boolean indicating
3107        /// whether an arithmetic overflow would occur. If an overflow would
3108        /// have occurred then the wrapped value is returned.
3109        ///
3110        /// # Examples
3111        ///
3112        /// ```
3113        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_signed(2), (", stringify!($SelfT), "::MAX, true));")]
3114        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_signed(-2), (3, false));")]
3115        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_sub_signed(-4), (1, true));")]
3116        /// ```
3117        #[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
3118        #[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
3119        #[must_use = "this returns the result of the operation, \
3120                      without modifying the original"]
3121        #[inline]
3122        pub const fn overflowing_sub_signed(self, rhs: $SignedT) -> (Self, bool) {
3123            let (res, overflow) = self.overflowing_sub(rhs as Self);
3124
3125            (res, overflow ^ (rhs < 0))
3126        }
3127
3128        /// Computes the absolute difference between `self` and `other`.
3129        ///
3130        /// # Examples
3131        ///
3132        /// ```
3133        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($SelfT), ");")]
3134        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($SelfT), ");")]
3135        /// ```
3136        #[stable(feature = "int_abs_diff", since = "1.60.0")]
3137        #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
3138        #[must_use = "this returns the result of the operation, \
3139                      without modifying the original"]
3140        #[inline]
3141        pub const fn abs_diff(self, other: Self) -> Self {
3142            if size_of::<Self>() == 1 {
3143                // Trick LLVM into generating the psadbw instruction when SSE2
3144                // is available and this function is autovectorized for u8's.
3145                (self as i32).wrapping_sub(other as i32).unsigned_abs() as Self
3146            } else {
3147                if self < other {
3148                    other - self
3149                } else {
3150                    self - other
3151                }
3152            }
3153        }
3154
3155        /// Calculates the multiplication of `self` and `rhs`.
3156        ///
3157        /// Returns a tuple of the multiplication along with a boolean
3158        /// indicating whether an arithmetic overflow would occur. If an
3159        /// overflow would have occurred then the wrapped value is returned.
3160        ///
3161        /// If you want the *value* of the overflow, rather than just *whether*
3162        /// an overflow occurred, see [`Self::carrying_mul`].
3163        ///
3164        /// # Examples
3165        ///
3166        /// Please note that this example is shared among integer types, which is why `u32` is used.
3167        ///
3168        /// ```
3169        /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3170        /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3171        /// ```
3172        #[stable(feature = "wrapping", since = "1.7.0")]
3173        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3174        #[must_use = "this returns the result of the operation, \
3175                          without modifying the original"]
3176        #[inline(always)]
3177        pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3178            let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3179            (a as Self, b)
3180        }
3181
3182        /// Calculates the "full multiplication" `self * rhs + carry`
3183        /// without the possibility to overflow.
3184        ///
3185        /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
3186        /// of the result as two separate values, in that order.
3187        ///
3188        /// Performs "long multiplication" which takes in an extra amount to add, and may return an
3189        /// additional amount of overflow. This allows for chaining together multiple
3190        /// multiplications to create "big integers" which represent larger values.
3191        ///
3192        /// If you also need to add a value, then use [`Self::carrying_mul_add`].
3193        ///
3194        /// # Examples
3195        ///
3196        /// Please note that this example is shared among integer types, which is why `u32` is used.
3197        ///
3198        /// ```
3199        /// assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
3200        /// assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
3201        /// assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
3202        /// assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
3203        #[doc = concat!("assert_eq!(",
3204            stringify!($SelfT), "::MAX.carrying_mul(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
3205            "(0, ", stringify!($SelfT), "::MAX));"
3206        )]
3207        /// ```
3208        ///
3209        /// This is the core operation needed for scalar multiplication when
3210        /// implementing it for wider-than-native types.
3211        ///
3212        /// ```
3213        /// fn scalar_mul_eq(little_endian_digits: &mut Vec<u16>, multiplicand: u16) {
3214        ///     let mut carry = 0;
3215        ///     for d in little_endian_digits.iter_mut() {
3216        ///         (*d, carry) = d.carrying_mul(multiplicand, carry);
3217        ///     }
3218        ///     if carry != 0 {
3219        ///         little_endian_digits.push(carry);
3220        ///     }
3221        /// }
3222        ///
3223        /// let mut v = vec![10, 20];
3224        /// scalar_mul_eq(&mut v, 3);
3225        /// assert_eq!(v, [30, 60]);
3226        ///
3227        /// assert_eq!(0x87654321_u64 * 0xFEED, 0x86D3D159E38D);
3228        /// let mut v = vec![0x4321, 0x8765];
3229        /// scalar_mul_eq(&mut v, 0xFEED);
3230        /// assert_eq!(v, [0xE38D, 0xD159, 0x86D3]);
3231        /// ```
3232        ///
3233        /// If `carry` is zero, this is similar to [`overflowing_mul`](Self::overflowing_mul),
3234        /// except that it gives the value of the overflow instead of just whether one happened:
3235        ///
3236        /// ```
3237        /// # #![allow(unused_features)]
3238        /// #![feature(const_unsigned_bigint_helpers)]
3239        /// let r = u8::carrying_mul(7, 13, 0);
3240        /// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));
3241        /// let r = u8::carrying_mul(13, 42, 0);
3242        /// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(13, 42));
3243        /// ```
3244        ///
3245        /// The value of the first field in the returned tuple matches what you'd get
3246        /// by combining the [`wrapping_mul`](Self::wrapping_mul) and
3247        /// [`wrapping_add`](Self::wrapping_add) methods:
3248        ///
3249        /// ```
3250        /// # #![allow(unused_features)]
3251        /// #![feature(const_unsigned_bigint_helpers)]
3252        /// assert_eq!(
3253        ///     789_u16.carrying_mul(456, 123).0,
3254        ///     789_u16.wrapping_mul(456).wrapping_add(123),
3255        /// );
3256        /// ```
3257        #[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
3258        #[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue = "152015")]
3259        #[must_use = "this returns the result of the operation, \
3260                      without modifying the original"]
3261        #[inline]
3262        pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
3263            Self::carrying_mul_add(self, rhs, carry, 0)
3264        }
3265
3266        /// Calculates the "full multiplication" `self * rhs + carry + add`.
3267        ///
3268        /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
3269        /// of the result as two separate values, in that order.
3270        ///
3271        /// This cannot overflow, as the double-width result has exactly enough
3272        /// space for the largest possible result. This is equivalent to how, in
3273        /// decimal, 9 × 9 + 9 + 9 = 81 + 18 = 99 = 9×10⁰ + 9×10¹ = 10² - 1.
3274        ///
3275        /// Performs "long multiplication" which takes in an extra amount to add, and may return an
3276        /// additional amount of overflow. This allows for chaining together multiple
3277        /// multiplications to create "big integers" which represent larger values.
3278        ///
3279        /// If you don't need the `add` part, then you can use [`Self::carrying_mul`] instead.
3280        ///
3281        /// # Examples
3282        ///
3283        /// Please note that this example is shared between integer types,
3284        /// which explains why `u32` is used here.
3285        ///
3286        /// ```
3287        /// assert_eq!(5u32.carrying_mul_add(2, 0, 0), (10, 0));
3288        /// assert_eq!(5u32.carrying_mul_add(2, 10, 10), (30, 0));
3289        /// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 0, 0), (1410065408, 2));
3290        /// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 10, 10), (1410065428, 2));
3291        #[doc = concat!("assert_eq!(",
3292            stringify!($SelfT), "::MAX.carrying_mul_add(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
3293            "(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX));"
3294        )]
3295        /// ```
3296        ///
3297        /// This is the core per-digit operation for "grade school" O(n²) multiplication.
3298        ///
3299        /// Please note that this example is shared between integer types,
3300        /// using `u8` for simplicity of the demonstration.
3301        ///
3302        /// ```
3303        /// fn quadratic_mul<const N: usize>(a: [u8; N], b: [u8; N]) -> [u8; N] {
3304        ///     let mut out = [0; N];
3305        ///     for j in 0..N {
3306        ///         let mut carry = 0;
3307        ///         for i in 0..(N - j) {
3308        ///             (out[j + i], carry) = u8::carrying_mul_add(a[i], b[j], out[j + i], carry);
3309        ///         }
3310        ///     }
3311        ///     out
3312        /// }
3313        ///
3314        /// // -1 * -1 == 1
3315        /// assert_eq!(quadratic_mul([0xFF; 3], [0xFF; 3]), [1, 0, 0]);
3316        ///
3317        /// assert_eq!(u32::wrapping_mul(0x9e3779b9, 0x7f4a7c15), 0xcffc982d);
3318        /// assert_eq!(
3319        ///     quadratic_mul(u32::to_le_bytes(0x9e3779b9), u32::to_le_bytes(0x7f4a7c15)),
3320        ///     u32::to_le_bytes(0xcffc982d)
3321        /// );
3322        /// ```
3323        #[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
3324        #[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue = "152015")]
3325        #[must_use = "this returns the result of the operation, \
3326                      without modifying the original"]
3327        #[inline]
3328        pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self) -> (Self, Self) {
3329            intrinsics::carrying_mul_add(self, rhs, carry, add)
3330        }
3331
3332        /// Calculates the divisor when `self` is divided by `rhs`.
3333        ///
3334        /// Returns a tuple of the divisor along with a boolean indicating
3335        /// whether an arithmetic overflow would occur. Note that for unsigned
3336        /// integers overflow never occurs, so the second value is always
3337        /// `false`.
3338        ///
3339        /// # Panics
3340        ///
3341        /// This function will panic if `rhs` is zero.
3342        ///
3343        /// # Examples
3344        ///
3345        /// ```
3346        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
3347        /// ```
3348        #[inline(always)]
3349        #[stable(feature = "wrapping", since = "1.7.0")]
3350        #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
3351        #[must_use = "this returns the result of the operation, \
3352                      without modifying the original"]
3353        #[track_caller]
3354        pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3355            (self / rhs, false)
3356        }
3357
3358        /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3359        ///
3360        /// Returns a tuple of the divisor along with a boolean indicating
3361        /// whether an arithmetic overflow would occur. Note that for unsigned
3362        /// integers overflow never occurs, so the second value is always
3363        /// `false`.
3364        /// Since, for the positive integers, all common
3365        /// definitions of division are equal, this
3366        /// is exactly equal to `self.overflowing_div(rhs)`.
3367        ///
3368        /// # Panics
3369        ///
3370        /// This function will panic if `rhs` is zero.
3371        ///
3372        /// # Examples
3373        ///
3374        /// ```
3375        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
3376        /// ```
3377        #[inline(always)]
3378        #[stable(feature = "euclidean_division", since = "1.38.0")]
3379        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3380        #[must_use = "this returns the result of the operation, \
3381                      without modifying the original"]
3382        #[track_caller]
3383        pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3384            (self / rhs, false)
3385        }
3386
3387        /// Calculates the remainder when `self` is divided by `rhs`.
3388        ///
3389        /// Returns a tuple of the remainder after dividing along with a boolean
3390        /// indicating whether an arithmetic overflow would occur. Note that for
3391        /// unsigned integers overflow never occurs, so the second value is
3392        /// always `false`.
3393        ///
3394        /// # Panics
3395        ///
3396        /// This function will panic if `rhs` is zero.
3397        ///
3398        /// # Examples
3399        ///
3400        /// ```
3401        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
3402        /// ```
3403        #[inline(always)]
3404        #[stable(feature = "wrapping", since = "1.7.0")]
3405        #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
3406        #[must_use = "this returns the result of the operation, \
3407                      without modifying the original"]
3408        #[track_caller]
3409        pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3410            (self % rhs, false)
3411        }
3412
3413        /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3414        ///
3415        /// Returns a tuple of the modulo after dividing along with a boolean
3416        /// indicating whether an arithmetic overflow would occur. Note that for
3417        /// unsigned integers overflow never occurs, so the second value is
3418        /// always `false`.
3419        /// Since, for the positive integers, all common
3420        /// definitions of division are equal, this operation
3421        /// is exactly equal to `self.overflowing_rem(rhs)`.
3422        ///
3423        /// # Panics
3424        ///
3425        /// This function will panic if `rhs` is zero.
3426        ///
3427        /// # Examples
3428        ///
3429        /// ```
3430        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
3431        /// ```
3432        #[inline(always)]
3433        #[stable(feature = "euclidean_division", since = "1.38.0")]
3434        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3435        #[must_use = "this returns the result of the operation, \
3436                      without modifying the original"]
3437        #[track_caller]
3438        pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3439            (self % rhs, false)
3440        }
3441
3442        /// Negates self in an overflowing fashion.
3443        ///
3444        /// Returns `!self + 1` using wrapping operations to return the value
3445        /// that represents the negation of this unsigned value. Note that for
3446        /// positive unsigned values overflow always occurs, but negating 0 does
3447        /// not overflow.
3448        ///
3449        /// # Examples
3450        ///
3451        /// ```
3452        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")]
3453        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")]
3454        /// ```
3455        #[inline(always)]
3456        #[stable(feature = "wrapping", since = "1.7.0")]
3457        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3458        #[must_use = "this returns the result of the operation, \
3459                      without modifying the original"]
3460        pub const fn overflowing_neg(self) -> (Self, bool) {
3461            ((!self).wrapping_add(1), self != 0)
3462        }
3463
3464        /// Shifts self left by `rhs` bits.
3465        ///
3466        /// Returns a tuple of the shifted version of self along with a boolean
3467        /// indicating whether the shift value was larger than or equal to the
3468        /// number of bits. If the shift value is too large, then value is
3469        /// masked (N-1) where N is the number of bits, and this value is then
3470        /// used to perform the shift.
3471        ///
3472        /// # Examples
3473        ///
3474        /// ```
3475        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")]
3476        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")]
3477        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shl(", stringify!($BITS_MINUS_ONE), "), (0, false));")]
3478        /// ```
3479        #[stable(feature = "wrapping", since = "1.7.0")]
3480        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3481        #[must_use = "this returns the result of the operation, \
3482                      without modifying the original"]
3483        #[inline(always)]
3484        pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3485            (self.wrapping_shl(rhs), rhs >= Self::BITS)
3486        }
3487
3488        /// Shifts self right by `rhs` bits.
3489        ///
3490        /// Returns a tuple of the shifted version of self along with a boolean
3491        /// indicating whether the shift value was larger than or equal to the
3492        /// number of bits. If the shift value is too large, then value is
3493        /// masked (N-1) where N is the number of bits, and this value is then
3494        /// used to perform the shift.
3495        ///
3496        /// # Examples
3497        ///
3498        /// ```
3499        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
3500        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")]
3501        /// ```
3502        #[stable(feature = "wrapping", since = "1.7.0")]
3503        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3504        #[must_use = "this returns the result of the operation, \
3505                      without modifying the original"]
3506        #[inline(always)]
3507        pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3508            (self.wrapping_shr(rhs), rhs >= Self::BITS)
3509        }
3510
3511        /// Raises self to the power of `exp`, using exponentiation by squaring.
3512        ///
3513        /// Returns a tuple of the exponentiation along with a bool indicating
3514        /// whether an overflow happened.
3515        ///
3516        /// # Examples
3517        ///
3518        /// ```
3519        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")]
3520        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".overflowing_pow(0), (1, false));")]
3521        /// assert_eq!(3u8.overflowing_pow(6), (217, true));
3522        /// ```
3523        #[stable(feature = "no_panic_pow", since = "1.34.0")]
3524        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3525        #[must_use = "this returns the result of the operation, \
3526                      without modifying the original"]
3527        #[inline]
3528        pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3529            if exp == 0{
3530                return (1,false);
3531            }
3532            let mut base = self;
3533            let mut acc: Self = 1;
3534            let mut overflown = false;
3535            // Scratch space for storing results of overflowing_mul.
3536            let mut r;
3537
3538            loop {
3539                if (exp & 1) == 1 {
3540                    r = acc.overflowing_mul(base);
3541                    // since exp!=0, finally the exp must be 1.
3542                    if exp == 1 {
3543                        r.1 |= overflown;
3544                        return r;
3545                    }
3546                    acc = r.0;
3547                    overflown |= r.1;
3548                }
3549                exp /= 2;
3550                r = base.overflowing_mul(base);
3551                base = r.0;
3552                overflown |= r.1;
3553            }
3554        }
3555
3556        /// Raises self to the power of `exp`, using exponentiation by squaring.
3557        ///
3558        /// # Examples
3559        ///
3560        /// ```
3561        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")]
3562        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".pow(0), 1);")]
3563        /// ```
3564        #[stable(feature = "rust1", since = "1.0.0")]
3565        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3566        #[must_use = "this returns the result of the operation, \
3567                      without modifying the original"]
3568        #[inline]
3569        #[rustc_inherit_overflow_checks]
3570        pub const fn pow(self, mut exp: u32) -> Self {
3571            if exp == 0 {
3572                return 1;
3573            }
3574            let mut base = self;
3575            let mut acc = 1;
3576
3577            if intrinsics::is_val_statically_known(exp) {
3578                while exp > 1 {
3579                    if (exp & 1) == 1 {
3580                        acc = acc * base;
3581                    }
3582                    exp /= 2;
3583                    base = base * base;
3584                }
3585
3586                // since exp!=0, finally the exp must be 1.
3587                // Deal with the final bit of the exponent separately, since
3588                // squaring the base afterwards is not necessary and may cause a
3589                // needless overflow.
3590                acc * base
3591            } else {
3592                // This is faster than the above when the exponent is not known
3593                // at compile time. We can't use the same code for the constant
3594                // exponent case because LLVM is currently unable to unroll
3595                // this loop.
3596                loop {
3597                    if (exp & 1) == 1 {
3598                        acc = acc * base;
3599                        // since exp!=0, finally the exp must be 1.
3600                        if exp == 1 {
3601                            return acc;
3602                        }
3603                    }
3604                    exp /= 2;
3605                    base = base * base;
3606                }
3607            }
3608        }
3609
3610        /// Returns the square root of the number, rounded down.
3611        ///
3612        /// # Examples
3613        ///
3614        /// ```
3615        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".isqrt(), 3);")]
3616        /// ```
3617        #[stable(feature = "isqrt", since = "1.84.0")]
3618        #[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
3619        #[must_use = "this returns the result of the operation, \
3620                      without modifying the original"]
3621        #[inline]
3622        pub const fn isqrt(self) -> Self {
3623            let result = imp::int_sqrt::$ActualT(self as $ActualT) as Self;
3624
3625            // Inform the optimizer what the range of outputs is. If testing
3626            // `core` crashes with no panic message and a `num::int_sqrt::u*`
3627            // test failed, it's because your edits caused these assertions or
3628            // the assertions in `fn isqrt` of `nonzero.rs` to become false.
3629            //
3630            // SAFETY: Integer square root is a monotonically nondecreasing
3631            // function, which means that increasing the input will never
3632            // cause the output to decrease. Thus, since the input for unsigned
3633            // integers is bounded by `[0, <$ActualT>::MAX]`, sqrt(n) will be
3634            // bounded by `[sqrt(0), sqrt(<$ActualT>::MAX)]` and bounding the
3635            // input by `[1, <$ActualT>::MAX]` bounds sqrt(n) by
3636            // `[sqrt(1), sqrt(<$ActualT>::MAX)]`.
3637            unsafe {
3638                const MAX_RESULT: $SelfT = imp::int_sqrt::$ActualT(<$ActualT>::MAX) as $SelfT;
3639                crate::hint::assert_unchecked(result <= MAX_RESULT)
3640            }
3641
3642            if self >= 1 {
3643                // SAFETY: The above statements about monotonicity also apply here.
3644                // Since the input in this branch is bounded by `[1, <$ActualT>::MAX]`,
3645                // sqrt(n) is bounded by `[sqrt(1), sqrt(<$ActualT>::MAX)]`, and
3646                // `sqrt(1) == 1`.
3647                unsafe { crate::hint::assert_unchecked(result >= 1) }
3648            }
3649
3650            // SAFETY: the isqrt implementation returns the square root and rounds down,
3651            // meaning `result * result <= self`. This implies `result <= self`.
3652            // The compiler needs both to optimize for both.
3653            // `result * result <= self` implies the multiplication will not overflow.
3654            unsafe {
3655                crate::hint::assert_unchecked(result.unchecked_mul(result) <= self);
3656                crate::hint::assert_unchecked(result <= self);
3657            }
3658
3659            result
3660        }
3661
3662        /// Performs Euclidean division.
3663        ///
3664        /// Since, for the positive integers, all common
3665        /// definitions of division are equal, this
3666        /// is exactly equal to `self / rhs`.
3667        ///
3668        /// # Panics
3669        ///
3670        /// This function will panic if `rhs` is zero.
3671        ///
3672        /// # Examples
3673        ///
3674        /// ```
3675        #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")]
3676        /// ```
3677        #[stable(feature = "euclidean_division", since = "1.38.0")]
3678        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3679        #[must_use = "this returns the result of the operation, \
3680                      without modifying the original"]
3681        #[inline(always)]
3682        #[track_caller]
3683        pub const fn div_euclid(self, rhs: Self) -> Self {
3684            self / rhs
3685        }
3686
3687
3688        /// Calculates the least remainder of `self` when divided by
3689        /// `rhs`.
3690        ///
3691        /// Since, for the positive integers, all common
3692        /// definitions of division are equal, this
3693        /// is exactly equal to `self % rhs`.
3694        ///
3695        /// # Panics
3696        ///
3697        /// This function will panic if `rhs` is zero.
3698        ///
3699        /// # Examples
3700        ///
3701        /// ```
3702        #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")]
3703        /// ```
3704        #[doc(alias = "modulo", alias = "mod")]
3705        #[stable(feature = "euclidean_division", since = "1.38.0")]
3706        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3707        #[must_use = "this returns the result of the operation, \
3708                      without modifying the original"]
3709        #[inline(always)]
3710        #[track_caller]
3711        pub const fn rem_euclid(self, rhs: Self) -> Self {
3712            self % rhs
3713        }
3714
3715        /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
3716        ///
3717        /// This is the same as performing `self / rhs` for all unsigned integers.
3718        ///
3719        /// # Panics
3720        ///
3721        /// This function will panic if `rhs` is zero.
3722        ///
3723        /// # Examples
3724        ///
3725        /// ```
3726        /// #![feature(int_roundings)]
3727        #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_floor(4), 1);")]
3728        /// ```
3729        #[unstable(feature = "int_roundings", issue = "88581")]
3730        #[must_use = "this returns the result of the operation, \
3731                      without modifying the original"]
3732        #[inline(always)]
3733        #[track_caller]
3734        pub const fn div_floor(self, rhs: Self) -> Self {
3735            self / rhs
3736        }
3737
3738        /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
3739        ///
3740        /// # Panics
3741        ///
3742        /// This function will panic if `rhs` is zero.
3743        ///
3744        /// # Examples
3745        ///
3746        /// ```
3747        #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_ceil(4), 2);")]
3748        /// ```
3749        #[stable(feature = "int_roundings1", since = "1.73.0")]
3750        #[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
3751        #[must_use = "this returns the result of the operation, \
3752                      without modifying the original"]
3753        #[inline]
3754        #[track_caller]
3755        pub const fn div_ceil(self, rhs: Self) -> Self {
3756            let d = self / rhs;
3757            let r = self % rhs;
3758            if r > 0 {
3759                d + 1
3760            } else {
3761                d
3762            }
3763        }
3764
3765        /// Calculates the smallest value greater than or equal to `self` that
3766        /// is a multiple of `rhs`.
3767        ///
3768        /// # Panics
3769        ///
3770        /// This function will panic if `rhs` is zero.
3771        ///
3772        /// ## Overflow behavior
3773        ///
3774        /// On overflow, this function will panic if overflow checks are enabled (default in debug
3775        /// mode) and wrap if overflow checks are disabled (default in release mode).
3776        ///
3777        /// # Examples
3778        ///
3779        /// ```
3780        #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
3781        #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
3782        /// ```
3783        #[stable(feature = "int_roundings1", since = "1.73.0")]
3784        #[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
3785        #[must_use = "this returns the result of the operation, \
3786                      without modifying the original"]
3787        #[inline]
3788        #[rustc_inherit_overflow_checks]
3789        pub const fn next_multiple_of(self, rhs: Self) -> Self {
3790            match self % rhs {
3791                0 => self,
3792                r => self + (rhs - r)
3793            }
3794        }
3795
3796        /// Calculates the smallest value greater than or equal to `self` that
3797        /// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
3798        /// operation would result in overflow.
3799        ///
3800        /// # Examples
3801        ///
3802        /// ```
3803        #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
3804        #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
3805        #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
3806        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
3807        /// ```
3808        #[stable(feature = "int_roundings1", since = "1.73.0")]
3809        #[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
3810        #[must_use = "this returns the result of the operation, \
3811                      without modifying the original"]
3812        #[inline]
3813        pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
3814            match try_opt!(self.checked_rem(rhs)) {
3815                0 => Some(self),
3816                // rhs - r cannot overflow because r is smaller than rhs
3817                r => self.checked_add(rhs - r)
3818            }
3819        }
3820
3821        /// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
3822        ///
3823        /// This function is equivalent to `self % rhs == 0`, except that it will not panic
3824        /// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
3825        /// `n.is_multiple_of(0) == false`.
3826        ///
3827        /// # Examples
3828        ///
3829        /// ```
3830        #[doc = concat!("assert!(6_", stringify!($SelfT), ".is_multiple_of(2));")]
3831        #[doc = concat!("assert!(!5_", stringify!($SelfT), ".is_multiple_of(2));")]
3832        ///
3833        #[doc = concat!("assert!(0_", stringify!($SelfT), ".is_multiple_of(0));")]
3834        #[doc = concat!("assert!(!6_", stringify!($SelfT), ".is_multiple_of(0));")]
3835        /// ```
3836        #[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
3837        #[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
3838        #[must_use]
3839        #[inline]
3840        pub const fn is_multiple_of(self, rhs: Self) -> bool {
3841            match rhs {
3842                0 => self == 0,
3843                _ => self % rhs == 0,
3844            }
3845        }
3846
3847        /// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
3848        ///
3849        /// # Examples
3850        ///
3851        /// ```
3852        #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")]
3853        #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")]
3854        /// ```
3855        #[must_use]
3856        #[stable(feature = "rust1", since = "1.0.0")]
3857        #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
3858        #[inline(always)]
3859        pub const fn is_power_of_two(self) -> bool {
3860            self.count_ones() == 1
3861        }
3862
3863        // Returns one less than next power of two.
3864        // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3865        //
3866        // 8u8.one_less_than_next_power_of_two() == 7
3867        // 6u8.one_less_than_next_power_of_two() == 7
3868        //
3869        // This method cannot overflow, as in the `next_power_of_two`
3870        // overflow cases it instead ends up returning the maximum value
3871        // of the type, and can return 0 for 0.
3872        #[inline]
3873        const fn one_less_than_next_power_of_two(self) -> Self {
3874            if self <= 1 { return 0; }
3875
3876            let p = self - 1;
3877            // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
3878            // That means the shift is always in-bounds, and some processors
3879            // (such as intel pre-haswell) have more efficient ctlz
3880            // intrinsics when the argument is non-zero.
3881            let z = unsafe { intrinsics::ctlz_nonzero(p) };
3882            <$SelfT>::MAX >> z
3883        }
3884
3885        /// Returns the smallest power of two greater than or equal to `self`.
3886        ///
3887        /// When return value overflows (i.e., `self > (1 << (N-1))` for type
3888        /// `uN`), it panics in debug mode and the return value is wrapped to 0 in
3889        /// release mode (the only situation in which this method can return 0).
3890        ///
3891        /// # Examples
3892        ///
3893        /// ```
3894        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")]
3895        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")]
3896        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".next_power_of_two(), 1);")]
3897        /// ```
3898        #[stable(feature = "rust1", since = "1.0.0")]
3899        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3900        #[must_use = "this returns the result of the operation, \
3901                      without modifying the original"]
3902        #[inline]
3903        #[rustc_inherit_overflow_checks]
3904        pub const fn next_power_of_two(self) -> Self {
3905            self.one_less_than_next_power_of_two() + 1
3906        }
3907
3908        /// Returns the smallest power of two greater than or equal to `self`. If
3909        /// the next power of two is greater than the type's maximum value,
3910        /// `None` is returned, otherwise the power of two is wrapped in `Some`.
3911        ///
3912        /// # Examples
3913        ///
3914        /// ```
3915        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")]
3916        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")]
3917        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")]
3918        /// ```
3919        #[inline]
3920        #[stable(feature = "rust1", since = "1.0.0")]
3921        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3922        #[must_use = "this returns the result of the operation, \
3923                      without modifying the original"]
3924        pub const fn checked_next_power_of_two(self) -> Option<Self> {
3925            self.one_less_than_next_power_of_two().checked_add(1)
3926        }
3927
3928        /// Returns the smallest power of two greater than or equal to `n`. If
3929        /// the next power of two is greater than the type's maximum value,
3930        /// the return value is wrapped to `0`.
3931        ///
3932        /// # Examples
3933        ///
3934        /// ```
3935        /// #![feature(wrapping_next_power_of_two)]
3936        ///
3937        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")]
3938        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")]
3939        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")]
3940        /// ```
3941        #[inline]
3942        #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3943                   reason = "needs decision on wrapping behavior")]
3944        #[must_use = "this returns the result of the operation, \
3945                      without modifying the original"]
3946        pub const fn wrapping_next_power_of_two(self) -> Self {
3947            self.one_less_than_next_power_of_two().wrapping_add(1)
3948        }
3949
3950        /// Returns the memory representation of this integer as a byte array in
3951        /// big-endian (network) byte order.
3952        ///
3953        #[doc = $to_xe_bytes_doc]
3954        ///
3955        /// # Examples
3956        ///
3957        /// ```
3958        #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
3959        #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
3960        /// ```
3961        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3962        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3963        #[must_use = "this returns the result of the operation, \
3964                      without modifying the original"]
3965        #[inline]
3966        pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
3967            self.to_be().to_ne_bytes()
3968        }
3969
3970        /// Returns the memory representation of this integer as a byte array in
3971        /// little-endian byte order.
3972        ///
3973        #[doc = $to_xe_bytes_doc]
3974        ///
3975        /// # Examples
3976        ///
3977        /// ```
3978        #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
3979        #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
3980        /// ```
3981        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3982        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3983        #[must_use = "this returns the result of the operation, \
3984                      without modifying the original"]
3985        #[inline]
3986        pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
3987            self.to_le().to_ne_bytes()
3988        }
3989
3990        /// Returns the memory representation of this integer as a byte array in
3991        /// native byte order.
3992        ///
3993        /// As the target platform's native endianness is used, portable code
3994        /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3995        /// instead.
3996        ///
3997        #[doc = $to_xe_bytes_doc]
3998        ///
3999        /// [`to_be_bytes`]: Self::to_be_bytes
4000        /// [`to_le_bytes`]: Self::to_le_bytes
4001        ///
4002        /// # Examples
4003        ///
4004        /// ```
4005        #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
4006        /// assert_eq!(
4007        ///     bytes,
4008        ///     if cfg!(target_endian = "big") {
4009        #[doc = concat!("        ", $be_bytes)]
4010        ///     } else {
4011        #[doc = concat!("        ", $le_bytes)]
4012        ///     }
4013        /// );
4014        /// ```
4015        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4016        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4017        #[must_use = "this returns the result of the operation, \
4018                      without modifying the original"]
4019        #[allow(unnecessary_transmutes)]
4020        // SAFETY: const sound because integers are plain old datatypes so we can always
4021        // transmute them to arrays of bytes
4022        #[inline]
4023        pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
4024            // SAFETY: integers are plain old datatypes so we can always transmute them to
4025            // arrays of bytes
4026            unsafe { mem::transmute(self) }
4027        }
4028
4029        /// Creates a native endian integer value from its representation
4030        /// as a byte array in big endian.
4031        ///
4032        #[doc = $from_xe_bytes_doc]
4033        ///
4034        /// # Examples
4035        ///
4036        /// ```
4037        #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
4038        #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
4039        /// ```
4040        ///
4041        /// When starting from a slice rather than an array, fallible conversion APIs can be used:
4042        ///
4043        /// ```
4044        #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
4045        #[doc = concat!("    let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
4046        ///     *input = rest;
4047        #[doc = concat!("    ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
4048        /// }
4049        /// ```
4050        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4051        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4052        #[must_use]
4053        #[inline]
4054        pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
4055            Self::from_be(Self::from_ne_bytes(bytes))
4056        }
4057
4058        /// Creates a native endian integer value from its representation
4059        /// as a byte array in little endian.
4060        ///
4061        #[doc = $from_xe_bytes_doc]
4062        ///
4063        /// # Examples
4064        ///
4065        /// ```
4066        #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
4067        #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
4068        /// ```
4069        ///
4070        /// When starting from a slice rather than an array, fallible conversion APIs can be used:
4071        ///
4072        /// ```
4073        #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
4074        #[doc = concat!("    let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
4075        ///     *input = rest;
4076        #[doc = concat!("    ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
4077        /// }
4078        /// ```
4079        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4080        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4081        #[must_use]
4082        #[inline]
4083        pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
4084            Self::from_le(Self::from_ne_bytes(bytes))
4085        }
4086
4087        /// Creates a native endian integer value from its memory representation
4088        /// as a byte array in native endianness.
4089        ///
4090        /// As the target platform's native endianness is used, portable code
4091        /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4092        /// appropriate instead.
4093        ///
4094        /// [`from_be_bytes`]: Self::from_be_bytes
4095        /// [`from_le_bytes`]: Self::from_le_bytes
4096        ///
4097        #[doc = $from_xe_bytes_doc]
4098        ///
4099        /// # Examples
4100        ///
4101        /// ```
4102        #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
4103        #[doc = concat!("    ", $be_bytes, "")]
4104        /// } else {
4105        #[doc = concat!("    ", $le_bytes, "")]
4106        /// });
4107        #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
4108        /// ```
4109        ///
4110        /// When starting from a slice rather than an array, fallible conversion APIs can be used:
4111        ///
4112        /// ```
4113        #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
4114        #[doc = concat!("    let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
4115        ///     *input = rest;
4116        #[doc = concat!("    ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
4117        /// }
4118        /// ```
4119        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4120        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4121        #[allow(unnecessary_transmutes)]
4122        #[must_use]
4123        // SAFETY: const sound because integers are plain old datatypes so we can always
4124        // transmute to them
4125        #[inline]
4126        pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
4127            // SAFETY: integers are plain old datatypes so we can always transmute to them
4128            unsafe { mem::transmute(bytes) }
4129        }
4130
4131        /// New code should prefer to use
4132        #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
4133        ///
4134        /// Returns the smallest value that can be represented by this integer type.
4135        #[stable(feature = "rust1", since = "1.0.0")]
4136        #[rustc_promotable]
4137        #[inline(always)]
4138        #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4139        #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
4140        #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_min_value")]
4141        pub const fn min_value() -> Self { Self::MIN }
4142
4143        /// New code should prefer to use
4144        #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
4145        ///
4146        /// Returns the largest value that can be represented by this integer type.
4147        #[stable(feature = "rust1", since = "1.0.0")]
4148        #[rustc_promotable]
4149        #[inline(always)]
4150        #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4151        #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
4152        #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_max_value")]
4153        pub const fn max_value() -> Self { Self::MAX }
4154
4155        /// Truncate an integer to an integer of the same size or smaller, preserving the least
4156        /// significant bits.
4157        ///
4158        /// # Examples
4159        ///
4160        /// ```
4161        /// #![feature(integer_widen_truncate)]
4162        #[doc = concat!("assert_eq!(120u8, 120", stringify!($SelfT), ".truncate());")]
4163        /// assert_eq!(120u8, 376u32.truncate());
4164        /// ```
4165        #[must_use = "this returns the truncated value and does not modify the original"]
4166        #[unstable(feature = "integer_widen_truncate", issue = "154330")]
4167        #[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
4168        #[inline]
4169        pub const fn truncate<Target>(self) -> Target
4170            where Self: [const] traits::TruncateTarget<Target>
4171        {
4172            traits::TruncateTarget::internal_truncate(self)
4173        }
4174
4175        /// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
4176        /// instead of truncating.
4177        ///
4178        /// # Examples
4179        ///
4180        /// ```
4181        /// #![feature(integer_widen_truncate)]
4182        #[doc = concat!("assert_eq!(120u8, 120", stringify!($SelfT), ".saturating_truncate());")]
4183        /// assert_eq!(255u8, 376u32.saturating_truncate());
4184        /// ```
4185        #[must_use = "this returns the truncated value and does not modify the original"]
4186        #[unstable(feature = "integer_widen_truncate", issue = "154330")]
4187        #[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
4188        #[inline]
4189        pub const fn saturating_truncate<Target>(self) -> Target
4190            where Self: [const] traits::TruncateTarget<Target>
4191        {
4192            traits::TruncateTarget::internal_saturating_truncate(self)
4193        }
4194
4195        /// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
4196        /// is outside the bounds of the smaller type.
4197        ///
4198        /// # Examples
4199        ///
4200        /// ```
4201        /// #![feature(integer_widen_truncate)]
4202        #[doc = concat!("assert_eq!(Some(120u8), 120", stringify!($SelfT), ".checked_truncate());")]
4203        /// assert_eq!(None, 376u32.checked_truncate::<u8>());
4204        /// ```
4205        #[must_use = "this returns the truncated value and does not modify the original"]
4206        #[unstable(feature = "integer_widen_truncate", issue = "154330")]
4207        #[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
4208        #[inline]
4209        pub const fn checked_truncate<Target>(self) -> Option<Target>
4210            where Self: [const] traits::TruncateTarget<Target>
4211        {
4212            traits::TruncateTarget::internal_checked_truncate(self)
4213        }
4214
4215        /// Widen to an integer of the same size or larger, preserving its value.
4216        ///
4217        /// # Examples
4218        ///
4219        /// ```
4220        /// #![feature(integer_widen_truncate)]
4221        #[doc = concat!("assert_eq!(120u128, 120u8.widen());")]
4222        /// ```
4223        #[must_use = "this returns the widened value and does not modify the original"]
4224        #[unstable(feature = "integer_widen_truncate", issue = "154330")]
4225        #[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
4226        #[inline]
4227        pub const fn widen<Target>(self) -> Target
4228            where Self: [const] traits::WidenTarget<Target>
4229        {
4230            traits::WidenTarget::internal_widen(self)
4231        }
4232    }
4233}