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