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