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        #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".unbounded_shl(0), 0b101);")]
1427        #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".unbounded_shl(1), 0b1010);")]
1428        #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".unbounded_shl(2), 0b10100);")]
1429        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".unbounded_shl(", stringify!($BITS), "), 0);")]
1430        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".unbounded_shl(1).unbounded_shl(", stringify!($BITS_MINUS_ONE), "), 0);")]
1431        #[doc = concat!("assert_eq!((-13_", stringify!($SelfT), ").unbounded_shl(", stringify!($BITS), "), 0);")]
1432        #[doc = concat!("assert_eq!((-13_", stringify!($SelfT), ").unbounded_shl(1).unbounded_shl(", stringify!($BITS_MINUS_ONE), "), 0);")]
1433        /// ```
1434        #[stable(feature = "unbounded_shifts", since = "1.87.0")]
1435        #[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
1436        #[must_use = "this returns the result of the operation, \
1437                      without modifying the original"]
1438        #[inline]
1439        pub const fn unbounded_shl(self, rhs: u32) -> $SelfT{
1440            if rhs < Self::BITS {
1441                // SAFETY:
1442                // rhs is just checked to be in-range above
1443                unsafe { self.unchecked_shl(rhs) }
1444            } else {
1445                0
1446            }
1447        }
1448
1449        /// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
1450        ///
1451        /// Returns `None` if any bits that would be shifted out differ from the resulting sign bit
1452        /// or if `rhs` >=
1453        #[doc = concat!("`", stringify!($SelfT), "::BITS`.")]
1454        /// Otherwise, returns `Some(self << rhs)`.
1455        ///
1456        /// # Examples
1457        ///
1458        /// ```
1459        /// #![feature(exact_bitshifts)]
1460        ///
1461        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".shl_exact(4), Some(0x10));")]
1462        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".shl_exact(", stringify!($SelfT), "::BITS - 2), Some(1 << ", stringify!($SelfT), "::BITS - 2));")]
1463        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".shl_exact(", stringify!($SelfT), "::BITS - 1), None);")]
1464        #[doc = concat!("assert_eq!((-0x2", stringify!($SelfT), ").shl_exact(", stringify!($SelfT), "::BITS - 2), Some(-0x2 << ", stringify!($SelfT), "::BITS - 2));")]
1465        #[doc = concat!("assert_eq!((-0x2", stringify!($SelfT), ").shl_exact(", stringify!($SelfT), "::BITS - 1), None);")]
1466        /// ```
1467        #[unstable(feature = "exact_bitshifts", issue = "144336")]
1468        #[must_use = "this returns the result of the operation, \
1469                      without modifying the original"]
1470        #[inline]
1471        pub const fn shl_exact(self, rhs: u32) -> Option<$SelfT> {
1472            if rhs < self.leading_zeros() || rhs < self.leading_ones() {
1473                // SAFETY: rhs is checked above
1474                Some(unsafe { self.unchecked_shl(rhs) })
1475            } else {
1476                None
1477            }
1478        }
1479
1480        /// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
1481        /// losslessly reversed and `rhs` cannot be larger than
1482        #[doc = concat!("`", stringify!($SelfT), "::BITS`.")]
1483        ///
1484        /// # Safety
1485        ///
1486        /// This results in undefined behavior when `rhs >= self.leading_zeros() && rhs >=
1487        /// self.leading_ones()` i.e. when
1488        #[doc = concat!("[`", stringify!($SelfT), "::shl_exact`]")]
1489        /// would return `None`.
1490        #[unstable(feature = "exact_bitshifts", issue = "144336")]
1491        #[must_use = "this returns the result of the operation, \
1492                      without modifying the original"]
1493        #[inline]
1494        pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> $SelfT {
1495            assert_unsafe_precondition!(
1496                check_library_ub,
1497                concat!(stringify!($SelfT), "::unchecked_shl_exact cannot shift out bits that would change the value of the first bit"),
1498                (
1499                    zeros: u32 = self.leading_zeros(),
1500                    ones: u32 = self.leading_ones(),
1501                    rhs: u32 = rhs,
1502                ) => rhs < zeros || rhs < ones,
1503            );
1504
1505            // SAFETY: this is guaranteed to be safe by the caller
1506            unsafe { self.unchecked_shl(rhs) }
1507        }
1508
1509        /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
1510        /// larger than or equal to the number of bits in `self`.
1511        ///
1512        /// # Examples
1513        ///
1514        /// ```
1515        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
1516        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);")]
1517        /// ```
1518        #[stable(feature = "wrapping", since = "1.7.0")]
1519        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1520        #[must_use = "this returns the result of the operation, \
1521                      without modifying the original"]
1522        #[inline]
1523        pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
1524            // Not using overflowing_shr as that's a wrapping shift
1525            if rhs < Self::BITS {
1526                // SAFETY: just checked the RHS is in-range
1527                Some(unsafe { self.unchecked_shr(rhs) })
1528            } else {
1529                None
1530            }
1531        }
1532
1533        /// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
1534        /// larger than or equal to the number of bits in `self`.
1535        ///
1536        /// # Panics
1537        ///
1538        /// ## Overflow behavior
1539        ///
1540        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1541        ///
1542        /// # Examples
1543        ///
1544        /// ```
1545        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".strict_shr(4), 0x1);")]
1546        /// ```
1547        ///
1548        /// The following panics because of overflow:
1549        ///
1550        /// ```should_panic
1551        #[doc = concat!("let _ = 0x10", stringify!($SelfT), ".strict_shr(128);")]
1552        /// ```
1553        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1554        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1555        #[must_use = "this returns the result of the operation, \
1556                      without modifying the original"]
1557        #[inline]
1558        #[track_caller]
1559        pub const fn strict_shr(self, rhs: u32) -> Self {
1560            let (a, b) = self.overflowing_shr(rhs);
1561            if b { overflow_panic::shr() } else { a }
1562        }
1563
1564        /// Unchecked shift right. Computes `self >> rhs`, assuming that
1565        /// `rhs` is less than the number of bits in `self`.
1566        ///
1567        /// # Safety
1568        ///
1569        /// This results in undefined behavior if `rhs` is larger than
1570        /// or equal to the number of bits in `self`,
1571        /// i.e. when [`checked_shr`] would return `None`.
1572        ///
1573        #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
1574        #[stable(feature = "unchecked_shifts", since = "1.93.0")]
1575        #[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
1576        #[must_use = "this returns the result of the operation, \
1577                      without modifying the original"]
1578        #[inline(always)]
1579        #[track_caller]
1580        pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
1581            assert_unsafe_precondition!(
1582                check_language_ub,
1583                concat!(stringify!($SelfT), "::unchecked_shr cannot overflow"),
1584                (
1585                    rhs: u32 = rhs,
1586                ) => rhs < <$ActualT>::BITS,
1587            );
1588
1589            // SAFETY: this is guaranteed to be safe by the caller.
1590            unsafe {
1591                intrinsics::unchecked_shr(self, rhs)
1592            }
1593        }
1594
1595        /// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
1596        ///
1597        /// If `rhs` is larger or equal to the number of bits in `self`,
1598        /// the entire value is shifted out, which yields `0` for a positive number,
1599        /// and `-1` for a negative number.
1600        ///
1601        /// # Examples
1602        ///
1603        /// ```
1604        #[doc = concat!("assert_eq!(0x10_", stringify!($SelfT), ".unbounded_shr(4), 0x1);")]
1605        #[doc = concat!("assert_eq!(0x10_", stringify!($SelfT), ".unbounded_shr(129), 0);")]
1606        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.unbounded_shr(129), -1);")]
1607        #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".unbounded_shr(0), 0b1010);")]
1608        #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".unbounded_shr(1), 0b101);")]
1609        #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".unbounded_shr(2), 0b10);")]
1610        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".unbounded_shr(", stringify!($BITS), "), 0);")]
1611        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".unbounded_shr(1).unbounded_shr(", stringify!($BITS_MINUS_ONE), "), 0);")]
1612        #[doc = concat!("assert_eq!((-13_", stringify!($SelfT), ").unbounded_shr(", stringify!($BITS), "), -1);")]
1613        #[doc = concat!("assert_eq!((-13_", stringify!($SelfT), ").unbounded_shr(1).unbounded_shr(", stringify!($BITS_MINUS_ONE), "), -1);")]
1614        /// ```
1615        #[stable(feature = "unbounded_shifts", since = "1.87.0")]
1616        #[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
1617        #[must_use = "this returns the result of the operation, \
1618                      without modifying the original"]
1619        #[inline]
1620        pub const fn unbounded_shr(self, rhs: u32) -> $SelfT{
1621            if rhs < Self::BITS {
1622                // SAFETY:
1623                // rhs is just checked to be in-range above
1624                unsafe { self.unchecked_shr(rhs) }
1625            } else {
1626                // A shift by `Self::BITS-1` suffices for signed integers, because the sign bit is copied for each of the shifted bits.
1627
1628                // SAFETY:
1629                // `Self::BITS-1` is guaranteed to be less than `Self::BITS`
1630                unsafe { self.unchecked_shr(Self::BITS - 1) }
1631            }
1632        }
1633
1634        /// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
1635        ///
1636        /// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
1637        #[doc = concat!("`", stringify!($SelfT), "::BITS`.")]
1638        /// Otherwise, returns `Some(self >> rhs)`.
1639        ///
1640        /// # Examples
1641        ///
1642        /// ```
1643        /// #![feature(exact_bitshifts)]
1644        ///
1645        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".shr_exact(4), Some(0x1));")]
1646        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".shr_exact(5), None);")]
1647        /// ```
1648        #[unstable(feature = "exact_bitshifts", issue = "144336")]
1649        #[must_use = "this returns the result of the operation, \
1650                      without modifying the original"]
1651        #[inline]
1652        pub const fn shr_exact(self, rhs: u32) -> Option<$SelfT> {
1653            if rhs <= self.trailing_zeros() && rhs < <$SelfT>::BITS {
1654                // SAFETY: rhs is checked above
1655                Some(unsafe { self.unchecked_shr(rhs) })
1656            } else {
1657                None
1658            }
1659        }
1660
1661        /// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
1662        /// losslessly reversed and `rhs` cannot be larger than
1663        #[doc = concat!("`", stringify!($SelfT), "::BITS`.")]
1664        ///
1665        /// # Safety
1666        ///
1667        /// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
1668        #[doc = concat!(stringify!($SelfT), "::BITS`")]
1669        /// i.e. when
1670        #[doc = concat!("[`", stringify!($SelfT), "::shr_exact`]")]
1671        /// would return `None`.
1672        #[unstable(feature = "exact_bitshifts", issue = "144336")]
1673        #[must_use = "this returns the result of the operation, \
1674                      without modifying the original"]
1675        #[inline]
1676        pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> $SelfT {
1677            assert_unsafe_precondition!(
1678                check_library_ub,
1679                concat!(stringify!($SelfT), "::unchecked_shr_exact cannot shift out non-zero bits"),
1680                (
1681                    zeros: u32 = self.trailing_zeros(),
1682                    bits: u32 =  <$SelfT>::BITS,
1683                    rhs: u32 = rhs,
1684                ) => rhs <= zeros && rhs < bits,
1685            );
1686
1687            // SAFETY: this is guaranteed to be safe by the caller
1688            unsafe { self.unchecked_shr(rhs) }
1689        }
1690
1691        /// Checked absolute value. Computes `self.abs()`, returning `None` if
1692        /// `self == MIN`.
1693        ///
1694        /// # Examples
1695        ///
1696        /// ```
1697        #[doc = concat!("assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));")]
1698        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);")]
1699        /// ```
1700        #[stable(feature = "no_panic_abs", since = "1.13.0")]
1701        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1702        #[must_use = "this returns the result of the operation, \
1703                      without modifying the original"]
1704        #[inline]
1705        pub const fn checked_abs(self) -> Option<Self> {
1706            if self.is_negative() {
1707                self.checked_neg()
1708            } else {
1709                Some(self)
1710            }
1711        }
1712
1713        /// Strict absolute value. Computes `self.abs()`, panicking if
1714        /// `self == MIN`.
1715        ///
1716        /// # Panics
1717        ///
1718        /// ## Overflow behavior
1719        ///
1720        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1721        ///
1722        /// # Examples
1723        ///
1724        /// ```
1725        #[doc = concat!("assert_eq!((-5", stringify!($SelfT), ").strict_abs(), 5);")]
1726        /// ```
1727        ///
1728        /// The following panics because of overflow:
1729        ///
1730        /// ```should_panic
1731        #[doc = concat!("let _ = ", stringify!($SelfT), "::MIN.strict_abs();")]
1732        /// ```
1733        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1734        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1735        #[must_use = "this returns the result of the operation, \
1736                      without modifying the original"]
1737        #[inline]
1738        #[track_caller]
1739        pub const fn strict_abs(self) -> Self {
1740            if self.is_negative() {
1741                self.strict_neg()
1742            } else {
1743                self
1744            }
1745        }
1746
1747        /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
1748        /// overflow occurred.
1749        ///
1750        /// # Examples
1751        ///
1752        /// ```
1753        #[doc = concat!("assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));")]
1754        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".checked_pow(0), Some(1));")]
1755        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
1756        /// ```
1757
1758        #[stable(feature = "no_panic_pow", since = "1.34.0")]
1759        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1760        #[must_use = "this returns the result of the operation, \
1761                      without modifying the original"]
1762        #[inline]
1763        pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
1764            if exp == 0 {
1765                return Some(1);
1766            }
1767            let mut base = self;
1768            let mut acc: Self = 1;
1769
1770            loop {
1771                if (exp & 1) == 1 {
1772                    acc = try_opt!(acc.checked_mul(base));
1773                    // since exp!=0, finally the exp must be 1.
1774                    if exp == 1 {
1775                        return Some(acc);
1776                    }
1777                }
1778                exp /= 2;
1779                base = try_opt!(base.checked_mul(base));
1780            }
1781        }
1782
1783        /// Strict exponentiation. Computes `self.pow(exp)`, panicking if
1784        /// overflow occurred.
1785        ///
1786        /// # Panics
1787        ///
1788        /// ## Overflow behavior
1789        ///
1790        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1791        ///
1792        /// # Examples
1793        ///
1794        /// ```
1795        #[doc = concat!("assert_eq!(8", stringify!($SelfT), ".strict_pow(2), 64);")]
1796        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".strict_pow(0), 1);")]
1797        /// ```
1798        ///
1799        /// The following panics because of overflow:
1800        ///
1801        /// ```should_panic
1802        #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_pow(2);")]
1803        /// ```
1804        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1805        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1806        #[must_use = "this returns the result of the operation, \
1807                      without modifying the original"]
1808        #[inline]
1809        #[track_caller]
1810        pub const fn strict_pow(self, mut exp: u32) -> Self {
1811            if exp == 0 {
1812                return 1;
1813            }
1814            let mut base = self;
1815            let mut acc: Self = 1;
1816
1817            loop {
1818                if (exp & 1) == 1 {
1819                    acc = acc.strict_mul(base);
1820                    // since exp!=0, finally the exp must be 1.
1821                    if exp == 1 {
1822                        return acc;
1823                    }
1824                }
1825                exp /= 2;
1826                base = base.strict_mul(base);
1827            }
1828        }
1829
1830        /// Returns the square root of the number, rounded down.
1831        ///
1832        /// Returns `None` if `self` is negative.
1833        ///
1834        /// # Examples
1835        ///
1836        /// ```
1837        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_isqrt(), Some(3));")]
1838        /// ```
1839        #[stable(feature = "isqrt", since = "1.84.0")]
1840        #[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
1841        #[must_use = "this returns the result of the operation, \
1842                      without modifying the original"]
1843        #[inline]
1844        pub const fn checked_isqrt(self) -> Option<Self> {
1845            if self < 0 {
1846                None
1847            } else {
1848                // SAFETY: Input is nonnegative in this `else` branch.
1849                let result = unsafe {
1850                    crate::num::int_sqrt::$ActualT(self as $ActualT) as $SelfT
1851                };
1852
1853                // Inform the optimizer what the range of outputs is. If
1854                // testing `core` crashes with no panic message and a
1855                // `num::int_sqrt::i*` test failed, it's because your edits
1856                // caused these assertions to become false.
1857                //
1858                // SAFETY: Integer square root is a monotonically nondecreasing
1859                // function, which means that increasing the input will never
1860                // cause the output to decrease. Thus, since the input for
1861                // nonnegative signed integers is bounded by
1862                // `[0, <$ActualT>::MAX]`, sqrt(n) will be bounded by
1863                // `[sqrt(0), sqrt(<$ActualT>::MAX)]`.
1864                unsafe {
1865                    // SAFETY: `<$ActualT>::MAX` is nonnegative.
1866                    const MAX_RESULT: $SelfT = unsafe {
1867                        crate::num::int_sqrt::$ActualT(<$ActualT>::MAX) as $SelfT
1868                    };
1869
1870                    crate::hint::assert_unchecked(result >= 0);
1871                    crate::hint::assert_unchecked(result <= MAX_RESULT);
1872                }
1873
1874                Some(result)
1875            }
1876        }
1877
1878        /// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
1879        /// bounds instead of overflowing.
1880        ///
1881        /// # Examples
1882        ///
1883        /// ```
1884        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
1885        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT), "::MAX);")]
1886        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT), "::MIN);")]
1887        /// ```
1888
1889        #[stable(feature = "rust1", since = "1.0.0")]
1890        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1891        #[must_use = "this returns the result of the operation, \
1892                      without modifying the original"]
1893        #[inline(always)]
1894        pub const fn saturating_add(self, rhs: Self) -> Self {
1895            intrinsics::saturating_add(self, rhs)
1896        }
1897
1898        /// Saturating addition with an unsigned integer. Computes `self + rhs`,
1899        /// saturating at the numeric bounds instead of overflowing.
1900        ///
1901        /// # Examples
1902        ///
1903        /// ```
1904        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_unsigned(2), 3);")]
1905        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add_unsigned(100), ", stringify!($SelfT), "::MAX);")]
1906        /// ```
1907        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
1908        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
1909        #[must_use = "this returns the result of the operation, \
1910                      without modifying the original"]
1911        #[inline]
1912        pub const fn saturating_add_unsigned(self, rhs: $UnsignedT) -> Self {
1913            // Overflow can only happen at the upper bound
1914            // We cannot use `unwrap_or` here because it is not `const`
1915            match self.checked_add_unsigned(rhs) {
1916                Some(x) => x,
1917                None => Self::MAX,
1918            }
1919        }
1920
1921        /// Saturating integer subtraction. Computes `self - rhs`, saturating at the
1922        /// numeric bounds instead of overflowing.
1923        ///
1924        /// # Examples
1925        ///
1926        /// ```
1927        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);")]
1928        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT), "::MIN);")]
1929        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT), "::MAX);")]
1930        /// ```
1931        #[stable(feature = "rust1", since = "1.0.0")]
1932        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1933        #[must_use = "this returns the result of the operation, \
1934                      without modifying the original"]
1935        #[inline(always)]
1936        pub const fn saturating_sub(self, rhs: Self) -> Self {
1937            intrinsics::saturating_sub(self, rhs)
1938        }
1939
1940        /// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
1941        /// saturating at the numeric bounds instead of overflowing.
1942        ///
1943        /// # Examples
1944        ///
1945        /// ```
1946        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub_unsigned(127), -27);")]
1947        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub_unsigned(100), ", stringify!($SelfT), "::MIN);")]
1948        /// ```
1949        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
1950        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
1951        #[must_use = "this returns the result of the operation, \
1952                      without modifying the original"]
1953        #[inline]
1954        pub const fn saturating_sub_unsigned(self, rhs: $UnsignedT) -> Self {
1955            // Overflow can only happen at the lower bound
1956            // We cannot use `unwrap_or` here because it is not `const`
1957            match self.checked_sub_unsigned(rhs) {
1958                Some(x) => x,
1959                None => Self::MIN,
1960            }
1961        }
1962
1963        /// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
1964        /// instead of overflowing.
1965        ///
1966        /// # Examples
1967        ///
1968        /// ```
1969        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);")]
1970        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);")]
1971        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT), "::MAX);")]
1972        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT), "::MIN + 1);")]
1973        /// ```
1974
1975        #[stable(feature = "saturating_neg", since = "1.45.0")]
1976        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1977        #[must_use = "this returns the result of the operation, \
1978                      without modifying the original"]
1979        #[inline(always)]
1980        pub const fn saturating_neg(self) -> Self {
1981            intrinsics::saturating_sub(0, self)
1982        }
1983
1984        /// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1985        /// MIN` instead of overflowing.
1986        ///
1987        /// # Examples
1988        ///
1989        /// ```
1990        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);")]
1991        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);")]
1992        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT), "::MAX);")]
1993        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT), "::MAX);")]
1994        /// ```
1995
1996        #[stable(feature = "saturating_neg", since = "1.45.0")]
1997        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1998        #[must_use = "this returns the result of the operation, \
1999                      without modifying the original"]
2000        #[inline]
2001        pub const fn saturating_abs(self) -> Self {
2002            if self.is_negative() {
2003                self.saturating_neg()
2004            } else {
2005                self
2006            }
2007        }
2008
2009        /// Saturating integer multiplication. Computes `self * rhs`, saturating at the
2010        /// numeric bounds instead of overflowing.
2011        ///
2012        /// # Examples
2013        ///
2014        /// ```
2015        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);")]
2016        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);")]
2017        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);")]
2018        /// ```
2019        #[stable(feature = "wrapping", since = "1.7.0")]
2020        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
2021        #[must_use = "this returns the result of the operation, \
2022                      without modifying the original"]
2023        #[inline]
2024        pub const fn saturating_mul(self, rhs: Self) -> Self {
2025            match self.checked_mul(rhs) {
2026                Some(x) => x,
2027                None => if (self < 0) == (rhs < 0) {
2028                    Self::MAX
2029                } else {
2030                    Self::MIN
2031                }
2032            }
2033        }
2034
2035        /// Saturating integer division. Computes `self / rhs`, saturating at the
2036        /// numeric bounds instead of overflowing.
2037        ///
2038        /// # Panics
2039        ///
2040        /// This function will panic if `rhs` is zero.
2041        ///
2042        /// # Examples
2043        ///
2044        /// ```
2045        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
2046        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_div(-1), ", stringify!($SelfT), "::MIN + 1);")]
2047        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_div(-1), ", stringify!($SelfT), "::MAX);")]
2048        ///
2049        /// ```
2050        #[stable(feature = "saturating_div", since = "1.58.0")]
2051        #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
2052        #[must_use = "this returns the result of the operation, \
2053                      without modifying the original"]
2054        #[inline]
2055        pub const fn saturating_div(self, rhs: Self) -> Self {
2056            match self.overflowing_div(rhs) {
2057                (result, false) => result,
2058                (_result, true) => Self::MAX, // MIN / -1 is the only possible saturating overflow
2059            }
2060        }
2061
2062        /// Saturating integer exponentiation. Computes `self.pow(exp)`,
2063        /// saturating at the numeric bounds instead of overflowing.
2064        ///
2065        /// # Examples
2066        ///
2067        /// ```
2068        #[doc = concat!("assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);")]
2069        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".saturating_pow(0), 1);")]
2070        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
2071        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);")]
2072        /// ```
2073        #[stable(feature = "no_panic_pow", since = "1.34.0")]
2074        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2075        #[must_use = "this returns the result of the operation, \
2076                      without modifying the original"]
2077        #[inline]
2078        pub const fn saturating_pow(self, exp: u32) -> Self {
2079            match self.checked_pow(exp) {
2080                Some(x) => x,
2081                None if self < 0 && exp % 2 == 1 => Self::MIN,
2082                None => Self::MAX,
2083            }
2084        }
2085
2086        /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
2087        /// boundary of the type.
2088        ///
2089        /// # Examples
2090        ///
2091        /// ```
2092        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);")]
2093        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT), "::MIN + 1);")]
2094        /// ```
2095        #[stable(feature = "rust1", since = "1.0.0")]
2096        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2097        #[must_use = "this returns the result of the operation, \
2098                      without modifying the original"]
2099        #[inline(always)]
2100        pub const fn wrapping_add(self, rhs: Self) -> Self {
2101            intrinsics::wrapping_add(self, rhs)
2102        }
2103
2104        /// Wrapping (modular) addition with an unsigned integer. Computes
2105        /// `self + rhs`, wrapping around at the boundary of the type.
2106        ///
2107        /// # Examples
2108        ///
2109        /// ```
2110        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add_unsigned(27), 127);")]
2111        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add_unsigned(2), ", stringify!($SelfT), "::MIN + 1);")]
2112        /// ```
2113        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2114        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2115        #[must_use = "this returns the result of the operation, \
2116                      without modifying the original"]
2117        #[inline(always)]
2118        pub const fn wrapping_add_unsigned(self, rhs: $UnsignedT) -> Self {
2119            self.wrapping_add(rhs as Self)
2120        }
2121
2122        /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
2123        /// boundary of the type.
2124        ///
2125        /// # Examples
2126        ///
2127        /// ```
2128        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);")]
2129        #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ", stringify!($SelfT), "::MAX);")]
2130        /// ```
2131        #[stable(feature = "rust1", since = "1.0.0")]
2132        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2133        #[must_use = "this returns the result of the operation, \
2134                      without modifying the original"]
2135        #[inline(always)]
2136        pub const fn wrapping_sub(self, rhs: Self) -> Self {
2137            intrinsics::wrapping_sub(self, rhs)
2138        }
2139
2140        /// Wrapping (modular) subtraction with an unsigned integer. Computes
2141        /// `self - rhs`, wrapping around at the boundary of the type.
2142        ///
2143        /// # Examples
2144        ///
2145        /// ```
2146        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub_unsigned(127), -127);")]
2147        #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub_unsigned(", stringify!($UnsignedT), "::MAX), -1);")]
2148        /// ```
2149        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2150        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2151        #[must_use = "this returns the result of the operation, \
2152                      without modifying the original"]
2153        #[inline(always)]
2154        pub const fn wrapping_sub_unsigned(self, rhs: $UnsignedT) -> Self {
2155            self.wrapping_sub(rhs as Self)
2156        }
2157
2158        /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
2159        /// the boundary of the type.
2160        ///
2161        /// # Examples
2162        ///
2163        /// ```
2164        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);")]
2165        /// assert_eq!(11i8.wrapping_mul(12), -124);
2166        /// ```
2167        #[stable(feature = "rust1", since = "1.0.0")]
2168        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2169        #[must_use = "this returns the result of the operation, \
2170                      without modifying the original"]
2171        #[inline(always)]
2172        pub const fn wrapping_mul(self, rhs: Self) -> Self {
2173            intrinsics::wrapping_mul(self, rhs)
2174        }
2175
2176        /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
2177        /// boundary of the type.
2178        ///
2179        /// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
2180        /// `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
2181        /// that is too large to represent in the type. In such a case, this function returns `MIN` itself.
2182        ///
2183        /// # Panics
2184        ///
2185        /// This function will panic if `rhs` is zero.
2186        ///
2187        /// # Examples
2188        ///
2189        /// ```
2190        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
2191        /// assert_eq!((-128i8).wrapping_div(-1), -128);
2192        /// ```
2193        #[stable(feature = "num_wrapping", since = "1.2.0")]
2194        #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
2195        #[must_use = "this returns the result of the operation, \
2196                      without modifying the original"]
2197        #[inline]
2198        pub const fn wrapping_div(self, rhs: Self) -> Self {
2199            self.overflowing_div(rhs).0
2200        }
2201
2202        /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
2203        /// wrapping around at the boundary of the type.
2204        ///
2205        /// Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
2206        /// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
2207        /// type. In this case, this method returns `MIN` itself.
2208        ///
2209        /// # Panics
2210        ///
2211        /// This function will panic if `rhs` is zero.
2212        ///
2213        /// # Examples
2214        ///
2215        /// ```
2216        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
2217        /// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
2218        /// ```
2219        #[stable(feature = "euclidean_division", since = "1.38.0")]
2220        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2221        #[must_use = "this returns the result of the operation, \
2222                      without modifying the original"]
2223        #[inline]
2224        pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
2225            self.overflowing_div_euclid(rhs).0
2226        }
2227
2228        /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
2229        /// boundary of the type.
2230        ///
2231        /// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
2232        /// invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
2233        /// this function returns `0`.
2234        ///
2235        /// # Panics
2236        ///
2237        /// This function will panic if `rhs` is zero.
2238        ///
2239        /// # Examples
2240        ///
2241        /// ```
2242        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
2243        /// assert_eq!((-128i8).wrapping_rem(-1), 0);
2244        /// ```
2245        #[stable(feature = "num_wrapping", since = "1.2.0")]
2246        #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
2247        #[must_use = "this returns the result of the operation, \
2248                      without modifying the original"]
2249        #[inline]
2250        pub const fn wrapping_rem(self, rhs: Self) -> Self {
2251            self.overflowing_rem(rhs).0
2252        }
2253
2254        /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
2255        /// at the boundary of the type.
2256        ///
2257        /// Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
2258        /// for the type). In this case, this method returns 0.
2259        ///
2260        /// # Panics
2261        ///
2262        /// This function will panic if `rhs` is zero.
2263        ///
2264        /// # Examples
2265        ///
2266        /// ```
2267        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
2268        /// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
2269        /// ```
2270        #[stable(feature = "euclidean_division", since = "1.38.0")]
2271        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2272        #[must_use = "this returns the result of the operation, \
2273                      without modifying the original"]
2274        #[inline]
2275        pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
2276            self.overflowing_rem_euclid(rhs).0
2277        }
2278
2279        /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
2280        /// of the type.
2281        ///
2282        /// The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
2283        /// is the negative minimal value for the type); this is a positive value that is too large to represent
2284        /// in the type. In such a case, this function returns `MIN` itself.
2285        ///
2286        /// # Examples
2287        ///
2288        /// ```
2289        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);")]
2290        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").wrapping_neg(), 100);")]
2291        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT), "::MIN);")]
2292        /// ```
2293        #[stable(feature = "num_wrapping", since = "1.2.0")]
2294        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2295        #[must_use = "this returns the result of the operation, \
2296                      without modifying the original"]
2297        #[inline(always)]
2298        pub const fn wrapping_neg(self) -> Self {
2299            (0 as $SelfT).wrapping_sub(self)
2300        }
2301
2302        /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
2303        /// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
2304        ///
2305        /// Beware that, unlike most other `wrapping_*` methods on integers, this
2306        /// does *not* give the same result as doing the shift in infinite precision
2307        /// then truncating as needed.  The behaviour matches what shift instructions
2308        /// do on many processors, and is what the `<<` operator does when overflow
2309        /// checks are disabled, but numerically it's weird.  Consider, instead,
2310        /// using [`Self::unbounded_shl`] which has nicer behaviour.
2311        ///
2312        /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
2313        /// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
2314        /// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
2315        /// which may be what you want instead.
2316        ///
2317        /// # Examples
2318        ///
2319        /// ```
2320        #[doc = concat!("assert_eq!((-1_", stringify!($SelfT), ").wrapping_shl(7), -128);")]
2321        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shl(", stringify!($BITS), "), 42);")]
2322        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shl(1).wrapping_shl(", stringify!($BITS_MINUS_ONE), "), 0);")]
2323        #[doc = concat!("assert_eq!((-1_", stringify!($SelfT), ").wrapping_shl(128), -1);")]
2324        #[doc = concat!("assert_eq!(5_", stringify!($SelfT), ".wrapping_shl(1025), 10);")]
2325        /// ```
2326        #[stable(feature = "num_wrapping", since = "1.2.0")]
2327        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2328        #[must_use = "this returns the result of the operation, \
2329                      without modifying the original"]
2330        #[inline(always)]
2331        pub const fn wrapping_shl(self, rhs: u32) -> Self {
2332            // SAFETY: the masking by the bitsize of the type ensures that we do not shift
2333            // out of bounds
2334            unsafe {
2335                self.unchecked_shl(rhs & (Self::BITS - 1))
2336            }
2337        }
2338
2339        /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
2340        /// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
2341        ///
2342        /// Beware that, unlike most other `wrapping_*` methods on integers, this
2343        /// does *not* give the same result as doing the shift in infinite precision
2344        /// then truncating as needed.  The behaviour matches what shift instructions
2345        /// do on many processors, and is what the `>>` operator does when overflow
2346        /// checks are disabled, but numerically it's weird.  Consider, instead,
2347        /// using [`Self::unbounded_shr`] which has nicer behaviour.
2348        ///
2349        /// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
2350        /// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
2351        /// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
2352        /// which may be what you want instead.
2353        ///
2354        /// # Examples
2355        ///
2356        /// ```
2357        #[doc = concat!("assert_eq!((-128_", stringify!($SelfT), ").wrapping_shr(7), -1);")]
2358        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shr(", stringify!($BITS), "), 42);")]
2359        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shr(1).wrapping_shr(", stringify!($BITS_MINUS_ONE), "), 0);")]
2360        /// assert_eq!((-128_i16).wrapping_shr(64), -128);
2361        #[doc = concat!("assert_eq!(10_", stringify!($SelfT), ".wrapping_shr(1025), 5);")]
2362        /// ```
2363        #[stable(feature = "num_wrapping", since = "1.2.0")]
2364        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2365        #[must_use = "this returns the result of the operation, \
2366                      without modifying the original"]
2367        #[inline(always)]
2368        pub const fn wrapping_shr(self, rhs: u32) -> Self {
2369            // SAFETY: the masking by the bitsize of the type ensures that we do not shift
2370            // out of bounds
2371            unsafe {
2372                self.unchecked_shr(rhs & (Self::BITS - 1))
2373            }
2374        }
2375
2376        /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
2377        /// the boundary of the type.
2378        ///
2379        /// The only case where such wrapping can occur is when one takes the absolute value of the negative
2380        /// minimal value for the type; this is a positive value that is too large to represent in the type. In
2381        /// such a case, this function returns `MIN` itself.
2382        ///
2383        /// # Examples
2384        ///
2385        /// ```
2386        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);")]
2387        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);")]
2388        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT), "::MIN);")]
2389        /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
2390        /// ```
2391        #[stable(feature = "no_panic_abs", since = "1.13.0")]
2392        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2393        #[must_use = "this returns the result of the operation, \
2394                      without modifying the original"]
2395        #[allow(unused_attributes)]
2396        #[inline]
2397        pub const fn wrapping_abs(self) -> Self {
2398             if self.is_negative() {
2399                 self.wrapping_neg()
2400             } else {
2401                 self
2402             }
2403        }
2404
2405        /// Computes the absolute value of `self` without any wrapping
2406        /// or panicking.
2407        ///
2408        ///
2409        /// # Examples
2410        ///
2411        /// ```
2412        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".unsigned_abs(), 100", stringify!($UnsignedT), ");")]
2413        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").unsigned_abs(), 100", stringify!($UnsignedT), ");")]
2414        /// assert_eq!((-128i8).unsigned_abs(), 128u8);
2415        /// ```
2416        #[stable(feature = "unsigned_abs", since = "1.51.0")]
2417        #[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
2418        #[must_use = "this returns the result of the operation, \
2419                      without modifying the original"]
2420        #[inline]
2421        pub const fn unsigned_abs(self) -> $UnsignedT {
2422             self.wrapping_abs() as $UnsignedT
2423        }
2424
2425        /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2426        /// wrapping around at the boundary of the type.
2427        ///
2428        /// # Examples
2429        ///
2430        /// ```
2431        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);")]
2432        /// assert_eq!(3i8.wrapping_pow(5), -13);
2433        /// assert_eq!(3i8.wrapping_pow(6), -39);
2434        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".wrapping_pow(0), 1);")]
2435        /// ```
2436        #[stable(feature = "no_panic_pow", since = "1.34.0")]
2437        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2438        #[must_use = "this returns the result of the operation, \
2439                      without modifying the original"]
2440        #[inline]
2441        pub const fn wrapping_pow(self, mut exp: u32) -> Self {
2442            if exp == 0 {
2443                return 1;
2444            }
2445            let mut base = self;
2446            let mut acc: Self = 1;
2447
2448            if intrinsics::is_val_statically_known(exp) {
2449                while exp > 1 {
2450                    if (exp & 1) == 1 {
2451                        acc = acc.wrapping_mul(base);
2452                    }
2453                    exp /= 2;
2454                    base = base.wrapping_mul(base);
2455                }
2456
2457                // since exp!=0, finally the exp must be 1.
2458                // Deal with the final bit of the exponent separately, since
2459                // squaring the base afterwards is not necessary.
2460                acc.wrapping_mul(base)
2461            } else {
2462                // This is faster than the above when the exponent is not known
2463                // at compile time. We can't use the same code for the constant
2464                // exponent case because LLVM is currently unable to unroll
2465                // this loop.
2466                loop {
2467                    if (exp & 1) == 1 {
2468                        acc = acc.wrapping_mul(base);
2469                        // since exp!=0, finally the exp must be 1.
2470                        if exp == 1 {
2471                            return acc;
2472                        }
2473                    }
2474                    exp /= 2;
2475                    base = base.wrapping_mul(base);
2476                }
2477            }
2478        }
2479
2480        /// Calculates `self` + `rhs`.
2481        ///
2482        /// Returns a tuple of the addition along with a boolean indicating
2483        /// whether an arithmetic overflow would occur. If an overflow would have
2484        /// occurred then the wrapped value is returned.
2485        ///
2486        /// # Examples
2487        ///
2488        /// ```
2489        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
2490        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT), "::MIN, true));")]
2491        /// ```
2492        #[stable(feature = "wrapping", since = "1.7.0")]
2493        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2494        #[must_use = "this returns the result of the operation, \
2495                      without modifying the original"]
2496        #[inline(always)]
2497        pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2498            let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
2499            (a as Self, b)
2500        }
2501
2502        /// Calculates `self` + `rhs` + `carry` and checks for overflow.
2503        ///
2504        /// Performs "ternary addition" of two integer operands and a carry-in
2505        /// bit, and returns a tuple of the sum along with a boolean indicating
2506        /// whether an arithmetic overflow would occur. On overflow, the wrapped
2507        /// value is returned.
2508        ///
2509        /// This allows chaining together multiple additions to create a wider
2510        /// addition, and can be useful for bignum addition. This method should
2511        /// only be used for the most significant word; for the less significant
2512        /// words the unsigned method
2513        #[doc = concat!("[`", stringify!($UnsignedT), "::carrying_add`]")]
2514        /// should be used.
2515        ///
2516        /// The output boolean returned by this method is *not* a carry flag,
2517        /// and should *not* be added to a more significant word.
2518        ///
2519        /// If the input carry is false, this method is equivalent to
2520        /// [`overflowing_add`](Self::overflowing_add).
2521        ///
2522        /// # Examples
2523        ///
2524        /// ```
2525        /// #![feature(bigint_helper_methods)]
2526        /// // Only the most significant word is signed.
2527        /// //
2528        #[doc = concat!("//   10  MAX    (a = 10 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
2529        #[doc = concat!("// + -5    9    (b = -5 × 2^", stringify!($BITS), " + 9)")]
2530        /// // ---------
2531        #[doc = concat!("//    6    8    (sum = 6 × 2^", stringify!($BITS), " + 8)")]
2532        ///
2533        #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($UnsignedT), ") = (10, ", stringify!($UnsignedT), "::MAX);")]
2534        #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($UnsignedT), ") = (-5, 9);")]
2535        /// let carry0 = false;
2536        ///
2537        #[doc = concat!("// ", stringify!($UnsignedT), "::carrying_add for the less significant words")]
2538        /// let (sum0, carry1) = a0.carrying_add(b0, carry0);
2539        /// assert_eq!(carry1, true);
2540        ///
2541        #[doc = concat!("// ", stringify!($SelfT), "::carrying_add for the most significant word")]
2542        /// let (sum1, overflow) = a1.carrying_add(b1, carry1);
2543        /// assert_eq!(overflow, false);
2544        ///
2545        /// assert_eq!((sum1, sum0), (6, 8));
2546        /// ```
2547        #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2548        #[must_use = "this returns the result of the operation, \
2549                      without modifying the original"]
2550        #[inline]
2551        pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
2552            // note: longer-term this should be done via an intrinsic.
2553            // note: no intermediate overflow is required (https://github.com/rust-lang/rust/issues/85532#issuecomment-1032214946).
2554            let (a, b) = self.overflowing_add(rhs);
2555            let (c, d) = a.overflowing_add(carry as $SelfT);
2556            (c, b != d)
2557        }
2558
2559        /// Calculates `self` + `rhs` with an unsigned `rhs`.
2560        ///
2561        /// Returns a tuple of the addition along with a boolean indicating
2562        /// whether an arithmetic overflow would occur. If an overflow would
2563        /// have occurred then the wrapped value is returned.
2564        ///
2565        /// # Examples
2566        ///
2567        /// ```
2568        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_unsigned(2), (3, false));")]
2569        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_add_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MAX, false));")]
2570        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_unsigned(3), (", stringify!($SelfT), "::MIN, true));")]
2571        /// ```
2572        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2573        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2574        #[must_use = "this returns the result of the operation, \
2575                      without modifying the original"]
2576        #[inline]
2577        pub const fn overflowing_add_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
2578            let rhs = rhs as Self;
2579            let (res, overflowed) = self.overflowing_add(rhs);
2580            (res, overflowed ^ (rhs < 0))
2581        }
2582
2583        /// Calculates `self` - `rhs`.
2584        ///
2585        /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
2586        /// would occur. If an overflow would have occurred then the wrapped value is returned.
2587        ///
2588        /// # Examples
2589        ///
2590        /// ```
2591        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
2592        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
2593        /// ```
2594        #[stable(feature = "wrapping", since = "1.7.0")]
2595        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2596        #[must_use = "this returns the result of the operation, \
2597                      without modifying the original"]
2598        #[inline(always)]
2599        pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2600            let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
2601            (a as Self, b)
2602        }
2603
2604        /// Calculates `self` &minus; `rhs` &minus; `borrow` and checks for
2605        /// overflow.
2606        ///
2607        /// Performs "ternary subtraction" by subtracting both an integer
2608        /// operand and a borrow-in bit from `self`, and returns a tuple of the
2609        /// difference along with a boolean indicating whether an arithmetic
2610        /// overflow would occur. On overflow, the wrapped value is returned.
2611        ///
2612        /// This allows chaining together multiple subtractions to create a
2613        /// wider subtraction, and can be useful for bignum subtraction. This
2614        /// method should only be used for the most significant word; for the
2615        /// less significant words the unsigned method
2616        #[doc = concat!("[`", stringify!($UnsignedT), "::borrowing_sub`]")]
2617        /// should be used.
2618        ///
2619        /// The output boolean returned by this method is *not* a borrow flag,
2620        /// and should *not* be subtracted from a more significant word.
2621        ///
2622        /// If the input borrow is false, this method is equivalent to
2623        /// [`overflowing_sub`](Self::overflowing_sub).
2624        ///
2625        /// # Examples
2626        ///
2627        /// ```
2628        /// #![feature(bigint_helper_methods)]
2629        /// // Only the most significant word is signed.
2630        /// //
2631        #[doc = concat!("//    6    8    (a = 6 × 2^", stringify!($BITS), " + 8)")]
2632        #[doc = concat!("// - -5    9    (b = -5 × 2^", stringify!($BITS), " + 9)")]
2633        /// // ---------
2634        #[doc = concat!("//   10  MAX    (diff = 10 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
2635        ///
2636        #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($UnsignedT), ") = (6, 8);")]
2637        #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($UnsignedT), ") = (-5, 9);")]
2638        /// let borrow0 = false;
2639        ///
2640        #[doc = concat!("// ", stringify!($UnsignedT), "::borrowing_sub for the less significant words")]
2641        /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
2642        /// assert_eq!(borrow1, true);
2643        ///
2644        #[doc = concat!("// ", stringify!($SelfT), "::borrowing_sub for the most significant word")]
2645        /// let (diff1, overflow) = a1.borrowing_sub(b1, borrow1);
2646        /// assert_eq!(overflow, false);
2647        ///
2648        #[doc = concat!("assert_eq!((diff1, diff0), (10, ", stringify!($UnsignedT), "::MAX));")]
2649        /// ```
2650        #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2651        #[must_use = "this returns the result of the operation, \
2652                      without modifying the original"]
2653        #[inline]
2654        pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
2655            // note: longer-term this should be done via an intrinsic.
2656            // note: no intermediate overflow is required (https://github.com/rust-lang/rust/issues/85532#issuecomment-1032214946).
2657            let (a, b) = self.overflowing_sub(rhs);
2658            let (c, d) = a.overflowing_sub(borrow as $SelfT);
2659            (c, b != d)
2660        }
2661
2662        /// Calculates `self` - `rhs` with an unsigned `rhs`.
2663        ///
2664        /// Returns a tuple of the subtraction along with a boolean indicating
2665        /// whether an arithmetic overflow would occur. If an overflow would
2666        /// have occurred then the wrapped value is returned.
2667        ///
2668        /// # Examples
2669        ///
2670        /// ```
2671        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_unsigned(2), (-1, false));")]
2672        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).overflowing_sub_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MIN, false));")]
2673        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).overflowing_sub_unsigned(3), (", stringify!($SelfT), "::MAX, true));")]
2674        /// ```
2675        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2676        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2677        #[must_use = "this returns the result of the operation, \
2678                      without modifying the original"]
2679        #[inline]
2680        pub const fn overflowing_sub_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
2681            let rhs = rhs as Self;
2682            let (res, overflowed) = self.overflowing_sub(rhs);
2683            (res, overflowed ^ (rhs < 0))
2684        }
2685
2686        /// Calculates the multiplication of `self` and `rhs`.
2687        ///
2688        /// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
2689        /// would occur. If an overflow would have occurred then the wrapped value is returned.
2690        ///
2691        /// # Examples
2692        ///
2693        /// ```
2694        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));")]
2695        /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
2696        /// ```
2697        #[stable(feature = "wrapping", since = "1.7.0")]
2698        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2699        #[must_use = "this returns the result of the operation, \
2700                      without modifying the original"]
2701        #[inline(always)]
2702        pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2703            let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
2704            (a as Self, b)
2705        }
2706
2707        /// Calculates the complete product `self * rhs` without the possibility to overflow.
2708        ///
2709        /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
2710        /// of the result as two separate values, in that order.
2711        ///
2712        /// If you also need to add a carry to the wide result, then you want
2713        /// [`Self::carrying_mul`] instead.
2714        ///
2715        /// # Examples
2716        ///
2717        /// Please note that this example is shared among integer types, which is why `i32` is used.
2718        ///
2719        /// ```
2720        /// #![feature(bigint_helper_methods)]
2721        /// assert_eq!(5i32.widening_mul(-2), (4294967286, -1));
2722        /// assert_eq!(1_000_000_000i32.widening_mul(-10), (2884901888, -3));
2723        /// ```
2724        #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2725        #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2726        #[must_use = "this returns the result of the operation, \
2727                      without modifying the original"]
2728        #[inline]
2729        pub const fn widening_mul(self, rhs: Self) -> ($UnsignedT, Self) {
2730            Self::carrying_mul_add(self, rhs, 0, 0)
2731        }
2732
2733        /// Calculates the "full multiplication" `self * rhs + carry`
2734        /// without the possibility to overflow.
2735        ///
2736        /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
2737        /// of the result as two separate values, in that order.
2738        ///
2739        /// Performs "long multiplication" which takes in an extra amount to add, and may return an
2740        /// additional amount of overflow. This allows for chaining together multiple
2741        /// multiplications to create "big integers" which represent larger values.
2742        ///
2743        /// If you don't need the `carry`, then you can use [`Self::widening_mul`] instead.
2744        ///
2745        /// # Examples
2746        ///
2747        /// Please note that this example is shared among integer types, which is why `i32` is used.
2748        ///
2749        /// ```
2750        /// #![feature(bigint_helper_methods)]
2751        /// assert_eq!(5i32.carrying_mul(-2, 0), (4294967286, -1));
2752        /// assert_eq!(5i32.carrying_mul(-2, 10), (0, 0));
2753        /// assert_eq!(1_000_000_000i32.carrying_mul(-10, 0), (2884901888, -3));
2754        /// assert_eq!(1_000_000_000i32.carrying_mul(-10, 10), (2884901898, -3));
2755        #[doc = concat!("assert_eq!(",
2756            stringify!($SelfT), "::MAX.carrying_mul(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
2757            "(", stringify!($SelfT), "::MAX.unsigned_abs() + 1, ", stringify!($SelfT), "::MAX / 2));"
2758        )]
2759        /// ```
2760        #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2761        #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2762        #[must_use = "this returns the result of the operation, \
2763                      without modifying the original"]
2764        #[inline]
2765        pub const fn carrying_mul(self, rhs: Self, carry: Self) -> ($UnsignedT, Self) {
2766            Self::carrying_mul_add(self, rhs, carry, 0)
2767        }
2768
2769        /// Calculates the "full multiplication" `self * rhs + carry + add`
2770        /// without the possibility to overflow.
2771        ///
2772        /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
2773        /// of the result as two separate values, in that order.
2774        ///
2775        /// Performs "long multiplication" which takes in an extra amount to add, and may return an
2776        /// additional amount of overflow. This allows for chaining together multiple
2777        /// multiplications to create "big integers" which represent larger values.
2778        ///
2779        /// If you don't need either `carry`, then you can use [`Self::widening_mul`] instead,
2780        /// and if you only need one `carry`, then you can use [`Self::carrying_mul`] instead.
2781        ///
2782        /// # Examples
2783        ///
2784        /// Please note that this example is shared among integer types, which is why `i32` is used.
2785        ///
2786        /// ```
2787        /// #![feature(bigint_helper_methods)]
2788        /// assert_eq!(5i32.carrying_mul_add(-2, 0, 0), (4294967286, -1));
2789        /// assert_eq!(5i32.carrying_mul_add(-2, 10, 10), (10, 0));
2790        /// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 0, 0), (2884901888, -3));
2791        /// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 10, 10), (2884901908, -3));
2792        #[doc = concat!("assert_eq!(",
2793            stringify!($SelfT), "::MAX.carrying_mul_add(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
2794            "(", stringify!($UnsignedT), "::MAX, ", stringify!($SelfT), "::MAX / 2));"
2795        )]
2796        /// ```
2797        #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2798        #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2799        #[must_use = "this returns the result of the operation, \
2800                      without modifying the original"]
2801        #[inline]
2802        pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self) -> ($UnsignedT, Self) {
2803            intrinsics::carrying_mul_add(self, rhs, carry, add)
2804        }
2805
2806        /// Calculates the divisor when `self` is divided by `rhs`.
2807        ///
2808        /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
2809        /// occur. If an overflow would occur then self is returned.
2810        ///
2811        /// # Panics
2812        ///
2813        /// This function will panic if `rhs` is zero.
2814        ///
2815        /// # Examples
2816        ///
2817        /// ```
2818        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
2819        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT), "::MIN, true));")]
2820        /// ```
2821        #[inline]
2822        #[stable(feature = "wrapping", since = "1.7.0")]
2823        #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
2824        #[must_use = "this returns the result of the operation, \
2825                      without modifying the original"]
2826        pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2827            // Using `&` helps LLVM see that it is the same check made in division.
2828            if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
2829                (self, true)
2830            } else {
2831                (self / rhs, false)
2832            }
2833        }
2834
2835        /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
2836        ///
2837        /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
2838        /// occur. If an overflow would occur then `self` is returned.
2839        ///
2840        /// # Panics
2841        ///
2842        /// This function will panic if `rhs` is zero.
2843        ///
2844        /// # Examples
2845        ///
2846        /// ```
2847        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
2848        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT), "::MIN, true));")]
2849        /// ```
2850        #[inline]
2851        #[stable(feature = "euclidean_division", since = "1.38.0")]
2852        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2853        #[must_use = "this returns the result of the operation, \
2854                      without modifying the original"]
2855        pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
2856            // Using `&` helps LLVM see that it is the same check made in division.
2857            if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
2858                (self, true)
2859            } else {
2860                (self.div_euclid(rhs), false)
2861            }
2862        }
2863
2864        /// Calculates the remainder when `self` is divided by `rhs`.
2865        ///
2866        /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
2867        /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
2868        ///
2869        /// # Panics
2870        ///
2871        /// This function will panic if `rhs` is zero.
2872        ///
2873        /// # Examples
2874        ///
2875        /// ```
2876        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
2877        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));")]
2878        /// ```
2879        #[inline]
2880        #[stable(feature = "wrapping", since = "1.7.0")]
2881        #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
2882        #[must_use = "this returns the result of the operation, \
2883                      without modifying the original"]
2884        pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2885            if intrinsics::unlikely(rhs == -1) {
2886                (0, self == Self::MIN)
2887            } else {
2888                (self % rhs, false)
2889            }
2890        }
2891
2892
2893        /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
2894        ///
2895        /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
2896        /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
2897        ///
2898        /// # Panics
2899        ///
2900        /// This function will panic if `rhs` is zero.
2901        ///
2902        /// # Examples
2903        ///
2904        /// ```
2905        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
2906        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));")]
2907        /// ```
2908        #[stable(feature = "euclidean_division", since = "1.38.0")]
2909        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2910        #[must_use = "this returns the result of the operation, \
2911                      without modifying the original"]
2912        #[inline]
2913        #[track_caller]
2914        pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
2915            if intrinsics::unlikely(rhs == -1) {
2916                (0, self == Self::MIN)
2917            } else {
2918                (self.rem_euclid(rhs), false)
2919            }
2920        }
2921
2922
2923        /// Negates self, overflowing if this is equal to the minimum value.
2924        ///
2925        /// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
2926        /// happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
2927        /// minimum value will be returned again and `true` will be returned for an overflow happening.
2928        ///
2929        /// # Examples
2930        ///
2931        /// ```
2932        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));")]
2933        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT), "::MIN, true));")]
2934        /// ```
2935        #[inline]
2936        #[stable(feature = "wrapping", since = "1.7.0")]
2937        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2938        #[must_use = "this returns the result of the operation, \
2939                      without modifying the original"]
2940        #[allow(unused_attributes)]
2941        pub const fn overflowing_neg(self) -> (Self, bool) {
2942            if intrinsics::unlikely(self == Self::MIN) {
2943                (Self::MIN, true)
2944            } else {
2945                (-self, false)
2946            }
2947        }
2948
2949        /// Shifts self left by `rhs` bits.
2950        ///
2951        /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
2952        /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
2953        /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
2954        ///
2955        /// # Examples
2956        ///
2957        /// ```
2958        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));")]
2959        /// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
2960        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shl(", stringify!($BITS_MINUS_ONE), "), (0, false));")]
2961        /// ```
2962        #[stable(feature = "wrapping", since = "1.7.0")]
2963        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2964        #[must_use = "this returns the result of the operation, \
2965                      without modifying the original"]
2966        #[inline]
2967        pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2968            (self.wrapping_shl(rhs), rhs >= Self::BITS)
2969        }
2970
2971        /// Shifts self right by `rhs` bits.
2972        ///
2973        /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
2974        /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
2975        /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
2976        ///
2977        /// # Examples
2978        ///
2979        /// ```
2980        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
2981        /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
2982        /// ```
2983        #[stable(feature = "wrapping", since = "1.7.0")]
2984        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2985        #[must_use = "this returns the result of the operation, \
2986                      without modifying the original"]
2987        #[inline]
2988        pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2989            (self.wrapping_shr(rhs), rhs >= Self::BITS)
2990        }
2991
2992        /// Computes the absolute value of `self`.
2993        ///
2994        /// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
2995        /// happened. If self is the minimum value
2996        #[doc = concat!("(e.g., ", stringify!($SelfT), "::MIN for values of type ", stringify!($SelfT), "),")]
2997        /// then the minimum value will be returned again and true will be returned
2998        /// for an overflow happening.
2999        ///
3000        /// # Examples
3001        ///
3002        /// ```
3003        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));")]
3004        #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));")]
3005        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT), "::MIN, true));")]
3006        /// ```
3007        #[stable(feature = "no_panic_abs", since = "1.13.0")]
3008        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
3009        #[must_use = "this returns the result of the operation, \
3010                      without modifying the original"]
3011        #[inline]
3012        pub const fn overflowing_abs(self) -> (Self, bool) {
3013            (self.wrapping_abs(), self == Self::MIN)
3014        }
3015
3016        /// Raises self to the power of `exp`, using exponentiation by squaring.
3017        ///
3018        /// Returns a tuple of the exponentiation along with a bool indicating
3019        /// whether an overflow happened.
3020        ///
3021        /// # Examples
3022        ///
3023        /// ```
3024        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));")]
3025        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".overflowing_pow(0), (1, false));")]
3026        /// assert_eq!(3i8.overflowing_pow(5), (-13, true));
3027        /// ```
3028        #[stable(feature = "no_panic_pow", since = "1.34.0")]
3029        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3030        #[must_use = "this returns the result of the operation, \
3031                      without modifying the original"]
3032        #[inline]
3033        pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3034            if exp == 0 {
3035                return (1,false);
3036            }
3037            let mut base = self;
3038            let mut acc: Self = 1;
3039            let mut overflown = false;
3040            // Scratch space for storing results of overflowing_mul.
3041            let mut r;
3042
3043            loop {
3044                if (exp & 1) == 1 {
3045                    r = acc.overflowing_mul(base);
3046                    // since exp!=0, finally the exp must be 1.
3047                    if exp == 1 {
3048                        r.1 |= overflown;
3049                        return r;
3050                    }
3051                    acc = r.0;
3052                    overflown |= r.1;
3053                }
3054                exp /= 2;
3055                r = base.overflowing_mul(base);
3056                base = r.0;
3057                overflown |= r.1;
3058            }
3059        }
3060
3061        /// Raises self to the power of `exp`, using exponentiation by squaring.
3062        ///
3063        /// # Examples
3064        ///
3065        /// ```
3066        #[doc = concat!("let x: ", stringify!($SelfT), " = 2; // or any other integer type")]
3067        ///
3068        /// assert_eq!(x.pow(5), 32);
3069        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".pow(0), 1);")]
3070        /// ```
3071        #[stable(feature = "rust1", since = "1.0.0")]
3072        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3073        #[must_use = "this returns the result of the operation, \
3074                      without modifying the original"]
3075        #[inline]
3076        #[rustc_inherit_overflow_checks]
3077        pub const fn pow(self, mut exp: u32) -> Self {
3078            if exp == 0 {
3079                return 1;
3080            }
3081            let mut base = self;
3082            let mut acc = 1;
3083
3084            if intrinsics::is_val_statically_known(exp) {
3085                while exp > 1 {
3086                    if (exp & 1) == 1 {
3087                        acc = acc * base;
3088                    }
3089                    exp /= 2;
3090                    base = base * base;
3091                }
3092
3093                // since exp!=0, finally the exp must be 1.
3094                // Deal with the final bit of the exponent separately, since
3095                // squaring the base afterwards is not necessary and may cause a
3096                // needless overflow.
3097                acc * base
3098            } else {
3099                // This is faster than the above when the exponent is not known
3100                // at compile time. We can't use the same code for the constant
3101                // exponent case because LLVM is currently unable to unroll
3102                // this loop.
3103                loop {
3104                    if (exp & 1) == 1 {
3105                        acc = acc * base;
3106                        // since exp!=0, finally the exp must be 1.
3107                        if exp == 1 {
3108                            return acc;
3109                        }
3110                    }
3111                    exp /= 2;
3112                    base = base * base;
3113                }
3114            }
3115        }
3116
3117        /// Returns the square root of the number, rounded down.
3118        ///
3119        /// # Panics
3120        ///
3121        /// This function will panic if `self` is negative.
3122        ///
3123        /// # Examples
3124        ///
3125        /// ```
3126        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".isqrt(), 3);")]
3127        /// ```
3128        #[stable(feature = "isqrt", since = "1.84.0")]
3129        #[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
3130        #[must_use = "this returns the result of the operation, \
3131                      without modifying the original"]
3132        #[inline]
3133        #[track_caller]
3134        pub const fn isqrt(self) -> Self {
3135            match self.checked_isqrt() {
3136                Some(sqrt) => sqrt,
3137                None => crate::num::int_sqrt::panic_for_negative_argument(),
3138            }
3139        }
3140
3141        /// Calculates the quotient of Euclidean division of `self` by `rhs`.
3142        ///
3143        /// This computes the integer `q` such that `self = q * rhs + r`, with
3144        /// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
3145        ///
3146        /// In other words, the result is `self / rhs` rounded to the integer `q`
3147        /// such that `self >= q * rhs`.
3148        /// If `self > 0`, this is equal to rounding towards zero (the default in Rust);
3149        /// if `self < 0`, this is equal to rounding away from zero (towards +/- infinity).
3150        /// If `rhs > 0`, this is equal to rounding towards -infinity;
3151        /// if `rhs < 0`, this is equal to rounding towards +infinity.
3152        ///
3153        /// # Panics
3154        ///
3155        /// This function will panic if `rhs` is zero or if `self` is `Self::MIN`
3156        /// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
3157        ///
3158        /// # Examples
3159        ///
3160        /// ```
3161        #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
3162        /// let b = 4;
3163        ///
3164        /// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
3165        /// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
3166        /// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
3167        /// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
3168        /// ```
3169        #[stable(feature = "euclidean_division", since = "1.38.0")]
3170        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3171        #[must_use = "this returns the result of the operation, \
3172                      without modifying the original"]
3173        #[inline]
3174        #[track_caller]
3175        pub const fn div_euclid(self, rhs: Self) -> Self {
3176            let q = self / rhs;
3177            if self % rhs < 0 {
3178                return if rhs > 0 { q - 1 } else { q + 1 }
3179            }
3180            q
3181        }
3182
3183
3184        /// Calculates the least nonnegative remainder of `self` when
3185        /// divided by `rhs`.
3186        ///
3187        /// This is done as if by the Euclidean division algorithm -- given
3188        /// `r = self.rem_euclid(rhs)`, the result satisfies
3189        /// `self = rhs * self.div_euclid(rhs) + r` and `0 <= r < abs(rhs)`.
3190        ///
3191        /// # Panics
3192        ///
3193        /// This function will panic if `rhs` is zero or if `self` is `Self::MIN` and
3194        /// `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
3195        ///
3196        /// # Examples
3197        ///
3198        /// ```
3199        #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
3200        /// let b = 4;
3201        ///
3202        /// assert_eq!(a.rem_euclid(b), 3);
3203        /// assert_eq!((-a).rem_euclid(b), 1);
3204        /// assert_eq!(a.rem_euclid(-b), 3);
3205        /// assert_eq!((-a).rem_euclid(-b), 1);
3206        /// ```
3207        ///
3208        /// This will panic:
3209        /// ```should_panic
3210        #[doc = concat!("let _ = ", stringify!($SelfT), "::MIN.rem_euclid(-1);")]
3211        /// ```
3212        #[doc(alias = "modulo", alias = "mod")]
3213        #[stable(feature = "euclidean_division", since = "1.38.0")]
3214        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3215        #[must_use = "this returns the result of the operation, \
3216                      without modifying the original"]
3217        #[inline]
3218        #[track_caller]
3219        pub const fn rem_euclid(self, rhs: Self) -> Self {
3220            let r = self % rhs;
3221            if r < 0 {
3222                // Semantically equivalent to `if rhs < 0 { r - rhs } else { r + rhs }`.
3223                // If `rhs` is not `Self::MIN`, then `r + abs(rhs)` will not overflow
3224                // and is clearly equivalent, because `r` is negative.
3225                // Otherwise, `rhs` is `Self::MIN`, then we have
3226                // `r.wrapping_add(Self::MIN.wrapping_abs())`, which evaluates
3227                // to `r.wrapping_add(Self::MIN)`, which is equivalent to
3228                // `r - Self::MIN`, which is what we wanted (and will not overflow
3229                // for negative `r`).
3230                r.wrapping_add(rhs.wrapping_abs())
3231            } else {
3232                r
3233            }
3234        }
3235
3236        /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
3237        ///
3238        /// # Panics
3239        ///
3240        /// This function will panic if `rhs` is zero or if `self` is `Self::MIN`
3241        /// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
3242        ///
3243        /// # Examples
3244        ///
3245        /// ```
3246        /// #![feature(int_roundings)]
3247        #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
3248        /// let b = 3;
3249        ///
3250        /// assert_eq!(a.div_floor(b), 2);
3251        /// assert_eq!(a.div_floor(-b), -3);
3252        /// assert_eq!((-a).div_floor(b), -3);
3253        /// assert_eq!((-a).div_floor(-b), 2);
3254        /// ```
3255        #[unstable(feature = "int_roundings", issue = "88581")]
3256        #[must_use = "this returns the result of the operation, \
3257                      without modifying the original"]
3258        #[inline]
3259        #[track_caller]
3260        pub const fn div_floor(self, rhs: Self) -> Self {
3261            let d = self / rhs;
3262            let r = self % rhs;
3263
3264            // If the remainder is non-zero, we need to subtract one if the
3265            // signs of self and rhs differ, as this means we rounded upwards
3266            // instead of downwards. We do this branchlessly by creating a mask
3267            // which is all-ones iff the signs differ, and 0 otherwise. Then by
3268            // adding this mask (which corresponds to the signed value -1), we
3269            // get our correction.
3270            let correction = (self ^ rhs) >> (Self::BITS - 1);
3271            if r != 0 {
3272                d + correction
3273            } else {
3274                d
3275            }
3276        }
3277
3278        /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
3279        ///
3280        /// # Panics
3281        ///
3282        /// This function will panic if `rhs` is zero or if `self` is `Self::MIN`
3283        /// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
3284        ///
3285        /// # Examples
3286        ///
3287        /// ```
3288        /// #![feature(int_roundings)]
3289        #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
3290        /// let b = 3;
3291        ///
3292        /// assert_eq!(a.div_ceil(b), 3);
3293        /// assert_eq!(a.div_ceil(-b), -2);
3294        /// assert_eq!((-a).div_ceil(b), -2);
3295        /// assert_eq!((-a).div_ceil(-b), 3);
3296        /// ```
3297        #[unstable(feature = "int_roundings", issue = "88581")]
3298        #[must_use = "this returns the result of the operation, \
3299                      without modifying the original"]
3300        #[inline]
3301        #[track_caller]
3302        pub const fn div_ceil(self, rhs: Self) -> Self {
3303            let d = self / rhs;
3304            let r = self % rhs;
3305
3306            // When remainder is non-zero we have a.div_ceil(b) == 1 + a.div_floor(b),
3307            // so we can re-use the algorithm from div_floor, just adding 1.
3308            let correction = 1 + ((self ^ rhs) >> (Self::BITS - 1));
3309            if r != 0 {
3310                d + correction
3311            } else {
3312                d
3313            }
3314        }
3315
3316        /// If `rhs` is positive, calculates the smallest value greater than or
3317        /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
3318        /// calculates the largest value less than or equal to `self` that is a
3319        /// multiple of `rhs`.
3320        ///
3321        /// # Panics
3322        ///
3323        /// This function will panic if `rhs` is zero.
3324        ///
3325        /// ## Overflow behavior
3326        ///
3327        /// On overflow, this function will panic if overflow checks are enabled (default in debug
3328        /// mode) and wrap if overflow checks are disabled (default in release mode).
3329        ///
3330        /// # Examples
3331        ///
3332        /// ```
3333        /// #![feature(int_roundings)]
3334        #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
3335        #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
3336        #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
3337        #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
3338        #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
3339        #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
3340        #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(-8), -16);")]
3341        #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(-8), -24);")]
3342        /// ```
3343        #[unstable(feature = "int_roundings", issue = "88581")]
3344        #[must_use = "this returns the result of the operation, \
3345                      without modifying the original"]
3346        #[inline]
3347        #[rustc_inherit_overflow_checks]
3348        pub const fn next_multiple_of(self, rhs: Self) -> Self {
3349            // This would otherwise fail when calculating `r` when self == T::MIN.
3350            if rhs == -1 {
3351                return self;
3352            }
3353
3354            let r = self % rhs;
3355            let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
3356                r + rhs
3357            } else {
3358                r
3359            };
3360
3361            if m == 0 {
3362                self
3363            } else {
3364                self + (rhs - m)
3365            }
3366        }
3367
3368        /// If `rhs` is positive, calculates the smallest value greater than or
3369        /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
3370        /// calculates the largest value less than or equal to `self` that is a
3371        /// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
3372        /// would result in overflow.
3373        ///
3374        /// # Examples
3375        ///
3376        /// ```
3377        /// #![feature(int_roundings)]
3378        #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
3379        #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
3380        #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
3381        #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
3382        #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
3383        #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
3384        #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-16));")]
3385        #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-24));")]
3386        #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
3387        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
3388        /// ```
3389        #[unstable(feature = "int_roundings", issue = "88581")]
3390        #[must_use = "this returns the result of the operation, \
3391                      without modifying the original"]
3392        #[inline]
3393        pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
3394            // This would otherwise fail when calculating `r` when self == T::MIN.
3395            if rhs == -1 {
3396                return Some(self);
3397            }
3398
3399            let r = try_opt!(self.checked_rem(rhs));
3400            let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
3401                // r + rhs cannot overflow because they have opposite signs
3402                r + rhs
3403            } else {
3404                r
3405            };
3406
3407            if m == 0 {
3408                Some(self)
3409            } else {
3410                // rhs - m cannot overflow because m has the same sign as rhs
3411                self.checked_add(rhs - m)
3412            }
3413        }
3414
3415        /// Returns the logarithm of the number with respect to an arbitrary base,
3416        /// rounded down.
3417        ///
3418        /// This method might not be optimized owing to implementation details;
3419        /// `ilog2` can produce results more efficiently for base 2, and `ilog10`
3420        /// can produce results more efficiently for base 10.
3421        ///
3422        /// # Panics
3423        ///
3424        /// This function will panic if `self` is less than or equal to zero,
3425        /// or if `base` is less than 2.
3426        ///
3427        /// # Examples
3428        ///
3429        /// ```
3430        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".ilog(5), 1);")]
3431        /// ```
3432        #[stable(feature = "int_log", since = "1.67.0")]
3433        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
3434        #[must_use = "this returns the result of the operation, \
3435                      without modifying the original"]
3436        #[inline]
3437        #[track_caller]
3438        pub const fn ilog(self, base: Self) -> u32 {
3439            assert!(base >= 2, "base of integer logarithm must be at least 2");
3440            if let Some(log) = self.checked_ilog(base) {
3441                log
3442            } else {
3443                int_log10::panic_for_nonpositive_argument()
3444            }
3445        }
3446
3447        /// Returns the base 2 logarithm of the number, rounded down.
3448        ///
3449        /// # Panics
3450        ///
3451        /// This function will panic if `self` is less than or equal to zero.
3452        ///
3453        /// # Examples
3454        ///
3455        /// ```
3456        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".ilog2(), 1);")]
3457        /// ```
3458        #[stable(feature = "int_log", since = "1.67.0")]
3459        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
3460        #[must_use = "this returns the result of the operation, \
3461                      without modifying the original"]
3462        #[inline]
3463        #[track_caller]
3464        pub const fn ilog2(self) -> u32 {
3465            if let Some(log) = self.checked_ilog2() {
3466                log
3467            } else {
3468                int_log10::panic_for_nonpositive_argument()
3469            }
3470        }
3471
3472        /// Returns the base 10 logarithm of the number, rounded down.
3473        ///
3474        /// # Panics
3475        ///
3476        /// This function will panic if `self` is less than or equal to zero.
3477        ///
3478        /// # Example
3479        ///
3480        /// ```
3481        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".ilog10(), 1);")]
3482        /// ```
3483        #[stable(feature = "int_log", since = "1.67.0")]
3484        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
3485        #[must_use = "this returns the result of the operation, \
3486                      without modifying the original"]
3487        #[inline]
3488        #[track_caller]
3489        pub const fn ilog10(self) -> u32 {
3490            if let Some(log) = self.checked_ilog10() {
3491                log
3492            } else {
3493                int_log10::panic_for_nonpositive_argument()
3494            }
3495        }
3496
3497        /// Returns the logarithm of the number with respect to an arbitrary base,
3498        /// rounded down.
3499        ///
3500        /// Returns `None` if the number is negative or zero, or if the base is not at least 2.
3501        ///
3502        /// This method might not be optimized owing to implementation details;
3503        /// `checked_ilog2` can produce results more efficiently for base 2, and
3504        /// `checked_ilog10` can produce results more efficiently for base 10.
3505        ///
3506        /// # Examples
3507        ///
3508        /// ```
3509        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_ilog(5), Some(1));")]
3510        /// ```
3511        #[stable(feature = "int_log", since = "1.67.0")]
3512        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
3513        #[must_use = "this returns the result of the operation, \
3514                      without modifying the original"]
3515        #[inline]
3516        pub const fn checked_ilog(self, base: Self) -> Option<u32> {
3517            if self <= 0 || base <= 1 {
3518                None
3519            } else {
3520                // Delegate to the unsigned implementation.
3521                // The condition makes sure that both casts are exact.
3522                (self as $UnsignedT).checked_ilog(base as $UnsignedT)
3523            }
3524        }
3525
3526        /// Returns the base 2 logarithm of the number, rounded down.
3527        ///
3528        /// Returns `None` if the number is negative or zero.
3529        ///
3530        /// # Examples
3531        ///
3532        /// ```
3533        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_ilog2(), Some(1));")]
3534        /// ```
3535        #[stable(feature = "int_log", since = "1.67.0")]
3536        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
3537        #[must_use = "this returns the result of the operation, \
3538                      without modifying the original"]
3539        #[inline]
3540        pub const fn checked_ilog2(self) -> Option<u32> {
3541            if self <= 0 {
3542                None
3543            } else {
3544                // SAFETY: We just checked that this number is positive
3545                let log = (Self::BITS - 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 };
3546                Some(log)
3547            }
3548        }
3549
3550        /// Returns the base 10 logarithm of the number, rounded down.
3551        ///
3552        /// Returns `None` if the number is negative or zero.
3553        ///
3554        /// # Example
3555        ///
3556        /// ```
3557        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_ilog10(), Some(1));")]
3558        /// ```
3559        #[stable(feature = "int_log", since = "1.67.0")]
3560        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
3561        #[must_use = "this returns the result of the operation, \
3562                      without modifying the original"]
3563        #[inline]
3564        pub const fn checked_ilog10(self) -> Option<u32> {
3565            int_log10::$ActualT(self as $ActualT)
3566        }
3567
3568        /// Computes the absolute value of `self`.
3569        ///
3570        /// # Overflow behavior
3571        ///
3572        /// The absolute value of
3573        #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
3574        /// cannot be represented as an
3575        #[doc = concat!("`", stringify!($SelfT), "`,")]
3576        /// and attempting to calculate it will cause an overflow. This means
3577        /// that code in debug mode will trigger a panic on this case and
3578        /// optimized code will return
3579        #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
3580        /// without a panic. If you do not want this behavior, consider
3581        /// using [`unsigned_abs`](Self::unsigned_abs) instead.
3582        ///
3583        /// # Examples
3584        ///
3585        /// ```
3586        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".abs(), 10);")]
3587        #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").abs(), 10);")]
3588        /// ```
3589        #[stable(feature = "rust1", since = "1.0.0")]
3590        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
3591        #[allow(unused_attributes)]
3592        #[must_use = "this returns the result of the operation, \
3593                      without modifying the original"]
3594        #[inline]
3595        #[rustc_inherit_overflow_checks]
3596        pub const fn abs(self) -> Self {
3597            // Note that the #[rustc_inherit_overflow_checks] and #[inline]
3598            // above mean that the overflow semantics of the subtraction
3599            // depend on the crate we're being called from.
3600            if self.is_negative() {
3601                -self
3602            } else {
3603                self
3604            }
3605        }
3606
3607        /// Computes the absolute difference between `self` and `other`.
3608        ///
3609        /// This function always returns the correct answer without overflow or
3610        /// panics by returning an unsigned integer.
3611        ///
3612        /// # Examples
3613        ///
3614        /// ```
3615        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($UnsignedT), ");")]
3616        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($UnsignedT), ");")]
3617        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(80), 180", stringify!($UnsignedT), ");")]
3618        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(-120), 20", stringify!($UnsignedT), ");")]
3619        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.abs_diff(", stringify!($SelfT), "::MAX), ", stringify!($UnsignedT), "::MAX);")]
3620        /// ```
3621        #[stable(feature = "int_abs_diff", since = "1.60.0")]
3622        #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
3623        #[must_use = "this returns the result of the operation, \
3624                      without modifying the original"]
3625        #[inline]
3626        pub const fn abs_diff(self, other: Self) -> $UnsignedT {
3627            if self < other {
3628                // Converting a non-negative x from signed to unsigned by using
3629                // `x as U` is left unchanged, but a negative x is converted
3630                // to value x + 2^N. Thus if `s` and `o` are binary variables
3631                // respectively indicating whether `self` and `other` are
3632                // negative, we are computing the mathematical value:
3633                //
3634                //    (other + o*2^N) - (self + s*2^N)    mod  2^N
3635                //    other - self + (o-s)*2^N            mod  2^N
3636                //    other - self                        mod  2^N
3637                //
3638                // Finally, taking the mod 2^N of the mathematical value of
3639                // `other - self` does not change it as it already is
3640                // in the range [0, 2^N).
3641                (other as $UnsignedT).wrapping_sub(self as $UnsignedT)
3642            } else {
3643                (self as $UnsignedT).wrapping_sub(other as $UnsignedT)
3644            }
3645        }
3646
3647        /// Returns a number representing sign of `self`.
3648        ///
3649        ///  - `0` if the number is zero
3650        ///  - `1` if the number is positive
3651        ///  - `-1` if the number is negative
3652        ///
3653        /// # Examples
3654        ///
3655        /// ```
3656        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".signum(), 1);")]
3657        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".signum(), 0);")]
3658        #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").signum(), -1);")]
3659        /// ```
3660        #[stable(feature = "rust1", since = "1.0.0")]
3661        #[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
3662        #[must_use = "this returns the result of the operation, \
3663                      without modifying the original"]
3664        #[inline(always)]
3665        pub const fn signum(self) -> Self {
3666            // Picking the right way to phrase this is complicated
3667            // (<https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign>)
3668            // so delegate it to `Ord` which is already producing -1/0/+1
3669            // exactly like we need and can be the place to deal with the complexity.
3670
3671            crate::intrinsics::three_way_compare(self, 0) as Self
3672        }
3673
3674        /// Returns `true` if `self` is positive and `false` if the number is zero or
3675        /// negative.
3676        ///
3677        /// # Examples
3678        ///
3679        /// ```
3680        #[doc = concat!("assert!(10", stringify!($SelfT), ".is_positive());")]
3681        #[doc = concat!("assert!(!(-10", stringify!($SelfT), ").is_positive());")]
3682        /// ```
3683        #[must_use]
3684        #[stable(feature = "rust1", since = "1.0.0")]
3685        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
3686        #[inline(always)]
3687        pub const fn is_positive(self) -> bool { self > 0 }
3688
3689        /// Returns `true` if `self` is negative and `false` if the number is zero or
3690        /// positive.
3691        ///
3692        /// # Examples
3693        ///
3694        /// ```
3695        #[doc = concat!("assert!((-10", stringify!($SelfT), ").is_negative());")]
3696        #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_negative());")]
3697        /// ```
3698        #[must_use]
3699        #[stable(feature = "rust1", since = "1.0.0")]
3700        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
3701        #[inline(always)]
3702        pub const fn is_negative(self) -> bool { self < 0 }
3703
3704        /// Returns the memory representation of this integer as a byte array in
3705        /// big-endian (network) byte order.
3706        ///
3707        #[doc = $to_xe_bytes_doc]
3708        ///
3709        /// # Examples
3710        ///
3711        /// ```
3712        #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
3713        #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
3714        /// ```
3715        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3716        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3717        #[must_use = "this returns the result of the operation, \
3718                      without modifying the original"]
3719        #[inline]
3720        pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
3721            self.to_be().to_ne_bytes()
3722        }
3723
3724        /// Returns the memory representation of this integer as a byte array in
3725        /// little-endian byte order.
3726        ///
3727        #[doc = $to_xe_bytes_doc]
3728        ///
3729        /// # Examples
3730        ///
3731        /// ```
3732        #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
3733        #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
3734        /// ```
3735        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3736        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3737        #[must_use = "this returns the result of the operation, \
3738                      without modifying the original"]
3739        #[inline]
3740        pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
3741            self.to_le().to_ne_bytes()
3742        }
3743
3744        /// Returns the memory representation of this integer as a byte array in
3745        /// native byte order.
3746        ///
3747        /// As the target platform's native endianness is used, portable code
3748        /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3749        /// instead.
3750        ///
3751        #[doc = $to_xe_bytes_doc]
3752        ///
3753        /// [`to_be_bytes`]: Self::to_be_bytes
3754        /// [`to_le_bytes`]: Self::to_le_bytes
3755        ///
3756        /// # Examples
3757        ///
3758        /// ```
3759        #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
3760        /// assert_eq!(
3761        ///     bytes,
3762        ///     if cfg!(target_endian = "big") {
3763        #[doc = concat!("        ", $be_bytes)]
3764        ///     } else {
3765        #[doc = concat!("        ", $le_bytes)]
3766        ///     }
3767        /// );
3768        /// ```
3769        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3770        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3771        #[allow(unnecessary_transmutes)]
3772        // SAFETY: const sound because integers are plain old datatypes so we can always
3773        // transmute them to arrays of bytes
3774        #[must_use = "this returns the result of the operation, \
3775                      without modifying the original"]
3776        #[inline]
3777        pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
3778            // SAFETY: integers are plain old datatypes so we can always transmute them to
3779            // arrays of bytes
3780            unsafe { mem::transmute(self) }
3781        }
3782
3783        /// Creates an integer value from its representation as a byte array in
3784        /// big endian.
3785        ///
3786        #[doc = $from_xe_bytes_doc]
3787        ///
3788        /// # Examples
3789        ///
3790        /// ```
3791        #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
3792        #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3793        /// ```
3794        ///
3795        /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3796        ///
3797        /// ```
3798        #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3799        #[doc = concat!("    let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
3800        ///     *input = rest;
3801        #[doc = concat!("    ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
3802        /// }
3803        /// ```
3804        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3805        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3806        #[must_use]
3807        #[inline]
3808        pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
3809            Self::from_be(Self::from_ne_bytes(bytes))
3810        }
3811
3812        /// Creates an integer value from its representation as a byte array in
3813        /// little endian.
3814        ///
3815        #[doc = $from_xe_bytes_doc]
3816        ///
3817        /// # Examples
3818        ///
3819        /// ```
3820        #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
3821        #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3822        /// ```
3823        ///
3824        /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3825        ///
3826        /// ```
3827        #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3828        #[doc = concat!("    let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
3829        ///     *input = rest;
3830        #[doc = concat!("    ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
3831        /// }
3832        /// ```
3833        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3834        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3835        #[must_use]
3836        #[inline]
3837        pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
3838            Self::from_le(Self::from_ne_bytes(bytes))
3839        }
3840
3841        /// Creates an integer value from its memory representation as a byte
3842        /// array in native endianness.
3843        ///
3844        /// As the target platform's native endianness is used, portable code
3845        /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3846        /// appropriate instead.
3847        ///
3848        /// [`from_be_bytes`]: Self::from_be_bytes
3849        /// [`from_le_bytes`]: Self::from_le_bytes
3850        ///
3851        #[doc = $from_xe_bytes_doc]
3852        ///
3853        /// # Examples
3854        ///
3855        /// ```
3856        #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
3857        #[doc = concat!("    ", $be_bytes)]
3858        /// } else {
3859        #[doc = concat!("    ", $le_bytes)]
3860        /// });
3861        #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3862        /// ```
3863        ///
3864        /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3865        ///
3866        /// ```
3867        #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3868        #[doc = concat!("    let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
3869        ///     *input = rest;
3870        #[doc = concat!("    ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
3871        /// }
3872        /// ```
3873        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3874        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3875        #[allow(unnecessary_transmutes)]
3876        #[must_use]
3877        // SAFETY: const sound because integers are plain old datatypes so we can always
3878        // transmute to them
3879        #[inline]
3880        pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
3881            // SAFETY: integers are plain old datatypes so we can always transmute to them
3882            unsafe { mem::transmute(bytes) }
3883        }
3884
3885        /// New code should prefer to use
3886        #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
3887        ///
3888        /// Returns the smallest value that can be represented by this integer type.
3889        #[stable(feature = "rust1", since = "1.0.0")]
3890        #[inline(always)]
3891        #[rustc_promotable]
3892        #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
3893        #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
3894        #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_min_value")]
3895        pub const fn min_value() -> Self {
3896            Self::MIN
3897        }
3898
3899        /// New code should prefer to use
3900        #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
3901        ///
3902        /// Returns the largest value that can be represented by this integer type.
3903        #[stable(feature = "rust1", since = "1.0.0")]
3904        #[inline(always)]
3905        #[rustc_promotable]
3906        #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
3907        #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
3908        #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_max_value")]
3909        pub const fn max_value() -> Self {
3910            Self::MAX
3911        }
3912
3913        /// Clamps this number to a symmetric range centred around zero.
3914        ///
3915        /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
3916        ///
3917        /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
3918        /// explicit about the intent.
3919        ///
3920        /// # Examples
3921        ///
3922        /// ```
3923        /// #![feature(clamp_magnitude)]
3924        #[doc = concat!("assert_eq!(120", stringify!($SelfT), ".clamp_magnitude(100), 100);")]
3925        #[doc = concat!("assert_eq!(-120", stringify!($SelfT), ".clamp_magnitude(100), -100);")]
3926        #[doc = concat!("assert_eq!(80", stringify!($SelfT), ".clamp_magnitude(100), 80);")]
3927        #[doc = concat!("assert_eq!(-80", stringify!($SelfT), ".clamp_magnitude(100), -80);")]
3928        /// ```
3929        #[must_use = "this returns the clamped value and does not modify the original"]
3930        #[unstable(feature = "clamp_magnitude", issue = "148519")]
3931        #[inline]
3932        pub fn clamp_magnitude(self, limit: $UnsignedT) -> Self {
3933            if let Ok(limit) = core::convert::TryInto::<$SelfT>::try_into(limit) {
3934                self.clamp(-limit, limit)
3935            } else {
3936                self
3937            }
3938        }
3939    }
3940}