Skip to main content

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