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