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