]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
Rollup merge of #67305 - kappa:patch-1, r=jonas-schievink
[rust.git] / src / libcore / num / mod.rs
1 // ignore-tidy-filelength
2
3 //! Numeric traits and functions for the built-in numeric types.
4
5 #![stable(feature = "rust1", since = "1.0.0")]
6
7 use crate::convert::Infallible;
8 use crate::fmt;
9 use crate::intrinsics;
10 use crate::mem;
11 use crate::ops;
12 use crate::str::FromStr;
13
14 macro_rules! impl_nonzero_fmt {
15     ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
16         $(
17             #[$stability]
18             impl fmt::$Trait for $Ty {
19                 #[inline]
20                 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21                     self.get().fmt(f)
22                 }
23             }
24         )+
25     }
26 }
27
28 macro_rules! doc_comment {
29     ($x:expr, $($tt:tt)*) => {
30         #[doc = $x]
31         $($tt)*
32     };
33 }
34
35 macro_rules! nonzero_integers {
36     ( $( #[$stability: meta] $Ty: ident($Int: ty); )+ ) => {
37         $(
38             doc_comment! {
39                 concat!("An integer that is known not to equal zero.
40
41 This enables some memory layout optimization.
42 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
43
44 ```rust
45 use std::mem::size_of;
46 assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
47 ">());
48 ```"),
49                 #[$stability]
50                 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
51                 #[repr(transparent)]
52                 #[rustc_layout_scalar_valid_range_start(1)]
53                 #[rustc_nonnull_optimization_guaranteed]
54                 pub struct $Ty($Int);
55             }
56
57             impl $Ty {
58                 /// Creates a non-zero without checking the value.
59                 ///
60                 /// # Safety
61                 ///
62                 /// The value must not be zero.
63                 #[$stability]
64                 #[cfg_attr(
65                     not(bootstrap),
66                     rustc_const_stable(feature = "nonzero", since = "1.34.0"),
67                 )]
68                 #[inline]
69                 pub const unsafe fn new_unchecked(n: $Int) -> Self {
70                     $Ty(n)
71                 }
72
73                 /// Creates a non-zero if the given value is not zero.
74                 #[$stability]
75                 #[inline]
76                 pub fn new(n: $Int) -> Option<Self> {
77                     if n != 0 {
78                         // SAFETY: we just checked that there's no `0`
79                         Some(unsafe { $Ty(n) })
80                     } else {
81                         None
82                     }
83                 }
84
85                 /// Returns the value as a primitive type.
86                 #[$stability]
87                 #[inline]
88                 #[cfg_attr(
89                     not(bootstrap),
90                     rustc_const_stable(feature = "nonzero", since = "1.34.0"),
91                 )]
92                 pub const fn get(self) -> $Int {
93                     self.0
94                 }
95
96             }
97
98             #[stable(feature = "from_nonzero", since = "1.31.0")]
99             impl From<$Ty> for $Int {
100                 fn from(nonzero: $Ty) -> Self {
101                     nonzero.0
102                 }
103             }
104
105             impl_nonzero_fmt! {
106                 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
107             }
108         )+
109     }
110 }
111
112 nonzero_integers! {
113     #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
114     #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
115     #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
116     #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
117     #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
118     #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
119     #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
120     #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
121     #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
122     #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
123     #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
124     #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
125 }
126
127 macro_rules! from_str_radix_nzint_impl {
128     ($($t:ty)*) => {$(
129         #[stable(feature = "nonzero_parse", since = "1.35.0")]
130         impl FromStr for $t {
131             type Err = ParseIntError;
132             fn from_str(src: &str) -> Result<Self, Self::Err> {
133                 Self::new(from_str_radix(src, 10)?)
134                     .ok_or(ParseIntError {
135                         kind: IntErrorKind::Zero
136                     })
137             }
138         }
139     )*}
140 }
141
142 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
143 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
144
145 /// Provides intentionally-wrapped arithmetic on `T`.
146 ///
147 /// Operations like `+` on `u32` values are intended to never overflow,
148 /// and in some debug configurations overflow is detected and results
149 /// in a panic. While most arithmetic falls into this category, some
150 /// code explicitly expects and relies upon modular arithmetic (e.g.,
151 /// hashing).
152 ///
153 /// Wrapping arithmetic can be achieved either through methods like
154 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
155 /// all standard arithmetic operations on the underlying value are
156 /// intended to have wrapping semantics.
157 ///
158 /// The underlying value can be retrieved through the `.0` index of the
159 /// `Wrapping` tuple.
160 ///
161 /// # Examples
162 ///
163 /// ```
164 /// use std::num::Wrapping;
165 ///
166 /// let zero = Wrapping(0u32);
167 /// let one = Wrapping(1u32);
168 ///
169 /// assert_eq!(std::u32::MAX, (zero - one).0);
170 /// ```
171 #[stable(feature = "rust1", since = "1.0.0")]
172 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
173 #[repr(transparent)]
174 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
175
176 #[stable(feature = "rust1", since = "1.0.0")]
177 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
178     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179         self.0.fmt(f)
180     }
181 }
182
183 #[stable(feature = "wrapping_display", since = "1.10.0")]
184 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
185     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186         self.0.fmt(f)
187     }
188 }
189
190 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
191 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
192     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193         self.0.fmt(f)
194     }
195 }
196
197 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
198 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
199     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200         self.0.fmt(f)
201     }
202 }
203
204 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
205 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
206     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207         self.0.fmt(f)
208     }
209 }
210
211 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
212 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
213     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214         self.0.fmt(f)
215     }
216 }
217
218 // All these modules are technically private and only exposed for coretests:
219 pub mod bignum;
220 pub mod dec2flt;
221 pub mod diy_float;
222 pub mod flt2dec;
223
224 mod wrapping;
225
226 macro_rules! usize_isize_to_xe_bytes_doc {
227     () => {
228         "
229
230 **Note**: This function returns an array of length 2, 4 or 8 bytes
231 depending on the target pointer size.
232
233 "
234     };
235 }
236
237 macro_rules! usize_isize_from_xe_bytes_doc {
238     () => {
239         "
240
241 **Note**: This function takes an array of length 2, 4 or 8 bytes
242 depending on the target pointer size.
243
244 "
245     };
246 }
247
248 macro_rules! int_impl {
249     ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
250      $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
251      $reversed:expr, $le_bytes:expr, $be_bytes:expr,
252      $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
253         doc_comment! {
254             concat!("Returns the smallest value that can be represented by this integer type.
255
256 # Examples
257
258 Basic usage:
259
260 ```
261 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
262 $EndFeature, "
263 ```"),
264             #[stable(feature = "rust1", since = "1.0.0")]
265             #[inline(always)]
266             #[rustc_promotable]
267             #[cfg_attr(
268                 not(bootstrap),
269                 rustc_const_stable(feature = "const_min_value", since = "1.32.0"),
270             )]
271             pub const fn min_value() -> Self {
272                 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
273             }
274         }
275
276         doc_comment! {
277             concat!("Returns the largest value that can be represented by this integer type.
278
279 # Examples
280
281 Basic usage:
282
283 ```
284 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
285 $EndFeature, "
286 ```"),
287             #[stable(feature = "rust1", since = "1.0.0")]
288             #[inline(always)]
289             #[rustc_promotable]
290             #[cfg_attr(
291                 not(bootstrap),
292                 rustc_const_stable(feature = "const_max_value", since = "1.32.0"),
293             )]
294             pub const fn max_value() -> Self {
295                 !Self::min_value()
296             }
297         }
298
299         doc_comment! {
300             concat!("Converts a string slice in a given base to an integer.
301
302 The string is expected to be an optional `+` or `-` sign followed by digits.
303 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
304 depending on `radix`:
305
306  * `0-9`
307  * `a-z`
308  * `A-Z`
309
310 # Panics
311
312 This function panics if `radix` is not in the range from 2 to 36.
313
314 # Examples
315
316 Basic usage:
317
318 ```
319 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
320 $EndFeature, "
321 ```"),
322             #[stable(feature = "rust1", since = "1.0.0")]
323             pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
324                 from_str_radix(src, radix)
325             }
326         }
327
328         doc_comment! {
329             concat!("Returns the number of ones in the binary representation of `self`.
330
331 # Examples
332
333 Basic usage:
334
335 ```
336 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
337
338 assert_eq!(n.count_ones(), 1);",
339 $EndFeature, "
340 ```
341 "),
342             #[stable(feature = "rust1", since = "1.0.0")]
343             #[cfg_attr(
344                 not(bootstrap),
345                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
346             )]
347             #[inline]
348             pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
349         }
350
351         doc_comment! {
352             concat!("Returns the number of zeros in the binary representation of `self`.
353
354 # Examples
355
356 Basic usage:
357
358 ```
359 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
360 ```"),
361             #[stable(feature = "rust1", since = "1.0.0")]
362             #[cfg_attr(
363                 not(bootstrap),
364                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
365             )]
366             #[inline]
367             pub const fn count_zeros(self) -> u32 {
368                 (!self).count_ones()
369             }
370         }
371
372         doc_comment! {
373             concat!("Returns the number of leading zeros in the binary representation of `self`.
374
375 # Examples
376
377 Basic usage:
378
379 ```
380 ", $Feature, "let n = -1", stringify!($SelfT), ";
381
382 assert_eq!(n.leading_zeros(), 0);",
383 $EndFeature, "
384 ```"),
385             #[stable(feature = "rust1", since = "1.0.0")]
386             #[cfg_attr(
387                 not(bootstrap),
388                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
389             )]
390             #[inline]
391             pub const fn leading_zeros(self) -> u32 {
392                 (self as $UnsignedT).leading_zeros()
393             }
394         }
395
396         doc_comment! {
397             concat!("Returns the number of trailing zeros in the binary representation of `self`.
398
399 # Examples
400
401 Basic usage:
402
403 ```
404 ", $Feature, "let n = -4", stringify!($SelfT), ";
405
406 assert_eq!(n.trailing_zeros(), 2);",
407 $EndFeature, "
408 ```"),
409             #[stable(feature = "rust1", since = "1.0.0")]
410             #[cfg_attr(
411                 not(bootstrap),
412                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
413             )]
414             #[inline]
415             pub const fn trailing_zeros(self) -> u32 {
416                 (self as $UnsignedT).trailing_zeros()
417             }
418         }
419
420         doc_comment! {
421             concat!("Shifts the bits to the left by a specified amount, `n`,
422 wrapping the truncated bits to the end of the resulting integer.
423
424 Please note this isn't the same operation as the `<<` shifting operator!
425
426 # Examples
427
428 Basic usage:
429
430 ```
431 let n = ", $rot_op, stringify!($SelfT), ";
432 let m = ", $rot_result, ";
433
434 assert_eq!(n.rotate_left(", $rot, "), m);
435 ```"),
436             #[stable(feature = "rust1", since = "1.0.0")]
437             #[cfg_attr(
438                 not(bootstrap),
439                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
440             )]
441             #[must_use = "this returns the result of the operation, \
442                           without modifying the original"]
443             #[inline]
444             pub const fn rotate_left(self, n: u32) -> Self {
445                 (self as $UnsignedT).rotate_left(n) as Self
446             }
447         }
448
449         doc_comment! {
450             concat!("Shifts the bits to the right by a specified amount, `n`,
451 wrapping the truncated bits to the beginning of the resulting
452 integer.
453
454 Please note this isn't the same operation as the `>>` shifting operator!
455
456 # Examples
457
458 Basic usage:
459
460 ```
461 let n = ", $rot_result, stringify!($SelfT), ";
462 let m = ", $rot_op, ";
463
464 assert_eq!(n.rotate_right(", $rot, "), m);
465 ```"),
466             #[stable(feature = "rust1", since = "1.0.0")]
467             #[cfg_attr(
468                 not(bootstrap),
469                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
470             )]
471             #[must_use = "this returns the result of the operation, \
472                           without modifying the original"]
473             #[inline]
474             pub const fn rotate_right(self, n: u32) -> Self {
475                 (self as $UnsignedT).rotate_right(n) as Self
476             }
477         }
478
479         doc_comment! {
480             concat!("Reverses the byte order of the integer.
481
482 # Examples
483
484 Basic usage:
485
486 ```
487 let n = ", $swap_op, stringify!($SelfT), ";
488
489 let m = n.swap_bytes();
490
491 assert_eq!(m, ", $swapped, ");
492 ```"),
493             #[stable(feature = "rust1", since = "1.0.0")]
494             #[cfg_attr(
495                 not(bootstrap),
496                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
497             )]
498             #[inline]
499             pub const fn swap_bytes(self) -> Self {
500                 (self as $UnsignedT).swap_bytes() as Self
501             }
502         }
503
504         doc_comment! {
505             concat!("Reverses the bit pattern of the integer.
506
507 # Examples
508
509 Basic usage:
510
511 ```
512 let n = ", $swap_op, stringify!($SelfT), ";
513 let m = n.reverse_bits();
514
515 assert_eq!(m, ", $reversed, ");
516 ```"),
517             #[stable(feature = "reverse_bits", since = "1.37.0")]
518             #[cfg_attr(
519                 not(bootstrap),
520                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
521             )]
522             #[inline]
523             #[must_use]
524             pub const fn reverse_bits(self) -> Self {
525                 (self as $UnsignedT).reverse_bits() as Self
526             }
527         }
528
529         doc_comment! {
530             concat!("Converts an integer from big endian to the target's endianness.
531
532 On big endian this is a no-op. On little endian the bytes are swapped.
533
534 # Examples
535
536 Basic usage:
537
538 ```
539 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
540
541 if cfg!(target_endian = \"big\") {
542     assert_eq!(", stringify!($SelfT), "::from_be(n), n)
543 } else {
544     assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
545 }",
546 $EndFeature, "
547 ```"),
548             #[stable(feature = "rust1", since = "1.0.0")]
549             #[cfg_attr(
550                 not(bootstrap),
551                 rustc_const_stable(feature = "const_int_conversions", since = "1.32.0"),
552             )]
553             #[inline]
554             pub const fn from_be(x: Self) -> Self {
555                 #[cfg(target_endian = "big")]
556                 {
557                     x
558                 }
559                 #[cfg(not(target_endian = "big"))]
560                 {
561                     x.swap_bytes()
562                 }
563             }
564         }
565
566         doc_comment! {
567             concat!("Converts an integer from little endian to the target's endianness.
568
569 On little endian this is a no-op. On big endian the bytes are swapped.
570
571 # Examples
572
573 Basic usage:
574
575 ```
576 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
577
578 if cfg!(target_endian = \"little\") {
579     assert_eq!(", stringify!($SelfT), "::from_le(n), n)
580 } else {
581     assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
582 }",
583 $EndFeature, "
584 ```"),
585             #[stable(feature = "rust1", since = "1.0.0")]
586             #[cfg_attr(
587                 not(bootstrap),
588                 rustc_const_stable(feature = "const_int_conversions", since = "1.32.0"),
589             )]
590             #[inline]
591             pub const fn from_le(x: Self) -> Self {
592                 #[cfg(target_endian = "little")]
593                 {
594                     x
595                 }
596                 #[cfg(not(target_endian = "little"))]
597                 {
598                     x.swap_bytes()
599                 }
600             }
601         }
602
603         doc_comment! {
604             concat!("Converts `self` to big endian from the target's endianness.
605
606 On big endian this is a no-op. On little endian the bytes are swapped.
607
608 # Examples
609
610 Basic usage:
611
612 ```
613 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
614
615 if cfg!(target_endian = \"big\") {
616     assert_eq!(n.to_be(), n)
617 } else {
618     assert_eq!(n.to_be(), n.swap_bytes())
619 }",
620 $EndFeature, "
621 ```"),
622             #[stable(feature = "rust1", since = "1.0.0")]
623             #[cfg_attr(
624                 not(bootstrap),
625                 rustc_const_stable(feature = "const_int_conversions", since = "1.32.0"),
626             )]
627             #[inline]
628             pub const fn to_be(self) -> Self { // or not to be?
629                 #[cfg(target_endian = "big")]
630                 {
631                     self
632                 }
633                 #[cfg(not(target_endian = "big"))]
634                 {
635                     self.swap_bytes()
636                 }
637             }
638         }
639
640         doc_comment! {
641             concat!("Converts `self` to little endian from the target's endianness.
642
643 On little endian this is a no-op. On big endian the bytes are swapped.
644
645 # Examples
646
647 Basic usage:
648
649 ```
650 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
651
652 if cfg!(target_endian = \"little\") {
653     assert_eq!(n.to_le(), n)
654 } else {
655     assert_eq!(n.to_le(), n.swap_bytes())
656 }",
657 $EndFeature, "
658 ```"),
659             #[stable(feature = "rust1", since = "1.0.0")]
660             #[cfg_attr(
661                 not(bootstrap),
662                 rustc_const_stable(feature = "const_int_conversions", since = "1.32.0"),
663             )]
664             #[inline]
665             pub const fn to_le(self) -> Self {
666                 #[cfg(target_endian = "little")]
667                 {
668                     self
669                 }
670                 #[cfg(not(target_endian = "little"))]
671                 {
672                     self.swap_bytes()
673                 }
674             }
675         }
676
677         doc_comment! {
678             concat!("Checked integer addition. Computes `self + rhs`, returning `None`
679 if overflow occurred.
680
681 # Examples
682
683 Basic usage:
684
685 ```
686 ", $Feature, "assert_eq!((", stringify!($SelfT),
687 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
688 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
689 $EndFeature, "
690 ```"),
691             #[stable(feature = "rust1", since = "1.0.0")]
692             #[must_use = "this returns the result of the operation, \
693                           without modifying the original"]
694             #[inline]
695             pub fn checked_add(self, rhs: Self) -> Option<Self> {
696                 let (a, b) = self.overflowing_add(rhs);
697                 if b {None} else {Some(a)}
698             }
699         }
700
701         doc_comment! {
702             concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
703 overflow occurred.
704
705 # Examples
706
707 Basic usage:
708
709 ```
710 ", $Feature, "assert_eq!((", stringify!($SelfT),
711 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
712 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
713 $EndFeature, "
714 ```"),
715             #[stable(feature = "rust1", since = "1.0.0")]
716             #[must_use = "this returns the result of the operation, \
717                           without modifying the original"]
718             #[inline]
719             pub fn checked_sub(self, rhs: Self) -> Option<Self> {
720                 let (a, b) = self.overflowing_sub(rhs);
721                 if b {None} else {Some(a)}
722             }
723         }
724
725         doc_comment! {
726             concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
727 overflow occurred.
728
729 # Examples
730
731 Basic usage:
732
733 ```
734 ", $Feature, "assert_eq!(", stringify!($SelfT),
735 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
736 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
737 $EndFeature, "
738 ```"),
739             #[stable(feature = "rust1", since = "1.0.0")]
740             #[must_use = "this returns the result of the operation, \
741                           without modifying the original"]
742             #[inline]
743             pub fn checked_mul(self, rhs: Self) -> Option<Self> {
744                 let (a, b) = self.overflowing_mul(rhs);
745                 if b {None} else {Some(a)}
746             }
747         }
748
749         doc_comment! {
750             concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
751 or the division results in overflow.
752
753 # Examples
754
755 Basic usage:
756
757 ```
758 ", $Feature, "assert_eq!((", stringify!($SelfT),
759 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
760 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
761 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
762 $EndFeature, "
763 ```"),
764             #[stable(feature = "rust1", since = "1.0.0")]
765             #[must_use = "this returns the result of the operation, \
766                           without modifying the original"]
767             #[inline]
768             pub fn checked_div(self, rhs: Self) -> Option<Self> {
769                 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
770                     None
771                 } else {
772                     // SAFETY: div by zero and by INT_MIN have been checked above
773                     Some(unsafe { intrinsics::unchecked_div(self, rhs) })
774                 }
775             }
776         }
777
778         doc_comment! {
779             concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
780 returning `None` if `rhs == 0` or the division results in overflow.
781
782 # Examples
783
784 Basic usage:
785
786 ```
787 assert_eq!((", stringify!($SelfT),
788 "::min_value() + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
789 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euclid(-1), None);
790 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
791 ```"),
792             #[stable(feature = "euclidean_division", since = "1.38.0")]
793             #[must_use = "this returns the result of the operation, \
794                           without modifying the original"]
795             #[inline]
796             pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
797                 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
798                     None
799                 } else {
800                     Some(self.div_euclid(rhs))
801                 }
802             }
803         }
804
805         doc_comment! {
806             concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
807 `rhs == 0` or the division results in overflow.
808
809 # Examples
810
811 Basic usage:
812
813 ```
814 ", $Feature, "use std::", stringify!($SelfT), ";
815
816 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
817 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
818 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
819 $EndFeature, "
820 ```"),
821             #[stable(feature = "wrapping", since = "1.7.0")]
822             #[must_use = "this returns the result of the operation, \
823                           without modifying the original"]
824             #[inline]
825             pub fn checked_rem(self, rhs: Self) -> Option<Self> {
826                 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
827                     None
828                 } else {
829                     // SAFETY: div by zero and by INT_MIN have been checked above
830                     Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
831                 }
832             }
833         }
834
835         doc_comment! {
836             concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
837 if `rhs == 0` or the division results in overflow.
838
839 # Examples
840
841 Basic usage:
842
843 ```
844 use std::", stringify!($SelfT), ";
845
846 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
847 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
848 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
849 ```"),
850             #[stable(feature = "euclidean_division", since = "1.38.0")]
851             #[must_use = "this returns the result of the operation, \
852                           without modifying the original"]
853             #[inline]
854             pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
855                 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
856                     None
857                 } else {
858                     Some(self.rem_euclid(rhs))
859                 }
860             }
861         }
862
863         doc_comment! {
864             concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
865
866 # Examples
867
868 Basic usage:
869
870 ```
871 ", $Feature, "use std::", stringify!($SelfT), ";
872
873 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
874 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
875 $EndFeature, "
876 ```"),
877             #[stable(feature = "wrapping", since = "1.7.0")]
878             #[inline]
879             pub fn checked_neg(self) -> Option<Self> {
880                 let (a, b) = self.overflowing_neg();
881                 if b {None} else {Some(a)}
882             }
883         }
884
885         doc_comment! {
886             concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
887 than or equal to the number of bits in `self`.
888
889 # Examples
890
891 Basic usage:
892
893 ```
894 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
895 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
896 $EndFeature, "
897 ```"),
898             #[stable(feature = "wrapping", since = "1.7.0")]
899             #[must_use = "this returns the result of the operation, \
900                           without modifying the original"]
901             #[inline]
902             pub fn checked_shl(self, rhs: u32) -> Option<Self> {
903                 let (a, b) = self.overflowing_shl(rhs);
904                 if b {None} else {Some(a)}
905             }
906         }
907
908         doc_comment! {
909             concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
910 larger than or equal to the number of bits in `self`.
911
912 # Examples
913
914 Basic usage:
915
916 ```
917 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
918 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
919 $EndFeature, "
920 ```"),
921             #[stable(feature = "wrapping", since = "1.7.0")]
922             #[must_use = "this returns the result of the operation, \
923                           without modifying the original"]
924             #[inline]
925             pub fn checked_shr(self, rhs: u32) -> Option<Self> {
926                 let (a, b) = self.overflowing_shr(rhs);
927                 if b {None} else {Some(a)}
928             }
929         }
930
931         doc_comment! {
932             concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
933 `self == MIN`.
934
935 # Examples
936
937 Basic usage:
938
939 ```
940 ", $Feature, "use std::", stringify!($SelfT), ";
941
942 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
943 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
944 $EndFeature, "
945 ```"),
946             #[stable(feature = "no_panic_abs", since = "1.13.0")]
947             #[inline]
948             pub fn checked_abs(self) -> Option<Self> {
949                 if self.is_negative() {
950                     self.checked_neg()
951                 } else {
952                     Some(self)
953                 }
954             }
955         }
956
957         doc_comment! {
958             concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
959 overflow occurred.
960
961 # Examples
962
963 Basic usage:
964
965 ```
966 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
967 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
968 $EndFeature, "
969 ```"),
970
971             #[stable(feature = "no_panic_pow", since = "1.34.0")]
972             #[must_use = "this returns the result of the operation, \
973                           without modifying the original"]
974             #[inline]
975             pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
976                 let mut base = self;
977                 let mut acc: Self = 1;
978
979                 while exp > 1 {
980                     if (exp & 1) == 1 {
981                         acc = acc.checked_mul(base)?;
982                     }
983                     exp /= 2;
984                     base = base.checked_mul(base)?;
985                 }
986
987                 // Deal with the final bit of the exponent separately, since
988                 // squaring the base afterwards is not necessary and may cause a
989                 // needless overflow.
990                 if exp == 1 {
991                     acc = acc.checked_mul(base)?;
992                 }
993
994                 Some(acc)
995             }
996         }
997
998         doc_comment! {
999             concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
1000 bounds instead of overflowing.
1001
1002 # Examples
1003
1004 Basic usage:
1005
1006 ```
1007 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
1008 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
1009 "::max_value());
1010 assert_eq!(", stringify!($SelfT), "::min_value().saturating_add(-1), ", stringify!($SelfT),
1011 "::min_value());",
1012 $EndFeature, "
1013 ```"),
1014
1015             #[stable(feature = "rust1", since = "1.0.0")]
1016             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_saturating_int_methods"))]
1017             #[cfg_attr(
1018                 not(bootstrap),
1019                 rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718"),
1020             )]
1021             #[must_use = "this returns the result of the operation, \
1022                           without modifying the original"]
1023             #[inline]
1024             pub const fn saturating_add(self, rhs: Self) -> Self {
1025                 intrinsics::saturating_add(self, rhs)
1026             }
1027         }
1028
1029         doc_comment! {
1030             concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
1031 numeric bounds instead of overflowing.
1032
1033 # Examples
1034
1035 Basic usage:
1036
1037 ```
1038 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
1039 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
1040 "::min_value());
1041 assert_eq!(", stringify!($SelfT), "::max_value().saturating_sub(-1), ", stringify!($SelfT),
1042 "::max_value());",
1043 $EndFeature, "
1044 ```"),
1045             #[stable(feature = "rust1", since = "1.0.0")]
1046             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_saturating_int_methods"))]
1047             #[cfg_attr(
1048                 not(bootstrap),
1049                 rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718"),
1050             )]
1051             #[must_use = "this returns the result of the operation, \
1052                           without modifying the original"]
1053             #[inline]
1054             pub const fn saturating_sub(self, rhs: Self) -> Self {
1055                 intrinsics::saturating_sub(self, rhs)
1056             }
1057         }
1058
1059         doc_comment! {
1060             concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
1061 instead of overflowing.
1062
1063 # Examples
1064
1065 Basic usage:
1066
1067 ```
1068 ", $Feature, "#![feature(saturating_neg)]
1069 assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
1070 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
1071 assert_eq!(", stringify!($SelfT), "::min_value().saturating_neg(), ", stringify!($SelfT),
1072 "::max_value());
1073 assert_eq!(", stringify!($SelfT), "::max_value().saturating_neg(), ", stringify!($SelfT),
1074 "::min_value() + 1);",
1075 $EndFeature, "
1076 ```"),
1077
1078             #[unstable(feature = "saturating_neg", issue = "59983")]
1079             #[inline]
1080             pub fn saturating_neg(self) -> Self {
1081                 intrinsics::saturating_sub(0, self)
1082             }
1083         }
1084
1085         doc_comment! {
1086             concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1087 MIN` instead of overflowing.
1088
1089 # Examples
1090
1091 Basic usage:
1092
1093 ```
1094 ", $Feature, "#![feature(saturating_neg)]
1095 assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
1096 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
1097 assert_eq!(", stringify!($SelfT), "::min_value().saturating_abs(), ", stringify!($SelfT),
1098 "::max_value());
1099 assert_eq!((", stringify!($SelfT), "::min_value() + 1).saturating_abs(), ", stringify!($SelfT),
1100 "::max_value());",
1101 $EndFeature, "
1102 ```"),
1103
1104             #[unstable(feature = "saturating_neg", issue = "59983")]
1105             #[inline]
1106             pub fn saturating_abs(self) -> Self {
1107                 if self.is_negative() {
1108                     self.saturating_neg()
1109                 } else {
1110                     self
1111                 }
1112             }
1113         }
1114
1115         doc_comment! {
1116             concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1117 numeric bounds instead of overflowing.
1118
1119 # Examples
1120
1121 Basic usage:
1122
1123 ```
1124 ", $Feature, "use std::", stringify!($SelfT), ";
1125
1126 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1127 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1128 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1129 $EndFeature, "
1130 ```"),
1131             #[stable(feature = "wrapping", since = "1.7.0")]
1132             #[must_use = "this returns the result of the operation, \
1133                           without modifying the original"]
1134             #[inline]
1135             pub fn saturating_mul(self, rhs: Self) -> Self {
1136                 self.checked_mul(rhs).unwrap_or_else(|| {
1137                     if (self < 0) == (rhs < 0) {
1138                         Self::max_value()
1139                     } else {
1140                         Self::min_value()
1141                     }
1142                 })
1143             }
1144         }
1145
1146         doc_comment! {
1147             concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1148 saturating at the numeric bounds instead of overflowing.
1149
1150 # Examples
1151
1152 Basic usage:
1153
1154 ```
1155 ", $Feature, "use std::", stringify!($SelfT), ";
1156
1157 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1158 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1159 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1160 $EndFeature, "
1161 ```"),
1162             #[stable(feature = "no_panic_pow", since = "1.34.0")]
1163             #[must_use = "this returns the result of the operation, \
1164                           without modifying the original"]
1165             #[inline]
1166             pub fn saturating_pow(self, exp: u32) -> Self {
1167                 match self.checked_pow(exp) {
1168                     Some(x) => x,
1169                     None if self < 0 && exp % 2 == 1 => Self::min_value(),
1170                     None => Self::max_value(),
1171                 }
1172             }
1173         }
1174
1175         doc_comment! {
1176             concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1177 boundary of the type.
1178
1179 # Examples
1180
1181 Basic usage:
1182
1183 ```
1184 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1185 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
1186 "::min_value() + 1);",
1187 $EndFeature, "
1188 ```"),
1189             #[stable(feature = "rust1", since = "1.0.0")]
1190             #[cfg_attr(
1191                 not(bootstrap),
1192                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1193             )]
1194             #[must_use = "this returns the result of the operation, \
1195                           without modifying the original"]
1196             #[inline]
1197             pub const fn wrapping_add(self, rhs: Self) -> Self {
1198                 intrinsics::wrapping_add(self, rhs)
1199             }
1200         }
1201
1202         doc_comment! {
1203             concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1204 boundary of the type.
1205
1206 # Examples
1207
1208 Basic usage:
1209
1210 ```
1211 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1212 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1213 stringify!($SelfT), "::max_value());",
1214 $EndFeature, "
1215 ```"),
1216             #[stable(feature = "rust1", since = "1.0.0")]
1217             #[cfg_attr(
1218                 not(bootstrap),
1219                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1220             )]
1221             #[must_use = "this returns the result of the operation, \
1222                           without modifying the original"]
1223             #[inline]
1224             pub const fn wrapping_sub(self, rhs: Self) -> Self {
1225                 intrinsics::wrapping_sub(self, rhs)
1226             }
1227         }
1228
1229         doc_comment! {
1230             concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1231 the boundary of the type.
1232
1233 # Examples
1234
1235 Basic usage:
1236
1237 ```
1238 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1239 assert_eq!(11i8.wrapping_mul(12), -124);",
1240 $EndFeature, "
1241 ```"),
1242             #[stable(feature = "rust1", since = "1.0.0")]
1243             #[cfg_attr(
1244                 not(bootstrap),
1245                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1246             )]
1247             #[must_use = "this returns the result of the operation, \
1248                           without modifying the original"]
1249             #[inline]
1250             pub const fn wrapping_mul(self, rhs: Self) -> Self {
1251                 intrinsics::wrapping_mul(self, rhs)
1252             }
1253         }
1254
1255         doc_comment! {
1256             concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1257 boundary of the type.
1258
1259 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1260 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1261 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1262
1263 # Panics
1264
1265 This function will panic if `rhs` is 0.
1266
1267 # Examples
1268
1269 Basic usage:
1270
1271 ```
1272 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1273 assert_eq!((-128i8).wrapping_div(-1), -128);",
1274 $EndFeature, "
1275 ```"),
1276             #[stable(feature = "num_wrapping", since = "1.2.0")]
1277             #[must_use = "this returns the result of the operation, \
1278                           without modifying the original"]
1279             #[inline]
1280             pub fn wrapping_div(self, rhs: Self) -> Self {
1281                 self.overflowing_div(rhs).0
1282             }
1283         }
1284
1285         doc_comment! {
1286             concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1287 wrapping around at the boundary of the type.
1288
1289 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1290 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1291 type. In this case, this method returns `MIN` itself.
1292
1293 # Panics
1294
1295 This function will panic if `rhs` is 0.
1296
1297 # Examples
1298
1299 Basic usage:
1300
1301 ```
1302 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1303 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1304 ```"),
1305             #[stable(feature = "euclidean_division", since = "1.38.0")]
1306             #[must_use = "this returns the result of the operation, \
1307                           without modifying the original"]
1308             #[inline]
1309             pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
1310                 self.overflowing_div_euclid(rhs).0
1311             }
1312         }
1313
1314         doc_comment! {
1315             concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1316 boundary of the type.
1317
1318 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1319 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1320 this function returns `0`.
1321
1322 # Panics
1323
1324 This function will panic if `rhs` is 0.
1325
1326 # Examples
1327
1328 Basic usage:
1329
1330 ```
1331 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1332 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1333 $EndFeature, "
1334 ```"),
1335             #[stable(feature = "num_wrapping", since = "1.2.0")]
1336             #[must_use = "this returns the result of the operation, \
1337                           without modifying the original"]
1338             #[inline]
1339             pub fn wrapping_rem(self, rhs: Self) -> Self {
1340                 self.overflowing_rem(rhs).0
1341             }
1342         }
1343
1344         doc_comment! {
1345             concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1346 at the boundary of the type.
1347
1348 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1349 for the type). In this case, this method returns 0.
1350
1351 # Panics
1352
1353 This function will panic if `rhs` is 0.
1354
1355 # Examples
1356
1357 Basic usage:
1358
1359 ```
1360 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1361 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1362 ```"),
1363             #[stable(feature = "euclidean_division", since = "1.38.0")]
1364             #[must_use = "this returns the result of the operation, \
1365                           without modifying the original"]
1366             #[inline]
1367             pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1368                 self.overflowing_rem_euclid(rhs).0
1369             }
1370         }
1371
1372         doc_comment! {
1373             concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1374 of the type.
1375
1376 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1377 is the negative minimal value for the type); this is a positive value that is too large to represent
1378 in the type. In such a case, this function returns `MIN` itself.
1379
1380 # Examples
1381
1382 Basic usage:
1383
1384 ```
1385 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1386 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1387 "::min_value());",
1388 $EndFeature, "
1389 ```"),
1390             #[stable(feature = "num_wrapping", since = "1.2.0")]
1391             #[cfg_attr(
1392                 not(bootstrap),
1393                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1394             )]
1395             #[inline]
1396             pub const fn wrapping_neg(self) -> Self {
1397                 self.overflowing_neg().0
1398             }
1399         }
1400
1401         doc_comment! {
1402             concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1403 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1404
1405 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1406 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1407 The primitive integer types all implement a `rotate_left` function, which may be what you want
1408 instead.
1409
1410 # Examples
1411
1412 Basic usage:
1413
1414 ```
1415 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1416 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1417 $EndFeature, "
1418 ```"),
1419             #[stable(feature = "num_wrapping", since = "1.2.0")]
1420             #[cfg_attr(
1421                 not(bootstrap),
1422                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1423             )]
1424             #[must_use = "this returns the result of the operation, \
1425                           without modifying the original"]
1426             #[inline]
1427             pub const fn wrapping_shl(self, rhs: u32) -> Self {
1428                 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1429                 // out of bounds
1430                 unsafe {
1431                     intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1432                 }
1433             }
1434         }
1435
1436         doc_comment! {
1437             concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1438 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1439
1440 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1441 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1442 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1443 instead.
1444
1445 # Examples
1446
1447 Basic usage:
1448
1449 ```
1450 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1451 assert_eq!((-128i16).wrapping_shr(64), -128);",
1452 $EndFeature, "
1453 ```"),
1454             #[stable(feature = "num_wrapping", since = "1.2.0")]
1455             #[cfg_attr(
1456                 not(bootstrap),
1457                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1458             )]
1459             #[must_use = "this returns the result of the operation, \
1460                           without modifying the original"]
1461             #[inline]
1462             pub const fn wrapping_shr(self, rhs: u32) -> Self {
1463                 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1464                 // out of bounds
1465                 unsafe {
1466                     intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1467                 }
1468             }
1469         }
1470
1471         doc_comment! {
1472             concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1473 the boundary of the type.
1474
1475 The only case where such wrapping can occur is when one takes the absolute value of the negative
1476 minimal value for the type this is a positive value that is too large to represent in the type. In
1477 such a case, this function returns `MIN` itself.
1478
1479 # Examples
1480
1481 Basic usage:
1482
1483 ```
1484 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1485 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1486 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1487 "::min_value());
1488 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1489 $EndFeature, "
1490 ```"),
1491             #[stable(feature = "no_panic_abs", since = "1.13.0")]
1492             #[cfg_attr(
1493                 not(bootstrap),
1494                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1495             )]
1496             #[inline]
1497             pub const fn wrapping_abs(self) -> Self {
1498                 // sign is -1 (all ones) for negative numbers, 0 otherwise.
1499                 let sign = self >> ($BITS - 1);
1500                 // For positive self, sign == 0 so the expression is simply
1501                 // (self ^ 0).wrapping_sub(0) == self == abs(self).
1502                 //
1503                 // For negative self, self ^ sign == self ^ all_ones.
1504                 // But all_ones ^ self == all_ones - self == -1 - self.
1505                 // So for negative numbers, (self ^ sign).wrapping_sub(sign) is
1506                 // (-1 - self).wrapping_sub(-1) == -self == abs(self).
1507                 (self ^ sign).wrapping_sub(sign)
1508             }
1509         }
1510
1511         doc_comment! {
1512             concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1513 wrapping around at the boundary of the type.
1514
1515 # Examples
1516
1517 Basic usage:
1518
1519 ```
1520 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1521 assert_eq!(3i8.wrapping_pow(5), -13);
1522 assert_eq!(3i8.wrapping_pow(6), -39);",
1523 $EndFeature, "
1524 ```"),
1525             #[stable(feature = "no_panic_pow", since = "1.34.0")]
1526             #[must_use = "this returns the result of the operation, \
1527                           without modifying the original"]
1528             #[inline]
1529             pub fn wrapping_pow(self, mut exp: u32) -> Self {
1530                 let mut base = self;
1531                 let mut acc: Self = 1;
1532
1533                 while exp > 1 {
1534                     if (exp & 1) == 1 {
1535                         acc = acc.wrapping_mul(base);
1536                     }
1537                     exp /= 2;
1538                     base = base.wrapping_mul(base);
1539                 }
1540
1541                 // Deal with the final bit of the exponent separately, since
1542                 // squaring the base afterwards is not necessary and may cause a
1543                 // needless overflow.
1544                 if exp == 1 {
1545                     acc = acc.wrapping_mul(base);
1546                 }
1547
1548                 acc
1549             }
1550         }
1551
1552         doc_comment! {
1553             concat!("Calculates `self` + `rhs`
1554
1555 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1556 occur. If an overflow would have occurred then the wrapped value is returned.
1557
1558 # Examples
1559
1560 Basic usage:
1561
1562 ```
1563 ", $Feature, "use std::", stringify!($SelfT), ";
1564
1565 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1566 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1567 "::MIN, true));", $EndFeature, "
1568 ```"),
1569             #[stable(feature = "wrapping", since = "1.7.0")]
1570             #[cfg_attr(
1571                 not(bootstrap),
1572                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1573             )]
1574             #[must_use = "this returns the result of the operation, \
1575                           without modifying the original"]
1576             #[inline]
1577             pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1578                 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1579                 (a as Self, b)
1580             }
1581         }
1582
1583         doc_comment! {
1584             concat!("Calculates `self` - `rhs`
1585
1586 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1587 would occur. If an overflow would have occurred then the wrapped value is returned.
1588
1589 # Examples
1590
1591 Basic usage:
1592
1593 ```
1594 ", $Feature, "use std::", stringify!($SelfT), ";
1595
1596 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1597 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1598 "::MAX, true));", $EndFeature, "
1599 ```"),
1600             #[stable(feature = "wrapping", since = "1.7.0")]
1601             #[cfg_attr(
1602                 not(bootstrap),
1603                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1604             )]
1605             #[must_use = "this returns the result of the operation, \
1606                           without modifying the original"]
1607             #[inline]
1608             pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1609                 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1610                 (a as Self, b)
1611             }
1612         }
1613
1614         doc_comment! {
1615             concat!("Calculates the multiplication of `self` and `rhs`.
1616
1617 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1618 would occur. If an overflow would have occurred then the wrapped value is returned.
1619
1620 # Examples
1621
1622 Basic usage:
1623
1624 ```
1625 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1626 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1627 $EndFeature, "
1628 ```"),
1629             #[stable(feature = "wrapping", since = "1.7.0")]
1630             #[cfg_attr(
1631                 not(bootstrap),
1632                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1633             )]
1634             #[must_use = "this returns the result of the operation, \
1635                           without modifying the original"]
1636             #[inline]
1637             pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1638                 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1639                 (a as Self, b)
1640             }
1641         }
1642
1643         doc_comment! {
1644             concat!("Calculates the divisor when `self` is divided by `rhs`.
1645
1646 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1647 occur. If an overflow would occur then self is returned.
1648
1649 # Panics
1650
1651 This function will panic if `rhs` is 0.
1652
1653 # Examples
1654
1655 Basic usage:
1656
1657 ```
1658 ", $Feature, "use std::", stringify!($SelfT), ";
1659
1660 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1661 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1662 "::MIN, true));",
1663 $EndFeature, "
1664 ```"),
1665             #[inline]
1666             #[stable(feature = "wrapping", since = "1.7.0")]
1667             #[must_use = "this returns the result of the operation, \
1668                           without modifying the original"]
1669             pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1670                 if self == Self::min_value() && rhs == -1 {
1671                     (self, true)
1672                 } else {
1673                     (self / rhs, false)
1674                 }
1675             }
1676         }
1677
1678         doc_comment! {
1679             concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1680
1681 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1682 occur. If an overflow would occur then `self` is returned.
1683
1684 # Panics
1685
1686 This function will panic if `rhs` is 0.
1687
1688 # Examples
1689
1690 Basic usage:
1691
1692 ```
1693 use std::", stringify!($SelfT), ";
1694
1695 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1696 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1697 "::MIN, true));
1698 ```"),
1699             #[inline]
1700             #[stable(feature = "euclidean_division", since = "1.38.0")]
1701             #[must_use = "this returns the result of the operation, \
1702                           without modifying the original"]
1703             pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1704                 if self == Self::min_value() && rhs == -1 {
1705                     (self, true)
1706                 } else {
1707                     (self.div_euclid(rhs), false)
1708                 }
1709             }
1710         }
1711
1712         doc_comment! {
1713             concat!("Calculates the remainder when `self` is divided by `rhs`.
1714
1715 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1716 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1717
1718 # Panics
1719
1720 This function will panic if `rhs` is 0.
1721
1722 # Examples
1723
1724 Basic usage:
1725
1726 ```
1727 ", $Feature, "use std::", stringify!($SelfT), ";
1728
1729 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1730 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1731 $EndFeature, "
1732 ```"),
1733             #[inline]
1734             #[stable(feature = "wrapping", since = "1.7.0")]
1735             #[must_use = "this returns the result of the operation, \
1736                           without modifying the original"]
1737             pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1738                 if self == Self::min_value() && rhs == -1 {
1739                     (0, true)
1740                 } else {
1741                     (self % rhs, false)
1742                 }
1743             }
1744         }
1745
1746
1747         doc_comment! {
1748             concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1749
1750 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1751 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1752
1753 # Panics
1754
1755 This function will panic if `rhs` is 0.
1756
1757 # Examples
1758
1759 Basic usage:
1760
1761 ```
1762 use std::", stringify!($SelfT), ";
1763
1764 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1765 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1766 ```"),
1767             #[stable(feature = "euclidean_division", since = "1.38.0")]
1768             #[must_use = "this returns the result of the operation, \
1769                           without modifying the original"]
1770             #[inline]
1771             pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1772                 if self == Self::min_value() && rhs == -1 {
1773                     (0, true)
1774                 } else {
1775                     (self.rem_euclid(rhs), false)
1776                 }
1777             }
1778         }
1779
1780
1781         doc_comment! {
1782             concat!("Negates self, overflowing if this is equal to the minimum value.
1783
1784 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1785 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1786 minimum value will be returned again and `true` will be returned for an overflow happening.
1787
1788 # Examples
1789
1790 Basic usage:
1791
1792 ```
1793 ", $Feature, "use std::", stringify!($SelfT), ";
1794
1795 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1796 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1797 "::MIN, true));", $EndFeature, "
1798 ```"),
1799             #[inline]
1800             #[stable(feature = "wrapping", since = "1.7.0")]
1801             #[cfg_attr(
1802                 not(bootstrap),
1803                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1804             )]
1805             pub const fn overflowing_neg(self) -> (Self, bool) {
1806                 ((!self).wrapping_add(1), self == Self::min_value())
1807             }
1808         }
1809
1810         doc_comment! {
1811             concat!("Shifts self left by `rhs` bits.
1812
1813 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1814 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1815 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1816
1817 # Examples
1818
1819 Basic usage:
1820
1821 ```
1822 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1823 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1824 $EndFeature, "
1825 ```"),
1826             #[stable(feature = "wrapping", since = "1.7.0")]
1827             #[cfg_attr(
1828                 not(bootstrap),
1829                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1830             )]
1831             #[must_use = "this returns the result of the operation, \
1832                           without modifying the original"]
1833             #[inline]
1834             pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1835                 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1836             }
1837         }
1838
1839         doc_comment! {
1840             concat!("Shifts self right by `rhs` bits.
1841
1842 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1843 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1844 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1845
1846 # Examples
1847
1848 Basic usage:
1849
1850 ```
1851 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1852 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1853 $EndFeature, "
1854 ```"),
1855             #[stable(feature = "wrapping", since = "1.7.0")]
1856             #[cfg_attr(
1857                 not(bootstrap),
1858                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1859             )]
1860             #[must_use = "this returns the result of the operation, \
1861                           without modifying the original"]
1862             #[inline]
1863             pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1864                 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1865             }
1866         }
1867
1868         doc_comment! {
1869             concat!("Computes the absolute value of `self`.
1870
1871 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1872 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1873  ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1874 for an overflow happening.
1875
1876 # Examples
1877
1878 Basic usage:
1879
1880 ```
1881 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1882 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1883 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1884 "::min_value(), true));",
1885 $EndFeature, "
1886 ```"),
1887             #[stable(feature = "no_panic_abs", since = "1.13.0")]
1888             #[cfg_attr(
1889                 not(bootstrap),
1890                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1891             )]
1892             #[inline]
1893             pub const fn overflowing_abs(self) -> (Self, bool) {
1894                 (self.wrapping_abs(), self == Self::min_value())
1895             }
1896         }
1897
1898         doc_comment! {
1899             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1900
1901 Returns a tuple of the exponentiation along with a bool indicating
1902 whether an overflow happened.
1903
1904 # Examples
1905
1906 Basic usage:
1907
1908 ```
1909 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1910 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1911 $EndFeature, "
1912 ```"),
1913             #[stable(feature = "no_panic_pow", since = "1.34.0")]
1914             #[must_use = "this returns the result of the operation, \
1915                           without modifying the original"]
1916             #[inline]
1917             pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1918                 let mut base = self;
1919                 let mut acc: Self = 1;
1920                 let mut overflown = false;
1921                 // Scratch space for storing results of overflowing_mul.
1922                 let mut r;
1923
1924                 while exp > 1 {
1925                     if (exp & 1) == 1 {
1926                         r = acc.overflowing_mul(base);
1927                         acc = r.0;
1928                         overflown |= r.1;
1929                     }
1930                     exp /= 2;
1931                     r = base.overflowing_mul(base);
1932                     base = r.0;
1933                     overflown |= r.1;
1934                 }
1935
1936                 // Deal with the final bit of the exponent separately, since
1937                 // squaring the base afterwards is not necessary and may cause a
1938                 // needless overflow.
1939                 if exp == 1 {
1940                     r = acc.overflowing_mul(base);
1941                     acc = r.0;
1942                     overflown |= r.1;
1943                 }
1944
1945                 (acc, overflown)
1946             }
1947         }
1948
1949         doc_comment! {
1950             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1951
1952 # Examples
1953
1954 Basic usage:
1955
1956 ```
1957 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1958
1959 assert_eq!(x.pow(5), 32);",
1960 $EndFeature, "
1961 ```"),
1962             #[stable(feature = "rust1", since = "1.0.0")]
1963             #[must_use = "this returns the result of the operation, \
1964                           without modifying the original"]
1965             #[inline]
1966             #[rustc_inherit_overflow_checks]
1967             pub fn pow(self, mut exp: u32) -> Self {
1968                 let mut base = self;
1969                 let mut acc = 1;
1970
1971                 while exp > 1 {
1972                     if (exp & 1) == 1 {
1973                         acc = acc * base;
1974                     }
1975                     exp /= 2;
1976                     base = base * base;
1977                 }
1978
1979                 // Deal with the final bit of the exponent separately, since
1980                 // squaring the base afterwards is not necessary and may cause a
1981                 // needless overflow.
1982                 if exp == 1 {
1983                     acc = acc * base;
1984                 }
1985
1986                 acc
1987             }
1988         }
1989
1990         doc_comment! {
1991             concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1992
1993 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
1994 with `0 <= self.rem_euclid(rhs) < rhs`.
1995
1996 In other words, the result is `self / rhs` rounded to the integer `n`
1997 such that `self >= n * rhs`.
1998 If `self > 0`, this is equal to round towards zero (the default in Rust);
1999 if `self < 0`, this is equal to round towards +/- infinity.
2000
2001 # Panics
2002
2003 This function will panic if `rhs` is 0 or the division results in overflow.
2004
2005 # Examples
2006
2007 Basic usage:
2008
2009 ```
2010 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2011 let b = 4;
2012
2013 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
2014 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
2015 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
2016 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
2017 ```"),
2018             #[stable(feature = "euclidean_division", since = "1.38.0")]
2019             #[must_use = "this returns the result of the operation, \
2020                           without modifying the original"]
2021             #[inline]
2022             #[rustc_inherit_overflow_checks]
2023             pub fn div_euclid(self, rhs: Self) -> Self {
2024                 let q = self / rhs;
2025                 if self % rhs < 0 {
2026                     return if rhs > 0 { q - 1 } else { q + 1 }
2027                 }
2028                 q
2029             }
2030         }
2031
2032
2033         doc_comment! {
2034             concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
2035
2036 This is done as if by the Euclidean division algorithm -- given
2037 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
2038 `0 <= r < abs(rhs)`.
2039
2040 # Panics
2041
2042 This function will panic if `rhs` is 0 or the division results in overflow.
2043
2044 # Examples
2045
2046 Basic usage:
2047
2048 ```
2049 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2050 let b = 4;
2051
2052 assert_eq!(a.rem_euclid(b), 3);
2053 assert_eq!((-a).rem_euclid(b), 1);
2054 assert_eq!(a.rem_euclid(-b), 3);
2055 assert_eq!((-a).rem_euclid(-b), 1);
2056 ```"),
2057             #[stable(feature = "euclidean_division", since = "1.38.0")]
2058             #[must_use = "this returns the result of the operation, \
2059                           without modifying the original"]
2060             #[inline]
2061             #[rustc_inherit_overflow_checks]
2062             pub fn rem_euclid(self, rhs: Self) -> Self {
2063                 let r = self % rhs;
2064                 if r < 0 {
2065                     if rhs < 0 {
2066                         r - rhs
2067                     } else {
2068                         r + rhs
2069                     }
2070                 } else {
2071                     r
2072                 }
2073             }
2074         }
2075
2076         doc_comment! {
2077             concat!("Computes the absolute value of `self`.
2078
2079 # Overflow behavior
2080
2081 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
2082 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
2083 code in debug mode will trigger a panic on this case and optimized code will return `",
2084 stringify!($SelfT), "::min_value()` without a panic.
2085
2086 # Examples
2087
2088 Basic usage:
2089
2090 ```
2091 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
2092 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
2093 $EndFeature, "
2094 ```"),
2095             #[stable(feature = "rust1", since = "1.0.0")]
2096             #[cfg_attr(
2097                 not(bootstrap),
2098                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
2099             )]
2100             #[inline]
2101             #[rustc_inherit_overflow_checks]
2102             pub const fn abs(self) -> Self {
2103                 // Note that the #[inline] above means that the overflow
2104                 // semantics of the subtraction depend on the crate we're being
2105                 // inlined into.
2106
2107                 // sign is -1 (all ones) for negative numbers, 0 otherwise.
2108                 let sign = self >> ($BITS - 1);
2109                 // For positive self, sign == 0 so the expression is simply
2110                 // (self ^ 0) - 0 == self == abs(self).
2111                 //
2112                 // For negative self, self ^ sign == self ^ all_ones.
2113                 // But all_ones ^ self == all_ones - self == -1 - self.
2114                 // So for negative numbers, (self ^ sign) - sign is
2115                 // (-1 - self) - -1 == -self == abs(self).
2116                 //
2117                 // The subtraction overflows when self is min_value(), because
2118                 // (-1 - min_value()) - -1 is max_value() - -1 which overflows.
2119                 // This is exactly when we want self.abs() to overflow.
2120                 (self ^ sign) - sign
2121             }
2122         }
2123
2124         doc_comment! {
2125             concat!("Returns a number representing sign of `self`.
2126
2127  - `0` if the number is zero
2128  - `1` if the number is positive
2129  - `-1` if the number is negative
2130
2131 # Examples
2132
2133 Basic usage:
2134
2135 ```
2136 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
2137 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
2138 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
2139 $EndFeature, "
2140 ```"),
2141             #[stable(feature = "rust1", since = "1.0.0")]
2142             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_sign"))]
2143             #[cfg_attr(
2144                 not(bootstrap),
2145                 rustc_const_unstable(feature = "const_int_sign", issue = "53718"),
2146             )]
2147             #[inline]
2148             pub const fn signum(self) -> Self {
2149                 (self > 0) as Self - (self < 0) as Self
2150             }
2151         }
2152
2153         doc_comment! {
2154             concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2155 negative.
2156
2157 # Examples
2158
2159 Basic usage:
2160
2161 ```
2162 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2163 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2164 $EndFeature, "
2165 ```"),
2166             #[stable(feature = "rust1", since = "1.0.0")]
2167             #[cfg_attr(
2168                 not(bootstrap),
2169                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
2170             )]
2171             #[inline]
2172             pub const fn is_positive(self) -> bool { self > 0 }
2173         }
2174
2175         doc_comment! {
2176             concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2177 positive.
2178
2179 # Examples
2180
2181 Basic usage:
2182
2183 ```
2184 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2185 assert!(!10", stringify!($SelfT), ".is_negative());",
2186 $EndFeature, "
2187 ```"),
2188             #[stable(feature = "rust1", since = "1.0.0")]
2189             #[cfg_attr(
2190                 not(bootstrap),
2191                 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
2192             )]
2193             #[inline]
2194             pub const fn is_negative(self) -> bool { self < 0 }
2195         }
2196
2197         doc_comment! {
2198             concat!("Return the memory representation of this integer as a byte array in
2199 big-endian (network) byte order.
2200 ",
2201 $to_xe_bytes_doc,
2202 "
2203 # Examples
2204
2205 ```
2206 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2207 assert_eq!(bytes, ", $be_bytes, ");
2208 ```"),
2209             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2210             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
2211             #[cfg_attr(
2212                 not(bootstrap),
2213                 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
2214             )]
2215             #[inline]
2216             pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2217                 self.to_be().to_ne_bytes()
2218             }
2219         }
2220
2221 doc_comment! {
2222             concat!("Return the memory representation of this integer as a byte array in
2223 little-endian byte order.
2224 ",
2225 $to_xe_bytes_doc,
2226 "
2227 # Examples
2228
2229 ```
2230 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2231 assert_eq!(bytes, ", $le_bytes, ");
2232 ```"),
2233             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2234             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
2235             #[cfg_attr(
2236                 not(bootstrap),
2237                 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
2238             )]
2239             #[inline]
2240             pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2241                 self.to_le().to_ne_bytes()
2242             }
2243         }
2244
2245         doc_comment! {
2246             concat!("
2247 Return the memory representation of this integer as a byte array in
2248 native byte order.
2249
2250 As the target platform's native endianness is used, portable code
2251 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2252 instead.
2253 ",
2254 $to_xe_bytes_doc,
2255 "
2256 [`to_be_bytes`]: #method.to_be_bytes
2257 [`to_le_bytes`]: #method.to_le_bytes
2258
2259 # Examples
2260
2261 ```
2262 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2263 assert_eq!(
2264     bytes,
2265     if cfg!(target_endian = \"big\") {
2266         ", $be_bytes, "
2267     } else {
2268         ", $le_bytes, "
2269     }
2270 );
2271 ```"),
2272             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2273             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
2274             #[cfg_attr(
2275                 not(bootstrap),
2276                 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
2277             )]
2278             #[inline]
2279             pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2280                 // SAFETY: integers are plain old datatypes so we can always transmute them to
2281                 // arrays of bytes
2282                 unsafe { mem::transmute(self) }
2283             }
2284         }
2285
2286 doc_comment! {
2287             concat!("Create an integer value from its representation as a byte array in
2288 big endian.
2289 ",
2290 $from_xe_bytes_doc,
2291 "
2292 # Examples
2293
2294 ```
2295 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2296 assert_eq!(value, ", $swap_op, ");
2297 ```
2298
2299 When starting from a slice rather than an array, fallible conversion APIs can be used:
2300
2301 ```
2302 use std::convert::TryInto;
2303
2304 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2305     let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2306     *input = rest;
2307     ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2308 }
2309 ```"),
2310             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2311             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
2312             #[cfg_attr(
2313                 not(bootstrap),
2314                 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
2315             )]
2316             #[inline]
2317             pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2318                 Self::from_be(Self::from_ne_bytes(bytes))
2319             }
2320         }
2321
2322 doc_comment! {
2323             concat!("
2324 Create an integer value from its representation as a byte array in
2325 little endian.
2326 ",
2327 $from_xe_bytes_doc,
2328 "
2329 # Examples
2330
2331 ```
2332 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2333 assert_eq!(value, ", $swap_op, ");
2334 ```
2335
2336 When starting from a slice rather than an array, fallible conversion APIs can be used:
2337
2338 ```
2339 use std::convert::TryInto;
2340
2341 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2342     let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2343     *input = rest;
2344     ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2345 }
2346 ```"),
2347             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2348             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
2349             #[cfg_attr(
2350                 not(bootstrap),
2351                 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
2352             )]
2353             #[inline]
2354             pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2355                 Self::from_le(Self::from_ne_bytes(bytes))
2356             }
2357         }
2358
2359         doc_comment! {
2360             concat!("Create an integer value from its memory representation as a byte
2361 array in native endianness.
2362
2363 As the target platform's native endianness is used, portable code
2364 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2365 appropriate instead.
2366
2367 [`from_be_bytes`]: #method.from_be_bytes
2368 [`from_le_bytes`]: #method.from_le_bytes
2369 ",
2370 $from_xe_bytes_doc,
2371 "
2372 # Examples
2373
2374 ```
2375 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2376     ", $be_bytes, "
2377 } else {
2378     ", $le_bytes, "
2379 });
2380 assert_eq!(value, ", $swap_op, ");
2381 ```
2382
2383 When starting from a slice rather than an array, fallible conversion APIs can be used:
2384
2385 ```
2386 use std::convert::TryInto;
2387
2388 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2389     let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2390     *input = rest;
2391     ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2392 }
2393 ```"),
2394             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2395             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
2396             #[cfg_attr(
2397                 not(bootstrap),
2398                 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
2399             )]
2400             #[inline]
2401             pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2402                 // SAFETY: integers are plain old datatypes so we can always transmute to them
2403                 unsafe { mem::transmute(bytes) }
2404             }
2405         }
2406     }
2407 }
2408
2409 #[lang = "i8"]
2410 impl i8 {
2411     int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2412     "[0x12]", "[0x12]", "", "" }
2413 }
2414
2415 #[lang = "i16"]
2416 impl i16 {
2417     int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2418     "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2419 }
2420
2421 #[lang = "i32"]
2422 impl i32 {
2423     int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2424     "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2425     "[0x12, 0x34, 0x56, 0x78]", "", "" }
2426 }
2427
2428 #[lang = "i64"]
2429 impl i64 {
2430     int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2431     "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2432     "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2433     "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2434 }
2435
2436 #[lang = "i128"]
2437 impl i128 {
2438     int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2439     170141183460469231731687303715884105727, "", "", 16,
2440     "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2441     "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2442     "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2443       0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2444     "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2445       0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2446 }
2447
2448 #[cfg(target_pointer_width = "16")]
2449 #[lang = "isize"]
2450 impl isize {
2451     int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2452     "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2453     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2454 }
2455
2456 #[cfg(target_pointer_width = "32")]
2457 #[lang = "isize"]
2458 impl isize {
2459     int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2460     "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2461     "[0x12, 0x34, 0x56, 0x78]",
2462     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2463 }
2464
2465 #[cfg(target_pointer_width = "64")]
2466 #[lang = "isize"]
2467 impl isize {
2468     int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2469     12, "0xaa00000000006e1", "0x6e10aa",  "0x1234567890123456", "0x5634129078563412",
2470      "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2471      "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2472      usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2473 }
2474
2475 macro_rules! uint_impl {
2476     ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2477         $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2478         $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2479         $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2480         doc_comment! {
2481             concat!("Returns the smallest value that can be represented by this integer type.
2482
2483 # Examples
2484
2485 Basic usage:
2486
2487 ```
2488 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2489 ```"),
2490             #[stable(feature = "rust1", since = "1.0.0")]
2491             #[rustc_promotable]
2492             #[inline(always)]
2493             #[cfg_attr(
2494                 not(bootstrap),
2495                 rustc_const_stable(feature = "const_min_value", since = "1.32.0"),
2496             )]
2497             pub const fn min_value() -> Self { 0 }
2498         }
2499
2500         doc_comment! {
2501             concat!("Returns the largest value that can be represented by this integer type.
2502
2503 # Examples
2504
2505 Basic usage:
2506
2507 ```
2508 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2509 stringify!($MaxV), ");", $EndFeature, "
2510 ```"),
2511             #[stable(feature = "rust1", since = "1.0.0")]
2512             #[rustc_promotable]
2513             #[inline(always)]
2514             #[cfg_attr(
2515                 not(bootstrap),
2516                 rustc_const_stable(feature = "const_max_value", since = "1.32.0"),
2517             )]
2518             pub const fn max_value() -> Self { !0 }
2519         }
2520
2521         doc_comment! {
2522             concat!("Converts a string slice in a given base to an integer.
2523
2524 The string is expected to be an optional `+` sign
2525 followed by digits.
2526 Leading and trailing whitespace represent an error.
2527 Digits are a subset of these characters, depending on `radix`:
2528
2529 * `0-9`
2530 * `a-z`
2531 * `A-Z`
2532
2533 # Panics
2534
2535 This function panics if `radix` is not in the range from 2 to 36.
2536
2537 # Examples
2538
2539 Basic usage:
2540
2541 ```
2542 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2543 $EndFeature, "
2544 ```"),
2545             #[stable(feature = "rust1", since = "1.0.0")]
2546             pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2547                 from_str_radix(src, radix)
2548             }
2549         }
2550
2551         doc_comment! {
2552             concat!("Returns the number of ones in the binary representation of `self`.
2553
2554 # Examples
2555
2556 Basic usage:
2557
2558 ```
2559 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2560
2561 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2562 ```"),
2563             #[stable(feature = "rust1", since = "1.0.0")]
2564             #[cfg_attr(
2565                 not(bootstrap),
2566                 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2567             )]
2568             #[inline]
2569             pub const fn count_ones(self) -> u32 {
2570                 intrinsics::ctpop(self as $ActualT) as u32
2571             }
2572         }
2573
2574         doc_comment! {
2575             concat!("Returns the number of zeros in the binary representation of `self`.
2576
2577 # Examples
2578
2579 Basic usage:
2580
2581 ```
2582 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2583 ```"),
2584             #[stable(feature = "rust1", since = "1.0.0")]
2585             #[cfg_attr(
2586                 not(bootstrap),
2587                 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2588             )]
2589             #[inline]
2590             pub const fn count_zeros(self) -> u32 {
2591                 (!self).count_ones()
2592             }
2593         }
2594
2595         doc_comment! {
2596             concat!("Returns the number of leading zeros in the binary representation of `self`.
2597
2598 # Examples
2599
2600 Basic usage:
2601
2602 ```
2603 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2604
2605 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2606 ```"),
2607             #[stable(feature = "rust1", since = "1.0.0")]
2608             #[cfg_attr(
2609                 not(bootstrap),
2610                 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2611             )]
2612             #[inline]
2613             pub const fn leading_zeros(self) -> u32 {
2614                 intrinsics::ctlz(self as $ActualT) as u32
2615             }
2616         }
2617
2618         doc_comment! {
2619             concat!("Returns the number of trailing zeros in the binary representation
2620 of `self`.
2621
2622 # Examples
2623
2624 Basic usage:
2625
2626 ```
2627 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2628
2629 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2630 ```"),
2631             #[stable(feature = "rust1", since = "1.0.0")]
2632             #[cfg_attr(
2633                 not(bootstrap),
2634                 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2635             )]
2636             #[inline]
2637             pub const fn trailing_zeros(self) -> u32 {
2638                 intrinsics::cttz(self) as u32
2639             }
2640         }
2641
2642         doc_comment! {
2643             concat!("Shifts the bits to the left by a specified amount, `n`,
2644 wrapping the truncated bits to the end of the resulting integer.
2645
2646 Please note this isn't the same operation as the `<<` shifting operator!
2647
2648 # Examples
2649
2650 Basic usage:
2651
2652 ```
2653 let n = ", $rot_op, stringify!($SelfT), ";
2654 let m = ", $rot_result, ";
2655
2656 assert_eq!(n.rotate_left(", $rot, "), m);
2657 ```"),
2658             #[stable(feature = "rust1", since = "1.0.0")]
2659             #[cfg_attr(
2660                 not(bootstrap),
2661                 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2662             )]
2663             #[must_use = "this returns the result of the operation, \
2664                           without modifying the original"]
2665             #[inline]
2666             pub const fn rotate_left(self, n: u32) -> Self {
2667                 intrinsics::rotate_left(self, n as $SelfT)
2668             }
2669         }
2670
2671         doc_comment! {
2672             concat!("Shifts the bits to the right by a specified amount, `n`,
2673 wrapping the truncated bits to the beginning of the resulting
2674 integer.
2675
2676 Please note this isn't the same operation as the `>>` shifting operator!
2677
2678 # Examples
2679
2680 Basic usage:
2681
2682 ```
2683 let n = ", $rot_result, stringify!($SelfT), ";
2684 let m = ", $rot_op, ";
2685
2686 assert_eq!(n.rotate_right(", $rot, "), m);
2687 ```"),
2688             #[stable(feature = "rust1", since = "1.0.0")]
2689             #[cfg_attr(
2690                 not(bootstrap),
2691                 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2692             )]
2693             #[must_use = "this returns the result of the operation, \
2694                           without modifying the original"]
2695             #[inline]
2696             pub const fn rotate_right(self, n: u32) -> Self {
2697                 intrinsics::rotate_right(self, n as $SelfT)
2698             }
2699         }
2700
2701         doc_comment! {
2702             concat!("
2703 Reverses the byte order of the integer.
2704
2705 # Examples
2706
2707 Basic usage:
2708
2709 ```
2710 let n = ", $swap_op, stringify!($SelfT), ";
2711 let m = n.swap_bytes();
2712
2713 assert_eq!(m, ", $swapped, ");
2714 ```"),
2715             #[stable(feature = "rust1", since = "1.0.0")]
2716             #[cfg_attr(
2717                 not(bootstrap),
2718                 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2719             )]
2720             #[inline]
2721             pub const fn swap_bytes(self) -> Self {
2722                 intrinsics::bswap(self as $ActualT) as Self
2723             }
2724         }
2725
2726         doc_comment! {
2727             concat!("Reverses the bit pattern of the integer.
2728
2729 # Examples
2730
2731 Basic usage:
2732
2733 ```
2734 let n = ", $swap_op, stringify!($SelfT), ";
2735 let m = n.reverse_bits();
2736
2737 assert_eq!(m, ", $reversed, ");
2738 ```"),
2739             #[stable(feature = "reverse_bits", since = "1.37.0")]
2740             #[cfg_attr(
2741                 not(bootstrap),
2742                 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2743             )]
2744             #[inline]
2745             #[must_use]
2746             pub const fn reverse_bits(self) -> Self {
2747                 intrinsics::bitreverse(self as $ActualT) as Self
2748             }
2749         }
2750
2751         doc_comment! {
2752             concat!("Converts an integer from big endian to the target's endianness.
2753
2754 On big endian this is a no-op. On little endian the bytes are
2755 swapped.
2756
2757 # Examples
2758
2759 Basic usage:
2760
2761 ```
2762 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2763
2764 if cfg!(target_endian = \"big\") {
2765     assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2766 } else {
2767     assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2768 }", $EndFeature, "
2769 ```"),
2770             #[stable(feature = "rust1", since = "1.0.0")]
2771             #[cfg_attr(
2772                 not(bootstrap),
2773                 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2774             )]
2775             #[inline]
2776             pub const fn from_be(x: Self) -> Self {
2777                 #[cfg(target_endian = "big")]
2778                 {
2779                     x
2780                 }
2781                 #[cfg(not(target_endian = "big"))]
2782                 {
2783                     x.swap_bytes()
2784                 }
2785             }
2786         }
2787
2788         doc_comment! {
2789             concat!("Converts an integer from little endian to the target's endianness.
2790
2791 On little endian this is a no-op. On big endian the bytes are
2792 swapped.
2793
2794 # Examples
2795
2796 Basic usage:
2797
2798 ```
2799 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2800
2801 if cfg!(target_endian = \"little\") {
2802     assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2803 } else {
2804     assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2805 }", $EndFeature, "
2806 ```"),
2807             #[stable(feature = "rust1", since = "1.0.0")]
2808             #[cfg_attr(
2809                 not(bootstrap),
2810                 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2811             )]
2812             #[inline]
2813             pub const fn from_le(x: Self) -> Self {
2814                 #[cfg(target_endian = "little")]
2815                 {
2816                     x
2817                 }
2818                 #[cfg(not(target_endian = "little"))]
2819                 {
2820                     x.swap_bytes()
2821                 }
2822             }
2823         }
2824
2825         doc_comment! {
2826             concat!("Converts `self` to big endian from the target's endianness.
2827
2828 On big endian this is a no-op. On little endian the bytes are
2829 swapped.
2830
2831 # Examples
2832
2833 Basic usage:
2834
2835 ```
2836 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2837
2838 if cfg!(target_endian = \"big\") {
2839     assert_eq!(n.to_be(), n)
2840 } else {
2841     assert_eq!(n.to_be(), n.swap_bytes())
2842 }", $EndFeature, "
2843 ```"),
2844             #[stable(feature = "rust1", since = "1.0.0")]
2845             #[cfg_attr(
2846                 not(bootstrap),
2847                 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2848             )]
2849             #[inline]
2850             pub const fn to_be(self) -> Self { // or not to be?
2851                 #[cfg(target_endian = "big")]
2852                 {
2853                     self
2854                 }
2855                 #[cfg(not(target_endian = "big"))]
2856                 {
2857                     self.swap_bytes()
2858                 }
2859             }
2860         }
2861
2862         doc_comment! {
2863             concat!("Converts `self` to little endian from the target's endianness.
2864
2865 On little endian this is a no-op. On big endian the bytes are
2866 swapped.
2867
2868 # Examples
2869
2870 Basic usage:
2871
2872 ```
2873 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2874
2875 if cfg!(target_endian = \"little\") {
2876     assert_eq!(n.to_le(), n)
2877 } else {
2878     assert_eq!(n.to_le(), n.swap_bytes())
2879 }", $EndFeature, "
2880 ```"),
2881             #[stable(feature = "rust1", since = "1.0.0")]
2882             #[cfg_attr(
2883                 not(bootstrap),
2884                 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2885             )]
2886             #[inline]
2887             pub const fn to_le(self) -> Self {
2888                 #[cfg(target_endian = "little")]
2889                 {
2890                     self
2891                 }
2892                 #[cfg(not(target_endian = "little"))]
2893                 {
2894                     self.swap_bytes()
2895                 }
2896             }
2897         }
2898
2899         doc_comment! {
2900             concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2901 if overflow occurred.
2902
2903 # Examples
2904
2905 Basic usage:
2906
2907 ```
2908 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2909 "Some(", stringify!($SelfT), "::max_value() - 1));
2910 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2911 ```"),
2912             #[stable(feature = "rust1", since = "1.0.0")]
2913             #[must_use = "this returns the result of the operation, \
2914                           without modifying the original"]
2915             #[inline]
2916             pub fn checked_add(self, rhs: Self) -> Option<Self> {
2917                 let (a, b) = self.overflowing_add(rhs);
2918                 if b {None} else {Some(a)}
2919             }
2920         }
2921
2922         doc_comment! {
2923             concat!("Checked integer subtraction. Computes `self - rhs`, returning
2924 `None` if overflow occurred.
2925
2926 # Examples
2927
2928 Basic usage:
2929
2930 ```
2931 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2932 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2933 ```"),
2934             #[stable(feature = "rust1", since = "1.0.0")]
2935             #[must_use = "this returns the result of the operation, \
2936                           without modifying the original"]
2937             #[inline]
2938             pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2939                 let (a, b) = self.overflowing_sub(rhs);
2940                 if b {None} else {Some(a)}
2941             }
2942         }
2943
2944         doc_comment! {
2945             concat!("Checked integer multiplication. Computes `self * rhs`, returning
2946 `None` if overflow occurred.
2947
2948 # Examples
2949
2950 Basic usage:
2951
2952 ```
2953 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2954 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2955 ```"),
2956             #[stable(feature = "rust1", since = "1.0.0")]
2957             #[must_use = "this returns the result of the operation, \
2958                           without modifying the original"]
2959             #[inline]
2960             pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2961                 let (a, b) = self.overflowing_mul(rhs);
2962                 if b {None} else {Some(a)}
2963             }
2964         }
2965
2966         doc_comment! {
2967             concat!("Checked integer division. Computes `self / rhs`, returning `None`
2968 if `rhs == 0`.
2969
2970 # Examples
2971
2972 Basic usage:
2973
2974 ```
2975 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2976 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2977 ```"),
2978             #[stable(feature = "rust1", since = "1.0.0")]
2979             #[must_use = "this returns the result of the operation, \
2980                           without modifying the original"]
2981             #[inline]
2982             pub fn checked_div(self, rhs: Self) -> Option<Self> {
2983                 match rhs {
2984                     0 => None,
2985                     // SAFETY: div by zero has been checked above and unsigned types have no other
2986                     // failure modes for division
2987                     rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2988                 }
2989             }
2990         }
2991
2992         doc_comment! {
2993             concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2994 if `rhs == 0`.
2995
2996 # Examples
2997
2998 Basic usage:
2999
3000 ```
3001 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
3002 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
3003 ```"),
3004             #[stable(feature = "euclidean_division", since = "1.38.0")]
3005             #[must_use = "this returns the result of the operation, \
3006                           without modifying the original"]
3007             #[inline]
3008             pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
3009                 if rhs == 0 {
3010                     None
3011                 } else {
3012                     Some(self.div_euclid(rhs))
3013                 }
3014             }
3015         }
3016
3017
3018         doc_comment! {
3019             concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
3020 if `rhs == 0`.
3021
3022 # Examples
3023
3024 Basic usage:
3025
3026 ```
3027 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
3028 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
3029 ```"),
3030             #[stable(feature = "wrapping", since = "1.7.0")]
3031             #[must_use = "this returns the result of the operation, \
3032                           without modifying the original"]
3033             #[inline]
3034             pub fn checked_rem(self, rhs: Self) -> Option<Self> {
3035                 if rhs == 0 {
3036                     None
3037                 } else {
3038                     // SAFETY: div by zero has been checked above and unsigned types have no other
3039                     // failure modes for division
3040                     Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3041                 }
3042             }
3043         }
3044
3045         doc_comment! {
3046             concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3047 if `rhs == 0`.
3048
3049 # Examples
3050
3051 Basic usage:
3052
3053 ```
3054 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3055 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3056 ```"),
3057             #[stable(feature = "euclidean_division", since = "1.38.0")]
3058             #[must_use = "this returns the result of the operation, \
3059                           without modifying the original"]
3060             #[inline]
3061             pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3062                 if rhs == 0 {
3063                     None
3064                 } else {
3065                     Some(self.rem_euclid(rhs))
3066                 }
3067             }
3068         }
3069
3070         doc_comment! {
3071             concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3072 0`.
3073
3074 Note that negating any positive integer will overflow.
3075
3076 # Examples
3077
3078 Basic usage:
3079
3080 ```
3081 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3082 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3083 ```"),
3084             #[stable(feature = "wrapping", since = "1.7.0")]
3085             #[inline]
3086             pub fn checked_neg(self) -> Option<Self> {
3087                 let (a, b) = self.overflowing_neg();
3088                 if b {None} else {Some(a)}
3089             }
3090         }
3091
3092         doc_comment! {
3093             concat!("Checked shift left. Computes `self << rhs`, returning `None`
3094 if `rhs` is larger than or equal to the number of bits in `self`.
3095
3096 # Examples
3097
3098 Basic usage:
3099
3100 ```
3101 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3102 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3103 ```"),
3104             #[stable(feature = "wrapping", since = "1.7.0")]
3105             #[must_use = "this returns the result of the operation, \
3106                           without modifying the original"]
3107             #[inline]
3108             pub fn checked_shl(self, rhs: u32) -> Option<Self> {
3109                 let (a, b) = self.overflowing_shl(rhs);
3110                 if b {None} else {Some(a)}
3111             }
3112         }
3113
3114         doc_comment! {
3115             concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3116 if `rhs` is larger than or equal to the number of bits in `self`.
3117
3118 # Examples
3119
3120 Basic usage:
3121
3122 ```
3123 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3124 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3125 ```"),
3126             #[stable(feature = "wrapping", since = "1.7.0")]
3127             #[must_use = "this returns the result of the operation, \
3128                           without modifying the original"]
3129             #[inline]
3130             pub fn checked_shr(self, rhs: u32) -> Option<Self> {
3131                 let (a, b) = self.overflowing_shr(rhs);
3132                 if b {None} else {Some(a)}
3133             }
3134         }
3135
3136         doc_comment! {
3137             concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3138 overflow occurred.
3139
3140 # Examples
3141
3142 Basic usage:
3143
3144 ```
3145 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3146 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
3147 ```"),
3148             #[stable(feature = "no_panic_pow", since = "1.34.0")]
3149             #[must_use = "this returns the result of the operation, \
3150                           without modifying the original"]
3151             #[inline]
3152             pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
3153                 let mut base = self;
3154                 let mut acc: Self = 1;
3155
3156                 while exp > 1 {
3157                     if (exp & 1) == 1 {
3158                         acc = acc.checked_mul(base)?;
3159                     }
3160                     exp /= 2;
3161                     base = base.checked_mul(base)?;
3162                 }
3163
3164                 // Deal with the final bit of the exponent separately, since
3165                 // squaring the base afterwards is not necessary and may cause a
3166                 // needless overflow.
3167                 if exp == 1 {
3168                     acc = acc.checked_mul(base)?;
3169                 }
3170
3171                 Some(acc)
3172             }
3173         }
3174
3175         doc_comment! {
3176             concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3177 the numeric bounds instead of overflowing.
3178
3179 # Examples
3180
3181 Basic usage:
3182
3183 ```
3184 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3185 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
3186 ```"),
3187
3188             #[stable(feature = "rust1", since = "1.0.0")]
3189             #[must_use = "this returns the result of the operation, \
3190                           without modifying the original"]
3191             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_saturating_int_methods"))]
3192             #[cfg_attr(
3193                 not(bootstrap),
3194                 rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718"),
3195             )]
3196             #[inline]
3197             pub const fn saturating_add(self, rhs: Self) -> Self {
3198                 intrinsics::saturating_add(self, rhs)
3199             }
3200         }
3201
3202         doc_comment! {
3203             concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3204 at the numeric bounds instead of overflowing.
3205
3206 # Examples
3207
3208 Basic usage:
3209
3210 ```
3211 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3212 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3213 ```"),
3214             #[stable(feature = "rust1", since = "1.0.0")]
3215             #[must_use = "this returns the result of the operation, \
3216                           without modifying the original"]
3217             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_saturating_int_methods"))]
3218             #[cfg_attr(
3219                 not(bootstrap),
3220                 rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718"),
3221             )]
3222             #[inline]
3223             pub const fn saturating_sub(self, rhs: Self) -> Self {
3224                 intrinsics::saturating_sub(self, rhs)
3225             }
3226         }
3227
3228         doc_comment! {
3229             concat!("Saturating integer multiplication. Computes `self * rhs`,
3230 saturating at the numeric bounds instead of overflowing.
3231
3232 # Examples
3233
3234 Basic usage:
3235
3236 ```
3237 ", $Feature, "use std::", stringify!($SelfT), ";
3238
3239 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3240 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3241 "::MAX);", $EndFeature, "
3242 ```"),
3243             #[stable(feature = "wrapping", since = "1.7.0")]
3244             #[must_use = "this returns the result of the operation, \
3245                           without modifying the original"]
3246             #[inline]
3247             pub fn saturating_mul(self, rhs: Self) -> Self {
3248                 self.checked_mul(rhs).unwrap_or(Self::max_value())
3249             }
3250         }
3251
3252         doc_comment! {
3253             concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3254 saturating at the numeric bounds instead of overflowing.
3255
3256 # Examples
3257
3258 Basic usage:
3259
3260 ```
3261 ", $Feature, "use std::", stringify!($SelfT), ";
3262
3263 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3264 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3265 $EndFeature, "
3266 ```"),
3267             #[stable(feature = "no_panic_pow", since = "1.34.0")]
3268             #[must_use = "this returns the result of the operation, \
3269                           without modifying the original"]
3270             #[inline]
3271             pub fn saturating_pow(self, exp: u32) -> Self {
3272                 match self.checked_pow(exp) {
3273                     Some(x) => x,
3274                     None => Self::max_value(),
3275                 }
3276             }
3277         }
3278
3279         doc_comment! {
3280             concat!("Wrapping (modular) addition. Computes `self + rhs`,
3281 wrapping around at the boundary of the type.
3282
3283 # Examples
3284
3285 Basic usage:
3286
3287 ```
3288 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3289 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
3290 $EndFeature, "
3291 ```"),
3292             #[stable(feature = "rust1", since = "1.0.0")]
3293             #[cfg_attr(
3294                 not(bootstrap),
3295                 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3296             )]
3297             #[must_use = "this returns the result of the operation, \
3298                           without modifying the original"]
3299             #[inline]
3300             pub const fn wrapping_add(self, rhs: Self) -> Self {
3301                 intrinsics::wrapping_add(self, rhs)
3302             }
3303         }
3304
3305         doc_comment! {
3306             concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3307 wrapping around at the boundary of the type.
3308
3309 # Examples
3310
3311 Basic usage:
3312
3313 ```
3314 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3315 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
3316 $EndFeature, "
3317 ```"),
3318             #[stable(feature = "rust1", since = "1.0.0")]
3319             #[cfg_attr(
3320                 not(bootstrap),
3321                 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3322             )]
3323             #[must_use = "this returns the result of the operation, \
3324                           without modifying the original"]
3325             #[inline]
3326             pub const fn wrapping_sub(self, rhs: Self) -> Self {
3327                 intrinsics::wrapping_sub(self, rhs)
3328             }
3329         }
3330
3331         /// Wrapping (modular) multiplication. Computes `self *
3332         /// rhs`, wrapping around at the boundary of the type.
3333         ///
3334         /// # Examples
3335         ///
3336         /// Basic usage:
3337         ///
3338         /// Please note that this example is shared between integer types.
3339         /// Which explains why `u8` is used here.
3340         ///
3341         /// ```
3342         /// assert_eq!(10u8.wrapping_mul(12), 120);
3343         /// assert_eq!(25u8.wrapping_mul(12), 44);
3344         /// ```
3345         #[stable(feature = "rust1", since = "1.0.0")]
3346         #[cfg_attr(
3347             not(bootstrap),
3348             rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3349         )]
3350         #[must_use = "this returns the result of the operation, \
3351                           without modifying the original"]
3352         #[inline]
3353         pub const fn wrapping_mul(self, rhs: Self) -> Self {
3354             intrinsics::wrapping_mul(self, rhs)
3355         }
3356
3357         doc_comment! {
3358             concat!("Wrapping (modular) division. Computes `self / rhs`.
3359 Wrapped division on unsigned types is just normal division.
3360 There's no way wrapping could ever happen.
3361 This function exists, so that all operations
3362 are accounted for in the wrapping operations.
3363
3364 # Examples
3365
3366 Basic usage:
3367
3368 ```
3369 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3370 ```"),
3371             #[stable(feature = "num_wrapping", since = "1.2.0")]
3372             #[must_use = "this returns the result of the operation, \
3373                           without modifying the original"]
3374             #[inline]
3375             pub fn wrapping_div(self, rhs: Self) -> Self {
3376                 self / rhs
3377             }
3378         }
3379
3380         doc_comment! {
3381             concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3382 Wrapped division on unsigned types is just normal division.
3383 There's no way wrapping could ever happen.
3384 This function exists, so that all operations
3385 are accounted for in the wrapping operations.
3386 Since, for the positive integers, all common
3387 definitions of division are equal, this
3388 is exactly equal to `self.wrapping_div(rhs)`.
3389
3390 # Examples
3391
3392 Basic usage:
3393
3394 ```
3395 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3396 ```"),
3397             #[stable(feature = "euclidean_division", since = "1.38.0")]
3398             #[must_use = "this returns the result of the operation, \
3399                           without modifying the original"]
3400             #[inline]
3401             pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
3402                 self / rhs
3403             }
3404         }
3405
3406         doc_comment! {
3407             concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3408 Wrapped remainder calculation on unsigned types is
3409 just the regular remainder calculation.
3410 There's no way wrapping could ever happen.
3411 This function exists, so that all operations
3412 are accounted for in the wrapping operations.
3413
3414 # Examples
3415
3416 Basic usage:
3417
3418 ```
3419 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3420 ```"),
3421             #[stable(feature = "num_wrapping", since = "1.2.0")]
3422             #[must_use = "this returns the result of the operation, \
3423                           without modifying the original"]
3424             #[inline]
3425             pub fn wrapping_rem(self, rhs: Self) -> Self {
3426                 self % rhs
3427             }
3428         }
3429
3430         doc_comment! {
3431             concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3432 Wrapped modulo calculation on unsigned types is
3433 just the regular remainder calculation.
3434 There's no way wrapping could ever happen.
3435 This function exists, so that all operations
3436 are accounted for in the wrapping operations.
3437 Since, for the positive integers, all common
3438 definitions of division are equal, this
3439 is exactly equal to `self.wrapping_rem(rhs)`.
3440
3441 # Examples
3442
3443 Basic usage:
3444
3445 ```
3446 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3447 ```"),
3448             #[stable(feature = "euclidean_division", since = "1.38.0")]
3449             #[must_use = "this returns the result of the operation, \
3450                           without modifying the original"]
3451             #[inline]
3452             pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3453                 self % rhs
3454             }
3455         }
3456
3457         /// Wrapping (modular) negation. Computes `-self`,
3458         /// wrapping around at the boundary of the type.
3459         ///
3460         /// Since unsigned types do not have negative equivalents
3461         /// all applications of this function will wrap (except for `-0`).
3462         /// For values smaller than the corresponding signed type's maximum
3463         /// the result is the same as casting the corresponding signed value.
3464         /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3465         /// `MAX` is the corresponding signed type's maximum.
3466         ///
3467         /// # Examples
3468         ///
3469         /// Basic usage:
3470         ///
3471         /// Please note that this example is shared between integer types.
3472         /// Which explains why `i8` is used here.
3473         ///
3474         /// ```
3475         /// assert_eq!(100i8.wrapping_neg(), -100);
3476         /// assert_eq!((-128i8).wrapping_neg(), -128);
3477         /// ```
3478         #[stable(feature = "num_wrapping", since = "1.2.0")]
3479         #[cfg_attr(
3480             not(bootstrap),
3481             rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3482         )]
3483         #[inline]
3484         pub const fn wrapping_neg(self) -> Self {
3485             self.overflowing_neg().0
3486         }
3487
3488         doc_comment! {
3489             concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3490 where `mask` removes any high-order bits of `rhs` that
3491 would cause the shift to exceed the bitwidth of the type.
3492
3493 Note that this is *not* the same as a rotate-left; the
3494 RHS of a wrapping shift-left is restricted to the range
3495 of the type, rather than the bits shifted out of the LHS
3496 being returned to the other end. The primitive integer
3497 types all implement a `rotate_left` function, which may
3498 be what you want instead.
3499
3500 # Examples
3501
3502 Basic usage:
3503
3504 ```
3505 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3506 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3507 ```"),
3508             #[stable(feature = "num_wrapping", since = "1.2.0")]
3509             #[cfg_attr(
3510                 not(bootstrap),
3511                 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3512             )]
3513             #[must_use = "this returns the result of the operation, \
3514                           without modifying the original"]
3515             #[inline]
3516             pub const fn wrapping_shl(self, rhs: u32) -> Self {
3517                 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3518                 // out of bounds
3519                 unsafe {
3520                     intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3521                 }
3522             }
3523         }
3524
3525         doc_comment! {
3526             concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3527 where `mask` removes any high-order bits of `rhs` that
3528 would cause the shift to exceed the bitwidth of the type.
3529
3530 Note that this is *not* the same as a rotate-right; the
3531 RHS of a wrapping shift-right is restricted to the range
3532 of the type, rather than the bits shifted out of the LHS
3533 being returned to the other end. The primitive integer
3534 types all implement a `rotate_right` function, which may
3535 be what you want instead.
3536
3537 # Examples
3538
3539 Basic usage:
3540
3541 ```
3542 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3543 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3544 ```"),
3545             #[stable(feature = "num_wrapping", since = "1.2.0")]
3546             #[cfg_attr(
3547                 not(bootstrap),
3548                 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3549             )]
3550             #[must_use = "this returns the result of the operation, \
3551                           without modifying the original"]
3552             #[inline]
3553             pub const fn wrapping_shr(self, rhs: u32) -> Self {
3554                 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3555                 // out of bounds
3556                 unsafe {
3557                     intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3558                 }
3559             }
3560         }
3561
3562         doc_comment! {
3563             concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3564 wrapping around at the boundary of the type.
3565
3566 # Examples
3567
3568 Basic usage:
3569
3570 ```
3571 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3572 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3573 ```"),
3574             #[stable(feature = "no_panic_pow", since = "1.34.0")]
3575             #[must_use = "this returns the result of the operation, \
3576                           without modifying the original"]
3577             #[inline]
3578             pub fn wrapping_pow(self, mut exp: u32) -> Self {
3579                 let mut base = self;
3580                 let mut acc: Self = 1;
3581
3582                 while exp > 1 {
3583                     if (exp & 1) == 1 {
3584                         acc = acc.wrapping_mul(base);
3585                     }
3586                     exp /= 2;
3587                     base = base.wrapping_mul(base);
3588                 }
3589
3590                 // Deal with the final bit of the exponent separately, since
3591                 // squaring the base afterwards is not necessary and may cause a
3592                 // needless overflow.
3593                 if exp == 1 {
3594                     acc = acc.wrapping_mul(base);
3595                 }
3596
3597                 acc
3598             }
3599         }
3600
3601         doc_comment! {
3602             concat!("Calculates `self` + `rhs`
3603
3604 Returns a tuple of the addition along with a boolean indicating
3605 whether an arithmetic overflow would occur. If an overflow would
3606 have occurred then the wrapped value is returned.
3607
3608 # Examples
3609
3610 Basic usage
3611
3612 ```
3613 ", $Feature, "use std::", stringify!($SelfT), ";
3614
3615 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3616 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3617 ```"),
3618             #[stable(feature = "wrapping", since = "1.7.0")]
3619             #[cfg_attr(
3620                 not(bootstrap),
3621                 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3622             )]
3623             #[must_use = "this returns the result of the operation, \
3624                           without modifying the original"]
3625             #[inline]
3626             pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3627                 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3628                 (a as Self, b)
3629             }
3630         }
3631
3632         doc_comment! {
3633             concat!("Calculates `self` - `rhs`
3634
3635 Returns a tuple of the subtraction along with a boolean indicating
3636 whether an arithmetic overflow would occur. If an overflow would
3637 have occurred then the wrapped value is returned.
3638
3639 # Examples
3640
3641 Basic usage
3642
3643 ```
3644 ", $Feature, "use std::", stringify!($SelfT), ";
3645
3646 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3647 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3648 $EndFeature, "
3649 ```"),
3650             #[stable(feature = "wrapping", since = "1.7.0")]
3651             #[cfg_attr(
3652                 not(bootstrap),
3653                 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3654             )]
3655             #[must_use = "this returns the result of the operation, \
3656                           without modifying the original"]
3657             #[inline]
3658             pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3659                 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3660                 (a as Self, b)
3661             }
3662         }
3663
3664         /// Calculates the multiplication of `self` and `rhs`.
3665         ///
3666         /// Returns a tuple of the multiplication along with a boolean
3667         /// indicating whether an arithmetic overflow would occur. If an
3668         /// overflow would have occurred then the wrapped value is returned.
3669         ///
3670         /// # Examples
3671         ///
3672         /// Basic usage:
3673         ///
3674         /// Please note that this example is shared between integer types.
3675         /// Which explains why `u32` is used here.
3676         ///
3677         /// ```
3678         /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3679         /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3680         /// ```
3681         #[stable(feature = "wrapping", since = "1.7.0")]
3682         #[cfg_attr(
3683             not(bootstrap),
3684             rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3685         )]
3686         #[must_use = "this returns the result of the operation, \
3687                           without modifying the original"]
3688         #[inline]
3689         pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3690             let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3691             (a as Self, b)
3692         }
3693
3694         doc_comment! {
3695             concat!("Calculates the divisor when `self` is divided by `rhs`.
3696
3697 Returns a tuple of the divisor along with a boolean indicating
3698 whether an arithmetic overflow would occur. Note that for unsigned
3699 integers overflow never occurs, so the second value is always
3700 `false`.
3701
3702 # Panics
3703
3704 This function will panic if `rhs` is 0.
3705
3706 # Examples
3707
3708 Basic usage
3709
3710 ```
3711 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3712 ```"),
3713             #[inline]
3714             #[stable(feature = "wrapping", since = "1.7.0")]
3715             #[must_use = "this returns the result of the operation, \
3716                           without modifying the original"]
3717             pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3718                 (self / rhs, false)
3719             }
3720         }
3721
3722         doc_comment! {
3723             concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3724
3725 Returns a tuple of the divisor along with a boolean indicating
3726 whether an arithmetic overflow would occur. Note that for unsigned
3727 integers overflow never occurs, so the second value is always
3728 `false`.
3729 Since, for the positive integers, all common
3730 definitions of division are equal, this
3731 is exactly equal to `self.overflowing_div(rhs)`.
3732
3733 # Panics
3734
3735 This function will panic if `rhs` is 0.
3736
3737 # Examples
3738
3739 Basic usage
3740
3741 ```
3742 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3743 ```"),
3744             #[inline]
3745             #[stable(feature = "euclidean_division", since = "1.38.0")]
3746             #[must_use = "this returns the result of the operation, \
3747                           without modifying the original"]
3748             pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3749                 (self / rhs, false)
3750             }
3751         }
3752
3753         doc_comment! {
3754             concat!("Calculates the remainder when `self` is divided by `rhs`.
3755
3756 Returns a tuple of the remainder after dividing along with a boolean
3757 indicating whether an arithmetic overflow would occur. Note that for
3758 unsigned integers overflow never occurs, so the second value is
3759 always `false`.
3760
3761 # Panics
3762
3763 This function will panic if `rhs` is 0.
3764
3765 # Examples
3766
3767 Basic usage
3768
3769 ```
3770 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3771 ```"),
3772             #[inline]
3773             #[stable(feature = "wrapping", since = "1.7.0")]
3774             #[must_use = "this returns the result of the operation, \
3775                           without modifying the original"]
3776             pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3777                 (self % rhs, false)
3778             }
3779         }
3780
3781         doc_comment! {
3782             concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3783
3784 Returns a tuple of the modulo after dividing along with a boolean
3785 indicating whether an arithmetic overflow would occur. Note that for
3786 unsigned integers overflow never occurs, so the second value is
3787 always `false`.
3788 Since, for the positive integers, all common
3789 definitions of division are equal, this operation
3790 is exactly equal to `self.overflowing_rem(rhs)`.
3791
3792 # Panics
3793
3794 This function will panic if `rhs` is 0.
3795
3796 # Examples
3797
3798 Basic usage
3799
3800 ```
3801 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3802 ```"),
3803             #[inline]
3804             #[stable(feature = "euclidean_division", since = "1.38.0")]
3805             #[must_use = "this returns the result of the operation, \
3806                           without modifying the original"]
3807             pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3808                 (self % rhs, false)
3809             }
3810         }
3811
3812         doc_comment! {
3813             concat!("Negates self in an overflowing fashion.
3814
3815 Returns `!self + 1` using wrapping operations to return the value
3816 that represents the negation of this unsigned value. Note that for
3817 positive unsigned values overflow always occurs, but negating 0 does
3818 not overflow.
3819
3820 # Examples
3821
3822 Basic usage
3823
3824 ```
3825 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3826 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3827 ", true));", $EndFeature, "
3828 ```"),
3829             #[inline]
3830             #[stable(feature = "wrapping", since = "1.7.0")]
3831             #[cfg_attr(
3832                 not(bootstrap),
3833                 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3834             )]
3835             pub const fn overflowing_neg(self) -> (Self, bool) {
3836                 ((!self).wrapping_add(1), self != 0)
3837             }
3838         }
3839
3840         doc_comment! {
3841             concat!("Shifts self left by `rhs` bits.
3842
3843 Returns a tuple of the shifted version of self along with a boolean
3844 indicating whether the shift value was larger than or equal to the
3845 number of bits. If the shift value is too large, then value is
3846 masked (N-1) where N is the number of bits, and this value is then
3847 used to perform the shift.
3848
3849 # Examples
3850
3851 Basic usage
3852
3853 ```
3854 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3855 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3856 ```"),
3857             #[stable(feature = "wrapping", since = "1.7.0")]
3858             #[cfg_attr(
3859                 not(bootstrap),
3860                 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3861             )]
3862             #[must_use = "this returns the result of the operation, \
3863                           without modifying the original"]
3864             #[inline]
3865             pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3866                 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3867             }
3868         }
3869
3870         doc_comment! {
3871             concat!("Shifts self right by `rhs` bits.
3872
3873 Returns a tuple of the shifted version of self along with a boolean
3874 indicating whether the shift value was larger than or equal to the
3875 number of bits. If the shift value is too large, then value is
3876 masked (N-1) where N is the number of bits, and this value is then
3877 used to perform the shift.
3878
3879 # Examples
3880
3881 Basic usage
3882
3883 ```
3884 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3885 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3886 ```"),
3887             #[stable(feature = "wrapping", since = "1.7.0")]
3888             #[cfg_attr(
3889                 not(bootstrap),
3890                 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3891             )]
3892             #[must_use = "this returns the result of the operation, \
3893                           without modifying the original"]
3894             #[inline]
3895             pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3896                 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3897             }
3898         }
3899
3900         doc_comment! {
3901             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3902
3903 Returns a tuple of the exponentiation along with a bool indicating
3904 whether an overflow happened.
3905
3906 # Examples
3907
3908 Basic usage:
3909
3910 ```
3911 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3912 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3913 ```"),
3914             #[stable(feature = "no_panic_pow", since = "1.34.0")]
3915             #[must_use = "this returns the result of the operation, \
3916                           without modifying the original"]
3917             #[inline]
3918             pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3919                 let mut base = self;
3920                 let mut acc: Self = 1;
3921                 let mut overflown = false;
3922                 // Scratch space for storing results of overflowing_mul.
3923                 let mut r;
3924
3925                 while exp > 1 {
3926                     if (exp & 1) == 1 {
3927                         r = acc.overflowing_mul(base);
3928                         acc = r.0;
3929                         overflown |= r.1;
3930                     }
3931                     exp /= 2;
3932                     r = base.overflowing_mul(base);
3933                     base = r.0;
3934                     overflown |= r.1;
3935                 }
3936
3937                 // Deal with the final bit of the exponent separately, since
3938                 // squaring the base afterwards is not necessary and may cause a
3939                 // needless overflow.
3940                 if exp == 1 {
3941                     r = acc.overflowing_mul(base);
3942                     acc = r.0;
3943                     overflown |= r.1;
3944                 }
3945
3946                 (acc, overflown)
3947             }
3948         }
3949
3950         doc_comment! {
3951             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3952
3953 # Examples
3954
3955 Basic usage:
3956
3957 ```
3958 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3959 ```"),
3960         #[stable(feature = "rust1", since = "1.0.0")]
3961         #[must_use = "this returns the result of the operation, \
3962                           without modifying the original"]
3963         #[inline]
3964         #[rustc_inherit_overflow_checks]
3965         pub fn pow(self, mut exp: u32) -> Self {
3966             let mut base = self;
3967             let mut acc = 1;
3968
3969             while exp > 1 {
3970                 if (exp & 1) == 1 {
3971                     acc = acc * base;
3972                 }
3973                 exp /= 2;
3974                 base = base * base;
3975             }
3976
3977             // Deal with the final bit of the exponent separately, since
3978             // squaring the base afterwards is not necessary and may cause a
3979             // needless overflow.
3980             if exp == 1 {
3981                 acc = acc * base;
3982             }
3983
3984             acc
3985         }
3986     }
3987
3988             doc_comment! {
3989             concat!("Performs Euclidean division.
3990
3991 Since, for the positive integers, all common
3992 definitions of division are equal, this
3993 is exactly equal to `self / rhs`.
3994
3995 # Panics
3996
3997 This function will panic if `rhs` is 0.
3998
3999 # Examples
4000
4001 Basic usage:
4002
4003 ```
4004 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
4005 ```"),
4006             #[stable(feature = "euclidean_division", since = "1.38.0")]
4007             #[must_use = "this returns the result of the operation, \
4008                           without modifying the original"]
4009             #[inline]
4010             #[rustc_inherit_overflow_checks]
4011             pub fn div_euclid(self, rhs: Self) -> Self {
4012                 self / rhs
4013             }
4014         }
4015
4016
4017         doc_comment! {
4018             concat!("Calculates the least remainder of `self (mod rhs)`.
4019
4020 Since, for the positive integers, all common
4021 definitions of division are equal, this
4022 is exactly equal to `self % rhs`.
4023
4024 # Panics
4025
4026 This function will panic if `rhs` is 0.
4027
4028 # Examples
4029
4030 Basic usage:
4031
4032 ```
4033 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
4034 ```"),
4035             #[stable(feature = "euclidean_division", since = "1.38.0")]
4036             #[must_use = "this returns the result of the operation, \
4037                           without modifying the original"]
4038             #[inline]
4039             #[rustc_inherit_overflow_checks]
4040             pub fn rem_euclid(self, rhs: Self) -> Self {
4041                 self % rhs
4042             }
4043         }
4044
4045         doc_comment! {
4046             concat!("Returns `true` if and only if `self == 2^k` for some `k`.
4047
4048 # Examples
4049
4050 Basic usage:
4051
4052 ```
4053 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
4054 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
4055 ```"),
4056             #[stable(feature = "rust1", since = "1.0.0")]
4057             #[cfg_attr(
4058                 not(bootstrap),
4059                 rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0"),
4060             )]
4061             #[inline]
4062             pub const fn is_power_of_two(self) -> bool {
4063                 self.count_ones() == 1
4064             }
4065         }
4066
4067         // Returns one less than next power of two.
4068         // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
4069         //
4070         // 8u8.one_less_than_next_power_of_two() == 7
4071         // 6u8.one_less_than_next_power_of_two() == 7
4072         //
4073         // This method cannot overflow, as in the `next_power_of_two`
4074         // overflow cases it instead ends up returning the maximum value
4075         // of the type, and can return 0 for 0.
4076         #[inline]
4077         fn one_less_than_next_power_of_two(self) -> Self {
4078             if self <= 1 { return 0; }
4079
4080             let p = self - 1;
4081             // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4082             // That means the shift is always in-bounds, and some processors
4083             // (such as intel pre-haswell) have more efficient ctlz
4084             // intrinsics when the argument is non-zero.
4085             let z = unsafe { intrinsics::ctlz_nonzero(p) };
4086             <$SelfT>::max_value() >> z
4087         }
4088
4089         doc_comment! {
4090             concat!("Returns the smallest power of two greater than or equal to `self`.
4091
4092 When return value overflows (i.e., `self > (1 << (N-1))` for type
4093 `uN`), it panics in debug mode and return value is wrapped to 0 in
4094 release mode (the only situation in which method can return 0).
4095
4096 # Examples
4097
4098 Basic usage:
4099
4100 ```
4101 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4102 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4103 ```"),
4104             #[stable(feature = "rust1", since = "1.0.0")]
4105             #[inline]
4106             pub fn next_power_of_two(self) -> Self {
4107                 // Call the trait to get overflow checks
4108                 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
4109             }
4110         }
4111
4112         doc_comment! {
4113             concat!("Returns the smallest power of two greater than or equal to `n`. If
4114 the next power of two is greater than the type's maximum value,
4115 `None` is returned, otherwise the power of two is wrapped in `Some`.
4116
4117 # Examples
4118
4119 Basic usage:
4120
4121 ```
4122 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4123 ".checked_next_power_of_two(), Some(2));
4124 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4125 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
4126 $EndFeature, "
4127 ```"),
4128             #[inline]
4129             #[stable(feature = "rust1", since = "1.0.0")]
4130             pub fn checked_next_power_of_two(self) -> Option<Self> {
4131                 self.one_less_than_next_power_of_two().checked_add(1)
4132             }
4133         }
4134
4135         doc_comment! {
4136             concat!("Returns the smallest power of two greater than or equal to `n`. If
4137 the next power of two is greater than the type's maximum value,
4138 the return value is wrapped to `0`.
4139
4140 # Examples
4141
4142 Basic usage:
4143
4144 ```
4145 #![feature(wrapping_next_power_of_two)]
4146 ", $Feature, "
4147 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4148 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4149 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
4150 $EndFeature, "
4151 ```"),
4152             #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4153                        reason = "needs decision on wrapping behaviour")]
4154             pub fn wrapping_next_power_of_two(self) -> Self {
4155                 self.one_less_than_next_power_of_two().wrapping_add(1)
4156             }
4157         }
4158
4159         doc_comment! {
4160             concat!("Return the memory representation of this integer as a byte array in
4161 big-endian (network) byte order.
4162 ",
4163 $to_xe_bytes_doc,
4164 "
4165 # Examples
4166
4167 ```
4168 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4169 assert_eq!(bytes, ", $be_bytes, ");
4170 ```"),
4171             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4172             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
4173             #[cfg_attr(
4174                 not(bootstrap),
4175                 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
4176             )]
4177             #[inline]
4178             pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4179                 self.to_be().to_ne_bytes()
4180             }
4181         }
4182
4183         doc_comment! {
4184             concat!("Return the memory representation of this integer as a byte array in
4185 little-endian byte order.
4186 ",
4187 $to_xe_bytes_doc,
4188 "
4189 # Examples
4190
4191 ```
4192 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4193 assert_eq!(bytes, ", $le_bytes, ");
4194 ```"),
4195             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4196             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
4197             #[cfg_attr(
4198                 not(bootstrap),
4199                 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
4200             )]
4201             #[inline]
4202             pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4203                 self.to_le().to_ne_bytes()
4204             }
4205         }
4206
4207         doc_comment! {
4208             concat!("
4209 Return the memory representation of this integer as a byte array in
4210 native byte order.
4211
4212 As the target platform's native endianness is used, portable code
4213 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4214 instead.
4215 ",
4216 $to_xe_bytes_doc,
4217 "
4218 [`to_be_bytes`]: #method.to_be_bytes
4219 [`to_le_bytes`]: #method.to_le_bytes
4220
4221 # Examples
4222
4223 ```
4224 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4225 assert_eq!(
4226     bytes,
4227     if cfg!(target_endian = \"big\") {
4228         ", $be_bytes, "
4229     } else {
4230         ", $le_bytes, "
4231     }
4232 );
4233 ```"),
4234             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4235             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
4236             #[cfg_attr(
4237                 not(bootstrap),
4238                 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
4239             )]
4240             #[inline]
4241             pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4242                 // SAFETY: integers are plain old datatypes so we can always transmute them to
4243                 // arrays of bytes
4244                 unsafe { mem::transmute(self) }
4245             }
4246         }
4247
4248         doc_comment! {
4249             concat!("Create an integer value from its representation as a byte array in
4250 big endian.
4251 ",
4252 $from_xe_bytes_doc,
4253 "
4254 # Examples
4255
4256 ```
4257 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4258 assert_eq!(value, ", $swap_op, ");
4259 ```
4260
4261 When starting from a slice rather than an array, fallible conversion APIs can be used:
4262
4263 ```
4264 use std::convert::TryInto;
4265
4266 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4267     let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4268     *input = rest;
4269     ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4270 }
4271 ```"),
4272             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4273             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
4274             #[cfg_attr(
4275                 not(bootstrap),
4276                 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
4277             )]
4278             #[inline]
4279             pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4280                 Self::from_be(Self::from_ne_bytes(bytes))
4281             }
4282         }
4283
4284         doc_comment! {
4285             concat!("
4286 Create an integer value from its representation as a byte array in
4287 little endian.
4288 ",
4289 $from_xe_bytes_doc,
4290 "
4291 # Examples
4292
4293 ```
4294 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4295 assert_eq!(value, ", $swap_op, ");
4296 ```
4297
4298 When starting from a slice rather than an array, fallible conversion APIs can be used:
4299
4300 ```
4301 use std::convert::TryInto;
4302
4303 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4304     let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4305     *input = rest;
4306     ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4307 }
4308 ```"),
4309             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4310             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
4311             #[cfg_attr(
4312                 not(bootstrap),
4313                 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
4314             )]
4315             #[inline]
4316             pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4317                 Self::from_le(Self::from_ne_bytes(bytes))
4318             }
4319         }
4320
4321         doc_comment! {
4322             concat!("Create an integer value from its memory representation as a byte
4323 array in native endianness.
4324
4325 As the target platform's native endianness is used, portable code
4326 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4327 appropriate instead.
4328
4329 [`from_be_bytes`]: #method.from_be_bytes
4330 [`from_le_bytes`]: #method.from_le_bytes
4331 ",
4332 $from_xe_bytes_doc,
4333 "
4334 # Examples
4335
4336 ```
4337 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4338     ", $be_bytes, "
4339 } else {
4340     ", $le_bytes, "
4341 });
4342 assert_eq!(value, ", $swap_op, ");
4343 ```
4344
4345 When starting from a slice rather than an array, fallible conversion APIs can be used:
4346
4347 ```
4348 use std::convert::TryInto;
4349
4350 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4351     let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4352     *input = rest;
4353     ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4354 }
4355 ```"),
4356             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4357             #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
4358             #[cfg_attr(
4359                 not(bootstrap),
4360                 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
4361             )]
4362             #[inline]
4363             pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4364                 // SAFETY: integers are plain old datatypes so we can always transmute to them
4365                 unsafe { mem::transmute(bytes) }
4366             }
4367         }
4368     }
4369 }
4370
4371 #[lang = "u8"]
4372 impl u8 {
4373     uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4374     "[0x12]", "", "" }
4375
4376     /// Checks if the value is within the ASCII range.
4377     ///
4378     /// # Examples
4379     ///
4380     /// ```
4381     /// let ascii = 97u8;
4382     /// let non_ascii = 150u8;
4383     ///
4384     /// assert!(ascii.is_ascii());
4385     /// assert!(!non_ascii.is_ascii());
4386     /// ```
4387     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4388     #[inline]
4389     pub fn is_ascii(&self) -> bool {
4390         *self & 128 == 0
4391     }
4392
4393     /// Makes a copy of the value in its ASCII upper case equivalent.
4394     ///
4395     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4396     /// but non-ASCII letters are unchanged.
4397     ///
4398     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4399     ///
4400     /// # Examples
4401     ///
4402     /// ```
4403     /// let lowercase_a = 97u8;
4404     ///
4405     /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4406     /// ```
4407     ///
4408     /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4409     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4410     #[inline]
4411     pub fn to_ascii_uppercase(&self) -> u8 {
4412         // Unset the fith bit if this is a lowercase letter
4413         *self & !((self.is_ascii_lowercase() as u8) << 5)
4414     }
4415
4416     /// Makes a copy of the value in its ASCII lower case equivalent.
4417     ///
4418     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4419     /// but non-ASCII letters are unchanged.
4420     ///
4421     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4422     ///
4423     /// # Examples
4424     ///
4425     /// ```
4426     /// let uppercase_a = 65u8;
4427     ///
4428     /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4429     /// ```
4430     ///
4431     /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4432     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4433     #[inline]
4434     pub fn to_ascii_lowercase(&self) -> u8 {
4435         // Set the fith bit if this is an uppercase letter
4436         *self | ((self.is_ascii_uppercase() as u8) << 5)
4437     }
4438
4439     /// Checks that two values are an ASCII case-insensitive match.
4440     ///
4441     /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4442     ///
4443     /// # Examples
4444     ///
4445     /// ```
4446     /// let lowercase_a = 97u8;
4447     /// let uppercase_a = 65u8;
4448     ///
4449     /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4450     /// ```
4451     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4452     #[inline]
4453     pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4454         self.to_ascii_lowercase() == other.to_ascii_lowercase()
4455     }
4456
4457     /// Converts this value to its ASCII upper case equivalent in-place.
4458     ///
4459     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4460     /// but non-ASCII letters are unchanged.
4461     ///
4462     /// To return a new uppercased value without modifying the existing one, use
4463     /// [`to_ascii_uppercase`].
4464     ///
4465     /// # Examples
4466     ///
4467     /// ```
4468     /// let mut byte = b'a';
4469     ///
4470     /// byte.make_ascii_uppercase();
4471     ///
4472     /// assert_eq!(b'A', byte);
4473     /// ```
4474     ///
4475     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4476     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4477     #[inline]
4478     pub fn make_ascii_uppercase(&mut self) {
4479         *self = self.to_ascii_uppercase();
4480     }
4481
4482     /// Converts this value to its ASCII lower case equivalent in-place.
4483     ///
4484     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4485     /// but non-ASCII letters are unchanged.
4486     ///
4487     /// To return a new lowercased value without modifying the existing one, use
4488     /// [`to_ascii_lowercase`].
4489     ///
4490     /// # Examples
4491     ///
4492     /// ```
4493     /// let mut byte = b'A';
4494     ///
4495     /// byte.make_ascii_lowercase();
4496     ///
4497     /// assert_eq!(b'a', byte);
4498     /// ```
4499     ///
4500     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4501     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4502     #[inline]
4503     pub fn make_ascii_lowercase(&mut self) {
4504         *self = self.to_ascii_lowercase();
4505     }
4506
4507     /// Checks if the value is an ASCII alphabetic character:
4508     ///
4509     /// - U+0041 'A' ..= U+005A 'Z', or
4510     /// - U+0061 'a' ..= U+007A 'z'.
4511     ///
4512     /// # Examples
4513     ///
4514     /// ```
4515     /// let uppercase_a = b'A';
4516     /// let uppercase_g = b'G';
4517     /// let a = b'a';
4518     /// let g = b'g';
4519     /// let zero = b'0';
4520     /// let percent = b'%';
4521     /// let space = b' ';
4522     /// let lf = b'\n';
4523     /// let esc = 0x1b_u8;
4524     ///
4525     /// assert!(uppercase_a.is_ascii_alphabetic());
4526     /// assert!(uppercase_g.is_ascii_alphabetic());
4527     /// assert!(a.is_ascii_alphabetic());
4528     /// assert!(g.is_ascii_alphabetic());
4529     /// assert!(!zero.is_ascii_alphabetic());
4530     /// assert!(!percent.is_ascii_alphabetic());
4531     /// assert!(!space.is_ascii_alphabetic());
4532     /// assert!(!lf.is_ascii_alphabetic());
4533     /// assert!(!esc.is_ascii_alphabetic());
4534     /// ```
4535     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4536     #[inline]
4537     pub fn is_ascii_alphabetic(&self) -> bool {
4538         match *self {
4539             b'A'..=b'Z' | b'a'..=b'z' => true,
4540             _ => false,
4541         }
4542     }
4543
4544     /// Checks if the value is an ASCII uppercase character:
4545     /// U+0041 'A' ..= U+005A 'Z'.
4546     ///
4547     /// # Examples
4548     ///
4549     /// ```
4550     /// let uppercase_a = b'A';
4551     /// let uppercase_g = b'G';
4552     /// let a = b'a';
4553     /// let g = b'g';
4554     /// let zero = b'0';
4555     /// let percent = b'%';
4556     /// let space = b' ';
4557     /// let lf = b'\n';
4558     /// let esc = 0x1b_u8;
4559     ///
4560     /// assert!(uppercase_a.is_ascii_uppercase());
4561     /// assert!(uppercase_g.is_ascii_uppercase());
4562     /// assert!(!a.is_ascii_uppercase());
4563     /// assert!(!g.is_ascii_uppercase());
4564     /// assert!(!zero.is_ascii_uppercase());
4565     /// assert!(!percent.is_ascii_uppercase());
4566     /// assert!(!space.is_ascii_uppercase());
4567     /// assert!(!lf.is_ascii_uppercase());
4568     /// assert!(!esc.is_ascii_uppercase());
4569     /// ```
4570     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4571     #[inline]
4572     pub fn is_ascii_uppercase(&self) -> bool {
4573         match *self {
4574             b'A'..=b'Z' => true,
4575             _ => false,
4576         }
4577     }
4578
4579     /// Checks if the value is an ASCII lowercase character:
4580     /// U+0061 'a' ..= U+007A 'z'.
4581     ///
4582     /// # Examples
4583     ///
4584     /// ```
4585     /// let uppercase_a = b'A';
4586     /// let uppercase_g = b'G';
4587     /// let a = b'a';
4588     /// let g = b'g';
4589     /// let zero = b'0';
4590     /// let percent = b'%';
4591     /// let space = b' ';
4592     /// let lf = b'\n';
4593     /// let esc = 0x1b_u8;
4594     ///
4595     /// assert!(!uppercase_a.is_ascii_lowercase());
4596     /// assert!(!uppercase_g.is_ascii_lowercase());
4597     /// assert!(a.is_ascii_lowercase());
4598     /// assert!(g.is_ascii_lowercase());
4599     /// assert!(!zero.is_ascii_lowercase());
4600     /// assert!(!percent.is_ascii_lowercase());
4601     /// assert!(!space.is_ascii_lowercase());
4602     /// assert!(!lf.is_ascii_lowercase());
4603     /// assert!(!esc.is_ascii_lowercase());
4604     /// ```
4605     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4606     #[inline]
4607     pub fn is_ascii_lowercase(&self) -> bool {
4608         match *self {
4609             b'a'..=b'z' => true,
4610             _ => false,
4611         }
4612     }
4613
4614     /// Checks if the value is an ASCII alphanumeric character:
4615     ///
4616     /// - U+0041 'A' ..= U+005A 'Z', or
4617     /// - U+0061 'a' ..= U+007A 'z', or
4618     /// - U+0030 '0' ..= U+0039 '9'.
4619     ///
4620     /// # Examples
4621     ///
4622     /// ```
4623     /// let uppercase_a = b'A';
4624     /// let uppercase_g = b'G';
4625     /// let a = b'a';
4626     /// let g = b'g';
4627     /// let zero = b'0';
4628     /// let percent = b'%';
4629     /// let space = b' ';
4630     /// let lf = b'\n';
4631     /// let esc = 0x1b_u8;
4632     ///
4633     /// assert!(uppercase_a.is_ascii_alphanumeric());
4634     /// assert!(uppercase_g.is_ascii_alphanumeric());
4635     /// assert!(a.is_ascii_alphanumeric());
4636     /// assert!(g.is_ascii_alphanumeric());
4637     /// assert!(zero.is_ascii_alphanumeric());
4638     /// assert!(!percent.is_ascii_alphanumeric());
4639     /// assert!(!space.is_ascii_alphanumeric());
4640     /// assert!(!lf.is_ascii_alphanumeric());
4641     /// assert!(!esc.is_ascii_alphanumeric());
4642     /// ```
4643     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4644     #[inline]
4645     pub fn is_ascii_alphanumeric(&self) -> bool {
4646         match *self {
4647             b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' => true,
4648             _ => false,
4649         }
4650     }
4651
4652     /// Checks if the value is an ASCII decimal digit:
4653     /// U+0030 '0' ..= U+0039 '9'.
4654     ///
4655     /// # Examples
4656     ///
4657     /// ```
4658     /// let uppercase_a = b'A';
4659     /// let uppercase_g = b'G';
4660     /// let a = b'a';
4661     /// let g = b'g';
4662     /// let zero = b'0';
4663     /// let percent = b'%';
4664     /// let space = b' ';
4665     /// let lf = b'\n';
4666     /// let esc = 0x1b_u8;
4667     ///
4668     /// assert!(!uppercase_a.is_ascii_digit());
4669     /// assert!(!uppercase_g.is_ascii_digit());
4670     /// assert!(!a.is_ascii_digit());
4671     /// assert!(!g.is_ascii_digit());
4672     /// assert!(zero.is_ascii_digit());
4673     /// assert!(!percent.is_ascii_digit());
4674     /// assert!(!space.is_ascii_digit());
4675     /// assert!(!lf.is_ascii_digit());
4676     /// assert!(!esc.is_ascii_digit());
4677     /// ```
4678     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4679     #[inline]
4680     pub fn is_ascii_digit(&self) -> bool {
4681         match *self {
4682             b'0'..=b'9' => true,
4683             _ => false,
4684         }
4685     }
4686
4687     /// Checks if the value is an ASCII hexadecimal digit:
4688     ///
4689     /// - U+0030 '0' ..= U+0039 '9', or
4690     /// - U+0041 'A' ..= U+0046 'F', or
4691     /// - U+0061 'a' ..= U+0066 'f'.
4692     ///
4693     /// # Examples
4694     ///
4695     /// ```
4696     /// let uppercase_a = b'A';
4697     /// let uppercase_g = b'G';
4698     /// let a = b'a';
4699     /// let g = b'g';
4700     /// let zero = b'0';
4701     /// let percent = b'%';
4702     /// let space = b' ';
4703     /// let lf = b'\n';
4704     /// let esc = 0x1b_u8;
4705     ///
4706     /// assert!(uppercase_a.is_ascii_hexdigit());
4707     /// assert!(!uppercase_g.is_ascii_hexdigit());
4708     /// assert!(a.is_ascii_hexdigit());
4709     /// assert!(!g.is_ascii_hexdigit());
4710     /// assert!(zero.is_ascii_hexdigit());
4711     /// assert!(!percent.is_ascii_hexdigit());
4712     /// assert!(!space.is_ascii_hexdigit());
4713     /// assert!(!lf.is_ascii_hexdigit());
4714     /// assert!(!esc.is_ascii_hexdigit());
4715     /// ```
4716     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4717     #[inline]
4718     pub fn is_ascii_hexdigit(&self) -> bool {
4719         match *self {
4720             b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f' => true,
4721             _ => false,
4722         }
4723     }
4724
4725     /// Checks if the value is an ASCII punctuation character:
4726     ///
4727     /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4728     /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4729     /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4730     /// - U+007B ..= U+007E `{ | } ~`
4731     ///
4732     /// # Examples
4733     ///
4734     /// ```
4735     /// let uppercase_a = b'A';
4736     /// let uppercase_g = b'G';
4737     /// let a = b'a';
4738     /// let g = b'g';
4739     /// let zero = b'0';
4740     /// let percent = b'%';
4741     /// let space = b' ';
4742     /// let lf = b'\n';
4743     /// let esc = 0x1b_u8;
4744     ///
4745     /// assert!(!uppercase_a.is_ascii_punctuation());
4746     /// assert!(!uppercase_g.is_ascii_punctuation());
4747     /// assert!(!a.is_ascii_punctuation());
4748     /// assert!(!g.is_ascii_punctuation());
4749     /// assert!(!zero.is_ascii_punctuation());
4750     /// assert!(percent.is_ascii_punctuation());
4751     /// assert!(!space.is_ascii_punctuation());
4752     /// assert!(!lf.is_ascii_punctuation());
4753     /// assert!(!esc.is_ascii_punctuation());
4754     /// ```
4755     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4756     #[inline]
4757     pub fn is_ascii_punctuation(&self) -> bool {
4758         match *self {
4759             b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~' => true,
4760             _ => false,
4761         }
4762     }
4763
4764     /// Checks if the value is an ASCII graphic character:
4765     /// U+0021 '!' ..= U+007E '~'.
4766     ///
4767     /// # Examples
4768     ///
4769     /// ```
4770     /// let uppercase_a = b'A';
4771     /// let uppercase_g = b'G';
4772     /// let a = b'a';
4773     /// let g = b'g';
4774     /// let zero = b'0';
4775     /// let percent = b'%';
4776     /// let space = b' ';
4777     /// let lf = b'\n';
4778     /// let esc = 0x1b_u8;
4779     ///
4780     /// assert!(uppercase_a.is_ascii_graphic());
4781     /// assert!(uppercase_g.is_ascii_graphic());
4782     /// assert!(a.is_ascii_graphic());
4783     /// assert!(g.is_ascii_graphic());
4784     /// assert!(zero.is_ascii_graphic());
4785     /// assert!(percent.is_ascii_graphic());
4786     /// assert!(!space.is_ascii_graphic());
4787     /// assert!(!lf.is_ascii_graphic());
4788     /// assert!(!esc.is_ascii_graphic());
4789     /// ```
4790     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4791     #[inline]
4792     pub fn is_ascii_graphic(&self) -> bool {
4793         match *self {
4794             b'!'..=b'~' => true,
4795             _ => false,
4796         }
4797     }
4798
4799     /// Checks if the value is an ASCII whitespace character:
4800     /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4801     /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4802     ///
4803     /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4804     /// whitespace][infra-aw]. There are several other definitions in
4805     /// wide use. For instance, [the POSIX locale][pct] includes
4806     /// U+000B VERTICAL TAB as well as all the above characters,
4807     /// but—from the very same specification—[the default rule for
4808     /// "field splitting" in the Bourne shell][bfs] considers *only*
4809     /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4810     ///
4811     /// If you are writing a program that will process an existing
4812     /// file format, check what that format's definition of whitespace is
4813     /// before using this function.
4814     ///
4815     /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4816     /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4817     /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4818     ///
4819     /// # Examples
4820     ///
4821     /// ```
4822     /// let uppercase_a = b'A';
4823     /// let uppercase_g = b'G';
4824     /// let a = b'a';
4825     /// let g = b'g';
4826     /// let zero = b'0';
4827     /// let percent = b'%';
4828     /// let space = b' ';
4829     /// let lf = b'\n';
4830     /// let esc = 0x1b_u8;
4831     ///
4832     /// assert!(!uppercase_a.is_ascii_whitespace());
4833     /// assert!(!uppercase_g.is_ascii_whitespace());
4834     /// assert!(!a.is_ascii_whitespace());
4835     /// assert!(!g.is_ascii_whitespace());
4836     /// assert!(!zero.is_ascii_whitespace());
4837     /// assert!(!percent.is_ascii_whitespace());
4838     /// assert!(space.is_ascii_whitespace());
4839     /// assert!(lf.is_ascii_whitespace());
4840     /// assert!(!esc.is_ascii_whitespace());
4841     /// ```
4842     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4843     #[inline]
4844     pub fn is_ascii_whitespace(&self) -> bool {
4845         match *self {
4846             b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' => true,
4847             _ => false,
4848         }
4849     }
4850
4851     /// Checks if the value is an ASCII control character:
4852     /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4853     /// Note that most ASCII whitespace characters are control
4854     /// characters, but SPACE is not.
4855     ///
4856     /// # Examples
4857     ///
4858     /// ```
4859     /// let uppercase_a = b'A';
4860     /// let uppercase_g = b'G';
4861     /// let a = b'a';
4862     /// let g = b'g';
4863     /// let zero = b'0';
4864     /// let percent = b'%';
4865     /// let space = b' ';
4866     /// let lf = b'\n';
4867     /// let esc = 0x1b_u8;
4868     ///
4869     /// assert!(!uppercase_a.is_ascii_control());
4870     /// assert!(!uppercase_g.is_ascii_control());
4871     /// assert!(!a.is_ascii_control());
4872     /// assert!(!g.is_ascii_control());
4873     /// assert!(!zero.is_ascii_control());
4874     /// assert!(!percent.is_ascii_control());
4875     /// assert!(!space.is_ascii_control());
4876     /// assert!(lf.is_ascii_control());
4877     /// assert!(esc.is_ascii_control());
4878     /// ```
4879     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4880     #[inline]
4881     pub fn is_ascii_control(&self) -> bool {
4882         match *self {
4883             b'\0'..=b'\x1F' | b'\x7F' => true,
4884             _ => false,
4885         }
4886     }
4887 }
4888
4889 #[lang = "u16"]
4890 impl u16 {
4891     uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4892     "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4893 }
4894
4895 #[lang = "u32"]
4896 impl u32 {
4897     uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4898     "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4899 }
4900
4901 #[lang = "u64"]
4902 impl u64 {
4903     uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4904     "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4905     "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4906     "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4907     "", ""}
4908 }
4909
4910 #[lang = "u128"]
4911 impl u128 {
4912     uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4913     "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4914     "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4915     "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4916       0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4917     "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4918       0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4919      "", ""}
4920 }
4921
4922 #[cfg(target_pointer_width = "16")]
4923 #[lang = "usize"]
4924 impl usize {
4925     uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4926     "[0x34, 0x12]", "[0x12, 0x34]",
4927     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4928 }
4929 #[cfg(target_pointer_width = "32")]
4930 #[lang = "usize"]
4931 impl usize {
4932     uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4933     "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4934     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4935 }
4936
4937 #[cfg(target_pointer_width = "64")]
4938 #[lang = "usize"]
4939 impl usize {
4940     uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4941     "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4942     "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4943      "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4944     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4945 }
4946
4947 /// A classification of floating point numbers.
4948 ///
4949 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4950 /// their documentation for more.
4951 ///
4952 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4953 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4954 ///
4955 /// # Examples
4956 ///
4957 /// ```
4958 /// use std::num::FpCategory;
4959 /// use std::f32;
4960 ///
4961 /// let num = 12.4_f32;
4962 /// let inf = f32::INFINITY;
4963 /// let zero = 0f32;
4964 /// let sub: f32 = 1.1754942e-38;
4965 /// let nan = f32::NAN;
4966 ///
4967 /// assert_eq!(num.classify(), FpCategory::Normal);
4968 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4969 /// assert_eq!(zero.classify(), FpCategory::Zero);
4970 /// assert_eq!(nan.classify(), FpCategory::Nan);
4971 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4972 /// ```
4973 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4974 #[stable(feature = "rust1", since = "1.0.0")]
4975 pub enum FpCategory {
4976     /// "Not a Number", often obtained by dividing by zero.
4977     #[stable(feature = "rust1", since = "1.0.0")]
4978     Nan,
4979
4980     /// Positive or negative infinity.
4981     #[stable(feature = "rust1", since = "1.0.0")]
4982     Infinite,
4983
4984     /// Positive or negative zero.
4985     #[stable(feature = "rust1", since = "1.0.0")]
4986     Zero,
4987
4988     /// De-normalized floating point representation (less precise than `Normal`).
4989     #[stable(feature = "rust1", since = "1.0.0")]
4990     Subnormal,
4991
4992     /// A regular floating point number.
4993     #[stable(feature = "rust1", since = "1.0.0")]
4994     Normal,
4995 }
4996
4997 macro_rules! from_str_radix_int_impl {
4998     ($($t:ty)*) => {$(
4999         #[stable(feature = "rust1", since = "1.0.0")]
5000         impl FromStr for $t {
5001             type Err = ParseIntError;
5002             fn from_str(src: &str) -> Result<Self, ParseIntError> {
5003                 from_str_radix(src, 10)
5004             }
5005         }
5006     )*}
5007 }
5008 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
5009
5010 /// The error type returned when a checked integral type conversion fails.
5011 #[stable(feature = "try_from", since = "1.34.0")]
5012 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
5013 pub struct TryFromIntError(pub(crate) ());
5014
5015 impl TryFromIntError {
5016     #[unstable(
5017         feature = "int_error_internals",
5018         reason = "available through Error trait and this method should \
5019                   not be exposed publicly",
5020         issue = "0"
5021     )]
5022     #[doc(hidden)]
5023     pub fn __description(&self) -> &str {
5024         "out of range integral type conversion attempted"
5025     }
5026 }
5027
5028 #[stable(feature = "try_from", since = "1.34.0")]
5029 impl fmt::Display for TryFromIntError {
5030     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
5031         self.__description().fmt(fmt)
5032     }
5033 }
5034
5035 #[stable(feature = "try_from", since = "1.34.0")]
5036 impl From<Infallible> for TryFromIntError {
5037     fn from(x: Infallible) -> TryFromIntError {
5038         match x {}
5039     }
5040 }
5041
5042 #[unstable(feature = "never_type", issue = "35121")]
5043 impl From<!> for TryFromIntError {
5044     fn from(never: !) -> TryFromIntError {
5045         // Match rather than coerce to make sure that code like
5046         // `From<Infallible> for TryFromIntError` above will keep working
5047         // when `Infallible` becomes an alias to `!`.
5048         match never {}
5049     }
5050 }
5051
5052 #[doc(hidden)]
5053 trait FromStrRadixHelper: PartialOrd + Copy {
5054     fn min_value() -> Self;
5055     fn max_value() -> Self;
5056     fn from_u32(u: u32) -> Self;
5057     fn checked_mul(&self, other: u32) -> Option<Self>;
5058     fn checked_sub(&self, other: u32) -> Option<Self>;
5059     fn checked_add(&self, other: u32) -> Option<Self>;
5060 }
5061
5062 macro_rules! doit {
5063     ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
5064         #[inline]
5065         fn min_value() -> Self { Self::min_value() }
5066         #[inline]
5067         fn max_value() -> Self { Self::max_value() }
5068         #[inline]
5069         fn from_u32(u: u32) -> Self { u as Self }
5070         #[inline]
5071         fn checked_mul(&self, other: u32) -> Option<Self> {
5072             Self::checked_mul(*self, other as Self)
5073         }
5074         #[inline]
5075         fn checked_sub(&self, other: u32) -> Option<Self> {
5076             Self::checked_sub(*self, other as Self)
5077         }
5078         #[inline]
5079         fn checked_add(&self, other: u32) -> Option<Self> {
5080             Self::checked_add(*self, other as Self)
5081         }
5082     })*)
5083 }
5084 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5085
5086 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5087     use self::IntErrorKind::*;
5088     use self::ParseIntError as PIE;
5089
5090     assert!(
5091         radix >= 2 && radix <= 36,
5092         "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5093         radix
5094     );
5095
5096     if src.is_empty() {
5097         return Err(PIE { kind: Empty });
5098     }
5099
5100     let is_signed_ty = T::from_u32(0) > T::min_value();
5101
5102     // all valid digits are ascii, so we will just iterate over the utf8 bytes
5103     // and cast them to chars. .to_digit() will safely return None for anything
5104     // other than a valid ascii digit for the given radix, including the first-byte
5105     // of multi-byte sequences
5106     let src = src.as_bytes();
5107
5108     let (is_positive, digits) = match src[0] {
5109         b'+' => (true, &src[1..]),
5110         b'-' if is_signed_ty => (false, &src[1..]),
5111         _ => (true, src),
5112     };
5113
5114     if digits.is_empty() {
5115         return Err(PIE { kind: Empty });
5116     }
5117
5118     let mut result = T::from_u32(0);
5119     if is_positive {
5120         // The number is positive
5121         for &c in digits {
5122             let x = match (c as char).to_digit(radix) {
5123                 Some(x) => x,
5124                 None => return Err(PIE { kind: InvalidDigit }),
5125             };
5126             result = match result.checked_mul(radix) {
5127                 Some(result) => result,
5128                 None => return Err(PIE { kind: Overflow }),
5129             };
5130             result = match result.checked_add(x) {
5131                 Some(result) => result,
5132                 None => return Err(PIE { kind: Overflow }),
5133             };
5134         }
5135     } else {
5136         // The number is negative
5137         for &c in digits {
5138             let x = match (c as char).to_digit(radix) {
5139                 Some(x) => x,
5140                 None => return Err(PIE { kind: InvalidDigit }),
5141             };
5142             result = match result.checked_mul(radix) {
5143                 Some(result) => result,
5144                 None => return Err(PIE { kind: Underflow }),
5145             };
5146             result = match result.checked_sub(x) {
5147                 Some(result) => result,
5148                 None => return Err(PIE { kind: Underflow }),
5149             };
5150         }
5151     }
5152     Ok(result)
5153 }
5154
5155 /// An error which can be returned when parsing an integer.
5156 ///
5157 /// This error is used as the error type for the `from_str_radix()` functions
5158 /// on the primitive integer types, such as [`i8::from_str_radix`].
5159 ///
5160 /// # Potential causes
5161 ///
5162 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5163 /// in the string e.g., when it is obtained from the standard input.
5164 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5165 ///
5166 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5167 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5168 #[derive(Debug, Clone, PartialEq, Eq)]
5169 #[stable(feature = "rust1", since = "1.0.0")]
5170 pub struct ParseIntError {
5171     kind: IntErrorKind,
5172 }
5173
5174 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5175 #[unstable(
5176     feature = "int_error_matching",
5177     reason = "it can be useful to match errors when making error messages \
5178               for integer parsing",
5179     issue = "22639"
5180 )]
5181 #[derive(Debug, Clone, PartialEq, Eq)]
5182 #[non_exhaustive]
5183 pub enum IntErrorKind {
5184     /// Value being parsed is empty.
5185     ///
5186     /// Among other causes, this variant will be constructed when parsing an empty string.
5187     Empty,
5188     /// Contains an invalid digit.
5189     ///
5190     /// Among other causes, this variant will be constructed when parsing a string that
5191     /// contains a letter.
5192     InvalidDigit,
5193     /// Integer is too large to store in target integer type.
5194     Overflow,
5195     /// Integer is too small to store in target integer type.
5196     Underflow,
5197     /// Value was Zero
5198     ///
5199     /// This variant will be emitted when the parsing string has a value of zero, which
5200     /// would be illegal for non-zero types.
5201     Zero,
5202 }
5203
5204 impl ParseIntError {
5205     /// Outputs the detailed cause of parsing an integer failing.
5206     #[unstable(
5207         feature = "int_error_matching",
5208         reason = "it can be useful to match errors when making error messages \
5209                   for integer parsing",
5210         issue = "22639"
5211     )]
5212     pub fn kind(&self) -> &IntErrorKind {
5213         &self.kind
5214     }
5215     #[unstable(
5216         feature = "int_error_internals",
5217         reason = "available through Error trait and this method should \
5218                   not be exposed publicly",
5219         issue = "0"
5220     )]
5221     #[doc(hidden)]
5222     pub fn __description(&self) -> &str {
5223         match self.kind {
5224             IntErrorKind::Empty => "cannot parse integer from empty string",
5225             IntErrorKind::InvalidDigit => "invalid digit found in string",
5226             IntErrorKind::Overflow => "number too large to fit in target type",
5227             IntErrorKind::Underflow => "number too small to fit in target type",
5228             IntErrorKind::Zero => "number would be zero for non-zero type",
5229         }
5230     }
5231 }
5232
5233 #[stable(feature = "rust1", since = "1.0.0")]
5234 impl fmt::Display for ParseIntError {
5235     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5236         self.__description().fmt(f)
5237     }
5238 }
5239
5240 #[stable(feature = "rust1", since = "1.0.0")]
5241 pub use crate::num::dec2flt::ParseFloatError;