Skip to main content

core/num/
int_macros.rs

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