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