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