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