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