core/num/
int_macros.rs

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