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