core\num/
uint_macros.rs

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