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