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