core/num/
int_macros.rs

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