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