core/num/
uint_macros.rs

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