core/num/
int_macros.rs

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