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