core/num/
int_macros.rs

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