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