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