Skip to main content

core/num/
int_macros.rs

1macro_rules! int_impl {
2    (
3        Self = $SelfT:ty,
4        ActualT = $ActualT:ident,
5        UnsignedT = $UnsignedT:ty,
6
7        // These are all for use *only* in doc comments.
8        // As such, they're all passed as literals -- passing them as a string
9        // literal is fine if they need to be multiple code tokens.
10        // In non-comments, use the associated constants rather than these.
11        BITS = $BITS:literal,
12        BITS_MINUS_ONE = $BITS_MINUS_ONE:literal,
13        Min = $Min:literal,
14        Max = $Max:literal,
15        rot = $rot:literal,
16        rot_op = $rot_op:literal,
17        rot_result = $rot_result:literal,
18        swap_op = $swap_op:literal,
19        swapped = $swapped:literal,
20        reversed = $reversed:literal,
21        le_bytes = $le_bytes:literal,
22        be_bytes = $be_bytes:literal,
23        to_xe_bytes_doc = $to_xe_bytes_doc:expr,
24        from_xe_bytes_doc = $from_xe_bytes_doc:expr,
25        bound_condition = $bound_condition:literal,
26    ) => {
27        /// The smallest value that can be represented by this integer type
28        #[doc = concat!("(&minus;2<sup>", $BITS_MINUS_ONE, "</sup>", $bound_condition, ").")]
29        ///
30        /// # Examples
31        ///
32        /// ```
33        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, ", stringify!($Min), ");")]
34        /// ```
35        #[stable(feature = "assoc_int_consts", since = "1.43.0")]
36        pub const MIN: Self = !Self::MAX;
37
38        /// The largest value that can be represented by this integer type
39        #[doc = concat!("(2<sup>", $BITS_MINUS_ONE, "</sup> &minus; 1", $bound_condition, ").")]
40        ///
41        /// # Examples
42        ///
43        /// ```
44        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");")]
45        /// ```
46        #[stable(feature = "assoc_int_consts", since = "1.43.0")]
47        pub const MAX: Self = (<$UnsignedT>::MAX >> 1) as Self;
48
49        /// The size of this integer type in bits.
50        ///
51        /// # Examples
52        ///
53        /// ```
54        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
55        /// ```
56        #[stable(feature = "int_bits_const", since = "1.53.0")]
57        pub const BITS: u32 = <$UnsignedT>::BITS;
58
59        /// Returns the number of ones in the binary representation of `self`.
60        ///
61        /// # Examples
62        ///
63        /// ```
64        #[doc = concat!("let n = 0b100_0000", stringify!($SelfT), ";")]
65        ///
66        /// assert_eq!(n.count_ones(), 1);
67        /// ```
68        ///
69        #[stable(feature = "rust1", since = "1.0.0")]
70        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
71        #[doc(alias = "popcount")]
72        #[doc(alias = "popcnt")]
73        #[must_use = "this returns the result of the operation, \
74                      without modifying the original"]
75        #[inline(always)]
76        pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
77
78        /// Returns the number of zeros in the binary representation of `self`.
79        ///
80        /// # Examples
81        ///
82        /// ```
83        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 1);")]
84        /// ```
85        #[stable(feature = "rust1", since = "1.0.0")]
86        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
87        #[must_use = "this returns the result of the operation, \
88                      without modifying the original"]
89        #[inline(always)]
90        pub const fn count_zeros(self) -> u32 {
91            (!self).count_ones()
92        }
93
94        /// Returns the number of leading zeros in the binary representation of `self`.
95        ///
96        /// Depending on what you're doing with the value, you might also be interested in the
97        /// [`ilog2`] function which returns a consistent number, even if the type widens.
98        ///
99        /// # Examples
100        ///
101        /// ```
102        #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
103        ///
104        /// assert_eq!(n.leading_zeros(), 0);
105        /// ```
106        #[doc = concat!("[`ilog2`]: ", stringify!($SelfT), "::ilog2")]
107        #[stable(feature = "rust1", since = "1.0.0")]
108        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
109        #[must_use = "this returns the result of the operation, \
110                      without modifying the original"]
111        #[inline(always)]
112        pub const fn leading_zeros(self) -> u32 {
113            (self as $UnsignedT).leading_zeros()
114        }
115
116        /// Returns the number of trailing zeros in the binary representation of `self`.
117        ///
118        /// # Examples
119        ///
120        /// ```
121        #[doc = concat!("let n = -4", stringify!($SelfT), ";")]
122        ///
123        /// assert_eq!(n.trailing_zeros(), 2);
124        /// ```
125        #[stable(feature = "rust1", since = "1.0.0")]
126        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
127        #[must_use = "this returns the result of the operation, \
128                      without modifying the original"]
129        #[inline(always)]
130        pub const fn trailing_zeros(self) -> u32 {
131            (self as $UnsignedT).trailing_zeros()
132        }
133
134        /// Returns the number of leading ones in the binary representation of `self`.
135        ///
136        /// # Examples
137        ///
138        /// ```
139        #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
140        ///
141        #[doc = concat!("assert_eq!(n.leading_ones(), ", stringify!($BITS), ");")]
142        /// ```
143        #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
144        #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
145        #[must_use = "this returns the result of the operation, \
146                      without modifying the original"]
147        #[inline(always)]
148        pub const fn leading_ones(self) -> u32 {
149            (self as $UnsignedT).leading_ones()
150        }
151
152        /// Returns the number of trailing ones in the binary representation of `self`.
153        ///
154        /// # Examples
155        ///
156        /// ```
157        #[doc = concat!("let n = 3", stringify!($SelfT), ";")]
158        ///
159        /// assert_eq!(n.trailing_ones(), 2);
160        /// ```
161        #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
162        #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
163        #[must_use = "this returns the result of the operation, \
164                      without modifying the original"]
165        #[inline(always)]
166        pub const fn trailing_ones(self) -> u32 {
167            (self as $UnsignedT).trailing_ones()
168        }
169
170        /// Returns `self` with only the most significant bit set, or `0` if
171        /// the input is `0`.
172        ///
173        /// # Examples
174        ///
175        /// ```
176        #[doc = concat!("let n: ", stringify!($SelfT), " = 0b_01100100;")]
177        ///
178        /// assert_eq!(n.isolate_highest_one(), 0b_01000000);
179        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".isolate_highest_one(), 0);")]
180        /// ```
181        #[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
182        #[rustc_const_stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
183        #[must_use = "this returns the result of the operation, \
184                      without modifying the original"]
185        #[inline(always)]
186        pub const fn isolate_highest_one(self) -> Self {
187            self & (((1 as $SelfT) << (<$SelfT>::BITS - 1)).wrapping_shr(self.leading_zeros()))
188        }
189
190        /// Returns `self` with only the least significant bit set, or `0` if
191        /// the input is `0`.
192        ///
193        /// # Examples
194        ///
195        /// ```
196        #[doc = concat!("let n: ", stringify!($SelfT), " = 0b_01100100;")]
197        ///
198        /// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
199        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".isolate_lowest_one(), 0);")]
200        /// ```
201        #[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
202        #[rustc_const_stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
203        #[must_use = "this returns the result of the operation, \
204                      without modifying the original"]
205        #[inline(always)]
206        pub const fn isolate_lowest_one(self) -> Self {
207            self & self.wrapping_neg()
208        }
209
210        /// Returns the index of the highest bit set to one in `self`, or `None`
211        /// if `self` is `0`.
212        ///
213        /// # 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 = "1.97.0")]
222        #[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
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 = "1.97.0")]
242        #[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
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            let mut base = self;
1833            let mut acc: Self = 1;
1834
1835            if intrinsics::is_val_statically_known(base) && base.unsigned_abs().is_power_of_two() {
1836                let k = base.unsigned_abs().ilog2();
1837                let shift = try_opt!(k.checked_mul(exp));
1838                return if base < 0 && (exp % 2) == 1 {
1839                    (-1 as Self).shl_exact(shift)
1840                } else {
1841                    (1 as Self).shl_exact(shift)
1842                }
1843            }
1844
1845            if exp == 0 {
1846                return Some(1);
1847            }
1848
1849            if intrinsics::is_val_statically_known(exp) {
1850                while exp > 1 {
1851                    if (exp & 1) == 1 {
1852                        acc = try_opt!(acc.checked_mul(base));
1853                    }
1854                    exp /= 2;
1855                    base = try_opt!(base.checked_mul(base));
1856                }
1857
1858                // since exp!=0, finally the exp must be 1.
1859                // Deal with the final bit of the exponent separately, since
1860                // squaring the base afterwards is not necessary and may cause a
1861                // needless overflow.
1862                return acc.checked_mul(base);
1863            }
1864
1865            loop {
1866                if (exp & 1) == 1 {
1867                    acc = try_opt!(acc.checked_mul(base));
1868                    // since exp!=0, finally the exp must be 1.
1869                    if exp == 1 {
1870                        return Some(acc);
1871                    }
1872                }
1873                exp /= 2;
1874                base = try_opt!(base.checked_mul(base));
1875            }
1876        }
1877
1878        /// Strict exponentiation. Computes `self.pow(exp)`, panicking if
1879        /// overflow occurred.
1880        ///
1881        /// # Panics
1882        ///
1883        /// ## Overflow behavior
1884        ///
1885        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1886        ///
1887        /// # Examples
1888        ///
1889        /// ```
1890        #[doc = concat!("assert_eq!(8", stringify!($SelfT), ".strict_pow(2), 64);")]
1891        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".strict_pow(0), 1);")]
1892        /// ```
1893        ///
1894        /// The following panics because of overflow:
1895        ///
1896        /// ```should_panic
1897        #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_pow(2);")]
1898        /// ```
1899        #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1900        #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1901        #[must_use = "this returns the result of the operation, \
1902                      without modifying the original"]
1903        #[inline]
1904        #[track_caller]
1905        pub const fn strict_pow(self, exp: u32) -> Self {
1906            match self.checked_pow(exp) {
1907                Some(x) => x,
1908                None => imp::overflow_panic::pow(),
1909            }
1910        }
1911
1912        /// Returns the integer square root of the number, rounded down.
1913        ///
1914        /// This function returns the **principal (non-negative) square root**.
1915        /// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
1916        /// this function always returns the non-negative value.
1917        ///
1918        /// Returns `None` if `self` is negative.
1919        ///
1920        /// # Examples
1921        ///
1922        /// ```
1923        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_isqrt(), Some(3));")]
1924        /// ```
1925        #[stable(feature = "isqrt", since = "1.84.0")]
1926        #[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
1927        #[must_use = "this returns the result of the operation, \
1928                      without modifying the original"]
1929        #[inline]
1930        pub const fn checked_isqrt(self) -> Option<Self> {
1931            if self < 0 {
1932                None
1933            } else {
1934                // The upper bound of `$UnsignedT::MAX.isqrt()` told to the compiler
1935                // in the unsigned function also tells it that `result >= 0`
1936                let result = self.cast_unsigned().isqrt().cast_signed();
1937
1938                // Inform the optimizer what the range of outputs is. If
1939                // testing `core` crashes with no panic message and a
1940                // `num::int_sqrt::i*` test failed, it's because your edits
1941                // caused these assertions to become false.
1942                //
1943                // SAFETY: Integer square root is a monotonically nondecreasing
1944                // function, which means that increasing the input will never
1945                // cause the output to decrease. Thus, since the input for
1946                // nonnegative signed integers is bounded by
1947                // `[0, <$ActualT>::MAX]`, sqrt(n) will be bounded by
1948                // `[sqrt(0), sqrt(<$ActualT>::MAX)]`.
1949                unsafe {
1950                    const MAX_RESULT: $SelfT = <$SelfT>::MAX.cast_unsigned().isqrt().cast_signed();
1951                    crate::hint::assert_unchecked(result <= MAX_RESULT);
1952                }
1953                Some(result)
1954            }
1955        }
1956
1957        /// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
1958        /// bounds instead of overflowing.
1959        ///
1960        /// # Examples
1961        ///
1962        /// ```
1963        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
1964        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT), "::MAX);")]
1965        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT), "::MIN);")]
1966        /// ```
1967
1968        #[stable(feature = "rust1", since = "1.0.0")]
1969        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1970        #[must_use = "this returns the result of the operation, \
1971                      without modifying the original"]
1972        #[inline(always)]
1973        pub const fn saturating_add(self, rhs: Self) -> Self {
1974            intrinsics::saturating_add(self, rhs)
1975        }
1976
1977        /// Saturating addition with an unsigned integer. Computes `self + rhs`,
1978        /// saturating at the numeric bounds instead of overflowing.
1979        ///
1980        /// # Examples
1981        ///
1982        /// ```
1983        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_unsigned(2), 3);")]
1984        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add_unsigned(100), ", stringify!($SelfT), "::MAX);")]
1985        /// ```
1986        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
1987        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
1988        #[must_use = "this returns the result of the operation, \
1989                      without modifying the original"]
1990        #[inline]
1991        pub const fn saturating_add_unsigned(self, rhs: $UnsignedT) -> Self {
1992            // Overflow can only happen at the upper bound
1993            // We cannot use `unwrap_or` here because it is not `const`
1994            match self.checked_add_unsigned(rhs) {
1995                Some(x) => x,
1996                None => Self::MAX,
1997            }
1998        }
1999
2000        /// Saturating integer subtraction. Computes `self - rhs`, saturating at the
2001        /// numeric bounds instead of overflowing.
2002        ///
2003        /// # Examples
2004        ///
2005        /// ```
2006        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);")]
2007        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT), "::MIN);")]
2008        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT), "::MAX);")]
2009        /// ```
2010        #[stable(feature = "rust1", since = "1.0.0")]
2011        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
2012        #[must_use = "this returns the result of the operation, \
2013                      without modifying the original"]
2014        #[inline(always)]
2015        pub const fn saturating_sub(self, rhs: Self) -> Self {
2016            intrinsics::saturating_sub(self, rhs)
2017        }
2018
2019        /// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
2020        /// saturating at the numeric bounds instead of overflowing.
2021        ///
2022        /// # Examples
2023        ///
2024        /// ```
2025        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub_unsigned(127), -27);")]
2026        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub_unsigned(100), ", stringify!($SelfT), "::MIN);")]
2027        /// ```
2028        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2029        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2030        #[must_use = "this returns the result of the operation, \
2031                      without modifying the original"]
2032        #[inline]
2033        pub const fn saturating_sub_unsigned(self, rhs: $UnsignedT) -> Self {
2034            // Overflow can only happen at the lower bound
2035            // We cannot use `unwrap_or` here because it is not `const`
2036            match self.checked_sub_unsigned(rhs) {
2037                Some(x) => x,
2038                None => Self::MIN,
2039            }
2040        }
2041
2042        /// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
2043        /// instead of overflowing.
2044        ///
2045        /// # Examples
2046        ///
2047        /// ```
2048        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);")]
2049        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);")]
2050        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT), "::MAX);")]
2051        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT), "::MIN + 1);")]
2052        /// ```
2053
2054        #[stable(feature = "saturating_neg", since = "1.45.0")]
2055        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
2056        #[must_use = "this returns the result of the operation, \
2057                      without modifying the original"]
2058        #[inline(always)]
2059        pub const fn saturating_neg(self) -> Self {
2060            intrinsics::saturating_sub(0, self)
2061        }
2062
2063        /// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
2064        /// MIN` instead of overflowing.
2065        ///
2066        /// # Examples
2067        ///
2068        /// ```
2069        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);")]
2070        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);")]
2071        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT), "::MAX);")]
2072        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT), "::MAX);")]
2073        /// ```
2074
2075        #[stable(feature = "saturating_neg", since = "1.45.0")]
2076        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
2077        #[must_use = "this returns the result of the operation, \
2078                      without modifying the original"]
2079        #[inline]
2080        pub const fn saturating_abs(self) -> Self {
2081            if self.is_negative() {
2082                self.saturating_neg()
2083            } else {
2084                self
2085            }
2086        }
2087
2088        /// Saturating integer multiplication. Computes `self * rhs`, saturating at the
2089        /// numeric bounds instead of overflowing.
2090        ///
2091        /// # Examples
2092        ///
2093        /// ```
2094        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);")]
2095        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);")]
2096        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);")]
2097        /// ```
2098        #[stable(feature = "wrapping", since = "1.7.0")]
2099        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
2100        #[must_use = "this returns the result of the operation, \
2101                      without modifying the original"]
2102        #[inline]
2103        pub const fn saturating_mul(self, rhs: Self) -> Self {
2104            match self.checked_mul(rhs) {
2105                Some(x) => x,
2106                None => if (self < 0) == (rhs < 0) {
2107                    Self::MAX
2108                } else {
2109                    Self::MIN
2110                }
2111            }
2112        }
2113
2114        /// Saturating integer division. Computes `self / rhs`, saturating at the
2115        /// numeric bounds instead of overflowing.
2116        ///
2117        /// # Panics
2118        ///
2119        /// This function will panic if `rhs` is zero.
2120        ///
2121        /// # Examples
2122        ///
2123        /// ```
2124        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
2125        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_div(-1), ", stringify!($SelfT), "::MIN + 1);")]
2126        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_div(-1), ", stringify!($SelfT), "::MAX);")]
2127        ///
2128        /// ```
2129        #[stable(feature = "saturating_div", since = "1.58.0")]
2130        #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
2131        #[must_use = "this returns the result of the operation, \
2132                      without modifying the original"]
2133        #[inline]
2134        pub const fn saturating_div(self, rhs: Self) -> Self {
2135            match self.overflowing_div(rhs) {
2136                (result, false) => result,
2137                (_result, true) => Self::MAX, // MIN / -1 is the only possible saturating overflow
2138            }
2139        }
2140
2141        /// Saturating integer exponentiation. Computes `self.pow(exp)`,
2142        /// saturating at the numeric bounds instead of overflowing.
2143        ///
2144        /// # Examples
2145        ///
2146        /// ```
2147        #[doc = concat!("assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);")]
2148        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".saturating_pow(0), 1);")]
2149        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
2150        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);")]
2151        /// ```
2152        #[stable(feature = "no_panic_pow", since = "1.34.0")]
2153        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2154        #[must_use = "this returns the result of the operation, \
2155                      without modifying the original"]
2156        #[inline]
2157        pub const fn saturating_pow(self, exp: u32) -> Self {
2158            match self.checked_pow(exp) {
2159                Some(x) => x,
2160                None if self < 0 && exp % 2 == 1 => Self::MIN,
2161                None => Self::MAX,
2162            }
2163        }
2164
2165        /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
2166        /// boundary of the type.
2167        ///
2168        /// # Examples
2169        ///
2170        /// ```
2171        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);")]
2172        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT), "::MIN + 1);")]
2173        /// ```
2174        #[stable(feature = "rust1", since = "1.0.0")]
2175        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2176        #[must_use = "this returns the result of the operation, \
2177                      without modifying the original"]
2178        #[inline(always)]
2179        pub const fn wrapping_add(self, rhs: Self) -> Self {
2180            intrinsics::wrapping_add(self, rhs)
2181        }
2182
2183        /// Wrapping (modular) addition with an unsigned integer. Computes
2184        /// `self + rhs`, wrapping around at the boundary of the type.
2185        ///
2186        /// # Examples
2187        ///
2188        /// ```
2189        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add_unsigned(27), 127);")]
2190        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add_unsigned(2), ", stringify!($SelfT), "::MIN + 1);")]
2191        /// ```
2192        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2193        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2194        #[must_use = "this returns the result of the operation, \
2195                      without modifying the original"]
2196        #[inline(always)]
2197        pub const fn wrapping_add_unsigned(self, rhs: $UnsignedT) -> Self {
2198            self.wrapping_add(rhs as Self)
2199        }
2200
2201        /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
2202        /// boundary of the type.
2203        ///
2204        /// # Examples
2205        ///
2206        /// ```
2207        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);")]
2208        #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ", stringify!($SelfT), "::MAX);")]
2209        /// ```
2210        #[stable(feature = "rust1", since = "1.0.0")]
2211        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2212        #[must_use = "this returns the result of the operation, \
2213                      without modifying the original"]
2214        #[inline(always)]
2215        pub const fn wrapping_sub(self, rhs: Self) -> Self {
2216            intrinsics::wrapping_sub(self, rhs)
2217        }
2218
2219        /// Wrapping (modular) subtraction with an unsigned integer. Computes
2220        /// `self - rhs`, wrapping around at the boundary of the type.
2221        ///
2222        /// # Examples
2223        ///
2224        /// ```
2225        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub_unsigned(127), -127);")]
2226        #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub_unsigned(", stringify!($UnsignedT), "::MAX), -1);")]
2227        /// ```
2228        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2229        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2230        #[must_use = "this returns the result of the operation, \
2231                      without modifying the original"]
2232        #[inline(always)]
2233        pub const fn wrapping_sub_unsigned(self, rhs: $UnsignedT) -> Self {
2234            self.wrapping_sub(rhs as Self)
2235        }
2236
2237        /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
2238        /// the boundary of the type.
2239        ///
2240        /// # Examples
2241        ///
2242        /// ```
2243        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);")]
2244        /// assert_eq!(11i8.wrapping_mul(12), -124);
2245        /// ```
2246        #[stable(feature = "rust1", since = "1.0.0")]
2247        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2248        #[must_use = "this returns the result of the operation, \
2249                      without modifying the original"]
2250        #[inline(always)]
2251        pub const fn wrapping_mul(self, rhs: Self) -> Self {
2252            intrinsics::wrapping_mul(self, rhs)
2253        }
2254
2255        /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
2256        /// boundary of the type.
2257        ///
2258        /// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
2259        /// `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
2260        /// that is too large to represent in the type. In such a case, this function returns `MIN` itself.
2261        ///
2262        /// # Panics
2263        ///
2264        /// This function will panic if `rhs` is zero.
2265        ///
2266        /// # Examples
2267        ///
2268        /// ```
2269        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
2270        /// assert_eq!((-128i8).wrapping_div(-1), -128);
2271        /// ```
2272        #[stable(feature = "num_wrapping", since = "1.2.0")]
2273        #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
2274        #[must_use = "this returns the result of the operation, \
2275                      without modifying the original"]
2276        #[inline]
2277        pub const fn wrapping_div(self, rhs: Self) -> Self {
2278            self.overflowing_div(rhs).0
2279        }
2280
2281        /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
2282        /// wrapping around at the boundary of the type.
2283        ///
2284        /// Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
2285        /// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
2286        /// type. In this case, this method returns `MIN` itself.
2287        ///
2288        /// # Panics
2289        ///
2290        /// This function will panic if `rhs` is zero.
2291        ///
2292        /// # Examples
2293        ///
2294        /// ```
2295        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
2296        /// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
2297        /// ```
2298        #[stable(feature = "euclidean_division", since = "1.38.0")]
2299        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2300        #[must_use = "this returns the result of the operation, \
2301                      without modifying the original"]
2302        #[inline]
2303        pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
2304            self.overflowing_div_euclid(rhs).0
2305        }
2306
2307        /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
2308        /// boundary of the type.
2309        ///
2310        /// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
2311        /// invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
2312        /// this function returns `0`.
2313        ///
2314        /// # Panics
2315        ///
2316        /// This function will panic if `rhs` is zero.
2317        ///
2318        /// # Examples
2319        ///
2320        /// ```
2321        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
2322        /// assert_eq!((-128i8).wrapping_rem(-1), 0);
2323        /// ```
2324        #[stable(feature = "num_wrapping", since = "1.2.0")]
2325        #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
2326        #[must_use = "this returns the result of the operation, \
2327                      without modifying the original"]
2328        #[inline]
2329        pub const fn wrapping_rem(self, rhs: Self) -> Self {
2330            self.overflowing_rem(rhs).0
2331        }
2332
2333        /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
2334        /// at the boundary of the type.
2335        ///
2336        /// Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
2337        /// for the type). In this case, this method returns 0.
2338        ///
2339        /// # Panics
2340        ///
2341        /// This function will panic if `rhs` is zero.
2342        ///
2343        /// # Examples
2344        ///
2345        /// ```
2346        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
2347        /// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
2348        /// ```
2349        #[stable(feature = "euclidean_division", since = "1.38.0")]
2350        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2351        #[must_use = "this returns the result of the operation, \
2352                      without modifying the original"]
2353        #[inline]
2354        pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
2355            self.overflowing_rem_euclid(rhs).0
2356        }
2357
2358        /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
2359        /// of the type.
2360        ///
2361        /// The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
2362        /// is the negative minimal value for the type); this is a positive value that is too large to represent
2363        /// in the type. In such a case, this function returns `MIN` itself.
2364        ///
2365        /// # Examples
2366        ///
2367        /// ```
2368        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);")]
2369        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").wrapping_neg(), 100);")]
2370        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT), "::MIN);")]
2371        /// ```
2372        #[stable(feature = "num_wrapping", since = "1.2.0")]
2373        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2374        #[must_use = "this returns the result of the operation, \
2375                      without modifying the original"]
2376        #[inline(always)]
2377        pub const fn wrapping_neg(self) -> Self {
2378            (0 as $SelfT).wrapping_sub(self)
2379        }
2380
2381        /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
2382        /// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
2383        ///
2384        /// Beware that, unlike most other `wrapping_*` methods on integers, this
2385        /// does *not* give the same result as doing the shift in infinite precision
2386        /// then truncating as needed.  The behaviour matches what shift instructions
2387        /// do on many processors, and is what the `<<` operator does when overflow
2388        /// checks are disabled, but numerically it's weird.  Consider, instead,
2389        /// using [`Self::unbounded_shl`] which has nicer behaviour.
2390        ///
2391        /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
2392        /// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
2393        /// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
2394        /// which may be what you want instead.
2395        ///
2396        /// # Examples
2397        ///
2398        /// ```
2399        #[doc = concat!("assert_eq!((-1_", stringify!($SelfT), ").wrapping_shl(7), -128);")]
2400        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shl(", stringify!($BITS), "), 42);")]
2401        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shl(1).wrapping_shl(", stringify!($BITS_MINUS_ONE), "), 0);")]
2402        #[doc = concat!("assert_eq!((-1_", stringify!($SelfT), ").wrapping_shl(128), -1);")]
2403        #[doc = concat!("assert_eq!(5_", stringify!($SelfT), ".wrapping_shl(1025), 10);")]
2404        /// ```
2405        #[stable(feature = "num_wrapping", since = "1.2.0")]
2406        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2407        #[must_use = "this returns the result of the operation, \
2408                      without modifying the original"]
2409        #[inline(always)]
2410        pub const fn wrapping_shl(self, rhs: u32) -> Self {
2411            // SAFETY: the masking by the bitsize of the type ensures that we do not shift
2412            // out of bounds
2413            unsafe {
2414                self.unchecked_shl(rhs & (Self::BITS - 1))
2415            }
2416        }
2417
2418        /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
2419        /// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
2420        ///
2421        /// Beware that, unlike most other `wrapping_*` methods on integers, this
2422        /// does *not* give the same result as doing the shift in infinite precision
2423        /// then truncating as needed.  The behaviour matches what shift instructions
2424        /// do on many processors, and is what the `>>` operator does when overflow
2425        /// checks are disabled, but numerically it's weird.  Consider, instead,
2426        /// using [`Self::unbounded_shr`] which has nicer behaviour.
2427        ///
2428        /// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
2429        /// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
2430        /// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
2431        /// which may be what you want instead.
2432        ///
2433        /// # Examples
2434        ///
2435        /// ```
2436        #[doc = concat!("assert_eq!((-128_", stringify!($SelfT), ").wrapping_shr(7), -1);")]
2437        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shr(", stringify!($BITS), "), 42);")]
2438        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shr(1).wrapping_shr(", stringify!($BITS_MINUS_ONE), "), 0);")]
2439        /// assert_eq!((-128_i16).wrapping_shr(64), -128);
2440        #[doc = concat!("assert_eq!(10_", stringify!($SelfT), ".wrapping_shr(1025), 5);")]
2441        /// ```
2442        #[stable(feature = "num_wrapping", since = "1.2.0")]
2443        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2444        #[must_use = "this returns the result of the operation, \
2445                      without modifying the original"]
2446        #[inline(always)]
2447        pub const fn wrapping_shr(self, rhs: u32) -> Self {
2448            // SAFETY: the masking by the bitsize of the type ensures that we do not shift
2449            // out of bounds
2450            unsafe {
2451                self.unchecked_shr(rhs & (Self::BITS - 1))
2452            }
2453        }
2454
2455        /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
2456        /// the boundary of the type.
2457        ///
2458        /// The only case where such wrapping can occur is when one takes the absolute value of the negative
2459        /// minimal value for the type; this is a positive value that is too large to represent in the type. In
2460        /// such a case, this function returns `MIN` itself.
2461        ///
2462        /// # Examples
2463        ///
2464        /// ```
2465        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);")]
2466        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);")]
2467        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT), "::MIN);")]
2468        /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
2469        /// ```
2470        #[stable(feature = "no_panic_abs", since = "1.13.0")]
2471        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2472        #[must_use = "this returns the result of the operation, \
2473                      without modifying the original"]
2474        #[allow(unused_attributes)]
2475        #[inline]
2476        pub const fn wrapping_abs(self) -> Self {
2477             if self.is_negative() {
2478                 self.wrapping_neg()
2479             } else {
2480                 self
2481             }
2482        }
2483
2484        /// Computes the absolute value of `self` without any wrapping
2485        /// or panicking.
2486        ///
2487        ///
2488        /// # Examples
2489        ///
2490        /// ```
2491        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".unsigned_abs(), 100", stringify!($UnsignedT), ");")]
2492        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").unsigned_abs(), 100", stringify!($UnsignedT), ");")]
2493        /// assert_eq!((-128i8).unsigned_abs(), 128u8);
2494        /// ```
2495        #[stable(feature = "unsigned_abs", since = "1.51.0")]
2496        #[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
2497        #[must_use = "this returns the result of the operation, \
2498                      without modifying the original"]
2499        #[inline]
2500        pub const fn unsigned_abs(self) -> $UnsignedT {
2501             self.wrapping_abs() as $UnsignedT
2502        }
2503
2504        /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2505        /// wrapping around at the boundary of the type.
2506        ///
2507        /// # Examples
2508        ///
2509        /// ```
2510        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);")]
2511        /// assert_eq!(3i8.wrapping_pow(5), -13);
2512        /// assert_eq!(3i8.wrapping_pow(6), -39);
2513        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".wrapping_pow(0), 1);")]
2514        /// ```
2515        #[stable(feature = "no_panic_pow", since = "1.34.0")]
2516        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2517        #[must_use = "this returns the result of the operation, \
2518                      without modifying the original"]
2519        #[inline]
2520        pub const fn wrapping_pow(self, exp: u32) -> Self {
2521            let (a, _) = self.overflowing_pow(exp);
2522            a
2523        }
2524
2525        /// Calculates `self` + `rhs`.
2526        ///
2527        /// Returns a tuple of the addition along with a boolean indicating
2528        /// whether an arithmetic overflow would occur. If an overflow would have
2529        /// occurred then the wrapped value is returned (negative if overflowed
2530        /// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
2531        ///
2532        /// # Examples
2533        ///
2534        /// ```
2535        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
2536        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT), "::MIN, true));")]
2537        /// ```
2538        #[stable(feature = "wrapping", since = "1.7.0")]
2539        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2540        #[must_use = "this returns the result of the operation, \
2541                      without modifying the original"]
2542        #[inline(always)]
2543        pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2544            let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
2545            (a as Self, b)
2546        }
2547
2548        /// Calculates `self` + `rhs` + `carry` and checks for overflow.
2549        ///
2550        /// Performs "ternary addition" of two integer operands and a carry-in
2551        /// bit, and returns a tuple of the sum along with a boolean indicating
2552        /// whether an arithmetic overflow would occur. On overflow, the wrapped
2553        /// value is returned.
2554        ///
2555        /// This allows chaining together multiple additions to create a wider
2556        /// addition, and can be useful for bignum addition. This method should
2557        /// only be used for the most significant word; for the less significant
2558        /// words the unsigned method
2559        #[doc = concat!("[`", stringify!($UnsignedT), "::carrying_add`]")]
2560        /// should be used.
2561        ///
2562        /// The output boolean returned by this method is *not* a carry flag,
2563        /// and should *not* be added to a more significant word.
2564        ///
2565        /// If overflow occurred, the wrapped value is returned (negative if overflowed
2566        /// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
2567        ///
2568        /// If the input carry is false, this method is equivalent to
2569        /// [`overflowing_add`](Self::overflowing_add).
2570        ///
2571        /// # Examples
2572        ///
2573        /// ```
2574        /// #![feature(signed_bigint_helpers)]
2575        /// // Only the most significant word is signed.
2576        /// //
2577        #[doc = concat!("//   10  MAX    (a = 10 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
2578        #[doc = concat!("// + -5    9    (b = -5 × 2^", stringify!($BITS), " + 9)")]
2579        /// // ---------
2580        #[doc = concat!("//    6    8    (sum = 6 × 2^", stringify!($BITS), " + 8)")]
2581        ///
2582        #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($UnsignedT), ") = (10, ", stringify!($UnsignedT), "::MAX);")]
2583        #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($UnsignedT), ") = (-5, 9);")]
2584        /// let carry0 = false;
2585        ///
2586        #[doc = concat!("// ", stringify!($UnsignedT), "::carrying_add for the less significant words")]
2587        /// let (sum0, carry1) = a0.carrying_add(b0, carry0);
2588        /// assert_eq!(carry1, true);
2589        ///
2590        #[doc = concat!("// ", stringify!($SelfT), "::carrying_add for the most significant word")]
2591        /// let (sum1, overflow) = a1.carrying_add(b1, carry1);
2592        /// assert_eq!(overflow, false);
2593        ///
2594        /// assert_eq!((sum1, sum0), (6, 8));
2595        /// ```
2596        #[unstable(feature = "signed_bigint_helpers", issue = "151989")]
2597        #[must_use = "this returns the result of the operation, \
2598                      without modifying the original"]
2599        #[inline]
2600        pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
2601            // note: longer-term this should be done via an intrinsic.
2602            // note: no intermediate overflow is required (https://github.com/rust-lang/rust/issues/85532#issuecomment-1032214946).
2603            let (a, b) = self.overflowing_add(rhs);
2604            let (c, d) = a.overflowing_add(carry as $SelfT);
2605            (c, b != d)
2606        }
2607
2608        /// Calculates `self` + `rhs` with an unsigned `rhs`.
2609        ///
2610        /// Returns a tuple of the addition along with a boolean indicating
2611        /// whether an arithmetic overflow would occur. If an overflow would
2612        /// have occurred then the wrapped value is returned.
2613        ///
2614        /// # Examples
2615        ///
2616        /// ```
2617        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_unsigned(2), (3, false));")]
2618        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_add_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MAX, false));")]
2619        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_unsigned(3), (", stringify!($SelfT), "::MIN, true));")]
2620        /// ```
2621        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2622        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2623        #[must_use = "this returns the result of the operation, \
2624                      without modifying the original"]
2625        #[inline]
2626        pub const fn overflowing_add_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
2627            let rhs = rhs as Self;
2628            let (res, overflowed) = self.overflowing_add(rhs);
2629            (res, overflowed ^ (rhs < 0))
2630        }
2631
2632        /// Calculates `self` - `rhs`.
2633        ///
2634        /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
2635        /// would occur. If an overflow would have occurred then the wrapped value is returned
2636        /// (negative if overflowed above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
2637        ///
2638        /// # Examples
2639        ///
2640        /// ```
2641        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
2642        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
2643        /// ```
2644        #[stable(feature = "wrapping", since = "1.7.0")]
2645        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2646        #[must_use = "this returns the result of the operation, \
2647                      without modifying the original"]
2648        #[inline(always)]
2649        pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2650            let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
2651            (a as Self, b)
2652        }
2653
2654        /// Calculates `self` &minus; `rhs` &minus; `borrow` and checks for
2655        /// overflow.
2656        ///
2657        /// Performs "ternary subtraction" by subtracting both an integer
2658        /// operand and a borrow-in bit from `self`, and returns a tuple of the
2659        /// difference along with a boolean indicating whether an arithmetic
2660        /// overflow would occur. On overflow, the wrapped value is returned.
2661        ///
2662        /// This allows chaining together multiple subtractions to create a
2663        /// wider subtraction, and can be useful for bignum subtraction. This
2664        /// method should only be used for the most significant word; for the
2665        /// less significant words the unsigned method
2666        #[doc = concat!("[`", stringify!($UnsignedT), "::borrowing_sub`]")]
2667        /// should be used.
2668        ///
2669        /// The output boolean returned by this method is *not* a borrow flag,
2670        /// and should *not* be subtracted from a more significant word.
2671        ///
2672        /// If overflow occurred, the wrapped value is returned (negative if overflowed
2673        /// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
2674        ///
2675        /// If the input borrow is false, this method is equivalent to
2676        /// [`overflowing_sub`](Self::overflowing_sub).
2677        ///
2678        /// # Examples
2679        ///
2680        /// ```
2681        /// #![feature(signed_bigint_helpers)]
2682        /// // Only the most significant word is signed.
2683        /// //
2684        #[doc = concat!("//    6    8    (a = 6 × 2^", stringify!($BITS), " + 8)")]
2685        #[doc = concat!("// - -5    9    (b = -5 × 2^", stringify!($BITS), " + 9)")]
2686        /// // ---------
2687        #[doc = concat!("//   10  MAX    (diff = 10 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
2688        ///
2689        #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($UnsignedT), ") = (6, 8);")]
2690        #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($UnsignedT), ") = (-5, 9);")]
2691        /// let borrow0 = false;
2692        ///
2693        #[doc = concat!("// ", stringify!($UnsignedT), "::borrowing_sub for the less significant words")]
2694        /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
2695        /// assert_eq!(borrow1, true);
2696        ///
2697        #[doc = concat!("// ", stringify!($SelfT), "::borrowing_sub for the most significant word")]
2698        /// let (diff1, overflow) = a1.borrowing_sub(b1, borrow1);
2699        /// assert_eq!(overflow, false);
2700        ///
2701        #[doc = concat!("assert_eq!((diff1, diff0), (10, ", stringify!($UnsignedT), "::MAX));")]
2702        /// ```
2703        #[unstable(feature = "signed_bigint_helpers", issue = "151989")]
2704        #[must_use = "this returns the result of the operation, \
2705                      without modifying the original"]
2706        #[inline]
2707        pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
2708            // note: longer-term this should be done via an intrinsic.
2709            // note: no intermediate overflow is required (https://github.com/rust-lang/rust/issues/85532#issuecomment-1032214946).
2710            let (a, b) = self.overflowing_sub(rhs);
2711            let (c, d) = a.overflowing_sub(borrow as $SelfT);
2712            (c, b != d)
2713        }
2714
2715        /// Calculates `self` - `rhs` with an unsigned `rhs`.
2716        ///
2717        /// Returns a tuple of the subtraction along with a boolean indicating
2718        /// whether an arithmetic overflow would occur. If an overflow would
2719        /// have occurred then the wrapped value is returned.
2720        ///
2721        /// # Examples
2722        ///
2723        /// ```
2724        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_unsigned(2), (-1, false));")]
2725        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).overflowing_sub_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MIN, false));")]
2726        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).overflowing_sub_unsigned(3), (", stringify!($SelfT), "::MAX, true));")]
2727        /// ```
2728        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2729        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2730        #[must_use = "this returns the result of the operation, \
2731                      without modifying the original"]
2732        #[inline]
2733        pub const fn overflowing_sub_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
2734            let rhs = rhs as Self;
2735            let (res, overflowed) = self.overflowing_sub(rhs);
2736            (res, overflowed ^ (rhs < 0))
2737        }
2738
2739        /// Calculates the multiplication of `self` and `rhs`.
2740        ///
2741        /// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
2742        /// would occur. If an overflow would have occurred then the wrapped value is returned.
2743        ///
2744        /// # Examples
2745        ///
2746        /// ```
2747        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));")]
2748        /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
2749        /// ```
2750        #[stable(feature = "wrapping", since = "1.7.0")]
2751        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2752        #[must_use = "this returns the result of the operation, \
2753                      without modifying the original"]
2754        #[inline(always)]
2755        pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2756            let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
2757            (a as Self, b)
2758        }
2759
2760        /// Calculates the "full multiplication" `self * rhs + carry`
2761        /// without the possibility to overflow.
2762        ///
2763        /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
2764        /// of the result as two separate values, in that order.
2765        ///
2766        /// Performs "long multiplication" which takes in an extra amount to add, and may return an
2767        /// additional amount of overflow. This allows for chaining together multiple
2768        /// multiplications to create "big integers" which represent larger values.
2769        ///
2770        /// # Examples
2771        ///
2772        /// Please note that this example is shared among integer types, which is why `i32` is used.
2773        ///
2774        /// ```
2775        /// #![feature(signed_bigint_helpers)]
2776        /// assert_eq!(5i32.carrying_mul(-2, 0), (4294967286, -1));
2777        /// assert_eq!(5i32.carrying_mul(-2, 10), (0, 0));
2778        /// assert_eq!(1_000_000_000i32.carrying_mul(-10, 0), (2884901888, -3));
2779        /// assert_eq!(1_000_000_000i32.carrying_mul(-10, 10), (2884901898, -3));
2780        #[doc = concat!("assert_eq!(",
2781            stringify!($SelfT), "::MAX.carrying_mul(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
2782            "(", stringify!($SelfT), "::MAX.unsigned_abs() + 1, ", stringify!($SelfT), "::MAX / 2));"
2783        )]
2784        /// ```
2785        #[unstable(feature = "signed_bigint_helpers", issue = "151989")]
2786        #[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
2787        #[must_use = "this returns the result of the operation, \
2788                      without modifying the original"]
2789        #[inline]
2790        pub const fn carrying_mul(self, rhs: Self, carry: Self) -> ($UnsignedT, Self) {
2791            Self::carrying_mul_add(self, rhs, carry, 0)
2792        }
2793
2794        /// Calculates the "full multiplication" `self * rhs + carry + add`
2795        /// without the possibility to overflow.
2796        ///
2797        /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
2798        /// of the result as two separate values, in that order.
2799        ///
2800        /// Performs "long multiplication" which takes in an extra amount to add, and may return an
2801        /// additional amount of overflow. This allows for chaining together multiple
2802        /// multiplications to create "big integers" which represent larger values.
2803        ///
2804        /// If you only need one `carry`, then you can use [`Self::carrying_mul`] instead.
2805        ///
2806        /// # Examples
2807        ///
2808        /// Please note that this example is shared among integer types, which is why `i32` is used.
2809        ///
2810        /// ```
2811        /// #![feature(signed_bigint_helpers)]
2812        /// assert_eq!(5i32.carrying_mul_add(-2, 0, 0), (4294967286, -1));
2813        /// assert_eq!(5i32.carrying_mul_add(-2, 10, 10), (10, 0));
2814        /// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 0, 0), (2884901888, -3));
2815        /// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 10, 10), (2884901908, -3));
2816        #[doc = concat!("assert_eq!(",
2817            stringify!($SelfT), "::MAX.carrying_mul_add(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
2818            "(", stringify!($UnsignedT), "::MAX, ", stringify!($SelfT), "::MAX / 2));"
2819        )]
2820        /// ```
2821        #[unstable(feature = "signed_bigint_helpers", issue = "151989")]
2822        #[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
2823        #[must_use = "this returns the result of the operation, \
2824                      without modifying the original"]
2825        #[inline]
2826        pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self) -> ($UnsignedT, Self) {
2827            intrinsics::carrying_mul_add(self, rhs, carry, add)
2828        }
2829
2830        /// Calculates the divisor when `self` is divided by `rhs`.
2831        ///
2832        /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
2833        /// occur. If an overflow would occur then self is returned.
2834        ///
2835        /// # Panics
2836        ///
2837        /// This function will panic if `rhs` is zero.
2838        ///
2839        /// # Examples
2840        ///
2841        /// ```
2842        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
2843        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT), "::MIN, true));")]
2844        /// ```
2845        #[inline]
2846        #[stable(feature = "wrapping", since = "1.7.0")]
2847        #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
2848        #[must_use = "this returns the result of the operation, \
2849                      without modifying the original"]
2850        pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2851            // Using `&` helps LLVM see that it is the same check made in division.
2852            if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
2853                (self, true)
2854            } else {
2855                (self / rhs, false)
2856            }
2857        }
2858
2859        /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
2860        ///
2861        /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
2862        /// occur. If an overflow would occur then `self` is returned.
2863        ///
2864        /// # Panics
2865        ///
2866        /// This function will panic if `rhs` is zero.
2867        ///
2868        /// # Examples
2869        ///
2870        /// ```
2871        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
2872        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT), "::MIN, true));")]
2873        /// ```
2874        #[inline]
2875        #[stable(feature = "euclidean_division", since = "1.38.0")]
2876        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2877        #[must_use = "this returns the result of the operation, \
2878                      without modifying the original"]
2879        pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
2880            // Using `&` helps LLVM see that it is the same check made in division.
2881            if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
2882                (self, true)
2883            } else {
2884                (self.div_euclid(rhs), false)
2885            }
2886        }
2887
2888        /// Calculates the remainder when `self` is divided by `rhs`.
2889        ///
2890        /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
2891        /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
2892        ///
2893        /// # Panics
2894        ///
2895        /// This function will panic if `rhs` is zero.
2896        ///
2897        /// # Examples
2898        ///
2899        /// ```
2900        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
2901        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));")]
2902        /// ```
2903        #[inline]
2904        #[stable(feature = "wrapping", since = "1.7.0")]
2905        #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
2906        #[must_use = "this returns the result of the operation, \
2907                      without modifying the original"]
2908        pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2909            if intrinsics::unlikely(rhs == -1) {
2910                (0, self == Self::MIN)
2911            } else {
2912                (self % rhs, false)
2913            }
2914        }
2915
2916
2917        /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
2918        ///
2919        /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
2920        /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
2921        ///
2922        /// # Panics
2923        ///
2924        /// This function will panic if `rhs` is zero.
2925        ///
2926        /// # Examples
2927        ///
2928        /// ```
2929        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
2930        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));")]
2931        /// ```
2932        #[stable(feature = "euclidean_division", since = "1.38.0")]
2933        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2934        #[must_use = "this returns the result of the operation, \
2935                      without modifying the original"]
2936        #[inline]
2937        #[track_caller]
2938        pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
2939            if intrinsics::unlikely(rhs == -1) {
2940                (0, self == Self::MIN)
2941            } else {
2942                (self.rem_euclid(rhs), false)
2943            }
2944        }
2945
2946
2947        /// Negates self, overflowing if this is equal to the minimum value.
2948        ///
2949        /// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
2950        /// happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
2951        /// minimum value will be returned again and `true` will be returned for an overflow happening.
2952        ///
2953        /// # Examples
2954        ///
2955        /// ```
2956        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));")]
2957        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT), "::MIN, true));")]
2958        /// ```
2959        #[inline]
2960        #[stable(feature = "wrapping", since = "1.7.0")]
2961        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2962        #[must_use = "this returns the result of the operation, \
2963                      without modifying the original"]
2964        #[allow(unused_attributes)]
2965        pub const fn overflowing_neg(self) -> (Self, bool) {
2966            if intrinsics::unlikely(self == Self::MIN) {
2967                (Self::MIN, true)
2968            } else {
2969                (-self, false)
2970            }
2971        }
2972
2973        /// Shifts self left by `rhs` bits.
2974        ///
2975        /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
2976        /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
2977        /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
2978        ///
2979        /// # Examples
2980        ///
2981        /// ```
2982        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));")]
2983        /// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
2984        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shl(", stringify!($BITS_MINUS_ONE), "), (0, false));")]
2985        /// ```
2986        #[stable(feature = "wrapping", since = "1.7.0")]
2987        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2988        #[must_use = "this returns the result of the operation, \
2989                      without modifying the original"]
2990        #[inline]
2991        pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2992            (self.wrapping_shl(rhs), rhs >= Self::BITS)
2993        }
2994
2995        /// Shifts self right by `rhs` bits.
2996        ///
2997        /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
2998        /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
2999        /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
3000        ///
3001        /// # Examples
3002        ///
3003        /// ```
3004        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
3005        /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
3006        /// ```
3007        #[stable(feature = "wrapping", since = "1.7.0")]
3008        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
3009        #[must_use = "this returns the result of the operation, \
3010                      without modifying the original"]
3011        #[inline]
3012        pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3013            (self.wrapping_shr(rhs), rhs >= Self::BITS)
3014        }
3015
3016        /// Computes the absolute value of `self`.
3017        ///
3018        /// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
3019        /// happened. If self is the minimum value
3020        #[doc = concat!("(e.g., ", stringify!($SelfT), "::MIN for values of type ", stringify!($SelfT), "),")]
3021        /// then the minimum value will be returned again and true will be returned
3022        /// for an overflow happening.
3023        ///
3024        /// # Examples
3025        ///
3026        /// ```
3027        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));")]
3028        #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));")]
3029        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT), "::MIN, true));")]
3030        /// ```
3031        #[stable(feature = "no_panic_abs", since = "1.13.0")]
3032        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
3033        #[must_use = "this returns the result of the operation, \
3034                      without modifying the original"]
3035        #[inline]
3036        pub const fn overflowing_abs(self) -> (Self, bool) {
3037            (self.wrapping_abs(), self == Self::MIN)
3038        }
3039
3040        /// Raises self to the power of `exp`, using exponentiation by squaring.
3041        ///
3042        /// Returns a tuple of the exponentiation along with a bool indicating
3043        /// whether an overflow happened.
3044        ///
3045        /// # Examples
3046        ///
3047        /// ```
3048        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));")]
3049        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".overflowing_pow(0), (1, false));")]
3050        /// assert_eq!(3i8.overflowing_pow(5), (-13, true));
3051        /// ```
3052        #[stable(feature = "no_panic_pow", since = "1.34.0")]
3053        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3054        #[must_use = "this returns the result of the operation, \
3055                      without modifying the original"]
3056        #[inline]
3057        pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3058            let mut base = self;
3059            let mut acc: Self = 1;
3060            let mut overflow = false;
3061            let mut tmp_overflow;
3062
3063            if intrinsics::is_val_statically_known(base) && base.unsigned_abs().is_power_of_two() {
3064                let k = base.unsigned_abs().ilog2();
3065                let Some(shift) = k.checked_mul(exp) else {
3066                    return (0, true)
3067                };
3068                let base: Self = if base < 0 && (exp % 2) != 0 { -1 } else { 1 };
3069                return (base.unbounded_shl(shift), base.shl_exact(shift).is_none());
3070            }
3071
3072            if exp == 0 {
3073                return (1, false);
3074            }
3075
3076            if intrinsics::is_val_statically_known(exp) {
3077                while exp > 1 {
3078                    if (exp & 1) == 1 {
3079                        (acc, tmp_overflow) = acc.overflowing_mul(base);
3080                        overflow |= tmp_overflow;
3081                    }
3082                    exp /= 2;
3083                    (base, tmp_overflow) = base.overflowing_mul(base);
3084                    overflow |= tmp_overflow;
3085                }
3086
3087                // since exp!=0, finally the exp must be 1.
3088                // Deal with the final bit of the exponent separately, since
3089                // squaring the base afterwards is not necessary and may cause a
3090                // needless overflow.
3091                (acc, tmp_overflow) = acc.overflowing_mul(base);
3092                overflow |= tmp_overflow;
3093                return (acc, overflow);
3094            }
3095
3096            loop {
3097                if (exp & 1) == 1 {
3098                    (acc, tmp_overflow) = acc.overflowing_mul(base);
3099                    overflow |= tmp_overflow;
3100                    // since exp!=0, finally the exp must be 1.
3101                    if exp == 1 {
3102                        return (acc, overflow);
3103                    }
3104                }
3105                exp /= 2;
3106                (base, tmp_overflow) = base.overflowing_mul(base);
3107                overflow |= tmp_overflow;
3108            }
3109        }
3110
3111        /// Raises self to the power of `exp`, using exponentiation by squaring.
3112        ///
3113        /// # Examples
3114        ///
3115        /// ```
3116        #[doc = concat!("let x: ", stringify!($SelfT), " = 2; // or any other integer type")]
3117        ///
3118        /// assert_eq!(x.pow(5), 32);
3119        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".pow(0), 1);")]
3120        /// ```
3121        #[stable(feature = "rust1", since = "1.0.0")]
3122        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3123        #[must_use = "this returns the result of the operation, \
3124                      without modifying the original"]
3125        #[inline]
3126        #[rustc_inherit_overflow_checks]
3127        pub const fn pow(self, exp: u32) -> Self {
3128            if intrinsics::overflow_checks() {
3129                self.strict_pow(exp)
3130            } else {
3131                self.wrapping_pow(exp)
3132            }
3133        }
3134
3135        /// Returns the integer square root of the number, rounded down.
3136        ///
3137        /// This function returns the **principal (non-negative) square root**.
3138        /// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
3139        /// this function always returns the non-negative value.
3140        ///
3141        /// # Panics
3142        ///
3143        /// This function will panic if `self` is negative.
3144        ///
3145        /// # Examples
3146        ///
3147        /// ```
3148        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".isqrt(), 3);")]
3149        /// ```
3150        #[stable(feature = "isqrt", since = "1.84.0")]
3151        #[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
3152        #[must_use = "this returns the result of the operation, \
3153                      without modifying the original"]
3154        #[inline]
3155        #[track_caller]
3156        pub const fn isqrt(self) -> Self {
3157            match self.checked_isqrt() {
3158                Some(sqrt) => sqrt,
3159                None => imp::int_sqrt::panic_for_negative_argument(),
3160            }
3161        }
3162
3163        /// Calculates the quotient of Euclidean division of `self` by `rhs`.
3164        ///
3165        /// This computes the integer `q` such that `self = q * rhs + r`, with
3166        /// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
3167        ///
3168        /// In other words, the result is `self / rhs` rounded to the integer `q`
3169        /// such that `self >= q * rhs`.
3170        /// If `self > 0`, this is equal to rounding towards zero (the default in Rust);
3171        /// if `self < 0`, this is equal to rounding away from zero (towards +/- infinity).
3172        /// If `rhs > 0`, this is equal to rounding towards -infinity;
3173        /// if `rhs < 0`, this is equal to rounding towards +infinity.
3174        ///
3175        /// # Panics
3176        ///
3177        /// This function will panic if `rhs` is zero or if `self` is `Self::MIN`
3178        /// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
3179        ///
3180        /// # Examples
3181        ///
3182        /// ```
3183        #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
3184        /// let b = 4;
3185        ///
3186        /// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
3187        /// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
3188        /// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
3189        /// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
3190        /// ```
3191        #[stable(feature = "euclidean_division", since = "1.38.0")]
3192        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3193        #[must_use = "this returns the result of the operation, \
3194                      without modifying the original"]
3195        #[inline]
3196        #[track_caller]
3197        pub const fn div_euclid(self, rhs: Self) -> Self {
3198            let q = self / rhs;
3199            if self % rhs < 0 {
3200                return if rhs > 0 { q - 1 } else { q + 1 }
3201            }
3202            q
3203        }
3204
3205
3206        /// Calculates the least nonnegative remainder of `self` when
3207        /// divided by `rhs`.
3208        ///
3209        /// This is done as if by the Euclidean division algorithm -- given
3210        /// `r = self.rem_euclid(rhs)`, the result satisfies
3211        /// `self = rhs * self.div_euclid(rhs) + r` and `0 <= r < abs(rhs)`.
3212        ///
3213        /// # Panics
3214        ///
3215        /// This function will panic if `rhs` is zero or if `self` is `Self::MIN` and
3216        /// `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
3217        ///
3218        /// # Examples
3219        ///
3220        /// ```
3221        #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
3222        /// let b = 4;
3223        ///
3224        /// assert_eq!(a.rem_euclid(b), 3);
3225        /// assert_eq!((-a).rem_euclid(b), 1);
3226        /// assert_eq!(a.rem_euclid(-b), 3);
3227        /// assert_eq!((-a).rem_euclid(-b), 1);
3228        /// ```
3229        ///
3230        /// This will panic:
3231        /// ```should_panic
3232        #[doc = concat!("let _ = ", stringify!($SelfT), "::MIN.rem_euclid(-1);")]
3233        /// ```
3234        #[doc(alias = "modulo", alias = "mod")]
3235        #[stable(feature = "euclidean_division", since = "1.38.0")]
3236        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3237        #[must_use = "this returns the result of the operation, \
3238                      without modifying the original"]
3239        #[inline]
3240        #[track_caller]
3241        pub const fn rem_euclid(self, rhs: Self) -> Self {
3242            let r = self % rhs;
3243            if r < 0 {
3244                // Semantically equivalent to `if rhs < 0 { r - rhs } else { r + rhs }`.
3245                // If `rhs` is not `Self::MIN`, then `r + abs(rhs)` will not overflow
3246                // and is clearly equivalent, because `r` is negative.
3247                // Otherwise, `rhs` is `Self::MIN`, then we have
3248                // `r.wrapping_add(Self::MIN.wrapping_abs())`, which evaluates
3249                // to `r.wrapping_add(Self::MIN)`, which is equivalent to
3250                // `r - Self::MIN`, which is what we wanted (and will not overflow
3251                // for negative `r`).
3252                r.wrapping_add(rhs.wrapping_abs())
3253            } else {
3254                r
3255            }
3256        }
3257
3258        /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
3259        ///
3260        /// # Panics
3261        ///
3262        /// This function will panic if `rhs` is zero or if `self` is `Self::MIN`
3263        /// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
3264        ///
3265        /// # Examples
3266        ///
3267        /// ```
3268        /// #![feature(int_roundings)]
3269        #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
3270        /// let b = 3;
3271        ///
3272        /// assert_eq!(a.div_floor(b), 2);
3273        /// assert_eq!(a.div_floor(-b), -3);
3274        /// assert_eq!((-a).div_floor(b), -3);
3275        /// assert_eq!((-a).div_floor(-b), 2);
3276        /// ```
3277        #[unstable(feature = "int_roundings", issue = "88581")]
3278        #[must_use = "this returns the result of the operation, \
3279                      without modifying the original"]
3280        #[inline]
3281        #[track_caller]
3282        pub const fn div_floor(self, rhs: Self) -> Self {
3283            let d = self / rhs;
3284            let r = self % rhs;
3285
3286            // If the remainder is non-zero, we need to subtract one if the
3287            // signs of self and rhs differ, as this means we rounded upwards
3288            // instead of downwards. We do this branchlessly by creating a mask
3289            // which is all-ones iff the signs differ, and 0 otherwise. Then by
3290            // adding this mask (which corresponds to the signed value -1), we
3291            // get our correction.
3292            let correction = (self ^ rhs) >> (Self::BITS - 1);
3293            if r != 0 {
3294                d + correction
3295            } else {
3296                d
3297            }
3298        }
3299
3300        /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
3301        ///
3302        /// # Panics
3303        ///
3304        /// This function will panic if `rhs` is zero or if `self` is `Self::MIN`
3305        /// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
3306        ///
3307        /// # Examples
3308        ///
3309        /// ```
3310        /// #![feature(int_roundings)]
3311        #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
3312        /// let b = 3;
3313        ///
3314        /// assert_eq!(a.div_ceil(b), 3);
3315        /// assert_eq!(a.div_ceil(-b), -2);
3316        /// assert_eq!((-a).div_ceil(b), -2);
3317        /// assert_eq!((-a).div_ceil(-b), 3);
3318        /// ```
3319        #[unstable(feature = "int_roundings", issue = "88581")]
3320        #[must_use = "this returns the result of the operation, \
3321                      without modifying the original"]
3322        #[inline]
3323        #[track_caller]
3324        pub const fn div_ceil(self, rhs: Self) -> Self {
3325            let d = self / rhs;
3326            let r = self % rhs;
3327
3328            // When remainder is non-zero we have a.div_ceil(b) == 1 + a.div_floor(b),
3329            // so we can re-use the algorithm from div_floor, just adding 1.
3330            let correction = 1 + ((self ^ rhs) >> (Self::BITS - 1));
3331            if r != 0 {
3332                d + correction
3333            } else {
3334                d
3335            }
3336        }
3337
3338        /// If `rhs` is positive, calculates the smallest value greater than or
3339        /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
3340        /// calculates the largest value less than or equal to `self` that is a
3341        /// multiple of `rhs`.
3342        ///
3343        /// # Panics
3344        ///
3345        /// This function will panic if `rhs` is zero.
3346        ///
3347        /// ## Overflow behavior
3348        ///
3349        /// On overflow, this function will panic if overflow checks are enabled (default in debug
3350        /// mode) and wrap if overflow checks are disabled (default in release mode).
3351        ///
3352        /// # Examples
3353        ///
3354        /// ```
3355        /// #![feature(int_roundings)]
3356        #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
3357        #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
3358        #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
3359        #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
3360        #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
3361        #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
3362        #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(-8), -16);")]
3363        #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(-8), -24);")]
3364        /// ```
3365        #[unstable(feature = "int_roundings", issue = "88581")]
3366        #[must_use = "this returns the result of the operation, \
3367                      without modifying the original"]
3368        #[inline]
3369        #[rustc_inherit_overflow_checks]
3370        pub const fn next_multiple_of(self, rhs: Self) -> Self {
3371            // This would otherwise fail when calculating `r` when self == T::MIN.
3372            if rhs == -1 {
3373                return self;
3374            }
3375
3376            let r = self % rhs;
3377            let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
3378                r + rhs
3379            } else {
3380                r
3381            };
3382
3383            if m == 0 {
3384                self
3385            } else {
3386                self + (rhs - m)
3387            }
3388        }
3389
3390        /// If `rhs` is positive, calculates the smallest value greater than or
3391        /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
3392        /// calculates the largest value less than or equal to `self` that is a
3393        /// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
3394        /// would result in overflow.
3395        ///
3396        /// # Examples
3397        ///
3398        /// ```
3399        /// #![feature(int_roundings)]
3400        #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
3401        #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
3402        #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
3403        #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
3404        #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
3405        #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
3406        #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-16));")]
3407        #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-24));")]
3408        #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
3409        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
3410        /// ```
3411        #[unstable(feature = "int_roundings", issue = "88581")]
3412        #[must_use = "this returns the result of the operation, \
3413                      without modifying the original"]
3414        #[inline]
3415        pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
3416            // This would otherwise fail when calculating `r` when self == T::MIN.
3417            if rhs == -1 {
3418                return Some(self);
3419            }
3420
3421            let r = try_opt!(self.checked_rem(rhs));
3422            let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
3423                // r + rhs cannot overflow because they have opposite signs
3424                r + rhs
3425            } else {
3426                r
3427            };
3428
3429            if m == 0 {
3430                Some(self)
3431            } else {
3432                // rhs - m cannot overflow because m has the same sign as rhs
3433                self.checked_add(rhs - m)
3434            }
3435        }
3436
3437        /// Returns the logarithm of the number with respect to an arbitrary base,
3438        /// rounded down.
3439        ///
3440        /// This method might not be optimized owing to implementation details;
3441        /// `ilog2` can produce results more efficiently for base 2, and `ilog10`
3442        /// can produce results more efficiently for base 10.
3443        ///
3444        /// # Panics
3445        ///
3446        /// This function will panic if `self` is less than or equal to zero,
3447        /// or if `base` is less than 2.
3448        ///
3449        /// # Examples
3450        ///
3451        /// ```
3452        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".ilog(5), 1);")]
3453        /// ```
3454        #[stable(feature = "int_log", since = "1.67.0")]
3455        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
3456        #[must_use = "this returns the result of the operation, \
3457                      without modifying the original"]
3458        #[inline]
3459        #[track_caller]
3460        pub const fn ilog(self, base: Self) -> u32 {
3461            assert!(base >= 2, "base of integer logarithm must be at least 2");
3462            if let Some(log) = self.checked_ilog(base) {
3463                log
3464            } else {
3465                imp::int_log10::panic_for_nonpositive_argument()
3466            }
3467        }
3468
3469        /// Returns the base 2 logarithm of the number, rounded down.
3470        ///
3471        /// # Panics
3472        ///
3473        /// This function will panic if `self` is less than or equal to zero.
3474        ///
3475        /// # Examples
3476        ///
3477        /// ```
3478        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".ilog2(), 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 ilog2(self) -> u32 {
3487            if let Some(log) = self.checked_ilog2() {
3488                log
3489            } else {
3490                imp::int_log10::panic_for_nonpositive_argument()
3491            }
3492        }
3493
3494        /// Returns the base 10 logarithm of the number, rounded down.
3495        ///
3496        /// # Panics
3497        ///
3498        /// This function will panic if `self` is less than or equal to zero.
3499        ///
3500        /// # Example
3501        ///
3502        /// ```
3503        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".ilog10(), 1);")]
3504        /// ```
3505        #[stable(feature = "int_log", since = "1.67.0")]
3506        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
3507        #[must_use = "this returns the result of the operation, \
3508                      without modifying the original"]
3509        #[inline]
3510        #[track_caller]
3511        pub const fn ilog10(self) -> u32 {
3512            if let Some(log) = self.checked_ilog10() {
3513                log
3514            } else {
3515                imp::int_log10::panic_for_nonpositive_argument()
3516            }
3517        }
3518
3519        /// Returns the logarithm of the number with respect to an arbitrary base,
3520        /// rounded down.
3521        ///
3522        /// Returns `None` if the number is negative or zero, or if the base is not at least 2.
3523        ///
3524        /// This method might not be optimized owing to implementation details;
3525        /// `checked_ilog2` can produce results more efficiently for base 2, and
3526        /// `checked_ilog10` can produce results more efficiently for base 10.
3527        ///
3528        /// # Examples
3529        ///
3530        /// ```
3531        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_ilog(5), Some(1));")]
3532        /// ```
3533        #[stable(feature = "int_log", since = "1.67.0")]
3534        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
3535        #[must_use = "this returns the result of the operation, \
3536                      without modifying the original"]
3537        #[inline]
3538        pub const fn checked_ilog(self, base: Self) -> Option<u32> {
3539            if self <= 0 || base <= 1 {
3540                None
3541            } else {
3542                // Delegate to the unsigned implementation.
3543                // The condition makes sure that both casts are exact.
3544                (self as $UnsignedT).checked_ilog(base as $UnsignedT)
3545            }
3546        }
3547
3548        /// Returns the base 2 logarithm of the number, rounded down.
3549        ///
3550        /// Returns `None` if the number is negative or zero.
3551        ///
3552        /// # Examples
3553        ///
3554        /// ```
3555        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_ilog2(), Some(1));")]
3556        /// ```
3557        #[stable(feature = "int_log", since = "1.67.0")]
3558        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
3559        #[must_use = "this returns the result of the operation, \
3560                      without modifying the original"]
3561        #[inline]
3562        pub const fn checked_ilog2(self) -> Option<u32> {
3563            if self <= 0 {
3564                None
3565            } else {
3566                // SAFETY: We just checked that this number is positive
3567                let log = (Self::BITS - 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 };
3568                Some(log)
3569            }
3570        }
3571
3572        /// Returns the base 10 logarithm of the number, rounded down.
3573        ///
3574        /// Returns `None` if the number is negative or zero.
3575        ///
3576        /// # Example
3577        ///
3578        /// ```
3579        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_ilog10(), Some(1));")]
3580        /// ```
3581        #[stable(feature = "int_log", since = "1.67.0")]
3582        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
3583        #[must_use = "this returns the result of the operation, \
3584                      without modifying the original"]
3585        #[inline]
3586        pub const fn checked_ilog10(self) -> Option<u32> {
3587            imp::int_log10::$ActualT(self as $ActualT)
3588        }
3589
3590        /// Computes the absolute value of `self`.
3591        ///
3592        /// # Overflow behavior
3593        ///
3594        /// The absolute value of
3595        #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
3596        /// cannot be represented as an
3597        #[doc = concat!("`", stringify!($SelfT), "`,")]
3598        /// and attempting to calculate it will cause an overflow. This means
3599        /// that code in debug mode will trigger a panic on this case and
3600        /// optimized code will return
3601        #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
3602        /// without a panic. If you do not want this behavior, consider
3603        /// using [`unsigned_abs`](Self::unsigned_abs) instead.
3604        ///
3605        /// # Examples
3606        ///
3607        /// ```
3608        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".abs(), 10);")]
3609        #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").abs(), 10);")]
3610        /// ```
3611        #[stable(feature = "rust1", since = "1.0.0")]
3612        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
3613        #[allow(unused_attributes)]
3614        #[must_use = "this returns the result of the operation, \
3615                      without modifying the original"]
3616        #[inline]
3617        #[rustc_inherit_overflow_checks]
3618        pub const fn abs(self) -> Self {
3619            // Note that the #[rustc_inherit_overflow_checks] and #[inline]
3620            // above mean that the overflow semantics of the subtraction
3621            // depend on the crate we're being called from.
3622            if self.is_negative() {
3623                -self
3624            } else {
3625                self
3626            }
3627        }
3628
3629        /// Computes the absolute difference between `self` and `other`.
3630        ///
3631        /// This function always returns the correct answer without overflow or
3632        /// panics by returning an unsigned integer.
3633        ///
3634        /// # Examples
3635        ///
3636        /// ```
3637        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($UnsignedT), ");")]
3638        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($UnsignedT), ");")]
3639        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(80), 180", stringify!($UnsignedT), ");")]
3640        #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(-120), 20", stringify!($UnsignedT), ");")]
3641        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.abs_diff(", stringify!($SelfT), "::MAX), ", stringify!($UnsignedT), "::MAX);")]
3642        /// ```
3643        #[stable(feature = "int_abs_diff", since = "1.60.0")]
3644        #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
3645        #[must_use = "this returns the result of the operation, \
3646                      without modifying the original"]
3647        #[inline]
3648        pub const fn abs_diff(self, other: Self) -> $UnsignedT {
3649            if self < other {
3650                // Converting a non-negative x from signed to unsigned by using
3651                // `x as U` is left unchanged, but a negative x is converted
3652                // to value x + 2^N. Thus if `s` and `o` are binary variables
3653                // respectively indicating whether `self` and `other` are
3654                // negative, we are computing the mathematical value:
3655                //
3656                //    (other + o*2^N) - (self + s*2^N)    mod  2^N
3657                //    other - self + (o-s)*2^N            mod  2^N
3658                //    other - self                        mod  2^N
3659                //
3660                // Finally, taking the mod 2^N of the mathematical value of
3661                // `other - self` does not change it as it already is
3662                // in the range [0, 2^N).
3663                (other as $UnsignedT).wrapping_sub(self as $UnsignedT)
3664            } else {
3665                (self as $UnsignedT).wrapping_sub(other as $UnsignedT)
3666            }
3667        }
3668
3669        /// Returns a number representing sign of `self`.
3670        ///
3671        ///  - `0` if the number is zero
3672        ///  - `1` if the number is positive
3673        ///  - `-1` if the number is negative
3674        ///
3675        /// # Examples
3676        ///
3677        /// ```
3678        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".signum(), 1);")]
3679        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".signum(), 0);")]
3680        #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").signum(), -1);")]
3681        /// ```
3682        #[stable(feature = "rust1", since = "1.0.0")]
3683        #[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
3684        #[must_use = "this returns the result of the operation, \
3685                      without modifying the original"]
3686        #[inline(always)]
3687        pub const fn signum(self) -> Self {
3688            // Picking the right way to phrase this is complicated
3689            // (<https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign>)
3690            // so delegate it to `Ord` which is already producing -1/0/+1
3691            // exactly like we need and can be the place to deal with the complexity.
3692
3693            crate::intrinsics::three_way_compare(self, 0) as Self
3694        }
3695
3696        /// Returns `true` if `self` is positive and `false` if the number is zero or
3697        /// negative.
3698        ///
3699        /// # Examples
3700        ///
3701        /// ```
3702        #[doc = concat!("assert!(10", stringify!($SelfT), ".is_positive());")]
3703        #[doc = concat!("assert!(!(-10", stringify!($SelfT), ").is_positive());")]
3704        /// ```
3705        #[must_use]
3706        #[stable(feature = "rust1", since = "1.0.0")]
3707        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
3708        #[inline(always)]
3709        pub const fn is_positive(self) -> bool { self > 0 }
3710
3711        /// Returns `true` if `self` is negative and `false` if the number is zero or
3712        /// positive.
3713        ///
3714        /// # Examples
3715        ///
3716        /// ```
3717        #[doc = concat!("assert!((-10", stringify!($SelfT), ").is_negative());")]
3718        #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_negative());")]
3719        /// ```
3720        #[must_use]
3721        #[stable(feature = "rust1", since = "1.0.0")]
3722        #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
3723        #[inline(always)]
3724        pub const fn is_negative(self) -> bool { self < 0 }
3725
3726        /// Returns the memory representation of this integer as a byte array in
3727        /// big-endian (network) byte order.
3728        ///
3729        #[doc = $to_xe_bytes_doc]
3730        ///
3731        /// # Examples
3732        ///
3733        /// ```
3734        #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
3735        #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
3736        /// ```
3737        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3738        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3739        #[must_use = "this returns the result of the operation, \
3740                      without modifying the original"]
3741        #[inline]
3742        pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
3743            self.to_be().to_ne_bytes()
3744        }
3745
3746        /// Returns the memory representation of this integer as a byte array in
3747        /// little-endian byte order.
3748        ///
3749        #[doc = $to_xe_bytes_doc]
3750        ///
3751        /// # Examples
3752        ///
3753        /// ```
3754        #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
3755        #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
3756        /// ```
3757        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3758        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3759        #[must_use = "this returns the result of the operation, \
3760                      without modifying the original"]
3761        #[inline]
3762        pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
3763            self.to_le().to_ne_bytes()
3764        }
3765
3766        /// Returns the memory representation of this integer as a byte array in
3767        /// native byte order.
3768        ///
3769        /// As the target platform's native endianness is used, portable code
3770        /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3771        /// instead.
3772        ///
3773        #[doc = $to_xe_bytes_doc]
3774        ///
3775        /// [`to_be_bytes`]: Self::to_be_bytes
3776        /// [`to_le_bytes`]: Self::to_le_bytes
3777        ///
3778        /// # Examples
3779        ///
3780        /// ```
3781        #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
3782        /// assert_eq!(
3783        ///     bytes,
3784        ///     if cfg!(target_endian = "big") {
3785        #[doc = concat!("        ", $be_bytes)]
3786        ///     } else {
3787        #[doc = concat!("        ", $le_bytes)]
3788        ///     }
3789        /// );
3790        /// ```
3791        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3792        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3793        #[allow(unnecessary_transmutes)]
3794        // SAFETY: const sound because integers are plain old datatypes so we can always
3795        // transmute them to arrays of bytes
3796        #[must_use = "this returns the result of the operation, \
3797                      without modifying the original"]
3798        #[inline]
3799        pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
3800            // SAFETY: integers are plain old datatypes so we can always transmute them to
3801            // arrays of bytes
3802            unsafe { mem::transmute(self) }
3803        }
3804
3805        /// Creates an integer value from its representation as a byte array in
3806        /// big endian.
3807        ///
3808        #[doc = $from_xe_bytes_doc]
3809        ///
3810        /// # Examples
3811        ///
3812        /// ```
3813        #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
3814        #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3815        /// ```
3816        ///
3817        /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3818        ///
3819        /// ```
3820        #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3821        #[doc = concat!("    let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
3822        ///     *input = rest;
3823        #[doc = concat!("    ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
3824        /// }
3825        /// ```
3826        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3827        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3828        #[must_use]
3829        #[inline]
3830        pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
3831            Self::from_be(Self::from_ne_bytes(bytes))
3832        }
3833
3834        /// Creates an integer value from its representation as a byte array in
3835        /// little endian.
3836        ///
3837        #[doc = $from_xe_bytes_doc]
3838        ///
3839        /// # Examples
3840        ///
3841        /// ```
3842        #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
3843        #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3844        /// ```
3845        ///
3846        /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3847        ///
3848        /// ```
3849        #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3850        #[doc = concat!("    let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
3851        ///     *input = rest;
3852        #[doc = concat!("    ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
3853        /// }
3854        /// ```
3855        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3856        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3857        #[must_use]
3858        #[inline]
3859        pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
3860            Self::from_le(Self::from_ne_bytes(bytes))
3861        }
3862
3863        /// Creates an integer value from its memory representation as a byte
3864        /// array in native endianness.
3865        ///
3866        /// As the target platform's native endianness is used, portable code
3867        /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3868        /// appropriate instead.
3869        ///
3870        /// [`from_be_bytes`]: Self::from_be_bytes
3871        /// [`from_le_bytes`]: Self::from_le_bytes
3872        ///
3873        #[doc = $from_xe_bytes_doc]
3874        ///
3875        /// # Examples
3876        ///
3877        /// ```
3878        #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
3879        #[doc = concat!("    ", $be_bytes)]
3880        /// } else {
3881        #[doc = concat!("    ", $le_bytes)]
3882        /// });
3883        #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3884        /// ```
3885        ///
3886        /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3887        ///
3888        /// ```
3889        #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3890        #[doc = concat!("    let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
3891        ///     *input = rest;
3892        #[doc = concat!("    ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
3893        /// }
3894        /// ```
3895        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3896        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3897        #[allow(unnecessary_transmutes)]
3898        #[must_use]
3899        // SAFETY: const sound because integers are plain old datatypes so we can always
3900        // transmute to them
3901        #[inline]
3902        pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
3903            // SAFETY: integers are plain old datatypes so we can always transmute to them
3904            unsafe { mem::transmute(bytes) }
3905        }
3906
3907        /// New code should prefer to use
3908        #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
3909        ///
3910        /// Returns the smallest value that can be represented by this integer type.
3911        #[stable(feature = "rust1", since = "1.0.0")]
3912        #[inline(always)]
3913        #[rustc_promotable]
3914        #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
3915        #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
3916        #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_min_value")]
3917        pub const fn min_value() -> Self {
3918            Self::MIN
3919        }
3920
3921        /// New code should prefer to use
3922        #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
3923        ///
3924        /// Returns the largest value that can be represented by this integer type.
3925        #[stable(feature = "rust1", since = "1.0.0")]
3926        #[inline(always)]
3927        #[rustc_promotable]
3928        #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
3929        #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
3930        #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_max_value")]
3931        pub const fn max_value() -> Self {
3932            Self::MAX
3933        }
3934
3935        /// Clamps this number to a symmetric range centred around zero.
3936        ///
3937        /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
3938        ///
3939        /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
3940        /// explicit about the intent.
3941        ///
3942        /// # Examples
3943        ///
3944        /// ```
3945        /// #![feature(clamp_magnitude)]
3946        #[doc = concat!("assert_eq!(120", stringify!($SelfT), ".clamp_magnitude(100), 100);")]
3947        #[doc = concat!("assert_eq!(-120", stringify!($SelfT), ".clamp_magnitude(100), -100);")]
3948        #[doc = concat!("assert_eq!(80", stringify!($SelfT), ".clamp_magnitude(100), 80);")]
3949        #[doc = concat!("assert_eq!(-80", stringify!($SelfT), ".clamp_magnitude(100), -80);")]
3950        /// ```
3951        #[must_use = "this returns the clamped value and does not modify the original"]
3952        #[unstable(feature = "clamp_magnitude", issue = "148519")]
3953        #[inline]
3954        pub fn clamp_magnitude(self, limit: $UnsignedT) -> Self {
3955            if let Ok(limit) = core::convert::TryInto::<$SelfT>::try_into(limit) {
3956                self.clamp(-limit, limit)
3957            } else {
3958                self
3959            }
3960        }
3961
3962        /// Truncate an integer to an integer of the same size or smaller, preserving the least
3963        /// significant bits.
3964        ///
3965        /// # Examples
3966        ///
3967        /// ```
3968        /// #![feature(integer_widen_truncate)]
3969        #[doc = concat!("assert_eq!(120i8, 120", stringify!($SelfT), ".truncate());")]
3970        #[doc = concat!("assert_eq!(-120i8, (-120", stringify!($SelfT), ").truncate());")]
3971        /// assert_eq!(120i8, 376i32.truncate());
3972        /// ```
3973        #[must_use = "this returns the truncated value and does not modify the original"]
3974        #[unstable(feature = "integer_widen_truncate", issue = "154330")]
3975        #[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
3976        #[inline]
3977        pub const fn truncate<Target>(self) -> Target
3978            where Self: [const] traits::TruncateTarget<Target>
3979        {
3980            traits::TruncateTarget::internal_truncate(self)
3981        }
3982
3983        /// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
3984        /// instead of truncating.
3985        ///
3986        /// # Examples
3987        ///
3988        /// ```
3989        /// #![feature(integer_widen_truncate)]
3990        #[doc = concat!("assert_eq!(120i8, 120", stringify!($SelfT), ".saturating_truncate());")]
3991        #[doc = concat!("assert_eq!(-120i8, (-120", stringify!($SelfT), ").saturating_truncate());")]
3992        /// assert_eq!(127i8, 376i32.saturating_truncate());
3993        /// assert_eq!(-128i8, (-1000i32).saturating_truncate());
3994        /// ```
3995        #[must_use = "this returns the truncated value and does not modify the original"]
3996        #[unstable(feature = "integer_widen_truncate", issue = "154330")]
3997        #[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
3998        #[inline]
3999        pub const fn saturating_truncate<Target>(self) -> Target
4000            where Self: [const] traits::TruncateTarget<Target>
4001        {
4002            traits::TruncateTarget::internal_saturating_truncate(self)
4003        }
4004
4005        /// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
4006        /// is outside the bounds of the smaller type.
4007        ///
4008        /// # Examples
4009        ///
4010        /// ```
4011        /// #![feature(integer_widen_truncate)]
4012        #[doc = concat!("assert_eq!(Some(120i8), 120", stringify!($SelfT), ".checked_truncate());")]
4013        #[doc = concat!("assert_eq!(Some(-120i8), (-120", stringify!($SelfT), ").checked_truncate());")]
4014        /// assert_eq!(None, 376i32.checked_truncate::<i8>());
4015        /// assert_eq!(None, (-1000i32).checked_truncate::<i8>());
4016        /// ```
4017        #[must_use = "this returns the truncated value and does not modify the original"]
4018        #[unstable(feature = "integer_widen_truncate", issue = "154330")]
4019        #[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
4020        #[inline]
4021        pub const fn checked_truncate<Target>(self) -> Option<Target>
4022            where Self: [const] traits::TruncateTarget<Target>
4023        {
4024            traits::TruncateTarget::internal_checked_truncate(self)
4025        }
4026
4027        /// Widen to an integer of the same size or larger, preserving its value.
4028        ///
4029        /// # Examples
4030        ///
4031        /// ```
4032        /// #![feature(integer_widen_truncate)]
4033        #[doc = concat!("assert_eq!(120i128, 120i8.widen());")]
4034        #[doc = concat!("assert_eq!(-120i128, (-120i8).widen());")]
4035        /// ```
4036        #[must_use = "this returns the widened value and does not modify the original"]
4037        #[unstable(feature = "integer_widen_truncate", issue = "154330")]
4038        #[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
4039        #[inline]
4040        pub const fn widen<Target>(self) -> Target
4041            where Self: [const] traits::WidenTarget<Target>
4042        {
4043            traits::WidenTarget::internal_widen(self)
4044        }
4045    }
4046}