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