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