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