core/num/
uint_macros.rs

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