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