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