Skip to main content

core/num/
int_macros.rs

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