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