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