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