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