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