]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
Rollup merge of #69213 - LeSeulArtichaut:improve-doc-iter, r=steveklabnik
[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_unstable(feature = "const_int_conversion", issue = "53718")]
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_unstable(feature = "const_int_conversion", issue = "53718")]
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_unstable(feature = "const_int_conversion", issue = "53718")]
2254             #[inline]
2255             pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2256                 // SAFETY: integers are plain old datatypes so we can always transmute them to
2257                 // arrays of bytes
2258                 unsafe { mem::transmute(self) }
2259             }
2260         }
2261
2262 doc_comment! {
2263             concat!("Create an integer value from its representation as a byte array in
2264 big endian.
2265 ",
2266 $from_xe_bytes_doc,
2267 "
2268 # Examples
2269
2270 ```
2271 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2272 assert_eq!(value, ", $swap_op, ");
2273 ```
2274
2275 When starting from a slice rather than an array, fallible conversion APIs can be used:
2276
2277 ```
2278 use std::convert::TryInto;
2279
2280 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2281     let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2282     *input = rest;
2283     ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2284 }
2285 ```"),
2286             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2287             #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2288             #[inline]
2289             pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2290                 Self::from_be(Self::from_ne_bytes(bytes))
2291             }
2292         }
2293
2294 doc_comment! {
2295             concat!("
2296 Create an integer value from its representation as a byte array in
2297 little endian.
2298 ",
2299 $from_xe_bytes_doc,
2300 "
2301 # Examples
2302
2303 ```
2304 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2305 assert_eq!(value, ", $swap_op, ");
2306 ```
2307
2308 When starting from a slice rather than an array, fallible conversion APIs can be used:
2309
2310 ```
2311 use std::convert::TryInto;
2312
2313 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2314     let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2315     *input = rest;
2316     ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2317 }
2318 ```"),
2319             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2320             #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2321             #[inline]
2322             pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2323                 Self::from_le(Self::from_ne_bytes(bytes))
2324             }
2325         }
2326
2327         doc_comment! {
2328             concat!("Create an integer value from its memory representation as a byte
2329 array in native endianness.
2330
2331 As the target platform's native endianness is used, portable code
2332 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2333 appropriate instead.
2334
2335 [`from_be_bytes`]: #method.from_be_bytes
2336 [`from_le_bytes`]: #method.from_le_bytes
2337 ",
2338 $from_xe_bytes_doc,
2339 "
2340 # Examples
2341
2342 ```
2343 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2344     ", $be_bytes, "
2345 } else {
2346     ", $le_bytes, "
2347 });
2348 assert_eq!(value, ", $swap_op, ");
2349 ```
2350
2351 When starting from a slice rather than an array, fallible conversion APIs can be used:
2352
2353 ```
2354 use std::convert::TryInto;
2355
2356 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2357     let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2358     *input = rest;
2359     ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2360 }
2361 ```"),
2362             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2363             #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2364             #[inline]
2365             pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2366                 // SAFETY: integers are plain old datatypes so we can always transmute to them
2367                 unsafe { mem::transmute(bytes) }
2368             }
2369         }
2370     }
2371 }
2372
2373 #[lang = "i8"]
2374 impl i8 {
2375     int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2376     "[0x12]", "[0x12]", "", "" }
2377 }
2378
2379 #[lang = "i16"]
2380 impl i16 {
2381     int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2382     "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2383 }
2384
2385 #[lang = "i32"]
2386 impl i32 {
2387     int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2388     "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2389     "[0x12, 0x34, 0x56, 0x78]", "", "" }
2390 }
2391
2392 #[lang = "i64"]
2393 impl i64 {
2394     int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2395     "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2396     "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2397     "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2398 }
2399
2400 #[lang = "i128"]
2401 impl i128 {
2402     int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2403     170141183460469231731687303715884105727, "", "", 16,
2404     "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2405     "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2406     "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2407       0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2408     "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2409       0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2410 }
2411
2412 #[cfg(target_pointer_width = "16")]
2413 #[lang = "isize"]
2414 impl isize {
2415     int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2416     "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2417     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2418 }
2419
2420 #[cfg(target_pointer_width = "32")]
2421 #[lang = "isize"]
2422 impl isize {
2423     int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2424     "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2425     "[0x12, 0x34, 0x56, 0x78]",
2426     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2427 }
2428
2429 #[cfg(target_pointer_width = "64")]
2430 #[lang = "isize"]
2431 impl isize {
2432     int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2433     12, "0xaa00000000006e1", "0x6e10aa",  "0x1234567890123456", "0x5634129078563412",
2434      "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2435      "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2436      usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2437 }
2438
2439 macro_rules! uint_impl {
2440     ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2441         $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2442         $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2443         $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2444         doc_comment! {
2445             concat!("The smallest value that can be represented by this integer type.
2446
2447 # Examples
2448
2449 Basic usage:
2450
2451 ```
2452 #![feature(assoc_int_consts)]
2453 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, 0);", $EndFeature, "
2454 ```"),
2455             #[unstable(feature = "assoc_int_consts", reason = "recently added", issue = "68490")]
2456             pub const MIN: Self = 0;
2457         }
2458
2459         doc_comment! {
2460             concat!("The largest value that can be represented by this integer type.
2461
2462 # Examples
2463
2464 Basic usage:
2465
2466 ```
2467 #![feature(assoc_int_consts)]
2468 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");",
2469 $EndFeature, "
2470 ```"),
2471             #[unstable(feature = "assoc_int_consts", reason = "recently added", issue = "68490")]
2472             pub const MAX: Self = !0;
2473         }
2474
2475         doc_comment! {
2476             "Returns the smallest value that can be represented by this integer type.",
2477             #[stable(feature = "rust1", since = "1.0.0")]
2478             #[rustc_promotable]
2479             #[inline(always)]
2480             #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2481             pub const fn min_value() -> Self { Self::MIN }
2482         }
2483
2484         doc_comment! {
2485             "Returns the largest value that can be represented by this integer type.",
2486             #[stable(feature = "rust1", since = "1.0.0")]
2487             #[rustc_promotable]
2488             #[inline(always)]
2489             #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2490             pub const fn max_value() -> Self { Self::MAX }
2491         }
2492
2493         doc_comment! {
2494             concat!("Converts a string slice in a given base to an integer.
2495
2496 The string is expected to be an optional `+` sign
2497 followed by digits.
2498 Leading and trailing whitespace represent an error.
2499 Digits are a subset of these characters, depending on `radix`:
2500
2501 * `0-9`
2502 * `a-z`
2503 * `A-Z`
2504
2505 # Panics
2506
2507 This function panics if `radix` is not in the range from 2 to 36.
2508
2509 # Examples
2510
2511 Basic usage:
2512
2513 ```
2514 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2515 $EndFeature, "
2516 ```"),
2517             #[stable(feature = "rust1", since = "1.0.0")]
2518             pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2519                 from_str_radix(src, radix)
2520             }
2521         }
2522
2523         doc_comment! {
2524             concat!("Returns the number of ones in the binary representation of `self`.
2525
2526 # Examples
2527
2528 Basic usage:
2529
2530 ```
2531 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2532
2533 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2534 ```"),
2535             #[stable(feature = "rust1", since = "1.0.0")]
2536             #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2537             #[inline]
2538             pub const fn count_ones(self) -> u32 {
2539                 intrinsics::ctpop(self as $ActualT) as u32
2540             }
2541         }
2542
2543         doc_comment! {
2544             concat!("Returns the number of zeros in the binary representation of `self`.
2545
2546 # Examples
2547
2548 Basic usage:
2549
2550 ```
2551 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2552 ```"),
2553             #[stable(feature = "rust1", since = "1.0.0")]
2554             #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2555             #[inline]
2556             pub const fn count_zeros(self) -> u32 {
2557                 (!self).count_ones()
2558             }
2559         }
2560
2561         doc_comment! {
2562             concat!("Returns the number of leading zeros in the binary representation of `self`.
2563
2564 # Examples
2565
2566 Basic usage:
2567
2568 ```
2569 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2570
2571 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2572 ```"),
2573             #[stable(feature = "rust1", since = "1.0.0")]
2574             #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2575             #[inline]
2576             pub const fn leading_zeros(self) -> u32 {
2577                 intrinsics::ctlz(self as $ActualT) as u32
2578             }
2579         }
2580
2581         doc_comment! {
2582             concat!("Returns the number of trailing zeros in the binary representation
2583 of `self`.
2584
2585 # Examples
2586
2587 Basic usage:
2588
2589 ```
2590 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2591
2592 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2593 ```"),
2594             #[stable(feature = "rust1", since = "1.0.0")]
2595             #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2596             #[inline]
2597             pub const fn trailing_zeros(self) -> u32 {
2598                 intrinsics::cttz(self) as u32
2599             }
2600         }
2601
2602         doc_comment! {
2603             concat!("Returns the number of leading ones in the binary representation of `self`.
2604
2605 # Examples
2606
2607 Basic usage:
2608
2609 ```
2610 ", $Feature, "#![feature(leading_trailing_ones)]
2611 let n = !(", stringify!($SelfT), "::max_value() >> 2);
2612
2613 assert_eq!(n.leading_ones(), 2);", $EndFeature, "
2614 ```"),
2615             #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2616             #[inline]
2617             pub const fn leading_ones(self) -> u32 {
2618                 (!self).leading_zeros()
2619             }
2620         }
2621
2622         doc_comment! {
2623             concat!("Returns the number of trailing ones in the binary representation
2624 of `self`.
2625
2626 # Examples
2627
2628 Basic usage:
2629
2630 ```
2631 ", $Feature, "#![feature(leading_trailing_ones)]
2632 let n = 0b1010111", stringify!($SelfT), ";
2633
2634 assert_eq!(n.trailing_ones(), 3);", $EndFeature, "
2635 ```"),
2636             #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2637             #[inline]
2638             pub const fn trailing_ones(self) -> u32 {
2639                 (!self).trailing_zeros()
2640             }
2641         }
2642
2643         doc_comment! {
2644             concat!("Shifts the bits to the left by a specified amount, `n`,
2645 wrapping the truncated bits to the end of the resulting integer.
2646
2647 Please note this isn't the same operation as the `<<` shifting operator!
2648
2649 # Examples
2650
2651 Basic usage:
2652
2653 ```
2654 let n = ", $rot_op, stringify!($SelfT), ";
2655 let m = ", $rot_result, ";
2656
2657 assert_eq!(n.rotate_left(", $rot, "), m);
2658 ```"),
2659             #[stable(feature = "rust1", since = "1.0.0")]
2660             #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2661             #[must_use = "this returns the result of the operation, \
2662                           without modifying the original"]
2663             #[inline]
2664             pub const fn rotate_left(self, n: u32) -> Self {
2665                 intrinsics::rotate_left(self, n as $SelfT)
2666             }
2667         }
2668
2669         doc_comment! {
2670             concat!("Shifts the bits to the right by a specified amount, `n`,
2671 wrapping the truncated bits to the beginning of the resulting
2672 integer.
2673
2674 Please note this isn't the same operation as the `>>` shifting operator!
2675
2676 # Examples
2677
2678 Basic usage:
2679
2680 ```
2681 let n = ", $rot_result, stringify!($SelfT), ";
2682 let m = ", $rot_op, ";
2683
2684 assert_eq!(n.rotate_right(", $rot, "), m);
2685 ```"),
2686             #[stable(feature = "rust1", since = "1.0.0")]
2687             #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2688             #[must_use = "this returns the result of the operation, \
2689                           without modifying the original"]
2690             #[inline]
2691             pub const fn rotate_right(self, n: u32) -> Self {
2692                 intrinsics::rotate_right(self, n as $SelfT)
2693             }
2694         }
2695
2696         doc_comment! {
2697             concat!("
2698 Reverses the byte order of the integer.
2699
2700 # Examples
2701
2702 Basic usage:
2703
2704 ```
2705 let n = ", $swap_op, stringify!($SelfT), ";
2706 let m = n.swap_bytes();
2707
2708 assert_eq!(m, ", $swapped, ");
2709 ```"),
2710             #[stable(feature = "rust1", since = "1.0.0")]
2711             #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2712             #[inline]
2713             pub const fn swap_bytes(self) -> Self {
2714                 intrinsics::bswap(self as $ActualT) as Self
2715             }
2716         }
2717
2718         doc_comment! {
2719             concat!("Reverses the bit pattern of the integer.
2720
2721 # Examples
2722
2723 Basic usage:
2724
2725 ```
2726 let n = ", $swap_op, stringify!($SelfT), ";
2727 let m = n.reverse_bits();
2728
2729 assert_eq!(m, ", $reversed, ");
2730 ```"),
2731             #[stable(feature = "reverse_bits", since = "1.37.0")]
2732             #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2733             #[inline]
2734             #[must_use]
2735             pub const fn reverse_bits(self) -> Self {
2736                 intrinsics::bitreverse(self as $ActualT) as Self
2737             }
2738         }
2739
2740         doc_comment! {
2741             concat!("Converts an integer from big endian to the target's endianness.
2742
2743 On big endian this is a no-op. On little endian the bytes are
2744 swapped.
2745
2746 # Examples
2747
2748 Basic usage:
2749
2750 ```
2751 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2752
2753 if cfg!(target_endian = \"big\") {
2754     assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2755 } else {
2756     assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2757 }", $EndFeature, "
2758 ```"),
2759             #[stable(feature = "rust1", since = "1.0.0")]
2760             #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2761             #[inline]
2762             pub const fn from_be(x: Self) -> Self {
2763                 #[cfg(target_endian = "big")]
2764                 {
2765                     x
2766                 }
2767                 #[cfg(not(target_endian = "big"))]
2768                 {
2769                     x.swap_bytes()
2770                 }
2771             }
2772         }
2773
2774         doc_comment! {
2775             concat!("Converts an integer from little endian to the target's endianness.
2776
2777 On little endian this is a no-op. On big endian the bytes are
2778 swapped.
2779
2780 # Examples
2781
2782 Basic usage:
2783
2784 ```
2785 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2786
2787 if cfg!(target_endian = \"little\") {
2788     assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2789 } else {
2790     assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2791 }", $EndFeature, "
2792 ```"),
2793             #[stable(feature = "rust1", since = "1.0.0")]
2794             #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2795             #[inline]
2796             pub const fn from_le(x: Self) -> Self {
2797                 #[cfg(target_endian = "little")]
2798                 {
2799                     x
2800                 }
2801                 #[cfg(not(target_endian = "little"))]
2802                 {
2803                     x.swap_bytes()
2804                 }
2805             }
2806         }
2807
2808         doc_comment! {
2809             concat!("Converts `self` to big endian from the target's endianness.
2810
2811 On big endian this is a no-op. On little endian the bytes are
2812 swapped.
2813
2814 # Examples
2815
2816 Basic usage:
2817
2818 ```
2819 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2820
2821 if cfg!(target_endian = \"big\") {
2822     assert_eq!(n.to_be(), n)
2823 } else {
2824     assert_eq!(n.to_be(), n.swap_bytes())
2825 }", $EndFeature, "
2826 ```"),
2827             #[stable(feature = "rust1", since = "1.0.0")]
2828             #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2829             #[inline]
2830             pub const fn to_be(self) -> Self { // or not to be?
2831                 #[cfg(target_endian = "big")]
2832                 {
2833                     self
2834                 }
2835                 #[cfg(not(target_endian = "big"))]
2836                 {
2837                     self.swap_bytes()
2838                 }
2839             }
2840         }
2841
2842         doc_comment! {
2843             concat!("Converts `self` to little endian from the target's endianness.
2844
2845 On little endian this is a no-op. On big endian the bytes are
2846 swapped.
2847
2848 # Examples
2849
2850 Basic usage:
2851
2852 ```
2853 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2854
2855 if cfg!(target_endian = \"little\") {
2856     assert_eq!(n.to_le(), n)
2857 } else {
2858     assert_eq!(n.to_le(), n.swap_bytes())
2859 }", $EndFeature, "
2860 ```"),
2861             #[stable(feature = "rust1", since = "1.0.0")]
2862             #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2863             #[inline]
2864             pub const fn to_le(self) -> Self {
2865                 #[cfg(target_endian = "little")]
2866                 {
2867                     self
2868                 }
2869                 #[cfg(not(target_endian = "little"))]
2870                 {
2871                     self.swap_bytes()
2872                 }
2873             }
2874         }
2875
2876         doc_comment! {
2877             concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2878 if overflow occurred.
2879
2880 # Examples
2881
2882 Basic usage:
2883
2884 ```
2885 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2886 "Some(", stringify!($SelfT), "::max_value() - 1));
2887 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2888 ```"),
2889             #[stable(feature = "rust1", since = "1.0.0")]
2890             #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2891             #[must_use = "this returns the result of the operation, \
2892                           without modifying the original"]
2893             #[inline]
2894             pub const fn checked_add(self, rhs: Self) -> Option<Self> {
2895                 let (a, b) = self.overflowing_add(rhs);
2896                 if b {None} else {Some(a)}
2897             }
2898         }
2899
2900         doc_comment! {
2901             concat!("Checked integer subtraction. Computes `self - rhs`, returning
2902 `None` if overflow occurred.
2903
2904 # Examples
2905
2906 Basic usage:
2907
2908 ```
2909 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2910 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2911 ```"),
2912             #[stable(feature = "rust1", since = "1.0.0")]
2913             #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2914             #[must_use = "this returns the result of the operation, \
2915                           without modifying the original"]
2916             #[inline]
2917             pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
2918                 let (a, b) = self.overflowing_sub(rhs);
2919                 if b {None} else {Some(a)}
2920             }
2921         }
2922
2923         doc_comment! {
2924             concat!("Checked integer multiplication. Computes `self * rhs`, returning
2925 `None` if overflow occurred.
2926
2927 # Examples
2928
2929 Basic usage:
2930
2931 ```
2932 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2933 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2934 ```"),
2935             #[stable(feature = "rust1", since = "1.0.0")]
2936             #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2937             #[must_use = "this returns the result of the operation, \
2938                           without modifying the original"]
2939             #[inline]
2940             pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
2941                 let (a, b) = self.overflowing_mul(rhs);
2942                 if b {None} else {Some(a)}
2943             }
2944         }
2945
2946         doc_comment! {
2947             concat!("Checked integer division. Computes `self / rhs`, returning `None`
2948 if `rhs == 0`.
2949
2950 # Examples
2951
2952 Basic usage:
2953
2954 ```
2955 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2956 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2957 ```"),
2958             #[stable(feature = "rust1", since = "1.0.0")]
2959             #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2960             #[must_use = "this returns the result of the operation, \
2961                           without modifying the original"]
2962             #[inline]
2963             pub const fn checked_div(self, rhs: Self) -> Option<Self> {
2964                 match rhs {
2965                     0 => None,
2966                     // SAFETY: div by zero has been checked above and unsigned types have no other
2967                     // failure modes for division
2968                     rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2969                 }
2970             }
2971         }
2972
2973         doc_comment! {
2974             concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2975 if `rhs == 0`.
2976
2977 # Examples
2978
2979 Basic usage:
2980
2981 ```
2982 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
2983 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
2984 ```"),
2985             #[stable(feature = "euclidean_division", since = "1.38.0")]
2986             #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2987             #[must_use = "this returns the result of the operation, \
2988                           without modifying the original"]
2989             #[inline]
2990             pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
2991                 if rhs == 0 {
2992                     None
2993                 } else {
2994                     Some(self.div_euclid(rhs))
2995                 }
2996             }
2997         }
2998
2999
3000         doc_comment! {
3001             concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
3002 if `rhs == 0`.
3003
3004 # Examples
3005
3006 Basic usage:
3007
3008 ```
3009 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
3010 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
3011 ```"),
3012             #[stable(feature = "wrapping", since = "1.7.0")]
3013             #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3014             #[must_use = "this returns the result of the operation, \
3015                           without modifying the original"]
3016             #[inline]
3017             pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
3018                 if rhs == 0 {
3019                     None
3020                 } else {
3021                     // SAFETY: div by zero has been checked above and unsigned types have no other
3022                     // failure modes for division
3023                     Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3024                 }
3025             }
3026         }
3027
3028         doc_comment! {
3029             concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3030 if `rhs == 0`.
3031
3032 # Examples
3033
3034 Basic usage:
3035
3036 ```
3037 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3038 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3039 ```"),
3040             #[stable(feature = "euclidean_division", since = "1.38.0")]
3041             #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3042             #[must_use = "this returns the result of the operation, \
3043                           without modifying the original"]
3044             #[inline]
3045             pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3046                 if rhs == 0 {
3047                     None
3048                 } else {
3049                     Some(self.rem_euclid(rhs))
3050                 }
3051             }
3052         }
3053
3054         doc_comment! {
3055             concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3056 0`.
3057
3058 Note that negating any positive integer will overflow.
3059
3060 # Examples
3061
3062 Basic usage:
3063
3064 ```
3065 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3066 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3067 ```"),
3068             #[stable(feature = "wrapping", since = "1.7.0")]
3069             #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3070             #[inline]
3071             pub const fn checked_neg(self) -> Option<Self> {
3072                 let (a, b) = self.overflowing_neg();
3073                 if b {None} else {Some(a)}
3074             }
3075         }
3076
3077         doc_comment! {
3078             concat!("Checked shift left. Computes `self << rhs`, returning `None`
3079 if `rhs` is larger than or equal to the number of bits in `self`.
3080
3081 # Examples
3082
3083 Basic usage:
3084
3085 ```
3086 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3087 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3088 ```"),
3089             #[stable(feature = "wrapping", since = "1.7.0")]
3090             #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3091             #[must_use = "this returns the result of the operation, \
3092                           without modifying the original"]
3093             #[inline]
3094             pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
3095                 let (a, b) = self.overflowing_shl(rhs);
3096                 if b {None} else {Some(a)}
3097             }
3098         }
3099
3100         doc_comment! {
3101             concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3102 if `rhs` is larger than or equal to the number of bits in `self`.
3103
3104 # Examples
3105
3106 Basic usage:
3107
3108 ```
3109 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3110 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3111 ```"),
3112             #[stable(feature = "wrapping", since = "1.7.0")]
3113             #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3114             #[must_use = "this returns the result of the operation, \
3115                           without modifying the original"]
3116             #[inline]
3117             pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
3118                 let (a, b) = self.overflowing_shr(rhs);
3119                 if b {None} else {Some(a)}
3120             }
3121         }
3122
3123         doc_comment! {
3124             concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3125 overflow occurred.
3126
3127 # Examples
3128
3129 Basic usage:
3130
3131 ```
3132 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3133 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
3134 ```"),
3135             #[stable(feature = "no_panic_pow", since = "1.34.0")]
3136             #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3137             #[must_use = "this returns the result of the operation, \
3138                           without modifying the original"]
3139             #[inline]
3140             pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
3141                 let mut base = self;
3142                 let mut acc: Self = 1;
3143
3144                 while exp > 1 {
3145                     if (exp & 1) == 1 {
3146                         acc = try_opt!(acc.checked_mul(base));
3147                     }
3148                     exp /= 2;
3149                     base = try_opt!(base.checked_mul(base));
3150                 }
3151
3152                 // Deal with the final bit of the exponent separately, since
3153                 // squaring the base afterwards is not necessary and may cause a
3154                 // needless overflow.
3155                 if exp == 1 {
3156                     acc = try_opt!(acc.checked_mul(base));
3157                 }
3158
3159                 Some(acc)
3160             }
3161         }
3162
3163         doc_comment! {
3164             concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3165 the numeric bounds instead of overflowing.
3166
3167 # Examples
3168
3169 Basic usage:
3170
3171 ```
3172 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3173 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
3174 ```"),
3175
3176             #[stable(feature = "rust1", since = "1.0.0")]
3177             #[must_use = "this returns the result of the operation, \
3178                           without modifying the original"]
3179             #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3180             #[inline]
3181             pub const fn saturating_add(self, rhs: Self) -> Self {
3182                 intrinsics::saturating_add(self, rhs)
3183             }
3184         }
3185
3186         doc_comment! {
3187             concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3188 at the numeric bounds instead of overflowing.
3189
3190 # Examples
3191
3192 Basic usage:
3193
3194 ```
3195 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3196 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3197 ```"),
3198             #[stable(feature = "rust1", since = "1.0.0")]
3199             #[must_use = "this returns the result of the operation, \
3200                           without modifying the original"]
3201             #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3202             #[inline]
3203             pub const fn saturating_sub(self, rhs: Self) -> Self {
3204                 intrinsics::saturating_sub(self, rhs)
3205             }
3206         }
3207
3208         doc_comment! {
3209             concat!("Saturating integer multiplication. Computes `self * rhs`,
3210 saturating at the numeric bounds instead of overflowing.
3211
3212 # Examples
3213
3214 Basic usage:
3215
3216 ```
3217 ", $Feature, "use std::", stringify!($SelfT), ";
3218
3219 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3220 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3221 "::MAX);", $EndFeature, "
3222 ```"),
3223             #[stable(feature = "wrapping", since = "1.7.0")]
3224             #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3225             #[must_use = "this returns the result of the operation, \
3226                           without modifying the original"]
3227             #[inline]
3228             pub const fn saturating_mul(self, rhs: Self) -> Self {
3229                 match self.checked_mul(rhs) {
3230                     Some(x) => x,
3231                     None => Self::max_value(),
3232                 }
3233             }
3234         }
3235
3236         doc_comment! {
3237             concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3238 saturating at the numeric bounds instead of overflowing.
3239
3240 # Examples
3241
3242 Basic usage:
3243
3244 ```
3245 ", $Feature, "use std::", stringify!($SelfT), ";
3246
3247 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3248 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3249 $EndFeature, "
3250 ```"),
3251             #[stable(feature = "no_panic_pow", since = "1.34.0")]
3252             #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3253             #[must_use = "this returns the result of the operation, \
3254                           without modifying the original"]
3255             #[inline]
3256             pub const fn saturating_pow(self, exp: u32) -> Self {
3257                 match self.checked_pow(exp) {
3258                     Some(x) => x,
3259                     None => Self::max_value(),
3260                 }
3261             }
3262         }
3263
3264         doc_comment! {
3265             concat!("Wrapping (modular) addition. Computes `self + rhs`,
3266 wrapping around at the boundary of the type.
3267
3268 # Examples
3269
3270 Basic usage:
3271
3272 ```
3273 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3274 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
3275 $EndFeature, "
3276 ```"),
3277             #[stable(feature = "rust1", since = "1.0.0")]
3278             #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3279             #[must_use = "this returns the result of the operation, \
3280                           without modifying the original"]
3281             #[inline]
3282             pub const fn wrapping_add(self, rhs: Self) -> Self {
3283                 intrinsics::wrapping_add(self, rhs)
3284             }
3285         }
3286
3287         doc_comment! {
3288             concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3289 wrapping around at the boundary of the type.
3290
3291 # Examples
3292
3293 Basic usage:
3294
3295 ```
3296 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3297 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
3298 $EndFeature, "
3299 ```"),
3300             #[stable(feature = "rust1", since = "1.0.0")]
3301             #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3302             #[must_use = "this returns the result of the operation, \
3303                           without modifying the original"]
3304             #[inline]
3305             pub const fn wrapping_sub(self, rhs: Self) -> Self {
3306                 intrinsics::wrapping_sub(self, rhs)
3307             }
3308         }
3309
3310         /// Wrapping (modular) multiplication. Computes `self *
3311         /// rhs`, wrapping around at the boundary of the type.
3312         ///
3313         /// # Examples
3314         ///
3315         /// Basic usage:
3316         ///
3317         /// Please note that this example is shared between integer types.
3318         /// Which explains why `u8` is used here.
3319         ///
3320         /// ```
3321         /// assert_eq!(10u8.wrapping_mul(12), 120);
3322         /// assert_eq!(25u8.wrapping_mul(12), 44);
3323         /// ```
3324         #[stable(feature = "rust1", since = "1.0.0")]
3325         #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3326         #[must_use = "this returns the result of the operation, \
3327                           without modifying the original"]
3328         #[inline]
3329         pub const fn wrapping_mul(self, rhs: Self) -> Self {
3330             intrinsics::wrapping_mul(self, rhs)
3331         }
3332
3333         doc_comment! {
3334             concat!("Wrapping (modular) division. Computes `self / rhs`.
3335 Wrapped division on unsigned types is just normal division.
3336 There's no way wrapping could ever happen.
3337 This function exists, so that all operations
3338 are accounted for in the wrapping operations.
3339
3340 # Examples
3341
3342 Basic usage:
3343
3344 ```
3345 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3346 ```"),
3347             #[stable(feature = "num_wrapping", since = "1.2.0")]
3348             #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3349             #[must_use = "this returns the result of the operation, \
3350                           without modifying the original"]
3351             #[inline]
3352             pub const fn wrapping_div(self, rhs: Self) -> Self {
3353                 self / rhs
3354             }
3355         }
3356
3357         doc_comment! {
3358             concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3359 Wrapped division on unsigned types is just normal division.
3360 There's no way wrapping could ever happen.
3361 This function exists, so that all operations
3362 are accounted for in the wrapping operations.
3363 Since, for the positive integers, all common
3364 definitions of division are equal, this
3365 is exactly equal to `self.wrapping_div(rhs)`.
3366
3367 # Examples
3368
3369 Basic usage:
3370
3371 ```
3372 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3373 ```"),
3374             #[stable(feature = "euclidean_division", since = "1.38.0")]
3375             #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3376             #[must_use = "this returns the result of the operation, \
3377                           without modifying the original"]
3378             #[inline]
3379             pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
3380                 self / rhs
3381             }
3382         }
3383
3384         doc_comment! {
3385             concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3386 Wrapped remainder calculation on unsigned types is
3387 just the regular remainder calculation.
3388 There's no way wrapping could ever happen.
3389 This function exists, so that all operations
3390 are accounted for in the wrapping operations.
3391
3392 # Examples
3393
3394 Basic usage:
3395
3396 ```
3397 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3398 ```"),
3399             #[stable(feature = "num_wrapping", since = "1.2.0")]
3400             #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3401             #[must_use = "this returns the result of the operation, \
3402                           without modifying the original"]
3403             #[inline]
3404             pub const fn wrapping_rem(self, rhs: Self) -> Self {
3405                 self % rhs
3406             }
3407         }
3408
3409         doc_comment! {
3410             concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3411 Wrapped modulo calculation on unsigned types is
3412 just the regular remainder calculation.
3413 There's no way wrapping could ever happen.
3414 This function exists, so that all operations
3415 are accounted for in the wrapping operations.
3416 Since, for the positive integers, all common
3417 definitions of division are equal, this
3418 is exactly equal to `self.wrapping_rem(rhs)`.
3419
3420 # Examples
3421
3422 Basic usage:
3423
3424 ```
3425 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3426 ```"),
3427             #[stable(feature = "euclidean_division", since = "1.38.0")]
3428             #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3429             #[must_use = "this returns the result of the operation, \
3430                           without modifying the original"]
3431             #[inline]
3432             pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3433                 self % rhs
3434             }
3435         }
3436
3437         /// Wrapping (modular) negation. Computes `-self`,
3438         /// wrapping around at the boundary of the type.
3439         ///
3440         /// Since unsigned types do not have negative equivalents
3441         /// all applications of this function will wrap (except for `-0`).
3442         /// For values smaller than the corresponding signed type's maximum
3443         /// the result is the same as casting the corresponding signed value.
3444         /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3445         /// `MAX` is the corresponding signed type's maximum.
3446         ///
3447         /// # Examples
3448         ///
3449         /// Basic usage:
3450         ///
3451         /// Please note that this example is shared between integer types.
3452         /// Which explains why `i8` is used here.
3453         ///
3454         /// ```
3455         /// assert_eq!(100i8.wrapping_neg(), -100);
3456         /// assert_eq!((-128i8).wrapping_neg(), -128);
3457         /// ```
3458         #[stable(feature = "num_wrapping", since = "1.2.0")]
3459         #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3460         #[inline]
3461         pub const fn wrapping_neg(self) -> Self {
3462             self.overflowing_neg().0
3463         }
3464
3465         doc_comment! {
3466             concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3467 where `mask` removes any high-order bits of `rhs` that
3468 would cause the shift to exceed the bitwidth of the type.
3469
3470 Note that this is *not* the same as a rotate-left; the
3471 RHS of a wrapping shift-left is restricted to the range
3472 of the type, rather than the bits shifted out of the LHS
3473 being returned to the other end. The primitive integer
3474 types all implement a `rotate_left` function, which may
3475 be what you want instead.
3476
3477 # Examples
3478
3479 Basic usage:
3480
3481 ```
3482 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3483 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3484 ```"),
3485             #[stable(feature = "num_wrapping", since = "1.2.0")]
3486             #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3487             #[must_use = "this returns the result of the operation, \
3488                           without modifying the original"]
3489             #[inline]
3490             pub const fn wrapping_shl(self, rhs: u32) -> Self {
3491                 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3492                 // out of bounds
3493                 unsafe {
3494                     intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3495                 }
3496             }
3497         }
3498
3499         doc_comment! {
3500             concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3501 where `mask` removes any high-order bits of `rhs` that
3502 would cause the shift to exceed the bitwidth of the type.
3503
3504 Note that this is *not* the same as a rotate-right; the
3505 RHS of a wrapping shift-right is restricted to the range
3506 of the type, rather than the bits shifted out of the LHS
3507 being returned to the other end. The primitive integer
3508 types all implement a `rotate_right` function, which may
3509 be what you want instead.
3510
3511 # Examples
3512
3513 Basic usage:
3514
3515 ```
3516 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3517 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3518 ```"),
3519             #[stable(feature = "num_wrapping", since = "1.2.0")]
3520             #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3521             #[must_use = "this returns the result of the operation, \
3522                           without modifying the original"]
3523             #[inline]
3524             pub const fn wrapping_shr(self, rhs: u32) -> Self {
3525                 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3526                 // out of bounds
3527                 unsafe {
3528                     intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3529                 }
3530             }
3531         }
3532
3533         doc_comment! {
3534             concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3535 wrapping around at the boundary of the type.
3536
3537 # Examples
3538
3539 Basic usage:
3540
3541 ```
3542 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3543 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3544 ```"),
3545             #[stable(feature = "no_panic_pow", since = "1.34.0")]
3546             #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3547             #[must_use = "this returns the result of the operation, \
3548                           without modifying the original"]
3549             #[inline]
3550             pub const fn wrapping_pow(self, mut exp: u32) -> Self {
3551                 let mut base = self;
3552                 let mut acc: Self = 1;
3553
3554                 while exp > 1 {
3555                     if (exp & 1) == 1 {
3556                         acc = acc.wrapping_mul(base);
3557                     }
3558                     exp /= 2;
3559                     base = base.wrapping_mul(base);
3560                 }
3561
3562                 // Deal with the final bit of the exponent separately, since
3563                 // squaring the base afterwards is not necessary and may cause a
3564                 // needless overflow.
3565                 if exp == 1 {
3566                     acc = acc.wrapping_mul(base);
3567                 }
3568
3569                 acc
3570             }
3571         }
3572
3573         doc_comment! {
3574             concat!("Calculates `self` + `rhs`
3575
3576 Returns a tuple of the addition along with a boolean indicating
3577 whether an arithmetic overflow would occur. If an overflow would
3578 have occurred then the wrapped value is returned.
3579
3580 # Examples
3581
3582 Basic usage
3583
3584 ```
3585 ", $Feature, "use std::", stringify!($SelfT), ";
3586
3587 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3588 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3589 ```"),
3590             #[stable(feature = "wrapping", since = "1.7.0")]
3591             #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3592             #[must_use = "this returns the result of the operation, \
3593                           without modifying the original"]
3594             #[inline]
3595             pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3596                 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3597                 (a as Self, b)
3598             }
3599         }
3600
3601         doc_comment! {
3602             concat!("Calculates `self` - `rhs`
3603
3604 Returns a tuple of the subtraction along with a boolean indicating
3605 whether an arithmetic overflow would occur. If an overflow would
3606 have occurred then the wrapped value is returned.
3607
3608 # Examples
3609
3610 Basic usage
3611
3612 ```
3613 ", $Feature, "use std::", stringify!($SelfT), ";
3614
3615 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3616 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3617 $EndFeature, "
3618 ```"),
3619             #[stable(feature = "wrapping", since = "1.7.0")]
3620             #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3621             #[must_use = "this returns the result of the operation, \
3622                           without modifying the original"]
3623             #[inline]
3624             pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3625                 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3626                 (a as Self, b)
3627             }
3628         }
3629
3630         /// Calculates the multiplication of `self` and `rhs`.
3631         ///
3632         /// Returns a tuple of the multiplication along with a boolean
3633         /// indicating whether an arithmetic overflow would occur. If an
3634         /// overflow would have occurred then the wrapped value is returned.
3635         ///
3636         /// # Examples
3637         ///
3638         /// Basic usage:
3639         ///
3640         /// Please note that this example is shared between integer types.
3641         /// Which explains why `u32` is used here.
3642         ///
3643         /// ```
3644         /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3645         /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3646         /// ```
3647         #[stable(feature = "wrapping", since = "1.7.0")]
3648         #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3649         #[must_use = "this returns the result of the operation, \
3650                           without modifying the original"]
3651         #[inline]
3652         pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3653             let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3654             (a as Self, b)
3655         }
3656
3657         doc_comment! {
3658             concat!("Calculates the divisor when `self` is divided by `rhs`.
3659
3660 Returns a tuple of the divisor along with a boolean indicating
3661 whether an arithmetic overflow would occur. Note that for unsigned
3662 integers overflow never occurs, so the second value is always
3663 `false`.
3664
3665 # Panics
3666
3667 This function will panic if `rhs` is 0.
3668
3669 # Examples
3670
3671 Basic usage
3672
3673 ```
3674 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3675 ```"),
3676             #[inline]
3677             #[stable(feature = "wrapping", since = "1.7.0")]
3678             #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3679             #[must_use = "this returns the result of the operation, \
3680                           without modifying the original"]
3681             pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3682                 (self / rhs, false)
3683             }
3684         }
3685
3686         doc_comment! {
3687             concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3688
3689 Returns a tuple of the divisor along with a boolean indicating
3690 whether an arithmetic overflow would occur. Note that for unsigned
3691 integers overflow never occurs, so the second value is always
3692 `false`.
3693 Since, for the positive integers, all common
3694 definitions of division are equal, this
3695 is exactly equal to `self.overflowing_div(rhs)`.
3696
3697 # Panics
3698
3699 This function will panic if `rhs` is 0.
3700
3701 # Examples
3702
3703 Basic usage
3704
3705 ```
3706 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3707 ```"),
3708             #[inline]
3709             #[stable(feature = "euclidean_division", since = "1.38.0")]
3710             #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3711             #[must_use = "this returns the result of the operation, \
3712                           without modifying the original"]
3713             pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3714                 (self / rhs, false)
3715             }
3716         }
3717
3718         doc_comment! {
3719             concat!("Calculates the remainder when `self` is divided by `rhs`.
3720
3721 Returns a tuple of the remainder after dividing along with a boolean
3722 indicating whether an arithmetic overflow would occur. Note that for
3723 unsigned integers overflow never occurs, so the second value is
3724 always `false`.
3725
3726 # Panics
3727
3728 This function will panic if `rhs` is 0.
3729
3730 # Examples
3731
3732 Basic usage
3733
3734 ```
3735 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3736 ```"),
3737             #[inline]
3738             #[stable(feature = "wrapping", since = "1.7.0")]
3739             #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3740             #[must_use = "this returns the result of the operation, \
3741                           without modifying the original"]
3742             pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3743                 (self % rhs, false)
3744             }
3745         }
3746
3747         doc_comment! {
3748             concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3749
3750 Returns a tuple of the modulo after dividing along with a boolean
3751 indicating whether an arithmetic overflow would occur. Note that for
3752 unsigned integers overflow never occurs, so the second value is
3753 always `false`.
3754 Since, for the positive integers, all common
3755 definitions of division are equal, this operation
3756 is exactly equal to `self.overflowing_rem(rhs)`.
3757
3758 # Panics
3759
3760 This function will panic if `rhs` is 0.
3761
3762 # Examples
3763
3764 Basic usage
3765
3766 ```
3767 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3768 ```"),
3769             #[inline]
3770             #[stable(feature = "euclidean_division", since = "1.38.0")]
3771             #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3772             #[must_use = "this returns the result of the operation, \
3773                           without modifying the original"]
3774             pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3775                 (self % rhs, false)
3776             }
3777         }
3778
3779         doc_comment! {
3780             concat!("Negates self in an overflowing fashion.
3781
3782 Returns `!self + 1` using wrapping operations to return the value
3783 that represents the negation of this unsigned value. Note that for
3784 positive unsigned values overflow always occurs, but negating 0 does
3785 not overflow.
3786
3787 # Examples
3788
3789 Basic usage
3790
3791 ```
3792 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3793 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3794 ", true));", $EndFeature, "
3795 ```"),
3796             #[inline]
3797             #[stable(feature = "wrapping", since = "1.7.0")]
3798             #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3799             pub const fn overflowing_neg(self) -> (Self, bool) {
3800                 ((!self).wrapping_add(1), self != 0)
3801             }
3802         }
3803
3804         doc_comment! {
3805             concat!("Shifts self left by `rhs` bits.
3806
3807 Returns a tuple of the shifted version of self along with a boolean
3808 indicating whether the shift value was larger than or equal to the
3809 number of bits. If the shift value is too large, then value is
3810 masked (N-1) where N is the number of bits, and this value is then
3811 used to perform the shift.
3812
3813 # Examples
3814
3815 Basic usage
3816
3817 ```
3818 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3819 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3820 ```"),
3821             #[stable(feature = "wrapping", since = "1.7.0")]
3822             #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3823             #[must_use = "this returns the result of the operation, \
3824                           without modifying the original"]
3825             #[inline]
3826             pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3827                 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3828             }
3829         }
3830
3831         doc_comment! {
3832             concat!("Shifts self right by `rhs` bits.
3833
3834 Returns a tuple of the shifted version of self along with a boolean
3835 indicating whether the shift value was larger than or equal to the
3836 number of bits. If the shift value is too large, then value is
3837 masked (N-1) where N is the number of bits, and this value is then
3838 used to perform the shift.
3839
3840 # Examples
3841
3842 Basic usage
3843
3844 ```
3845 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3846 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3847 ```"),
3848             #[stable(feature = "wrapping", since = "1.7.0")]
3849             #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3850             #[must_use = "this returns the result of the operation, \
3851                           without modifying the original"]
3852             #[inline]
3853             pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3854                 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3855             }
3856         }
3857
3858         doc_comment! {
3859             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3860
3861 Returns a tuple of the exponentiation along with a bool indicating
3862 whether an overflow happened.
3863
3864 # Examples
3865
3866 Basic usage:
3867
3868 ```
3869 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3870 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3871 ```"),
3872             #[stable(feature = "no_panic_pow", since = "1.34.0")]
3873             #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3874             #[must_use = "this returns the result of the operation, \
3875                           without modifying the original"]
3876             #[inline]
3877             pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3878                 let mut base = self;
3879                 let mut acc: Self = 1;
3880                 let mut overflown = false;
3881                 // Scratch space for storing results of overflowing_mul.
3882                 let mut r;
3883
3884                 while exp > 1 {
3885                     if (exp & 1) == 1 {
3886                         r = acc.overflowing_mul(base);
3887                         acc = r.0;
3888                         overflown |= r.1;
3889                     }
3890                     exp /= 2;
3891                     r = base.overflowing_mul(base);
3892                     base = r.0;
3893                     overflown |= r.1;
3894                 }
3895
3896                 // Deal with the final bit of the exponent separately, since
3897                 // squaring the base afterwards is not necessary and may cause a
3898                 // needless overflow.
3899                 if exp == 1 {
3900                     r = acc.overflowing_mul(base);
3901                     acc = r.0;
3902                     overflown |= r.1;
3903                 }
3904
3905                 (acc, overflown)
3906             }
3907         }
3908
3909         doc_comment! {
3910             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3911
3912 # Examples
3913
3914 Basic usage:
3915
3916 ```
3917 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3918 ```"),
3919         #[stable(feature = "rust1", since = "1.0.0")]
3920         #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3921         #[must_use = "this returns the result of the operation, \
3922                           without modifying the original"]
3923         #[inline]
3924         #[rustc_inherit_overflow_checks]
3925         pub const fn pow(self, mut exp: u32) -> Self {
3926             let mut base = self;
3927             let mut acc = 1;
3928
3929             while exp > 1 {
3930                 if (exp & 1) == 1 {
3931                     acc = acc * base;
3932                 }
3933                 exp /= 2;
3934                 base = base * base;
3935             }
3936
3937             // Deal with the final bit of the exponent separately, since
3938             // squaring the base afterwards is not necessary and may cause a
3939             // needless overflow.
3940             if exp == 1 {
3941                 acc = acc * base;
3942             }
3943
3944             acc
3945         }
3946     }
3947
3948             doc_comment! {
3949             concat!("Performs Euclidean division.
3950
3951 Since, for the positive integers, all common
3952 definitions of division are equal, this
3953 is exactly equal to `self / rhs`.
3954
3955 # Panics
3956
3957 This function will panic if `rhs` is 0.
3958
3959 # Examples
3960
3961 Basic usage:
3962
3963 ```
3964 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
3965 ```"),
3966             #[stable(feature = "euclidean_division", since = "1.38.0")]
3967             #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3968             #[must_use = "this returns the result of the operation, \
3969                           without modifying the original"]
3970             #[inline]
3971             #[rustc_inherit_overflow_checks]
3972             pub const fn div_euclid(self, rhs: Self) -> Self {
3973                 self / rhs
3974             }
3975         }
3976
3977
3978         doc_comment! {
3979             concat!("Calculates the least remainder of `self (mod rhs)`.
3980
3981 Since, for the positive integers, all common
3982 definitions of division are equal, this
3983 is exactly equal to `self % rhs`.
3984
3985 # Panics
3986
3987 This function will panic if `rhs` is 0.
3988
3989 # Examples
3990
3991 Basic usage:
3992
3993 ```
3994 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
3995 ```"),
3996             #[stable(feature = "euclidean_division", since = "1.38.0")]
3997             #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3998             #[must_use = "this returns the result of the operation, \
3999                           without modifying the original"]
4000             #[inline]
4001             #[rustc_inherit_overflow_checks]
4002             pub const fn rem_euclid(self, rhs: Self) -> Self {
4003                 self % rhs
4004             }
4005         }
4006
4007         doc_comment! {
4008             concat!("Returns `true` if and only if `self == 2^k` for some `k`.
4009
4010 # Examples
4011
4012 Basic usage:
4013
4014 ```
4015 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
4016 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
4017 ```"),
4018             #[stable(feature = "rust1", since = "1.0.0")]
4019             #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
4020             #[inline]
4021             pub const fn is_power_of_two(self) -> bool {
4022                 self.count_ones() == 1
4023             }
4024         }
4025
4026         // Returns one less than next power of two.
4027         // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
4028         //
4029         // 8u8.one_less_than_next_power_of_two() == 7
4030         // 6u8.one_less_than_next_power_of_two() == 7
4031         //
4032         // This method cannot overflow, as in the `next_power_of_two`
4033         // overflow cases it instead ends up returning the maximum value
4034         // of the type, and can return 0 for 0.
4035         #[inline]
4036         #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4037         const fn one_less_than_next_power_of_two(self) -> Self {
4038             if self <= 1 { return 0; }
4039
4040             let p = self - 1;
4041             // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4042             // That means the shift is always in-bounds, and some processors
4043             // (such as intel pre-haswell) have more efficient ctlz
4044             // intrinsics when the argument is non-zero.
4045             let z = unsafe { intrinsics::ctlz_nonzero(p) };
4046             <$SelfT>::max_value() >> z
4047         }
4048
4049         doc_comment! {
4050             concat!("Returns the smallest power of two greater than or equal to `self`.
4051
4052 When return value overflows (i.e., `self > (1 << (N-1))` for type
4053 `uN`), it panics in debug mode and return value is wrapped to 0 in
4054 release mode (the only situation in which method can return 0).
4055
4056 # Examples
4057
4058 Basic usage:
4059
4060 ```
4061 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4062 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4063 ```"),
4064             #[stable(feature = "rust1", since = "1.0.0")]
4065             #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4066             #[inline]
4067             #[rustc_inherit_overflow_checks]
4068             pub const fn next_power_of_two(self) -> Self {
4069                 self.one_less_than_next_power_of_two() + 1
4070             }
4071         }
4072
4073         doc_comment! {
4074             concat!("Returns the smallest power of two greater than or equal to `n`. If
4075 the next power of two is greater than the type's maximum value,
4076 `None` is returned, otherwise the power of two is wrapped in `Some`.
4077
4078 # Examples
4079
4080 Basic usage:
4081
4082 ```
4083 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4084 ".checked_next_power_of_two(), Some(2));
4085 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4086 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
4087 $EndFeature, "
4088 ```"),
4089             #[inline]
4090             #[stable(feature = "rust1", since = "1.0.0")]
4091             #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4092             pub const fn checked_next_power_of_two(self) -> Option<Self> {
4093                 self.one_less_than_next_power_of_two().checked_add(1)
4094             }
4095         }
4096
4097         doc_comment! {
4098             concat!("Returns the smallest power of two greater than or equal to `n`. If
4099 the next power of two is greater than the type's maximum value,
4100 the return value is wrapped to `0`.
4101
4102 # Examples
4103
4104 Basic usage:
4105
4106 ```
4107 #![feature(wrapping_next_power_of_two)]
4108 ", $Feature, "
4109 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4110 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4111 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
4112 $EndFeature, "
4113 ```"),
4114             #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4115                        reason = "needs decision on wrapping behaviour")]
4116             #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4117             pub const fn wrapping_next_power_of_two(self) -> Self {
4118                 self.one_less_than_next_power_of_two().wrapping_add(1)
4119             }
4120         }
4121
4122         doc_comment! {
4123             concat!("Return the memory representation of this integer as a byte array in
4124 big-endian (network) byte order.
4125 ",
4126 $to_xe_bytes_doc,
4127 "
4128 # Examples
4129
4130 ```
4131 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4132 assert_eq!(bytes, ", $be_bytes, ");
4133 ```"),
4134             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4135             #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4136             #[inline]
4137             pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4138                 self.to_be().to_ne_bytes()
4139             }
4140         }
4141
4142         doc_comment! {
4143             concat!("Return the memory representation of this integer as a byte array in
4144 little-endian byte order.
4145 ",
4146 $to_xe_bytes_doc,
4147 "
4148 # Examples
4149
4150 ```
4151 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4152 assert_eq!(bytes, ", $le_bytes, ");
4153 ```"),
4154             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4155             #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4156             #[inline]
4157             pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4158                 self.to_le().to_ne_bytes()
4159             }
4160         }
4161
4162         doc_comment! {
4163             concat!("
4164 Return the memory representation of this integer as a byte array in
4165 native byte order.
4166
4167 As the target platform's native endianness is used, portable code
4168 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4169 instead.
4170 ",
4171 $to_xe_bytes_doc,
4172 "
4173 [`to_be_bytes`]: #method.to_be_bytes
4174 [`to_le_bytes`]: #method.to_le_bytes
4175
4176 # Examples
4177
4178 ```
4179 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4180 assert_eq!(
4181     bytes,
4182     if cfg!(target_endian = \"big\") {
4183         ", $be_bytes, "
4184     } else {
4185         ", $le_bytes, "
4186     }
4187 );
4188 ```"),
4189             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4190             #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4191             #[inline]
4192             pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4193                 // SAFETY: integers are plain old datatypes so we can always transmute them to
4194                 // arrays of bytes
4195                 unsafe { mem::transmute(self) }
4196             }
4197         }
4198
4199         doc_comment! {
4200             concat!("Create an integer value from its representation as a byte array in
4201 big endian.
4202 ",
4203 $from_xe_bytes_doc,
4204 "
4205 # Examples
4206
4207 ```
4208 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4209 assert_eq!(value, ", $swap_op, ");
4210 ```
4211
4212 When starting from a slice rather than an array, fallible conversion APIs can be used:
4213
4214 ```
4215 use std::convert::TryInto;
4216
4217 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4218     let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4219     *input = rest;
4220     ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4221 }
4222 ```"),
4223             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4224             #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4225             #[inline]
4226             pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4227                 Self::from_be(Self::from_ne_bytes(bytes))
4228             }
4229         }
4230
4231         doc_comment! {
4232             concat!("
4233 Create an integer value from its representation as a byte array in
4234 little endian.
4235 ",
4236 $from_xe_bytes_doc,
4237 "
4238 # Examples
4239
4240 ```
4241 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4242 assert_eq!(value, ", $swap_op, ");
4243 ```
4244
4245 When starting from a slice rather than an array, fallible conversion APIs can be used:
4246
4247 ```
4248 use std::convert::TryInto;
4249
4250 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4251     let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4252     *input = rest;
4253     ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4254 }
4255 ```"),
4256             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4257             #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4258             #[inline]
4259             pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4260                 Self::from_le(Self::from_ne_bytes(bytes))
4261             }
4262         }
4263
4264         doc_comment! {
4265             concat!("Create an integer value from its memory representation as a byte
4266 array in native endianness.
4267
4268 As the target platform's native endianness is used, portable code
4269 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4270 appropriate instead.
4271
4272 [`from_be_bytes`]: #method.from_be_bytes
4273 [`from_le_bytes`]: #method.from_le_bytes
4274 ",
4275 $from_xe_bytes_doc,
4276 "
4277 # Examples
4278
4279 ```
4280 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4281     ", $be_bytes, "
4282 } else {
4283     ", $le_bytes, "
4284 });
4285 assert_eq!(value, ", $swap_op, ");
4286 ```
4287
4288 When starting from a slice rather than an array, fallible conversion APIs can be used:
4289
4290 ```
4291 use std::convert::TryInto;
4292
4293 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4294     let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4295     *input = rest;
4296     ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4297 }
4298 ```"),
4299             #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4300             #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4301             #[inline]
4302             pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4303                 // SAFETY: integers are plain old datatypes so we can always transmute to them
4304                 unsafe { mem::transmute(bytes) }
4305             }
4306         }
4307     }
4308 }
4309
4310 #[lang = "u8"]
4311 impl u8 {
4312     uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4313     "[0x12]", "", "" }
4314
4315     /// Checks if the value is within the ASCII range.
4316     ///
4317     /// # Examples
4318     ///
4319     /// ```
4320     /// let ascii = 97u8;
4321     /// let non_ascii = 150u8;
4322     ///
4323     /// assert!(ascii.is_ascii());
4324     /// assert!(!non_ascii.is_ascii());
4325     /// ```
4326     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4327     #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.43.0")]
4328     #[inline]
4329     pub const fn is_ascii(&self) -> bool {
4330         *self & 128 == 0
4331     }
4332
4333     /// Makes a copy of the value in its ASCII upper case equivalent.
4334     ///
4335     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4336     /// but non-ASCII letters are unchanged.
4337     ///
4338     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4339     ///
4340     /// # Examples
4341     ///
4342     /// ```
4343     /// let lowercase_a = 97u8;
4344     ///
4345     /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4346     /// ```
4347     ///
4348     /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4349     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4350     #[inline]
4351     pub fn to_ascii_uppercase(&self) -> u8 {
4352         // Unset the fith bit if this is a lowercase letter
4353         *self & !((self.is_ascii_lowercase() as u8) << 5)
4354     }
4355
4356     /// Makes a copy of the value in its ASCII lower case equivalent.
4357     ///
4358     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4359     /// but non-ASCII letters are unchanged.
4360     ///
4361     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4362     ///
4363     /// # Examples
4364     ///
4365     /// ```
4366     /// let uppercase_a = 65u8;
4367     ///
4368     /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4369     /// ```
4370     ///
4371     /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4372     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4373     #[inline]
4374     pub fn to_ascii_lowercase(&self) -> u8 {
4375         // Set the fith bit if this is an uppercase letter
4376         *self | ((self.is_ascii_uppercase() as u8) << 5)
4377     }
4378
4379     /// Checks that two values are an ASCII case-insensitive match.
4380     ///
4381     /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4382     ///
4383     /// # Examples
4384     ///
4385     /// ```
4386     /// let lowercase_a = 97u8;
4387     /// let uppercase_a = 65u8;
4388     ///
4389     /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4390     /// ```
4391     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4392     #[inline]
4393     pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4394         self.to_ascii_lowercase() == other.to_ascii_lowercase()
4395     }
4396
4397     /// Converts this value to its ASCII upper case equivalent in-place.
4398     ///
4399     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4400     /// but non-ASCII letters are unchanged.
4401     ///
4402     /// To return a new uppercased value without modifying the existing one, use
4403     /// [`to_ascii_uppercase`].
4404     ///
4405     /// # Examples
4406     ///
4407     /// ```
4408     /// let mut byte = b'a';
4409     ///
4410     /// byte.make_ascii_uppercase();
4411     ///
4412     /// assert_eq!(b'A', byte);
4413     /// ```
4414     ///
4415     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4416     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4417     #[inline]
4418     pub fn make_ascii_uppercase(&mut self) {
4419         *self = self.to_ascii_uppercase();
4420     }
4421
4422     /// Converts this value to its ASCII lower case equivalent in-place.
4423     ///
4424     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4425     /// but non-ASCII letters are unchanged.
4426     ///
4427     /// To return a new lowercased value without modifying the existing one, use
4428     /// [`to_ascii_lowercase`].
4429     ///
4430     /// # Examples
4431     ///
4432     /// ```
4433     /// let mut byte = b'A';
4434     ///
4435     /// byte.make_ascii_lowercase();
4436     ///
4437     /// assert_eq!(b'a', byte);
4438     /// ```
4439     ///
4440     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4441     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4442     #[inline]
4443     pub fn make_ascii_lowercase(&mut self) {
4444         *self = self.to_ascii_lowercase();
4445     }
4446
4447     /// Checks if the value is an ASCII alphabetic character:
4448     ///
4449     /// - U+0041 'A' ..= U+005A 'Z', or
4450     /// - U+0061 'a' ..= U+007A 'z'.
4451     ///
4452     /// # Examples
4453     ///
4454     /// ```
4455     /// let uppercase_a = b'A';
4456     /// let uppercase_g = b'G';
4457     /// let a = b'a';
4458     /// let g = b'g';
4459     /// let zero = b'0';
4460     /// let percent = b'%';
4461     /// let space = b' ';
4462     /// let lf = b'\n';
4463     /// let esc = 0x1b_u8;
4464     ///
4465     /// assert!(uppercase_a.is_ascii_alphabetic());
4466     /// assert!(uppercase_g.is_ascii_alphabetic());
4467     /// assert!(a.is_ascii_alphabetic());
4468     /// assert!(g.is_ascii_alphabetic());
4469     /// assert!(!zero.is_ascii_alphabetic());
4470     /// assert!(!percent.is_ascii_alphabetic());
4471     /// assert!(!space.is_ascii_alphabetic());
4472     /// assert!(!lf.is_ascii_alphabetic());
4473     /// assert!(!esc.is_ascii_alphabetic());
4474     /// ```
4475     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4476     #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4477     #[inline]
4478     pub const fn is_ascii_alphabetic(&self) -> bool {
4479         matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
4480     }
4481
4482     /// Checks if the value is an ASCII uppercase character:
4483     /// U+0041 'A' ..= U+005A 'Z'.
4484     ///
4485     /// # Examples
4486     ///
4487     /// ```
4488     /// let uppercase_a = b'A';
4489     /// let uppercase_g = b'G';
4490     /// let a = b'a';
4491     /// let g = b'g';
4492     /// let zero = b'0';
4493     /// let percent = b'%';
4494     /// let space = b' ';
4495     /// let lf = b'\n';
4496     /// let esc = 0x1b_u8;
4497     ///
4498     /// assert!(uppercase_a.is_ascii_uppercase());
4499     /// assert!(uppercase_g.is_ascii_uppercase());
4500     /// assert!(!a.is_ascii_uppercase());
4501     /// assert!(!g.is_ascii_uppercase());
4502     /// assert!(!zero.is_ascii_uppercase());
4503     /// assert!(!percent.is_ascii_uppercase());
4504     /// assert!(!space.is_ascii_uppercase());
4505     /// assert!(!lf.is_ascii_uppercase());
4506     /// assert!(!esc.is_ascii_uppercase());
4507     /// ```
4508     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4509     #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4510     #[inline]
4511     pub const fn is_ascii_uppercase(&self) -> bool {
4512         matches!(*self, b'A'..=b'Z')
4513     }
4514
4515     /// Checks if the value is an ASCII lowercase character:
4516     /// U+0061 'a' ..= U+007A 'z'.
4517     ///
4518     /// # Examples
4519     ///
4520     /// ```
4521     /// let uppercase_a = b'A';
4522     /// let uppercase_g = b'G';
4523     /// let a = b'a';
4524     /// let g = b'g';
4525     /// let zero = b'0';
4526     /// let percent = b'%';
4527     /// let space = b' ';
4528     /// let lf = b'\n';
4529     /// let esc = 0x1b_u8;
4530     ///
4531     /// assert!(!uppercase_a.is_ascii_lowercase());
4532     /// assert!(!uppercase_g.is_ascii_lowercase());
4533     /// assert!(a.is_ascii_lowercase());
4534     /// assert!(g.is_ascii_lowercase());
4535     /// assert!(!zero.is_ascii_lowercase());
4536     /// assert!(!percent.is_ascii_lowercase());
4537     /// assert!(!space.is_ascii_lowercase());
4538     /// assert!(!lf.is_ascii_lowercase());
4539     /// assert!(!esc.is_ascii_lowercase());
4540     /// ```
4541     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4542     #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4543     #[inline]
4544     pub const fn is_ascii_lowercase(&self) -> bool {
4545         matches!(*self, b'a'..=b'z')
4546     }
4547
4548     /// Checks if the value is an ASCII alphanumeric character:
4549     ///
4550     /// - U+0041 'A' ..= U+005A 'Z', or
4551     /// - U+0061 'a' ..= U+007A 'z', or
4552     /// - U+0030 '0' ..= U+0039 '9'.
4553     ///
4554     /// # Examples
4555     ///
4556     /// ```
4557     /// let uppercase_a = b'A';
4558     /// let uppercase_g = b'G';
4559     /// let a = b'a';
4560     /// let g = b'g';
4561     /// let zero = b'0';
4562     /// let percent = b'%';
4563     /// let space = b' ';
4564     /// let lf = b'\n';
4565     /// let esc = 0x1b_u8;
4566     ///
4567     /// assert!(uppercase_a.is_ascii_alphanumeric());
4568     /// assert!(uppercase_g.is_ascii_alphanumeric());
4569     /// assert!(a.is_ascii_alphanumeric());
4570     /// assert!(g.is_ascii_alphanumeric());
4571     /// assert!(zero.is_ascii_alphanumeric());
4572     /// assert!(!percent.is_ascii_alphanumeric());
4573     /// assert!(!space.is_ascii_alphanumeric());
4574     /// assert!(!lf.is_ascii_alphanumeric());
4575     /// assert!(!esc.is_ascii_alphanumeric());
4576     /// ```
4577     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4578     #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4579     #[inline]
4580     pub const fn is_ascii_alphanumeric(&self) -> bool {
4581         matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
4582     }
4583
4584     /// Checks if the value is an ASCII decimal digit:
4585     /// U+0030 '0' ..= U+0039 '9'.
4586     ///
4587     /// # Examples
4588     ///
4589     /// ```
4590     /// let uppercase_a = b'A';
4591     /// let uppercase_g = b'G';
4592     /// let a = b'a';
4593     /// let g = b'g';
4594     /// let zero = b'0';
4595     /// let percent = b'%';
4596     /// let space = b' ';
4597     /// let lf = b'\n';
4598     /// let esc = 0x1b_u8;
4599     ///
4600     /// assert!(!uppercase_a.is_ascii_digit());
4601     /// assert!(!uppercase_g.is_ascii_digit());
4602     /// assert!(!a.is_ascii_digit());
4603     /// assert!(!g.is_ascii_digit());
4604     /// assert!(zero.is_ascii_digit());
4605     /// assert!(!percent.is_ascii_digit());
4606     /// assert!(!space.is_ascii_digit());
4607     /// assert!(!lf.is_ascii_digit());
4608     /// assert!(!esc.is_ascii_digit());
4609     /// ```
4610     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4611     #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4612     #[inline]
4613     pub const fn is_ascii_digit(&self) -> bool {
4614         matches!(*self, b'0'..=b'9')
4615     }
4616
4617     /// Checks if the value is an ASCII hexadecimal digit:
4618     ///
4619     /// - U+0030 '0' ..= U+0039 '9', or
4620     /// - U+0041 'A' ..= U+0046 'F', or
4621     /// - U+0061 'a' ..= U+0066 'f'.
4622     ///
4623     /// # Examples
4624     ///
4625     /// ```
4626     /// let uppercase_a = b'A';
4627     /// let uppercase_g = b'G';
4628     /// let a = b'a';
4629     /// let g = b'g';
4630     /// let zero = b'0';
4631     /// let percent = b'%';
4632     /// let space = b' ';
4633     /// let lf = b'\n';
4634     /// let esc = 0x1b_u8;
4635     ///
4636     /// assert!(uppercase_a.is_ascii_hexdigit());
4637     /// assert!(!uppercase_g.is_ascii_hexdigit());
4638     /// assert!(a.is_ascii_hexdigit());
4639     /// assert!(!g.is_ascii_hexdigit());
4640     /// assert!(zero.is_ascii_hexdigit());
4641     /// assert!(!percent.is_ascii_hexdigit());
4642     /// assert!(!space.is_ascii_hexdigit());
4643     /// assert!(!lf.is_ascii_hexdigit());
4644     /// assert!(!esc.is_ascii_hexdigit());
4645     /// ```
4646     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4647     #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4648     #[inline]
4649     pub const fn is_ascii_hexdigit(&self) -> bool {
4650         matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
4651     }
4652
4653     /// Checks if the value is an ASCII punctuation character:
4654     ///
4655     /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4656     /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4657     /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4658     /// - U+007B ..= U+007E `{ | } ~`
4659     ///
4660     /// # Examples
4661     ///
4662     /// ```
4663     /// let uppercase_a = b'A';
4664     /// let uppercase_g = b'G';
4665     /// let a = b'a';
4666     /// let g = b'g';
4667     /// let zero = b'0';
4668     /// let percent = b'%';
4669     /// let space = b' ';
4670     /// let lf = b'\n';
4671     /// let esc = 0x1b_u8;
4672     ///
4673     /// assert!(!uppercase_a.is_ascii_punctuation());
4674     /// assert!(!uppercase_g.is_ascii_punctuation());
4675     /// assert!(!a.is_ascii_punctuation());
4676     /// assert!(!g.is_ascii_punctuation());
4677     /// assert!(!zero.is_ascii_punctuation());
4678     /// assert!(percent.is_ascii_punctuation());
4679     /// assert!(!space.is_ascii_punctuation());
4680     /// assert!(!lf.is_ascii_punctuation());
4681     /// assert!(!esc.is_ascii_punctuation());
4682     /// ```
4683     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4684     #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4685     #[inline]
4686     pub const fn is_ascii_punctuation(&self) -> bool {
4687         matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
4688     }
4689
4690     /// Checks if the value is an ASCII graphic character:
4691     /// U+0021 '!' ..= U+007E '~'.
4692     ///
4693     /// # Examples
4694     ///
4695     /// ```
4696     /// let uppercase_a = b'A';
4697     /// let uppercase_g = b'G';
4698     /// let a = b'a';
4699     /// let g = b'g';
4700     /// let zero = b'0';
4701     /// let percent = b'%';
4702     /// let space = b' ';
4703     /// let lf = b'\n';
4704     /// let esc = 0x1b_u8;
4705     ///
4706     /// assert!(uppercase_a.is_ascii_graphic());
4707     /// assert!(uppercase_g.is_ascii_graphic());
4708     /// assert!(a.is_ascii_graphic());
4709     /// assert!(g.is_ascii_graphic());
4710     /// assert!(zero.is_ascii_graphic());
4711     /// assert!(percent.is_ascii_graphic());
4712     /// assert!(!space.is_ascii_graphic());
4713     /// assert!(!lf.is_ascii_graphic());
4714     /// assert!(!esc.is_ascii_graphic());
4715     /// ```
4716     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4717     #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4718     #[inline]
4719     pub const fn is_ascii_graphic(&self) -> bool {
4720         matches!(*self, b'!'..=b'~')
4721     }
4722
4723     /// Checks if the value is an ASCII whitespace character:
4724     /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4725     /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4726     ///
4727     /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4728     /// whitespace][infra-aw]. There are several other definitions in
4729     /// wide use. For instance, [the POSIX locale][pct] includes
4730     /// U+000B VERTICAL TAB as well as all the above characters,
4731     /// but—from the very same specification—[the default rule for
4732     /// "field splitting" in the Bourne shell][bfs] considers *only*
4733     /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4734     ///
4735     /// If you are writing a program that will process an existing
4736     /// file format, check what that format's definition of whitespace is
4737     /// before using this function.
4738     ///
4739     /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4740     /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4741     /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4742     ///
4743     /// # Examples
4744     ///
4745     /// ```
4746     /// let uppercase_a = b'A';
4747     /// let uppercase_g = b'G';
4748     /// let a = b'a';
4749     /// let g = b'g';
4750     /// let zero = b'0';
4751     /// let percent = b'%';
4752     /// let space = b' ';
4753     /// let lf = b'\n';
4754     /// let esc = 0x1b_u8;
4755     ///
4756     /// assert!(!uppercase_a.is_ascii_whitespace());
4757     /// assert!(!uppercase_g.is_ascii_whitespace());
4758     /// assert!(!a.is_ascii_whitespace());
4759     /// assert!(!g.is_ascii_whitespace());
4760     /// assert!(!zero.is_ascii_whitespace());
4761     /// assert!(!percent.is_ascii_whitespace());
4762     /// assert!(space.is_ascii_whitespace());
4763     /// assert!(lf.is_ascii_whitespace());
4764     /// assert!(!esc.is_ascii_whitespace());
4765     /// ```
4766     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4767     #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4768     #[inline]
4769     pub const fn is_ascii_whitespace(&self) -> bool {
4770         matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
4771     }
4772
4773     /// Checks if the value is an ASCII control character:
4774     /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4775     /// Note that most ASCII whitespace characters are control
4776     /// characters, but SPACE is not.
4777     ///
4778     /// # Examples
4779     ///
4780     /// ```
4781     /// let uppercase_a = b'A';
4782     /// let uppercase_g = b'G';
4783     /// let a = b'a';
4784     /// let g = b'g';
4785     /// let zero = b'0';
4786     /// let percent = b'%';
4787     /// let space = b' ';
4788     /// let lf = b'\n';
4789     /// let esc = 0x1b_u8;
4790     ///
4791     /// assert!(!uppercase_a.is_ascii_control());
4792     /// assert!(!uppercase_g.is_ascii_control());
4793     /// assert!(!a.is_ascii_control());
4794     /// assert!(!g.is_ascii_control());
4795     /// assert!(!zero.is_ascii_control());
4796     /// assert!(!percent.is_ascii_control());
4797     /// assert!(!space.is_ascii_control());
4798     /// assert!(lf.is_ascii_control());
4799     /// assert!(esc.is_ascii_control());
4800     /// ```
4801     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4802     #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4803     #[inline]
4804     pub const fn is_ascii_control(&self) -> bool {
4805         matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
4806     }
4807 }
4808
4809 #[lang = "u16"]
4810 impl u16 {
4811     uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4812     "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4813 }
4814
4815 #[lang = "u32"]
4816 impl u32 {
4817     uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4818     "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4819 }
4820
4821 #[lang = "u64"]
4822 impl u64 {
4823     uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4824     "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4825     "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4826     "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4827     "", ""}
4828 }
4829
4830 #[lang = "u128"]
4831 impl u128 {
4832     uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4833     "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4834     "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4835     "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4836       0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4837     "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4838       0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4839      "", ""}
4840 }
4841
4842 #[cfg(target_pointer_width = "16")]
4843 #[lang = "usize"]
4844 impl usize {
4845     uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4846     "[0x34, 0x12]", "[0x12, 0x34]",
4847     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4848 }
4849 #[cfg(target_pointer_width = "32")]
4850 #[lang = "usize"]
4851 impl usize {
4852     uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4853     "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4854     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4855 }
4856
4857 #[cfg(target_pointer_width = "64")]
4858 #[lang = "usize"]
4859 impl usize {
4860     uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4861     "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4862     "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4863      "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4864     usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4865 }
4866
4867 /// A classification of floating point numbers.
4868 ///
4869 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4870 /// their documentation for more.
4871 ///
4872 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4873 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4874 ///
4875 /// # Examples
4876 ///
4877 /// ```
4878 /// use std::num::FpCategory;
4879 /// use std::f32;
4880 ///
4881 /// let num = 12.4_f32;
4882 /// let inf = f32::INFINITY;
4883 /// let zero = 0f32;
4884 /// let sub: f32 = 1.1754942e-38;
4885 /// let nan = f32::NAN;
4886 ///
4887 /// assert_eq!(num.classify(), FpCategory::Normal);
4888 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4889 /// assert_eq!(zero.classify(), FpCategory::Zero);
4890 /// assert_eq!(nan.classify(), FpCategory::Nan);
4891 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4892 /// ```
4893 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4894 #[stable(feature = "rust1", since = "1.0.0")]
4895 pub enum FpCategory {
4896     /// "Not a Number", often obtained by dividing by zero.
4897     #[stable(feature = "rust1", since = "1.0.0")]
4898     Nan,
4899
4900     /// Positive or negative infinity.
4901     #[stable(feature = "rust1", since = "1.0.0")]
4902     Infinite,
4903
4904     /// Positive or negative zero.
4905     #[stable(feature = "rust1", since = "1.0.0")]
4906     Zero,
4907
4908     /// De-normalized floating point representation (less precise than `Normal`).
4909     #[stable(feature = "rust1", since = "1.0.0")]
4910     Subnormal,
4911
4912     /// A regular floating point number.
4913     #[stable(feature = "rust1", since = "1.0.0")]
4914     Normal,
4915 }
4916
4917 macro_rules! from_str_radix_int_impl {
4918     ($($t:ty)*) => {$(
4919         #[stable(feature = "rust1", since = "1.0.0")]
4920         impl FromStr for $t {
4921             type Err = ParseIntError;
4922             fn from_str(src: &str) -> Result<Self, ParseIntError> {
4923                 from_str_radix(src, 10)
4924             }
4925         }
4926     )*}
4927 }
4928 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4929
4930 /// The error type returned when a checked integral type conversion fails.
4931 #[stable(feature = "try_from", since = "1.34.0")]
4932 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4933 pub struct TryFromIntError(pub(crate) ());
4934
4935 impl TryFromIntError {
4936     #[unstable(
4937         feature = "int_error_internals",
4938         reason = "available through Error trait and this method should \
4939                   not be exposed publicly",
4940         issue = "none"
4941     )]
4942     #[doc(hidden)]
4943     pub fn __description(&self) -> &str {
4944         "out of range integral type conversion attempted"
4945     }
4946 }
4947
4948 #[stable(feature = "try_from", since = "1.34.0")]
4949 impl fmt::Display for TryFromIntError {
4950     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4951         self.__description().fmt(fmt)
4952     }
4953 }
4954
4955 #[stable(feature = "try_from", since = "1.34.0")]
4956 impl From<Infallible> for TryFromIntError {
4957     fn from(x: Infallible) -> TryFromIntError {
4958         match x {}
4959     }
4960 }
4961
4962 #[unstable(feature = "never_type", issue = "35121")]
4963 impl From<!> for TryFromIntError {
4964     fn from(never: !) -> TryFromIntError {
4965         // Match rather than coerce to make sure that code like
4966         // `From<Infallible> for TryFromIntError` above will keep working
4967         // when `Infallible` becomes an alias to `!`.
4968         match never {}
4969     }
4970 }
4971
4972 #[doc(hidden)]
4973 trait FromStrRadixHelper: PartialOrd + Copy {
4974     fn min_value() -> Self;
4975     fn max_value() -> Self;
4976     fn from_u32(u: u32) -> Self;
4977     fn checked_mul(&self, other: u32) -> Option<Self>;
4978     fn checked_sub(&self, other: u32) -> Option<Self>;
4979     fn checked_add(&self, other: u32) -> Option<Self>;
4980 }
4981
4982 macro_rules! doit {
4983     ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4984         #[inline]
4985         fn min_value() -> Self { Self::min_value() }
4986         #[inline]
4987         fn max_value() -> Self { Self::max_value() }
4988         #[inline]
4989         fn from_u32(u: u32) -> Self { u as Self }
4990         #[inline]
4991         fn checked_mul(&self, other: u32) -> Option<Self> {
4992             Self::checked_mul(*self, other as Self)
4993         }
4994         #[inline]
4995         fn checked_sub(&self, other: u32) -> Option<Self> {
4996             Self::checked_sub(*self, other as Self)
4997         }
4998         #[inline]
4999         fn checked_add(&self, other: u32) -> Option<Self> {
5000             Self::checked_add(*self, other as Self)
5001         }
5002     })*)
5003 }
5004 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5005
5006 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5007     use self::IntErrorKind::*;
5008     use self::ParseIntError as PIE;
5009
5010     assert!(
5011         radix >= 2 && radix <= 36,
5012         "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5013         radix
5014     );
5015
5016     if src.is_empty() {
5017         return Err(PIE { kind: Empty });
5018     }
5019
5020     let is_signed_ty = T::from_u32(0) > T::min_value();
5021
5022     // all valid digits are ascii, so we will just iterate over the utf8 bytes
5023     // and cast them to chars. .to_digit() will safely return None for anything
5024     // other than a valid ascii digit for the given radix, including the first-byte
5025     // of multi-byte sequences
5026     let src = src.as_bytes();
5027
5028     let (is_positive, digits) = match src[0] {
5029         b'+' => (true, &src[1..]),
5030         b'-' if is_signed_ty => (false, &src[1..]),
5031         _ => (true, src),
5032     };
5033
5034     if digits.is_empty() {
5035         return Err(PIE { kind: Empty });
5036     }
5037
5038     let mut result = T::from_u32(0);
5039     if is_positive {
5040         // The number is positive
5041         for &c in digits {
5042             let x = match (c as char).to_digit(radix) {
5043                 Some(x) => x,
5044                 None => return Err(PIE { kind: InvalidDigit }),
5045             };
5046             result = match result.checked_mul(radix) {
5047                 Some(result) => result,
5048                 None => return Err(PIE { kind: Overflow }),
5049             };
5050             result = match result.checked_add(x) {
5051                 Some(result) => result,
5052                 None => return Err(PIE { kind: Overflow }),
5053             };
5054         }
5055     } else {
5056         // The number is negative
5057         for &c in digits {
5058             let x = match (c as char).to_digit(radix) {
5059                 Some(x) => x,
5060                 None => return Err(PIE { kind: InvalidDigit }),
5061             };
5062             result = match result.checked_mul(radix) {
5063                 Some(result) => result,
5064                 None => return Err(PIE { kind: Underflow }),
5065             };
5066             result = match result.checked_sub(x) {
5067                 Some(result) => result,
5068                 None => return Err(PIE { kind: Underflow }),
5069             };
5070         }
5071     }
5072     Ok(result)
5073 }
5074
5075 /// An error which can be returned when parsing an integer.
5076 ///
5077 /// This error is used as the error type for the `from_str_radix()` functions
5078 /// on the primitive integer types, such as [`i8::from_str_radix`].
5079 ///
5080 /// # Potential causes
5081 ///
5082 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5083 /// in the string e.g., when it is obtained from the standard input.
5084 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5085 ///
5086 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5087 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5088 #[derive(Debug, Clone, PartialEq, Eq)]
5089 #[stable(feature = "rust1", since = "1.0.0")]
5090 pub struct ParseIntError {
5091     kind: IntErrorKind,
5092 }
5093
5094 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5095 #[unstable(
5096     feature = "int_error_matching",
5097     reason = "it can be useful to match errors when making error messages \
5098               for integer parsing",
5099     issue = "22639"
5100 )]
5101 #[derive(Debug, Clone, PartialEq, Eq)]
5102 #[non_exhaustive]
5103 pub enum IntErrorKind {
5104     /// Value being parsed is empty.
5105     ///
5106     /// Among other causes, this variant will be constructed when parsing an empty string.
5107     Empty,
5108     /// Contains an invalid digit.
5109     ///
5110     /// Among other causes, this variant will be constructed when parsing a string that
5111     /// contains a letter.
5112     InvalidDigit,
5113     /// Integer is too large to store in target integer type.
5114     Overflow,
5115     /// Integer is too small to store in target integer type.
5116     Underflow,
5117     /// Value was Zero
5118     ///
5119     /// This variant will be emitted when the parsing string has a value of zero, which
5120     /// would be illegal for non-zero types.
5121     Zero,
5122 }
5123
5124 impl ParseIntError {
5125     /// Outputs the detailed cause of parsing an integer failing.
5126     #[unstable(
5127         feature = "int_error_matching",
5128         reason = "it can be useful to match errors when making error messages \
5129                   for integer parsing",
5130         issue = "22639"
5131     )]
5132     pub fn kind(&self) -> &IntErrorKind {
5133         &self.kind
5134     }
5135     #[unstable(
5136         feature = "int_error_internals",
5137         reason = "available through Error trait and this method should \
5138                   not be exposed publicly",
5139         issue = "none"
5140     )]
5141     #[doc(hidden)]
5142     pub fn __description(&self) -> &str {
5143         match self.kind {
5144             IntErrorKind::Empty => "cannot parse integer from empty string",
5145             IntErrorKind::InvalidDigit => "invalid digit found in string",
5146             IntErrorKind::Overflow => "number too large to fit in target type",
5147             IntErrorKind::Underflow => "number too small to fit in target type",
5148             IntErrorKind::Zero => "number would be zero for non-zero type",
5149         }
5150     }
5151 }
5152
5153 #[stable(feature = "rust1", since = "1.0.0")]
5154 impl fmt::Display for ParseIntError {
5155     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5156         self.__description().fmt(f)
5157     }
5158 }
5159
5160 #[stable(feature = "rust1", since = "1.0.0")]
5161 pub use crate::num::dec2flt::ParseFloatError;