]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
Implement RFC #2169 (Euclidean division).
[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)`, returning `None` if `rhs == 0`
638 or the division results in overflow.
639
640 # Examples
641
642 Basic usage:
643
644 ```
645 ", $Feature, "assert_eq!((", stringify!($SelfT),
646 "::min_value() + 1).checked_div_euc(-1), Some(", stringify!($Max), "));
647 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euc(-1), None);
648 assert_eq!((1", stringify!($SelfT), ").checked_div_euc(0), None);",
649 $EndFeature, "
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, "use std::", stringify!($SelfT), ";
699
700 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
701 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
702 assert_eq!(", stringify!($SelfT), "::MIN.checked_mod_euc(-1), None);",
703 $EndFeature, "
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)`, wrapping around at the
1051 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 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
1067 assert_eq!((-128i8).wrapping_div_euc(-1), -128);",
1068 $EndFeature, "
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, "assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
1123 assert_eq!((-128i8).wrapping_mod_euc(-1), 0);",
1124 $EndFeature, "
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, "use std::", stringify!($SelfT), ";
1414
1415 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
1416 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euc(-1), (", stringify!($SelfT),
1417 "::MIN, true));",
1418 $EndFeature, "
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 modulo of Euclidean divsion `self.mod_euc(rhs)`.
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, "use std::", stringify!($SelfT), ";
1480
1481 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
1482 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_mod_euc(-1), (0, true));",
1483 $EndFeature, "
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, "let a: ", stringify!($SelfT), " = 7; // or any other integer type
1708 let b = 4;
1709
1710 assert_eq!(a.div_euc(b), 1); // 7 >= 4 * 1
1711 assert_eq!(a.div_euc(-b), -1); // 7 >= -4 * -1
1712 assert_eq!((-a).div_euc(b), -2); // -7 >= 4 * -2
1713 assert_eq!((-a).div_euc(-b), 2); // -7 >= -4 * 2",
1714 $EndFeature, "
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 modulo `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, "let a: ", stringify!($SelfT), " = 7; // or any other integer type
1744 let b = 4;
1745
1746 assert_eq!(a.mod_euc(b), 3);
1747 assert_eq!((-a).mod_euc(b), 1);
1748 assert_eq!(a.mod_euc(-b), 3);
1749 assert_eq!((-a).mod_euc(-b), 1);",
1750 $EndFeature, "
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, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2366 assert_eq!(1", stringify!($SelfT), ".checked_div_euc(0), None);
2367 ```"),
2368             #[unstable(feature = "euclidean_division", issue = "49048")]
2369             #[inline]
2370             pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
2371                 if rhs == 0 {
2372                     None
2373                 } else {
2374                     Some(self.div_euc(rhs))
2375                 }
2376             }
2377         }
2378
2379
2380         doc_comment! {
2381             concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2382 if `rhs == 0`.
2383
2384 # Examples
2385
2386 Basic usage:
2387
2388 ```
2389 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2390 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2391 ```"),
2392             #[stable(feature = "wrapping", since = "1.7.0")]
2393             #[inline]
2394             pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2395                 if rhs == 0 {
2396                     None
2397                 } else {
2398                     Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2399                 }
2400             }
2401         }
2402
2403         doc_comment! {
2404             concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None`
2405 if `rhs == 0`.
2406
2407 # Examples
2408
2409 Basic usage:
2410
2411 ```
2412 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
2413 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);",
2414 $EndFeature, "
2415 ```"),
2416             #[unstable(feature = "euclidean_division", issue = "49048")]
2417             #[inline]
2418             pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
2419                 if rhs == 0 {
2420                     None
2421                 } else {
2422                     Some(self.mod_euc(rhs))
2423                 }
2424             }
2425         }
2426
2427         doc_comment! {
2428             concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2429 0`.
2430
2431 Note that negating any positive integer will overflow.
2432
2433 # Examples
2434
2435 Basic usage:
2436
2437 ```
2438 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2439 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2440 ```"),
2441             #[stable(feature = "wrapping", since = "1.7.0")]
2442             #[inline]
2443             pub fn checked_neg(self) -> Option<Self> {
2444                 let (a, b) = self.overflowing_neg();
2445                 if b {None} else {Some(a)}
2446             }
2447         }
2448
2449         doc_comment! {
2450             concat!("Checked shift left. Computes `self << rhs`, returning `None`
2451 if `rhs` is larger than or equal to the number of bits in `self`.
2452
2453 # Examples
2454
2455 Basic usage:
2456
2457 ```
2458 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2459 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2460 ```"),
2461             #[stable(feature = "wrapping", since = "1.7.0")]
2462             #[inline]
2463             pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2464                 let (a, b) = self.overflowing_shl(rhs);
2465                 if b {None} else {Some(a)}
2466             }
2467         }
2468
2469         doc_comment! {
2470             concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2471 if `rhs` is larger than or equal to the number of bits in `self`.
2472
2473 # Examples
2474
2475 Basic usage:
2476
2477 ```
2478 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2479 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2480 ```"),
2481             #[stable(feature = "wrapping", since = "1.7.0")]
2482             #[inline]
2483             pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2484                 let (a, b) = self.overflowing_shr(rhs);
2485                 if b {None} else {Some(a)}
2486             }
2487         }
2488
2489         doc_comment! {
2490             concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2491 overflow occurred.
2492
2493 # Examples
2494
2495 Basic usage:
2496
2497 ```
2498 #![feature(no_panic_pow)]
2499 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2500 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2501 ```"),
2502             #[unstable(feature = "no_panic_pow", issue = "48320")]
2503             #[inline]
2504             pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2505                 let mut base = self;
2506                 let mut acc: Self = 1;
2507
2508                 while exp > 1 {
2509                     if (exp & 1) == 1 {
2510                         acc = acc.checked_mul(base)?;
2511                     }
2512                     exp /= 2;
2513                     base = base.checked_mul(base)?;
2514                 }
2515
2516                 // Deal with the final bit of the exponent separately, since
2517                 // squaring the base afterwards is not necessary and may cause a
2518                 // needless overflow.
2519                 if exp == 1 {
2520                     acc = acc.checked_mul(base)?;
2521                 }
2522
2523                 Some(acc)
2524             }
2525         }
2526
2527         doc_comment! {
2528             concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2529 the numeric bounds instead of overflowing.
2530
2531 # Examples
2532
2533 Basic usage:
2534
2535 ```
2536 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2537 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2538 ```"),
2539             #[stable(feature = "rust1", since = "1.0.0")]
2540             #[inline]
2541             pub fn saturating_add(self, rhs: Self) -> Self {
2542                 match self.checked_add(rhs) {
2543                     Some(x) => x,
2544                     None => Self::max_value(),
2545                 }
2546             }
2547         }
2548
2549         doc_comment! {
2550             concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2551 at the numeric bounds instead of overflowing.
2552
2553 # Examples
2554
2555 Basic usage:
2556
2557 ```
2558 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2559 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2560 ```"),
2561             #[stable(feature = "rust1", since = "1.0.0")]
2562             #[inline]
2563             pub fn saturating_sub(self, rhs: Self) -> Self {
2564                 match self.checked_sub(rhs) {
2565                     Some(x) => x,
2566                     None => Self::min_value(),
2567                 }
2568             }
2569         }
2570
2571         doc_comment! {
2572             concat!("Saturating integer multiplication. Computes `self * rhs`,
2573 saturating at the numeric bounds instead of overflowing.
2574
2575 # Examples
2576
2577 Basic usage:
2578
2579 ```
2580 ", $Feature, "use std::", stringify!($SelfT), ";
2581
2582 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2583 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2584 "::MAX);", $EndFeature, "
2585 ```"),
2586             #[stable(feature = "wrapping", since = "1.7.0")]
2587             #[inline]
2588             pub fn saturating_mul(self, rhs: Self) -> Self {
2589                 self.checked_mul(rhs).unwrap_or(Self::max_value())
2590             }
2591         }
2592
2593         doc_comment! {
2594             concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2595 saturating at the numeric bounds instead of overflowing.
2596
2597 # Examples
2598
2599 Basic usage:
2600
2601 ```
2602 #![feature(no_panic_pow)]
2603 ", $Feature, "use std::", stringify!($SelfT), ";
2604
2605 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2606 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2607 $EndFeature, "
2608 ```"),
2609             #[unstable(feature = "no_panic_pow", issue = "48320")]
2610             #[inline]
2611             pub fn saturating_pow(self, exp: u32) -> Self {
2612                 match self.checked_pow(exp) {
2613                     Some(x) => x,
2614                     None => Self::max_value(),
2615                 }
2616             }
2617         }
2618
2619         doc_comment! {
2620             concat!("Wrapping (modular) addition. Computes `self + rhs`,
2621 wrapping around at the boundary of the type.
2622
2623 # Examples
2624
2625 Basic usage:
2626
2627 ```
2628 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2629 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2630 $EndFeature, "
2631 ```"),
2632             #[stable(feature = "rust1", since = "1.0.0")]
2633             #[inline]
2634             pub fn wrapping_add(self, rhs: Self) -> Self {
2635                 unsafe {
2636                     intrinsics::overflowing_add(self, rhs)
2637                 }
2638             }
2639         }
2640
2641         doc_comment! {
2642             concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2643 wrapping around at the boundary of the type.
2644
2645 # Examples
2646
2647 Basic usage:
2648
2649 ```
2650 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2651 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2652 $EndFeature, "
2653 ```"),
2654             #[stable(feature = "rust1", since = "1.0.0")]
2655             #[inline]
2656             pub fn wrapping_sub(self, rhs: Self) -> Self {
2657                 unsafe {
2658                     intrinsics::overflowing_sub(self, rhs)
2659                 }
2660             }
2661         }
2662
2663         /// Wrapping (modular) multiplication. Computes `self *
2664         /// rhs`, wrapping around at the boundary of the type.
2665         ///
2666         /// # Examples
2667         ///
2668         /// Basic usage:
2669         ///
2670         /// Please note that this example is shared between integer types.
2671         /// Which explains why `u8` is used here.
2672         ///
2673         /// ```
2674         /// assert_eq!(10u8.wrapping_mul(12), 120);
2675         /// assert_eq!(25u8.wrapping_mul(12), 44);
2676         /// ```
2677         #[stable(feature = "rust1", since = "1.0.0")]
2678         #[inline]
2679         pub fn wrapping_mul(self, rhs: Self) -> Self {
2680             unsafe {
2681                 intrinsics::overflowing_mul(self, rhs)
2682             }
2683         }
2684
2685         doc_comment! {
2686             concat!("Wrapping (modular) division. Computes `self / rhs`.
2687 Wrapped division on unsigned types is just normal division.
2688 There's no way wrapping could ever happen.
2689 This function exists, so that all operations
2690 are accounted for in the wrapping operations.
2691
2692 # Examples
2693
2694 Basic usage:
2695
2696 ```
2697 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2698 ```"),
2699             #[stable(feature = "num_wrapping", since = "1.2.0")]
2700             #[inline]
2701             pub fn wrapping_div(self, rhs: Self) -> Self {
2702                 self / rhs
2703             }
2704         }
2705
2706         doc_comment! {
2707             concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`.
2708 Wrapped division on unsigned types is just normal division.
2709 There's no way wrapping could ever happen.
2710 This function exists, so that all operations
2711 are accounted for in the wrapping operations.
2712
2713 # Examples
2714
2715 Basic usage:
2716
2717 ```
2718 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);", $EndFeature, "
2719 ```"),
2720             #[unstable(feature = "euclidean_division", issue = "49048")]
2721             #[inline]
2722             pub fn wrapping_div_euc(self, rhs: Self) -> Self {
2723                 self.div_euc(rhs)
2724             }
2725         }
2726
2727         doc_comment! {
2728             concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2729 Wrapped remainder calculation on unsigned types is
2730 just the regular remainder calculation.
2731 There's no way wrapping could ever happen.
2732 This function exists, so that all operations
2733 are accounted for in the wrapping operations.
2734
2735 # Examples
2736
2737 Basic usage:
2738
2739 ```
2740 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2741 ```"),
2742             #[stable(feature = "num_wrapping", since = "1.2.0")]
2743             #[inline]
2744             pub fn wrapping_rem(self, rhs: Self) -> Self {
2745                 self % rhs
2746             }
2747         }
2748
2749         doc_comment! {
2750             concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`.
2751 Wrapped modulo calculation on unsigned types is
2752 just the regular remainder calculation.
2753 There's no way wrapping could ever happen.
2754 This function exists, so that all operations
2755 are accounted for in the wrapping operations.
2756
2757 # Examples
2758
2759 Basic usage:
2760
2761 ```
2762 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);", $EndFeature, "
2763 ```"),
2764             #[unstable(feature = "euclidean_division", issue = "49048")]
2765             #[inline]
2766             pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
2767                 self % rhs
2768             }
2769         }
2770
2771         /// Wrapping (modular) negation. Computes `-self`,
2772         /// wrapping around at the boundary of the type.
2773         ///
2774         /// Since unsigned types do not have negative equivalents
2775         /// all applications of this function will wrap (except for `-0`).
2776         /// For values smaller than the corresponding signed type's maximum
2777         /// the result is the same as casting the corresponding signed value.
2778         /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2779         /// `MAX` is the corresponding signed type's maximum.
2780         ///
2781         /// # Examples
2782         ///
2783         /// Basic usage:
2784         ///
2785         /// Please note that this example is shared between integer types.
2786         /// Which explains why `i8` is used here.
2787         ///
2788         /// ```
2789         /// assert_eq!(100i8.wrapping_neg(), -100);
2790         /// assert_eq!((-128i8).wrapping_neg(), -128);
2791         /// ```
2792         #[stable(feature = "num_wrapping", since = "1.2.0")]
2793         #[inline]
2794         pub fn wrapping_neg(self) -> Self {
2795             self.overflowing_neg().0
2796         }
2797
2798         doc_comment! {
2799             concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2800 where `mask` removes any high-order bits of `rhs` that
2801 would cause the shift to exceed the bitwidth of the type.
2802
2803 Note that this is *not* the same as a rotate-left; the
2804 RHS of a wrapping shift-left is restricted to the range
2805 of the type, rather than the bits shifted out of the LHS
2806 being returned to the other end. The primitive integer
2807 types all implement a `rotate_left` function, which may
2808 be what you want instead.
2809
2810 # Examples
2811
2812 Basic usage:
2813
2814 ```
2815 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2816 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2817 ```"),
2818             #[stable(feature = "num_wrapping", since = "1.2.0")]
2819             #[inline]
2820             pub fn wrapping_shl(self, rhs: u32) -> Self {
2821                 unsafe {
2822                     intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
2823                 }
2824             }
2825         }
2826
2827         doc_comment! {
2828             concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2829 where `mask` removes any high-order bits of `rhs` that
2830 would cause the shift to exceed the bitwidth of the type.
2831
2832 Note that this is *not* the same as a rotate-right; the
2833 RHS of a wrapping shift-right is restricted to the range
2834 of the type, rather than the bits shifted out of the LHS
2835 being returned to the other end. The primitive integer
2836 types all implement a `rotate_right` function, which may
2837 be what you want instead.
2838
2839 # Examples
2840
2841 Basic usage:
2842
2843 ```
2844 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
2845 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
2846 ```"),
2847             #[stable(feature = "num_wrapping", since = "1.2.0")]
2848             #[inline]
2849             pub fn wrapping_shr(self, rhs: u32) -> Self {
2850                 unsafe {
2851                     intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
2852                 }
2853             }
2854         }
2855
2856         doc_comment! {
2857             concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2858 wrapping around at the boundary of the type.
2859
2860 # Examples
2861
2862 Basic usage:
2863
2864 ```
2865 #![feature(no_panic_pow)]
2866 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
2867 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
2868 ```"),
2869             #[unstable(feature = "no_panic_pow", issue = "48320")]
2870             #[inline]
2871             pub fn wrapping_pow(self, mut exp: u32) -> Self {
2872                 let mut base = self;
2873                 let mut acc: Self = 1;
2874
2875                 while exp > 1 {
2876                     if (exp & 1) == 1 {
2877                         acc = acc.wrapping_mul(base);
2878                     }
2879                     exp /= 2;
2880                     base = base.wrapping_mul(base);
2881                 }
2882
2883                 // Deal with the final bit of the exponent separately, since
2884                 // squaring the base afterwards is not necessary and may cause a
2885                 // needless overflow.
2886                 if exp == 1 {
2887                     acc = acc.wrapping_mul(base);
2888                 }
2889
2890                 acc
2891             }
2892         }
2893
2894         doc_comment! {
2895             concat!("Calculates `self` + `rhs`
2896
2897 Returns a tuple of the addition along with a boolean indicating
2898 whether an arithmetic overflow would occur. If an overflow would
2899 have occurred then the wrapped value is returned.
2900
2901 # Examples
2902
2903 Basic usage
2904
2905 ```
2906 ", $Feature, "use std::", stringify!($SelfT), ";
2907
2908 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
2909 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
2910 ```"),
2911             #[inline]
2912             #[stable(feature = "wrapping", since = "1.7.0")]
2913             pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2914                 let (a, b) = unsafe {
2915                     intrinsics::add_with_overflow(self as $ActualT,
2916                                                   rhs as $ActualT)
2917                 };
2918                 (a as Self, b)
2919             }
2920         }
2921
2922         doc_comment! {
2923             concat!("Calculates `self` - `rhs`
2924
2925 Returns a tuple of the subtraction along with a boolean indicating
2926 whether an arithmetic overflow would occur. If an overflow would
2927 have occurred then the wrapped value is returned.
2928
2929 # Examples
2930
2931 Basic usage
2932
2933 ```
2934 ", $Feature, "use std::", stringify!($SelfT), ";
2935
2936 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
2937 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
2938 $EndFeature, "
2939 ```"),
2940             #[inline]
2941             #[stable(feature = "wrapping", since = "1.7.0")]
2942             pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2943                 let (a, b) = unsafe {
2944                     intrinsics::sub_with_overflow(self as $ActualT,
2945                                                   rhs as $ActualT)
2946                 };
2947                 (a as Self, b)
2948             }
2949         }
2950
2951         /// Calculates the multiplication of `self` and `rhs`.
2952         ///
2953         /// Returns a tuple of the multiplication along with a boolean
2954         /// indicating whether an arithmetic overflow would occur. If an
2955         /// overflow would have occurred then the wrapped value is returned.
2956         ///
2957         /// # Examples
2958         ///
2959         /// Basic usage:
2960         ///
2961         /// Please note that this example is shared between integer types.
2962         /// Which explains why `u32` is used here.
2963         ///
2964         /// ```
2965         /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2966         /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2967         /// ```
2968         #[inline]
2969         #[stable(feature = "wrapping", since = "1.7.0")]
2970         pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2971             let (a, b) = unsafe {
2972                 intrinsics::mul_with_overflow(self as $ActualT,
2973                                               rhs as $ActualT)
2974             };
2975             (a as Self, b)
2976         }
2977
2978         doc_comment! {
2979             concat!("Calculates the divisor when `self` is divided by `rhs`.
2980
2981 Returns a tuple of the divisor along with a boolean indicating
2982 whether an arithmetic overflow would occur. Note that for unsigned
2983 integers overflow never occurs, so the second value is always
2984 `false`.
2985
2986 # Panics
2987
2988 This function will panic if `rhs` is 0.
2989
2990 # Examples
2991
2992 Basic usage
2993
2994 ```
2995 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
2996 ```"),
2997             #[inline]
2998             #[stable(feature = "wrapping", since = "1.7.0")]
2999             pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3000                 (self / rhs, false)
3001             }
3002         }
3003
3004         doc_comment! {
3005             concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
3006
3007 Returns a tuple of the divisor along with a boolean indicating
3008 whether an arithmetic overflow would occur. Note that for unsigned
3009 integers overflow never occurs, so the second value is always
3010 `false`.
3011
3012 # Panics
3013
3014 This function will panic if `rhs` is 0.
3015
3016 # Examples
3017
3018 Basic usage
3019
3020 ```
3021 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));", $EndFeature, "
3022 ```"),
3023             #[inline]
3024             #[unstable(feature = "euclidean_division", issue = "49048")]
3025             pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
3026                 (self / rhs, false)
3027             }
3028         }
3029
3030         doc_comment! {
3031             concat!("Calculates the remainder when `self` is divided by `rhs`.
3032
3033 Returns a tuple of the remainder after dividing along with a boolean
3034 indicating whether an arithmetic overflow would occur. Note that for
3035 unsigned integers overflow never occurs, so the second value is
3036 always `false`.
3037
3038 # Panics
3039
3040 This function will panic if `rhs` is 0.
3041
3042 # Examples
3043
3044 Basic usage
3045
3046 ```
3047 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3048 ```"),
3049             #[inline]
3050             #[stable(feature = "wrapping", since = "1.7.0")]
3051             pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3052                 (self % rhs, false)
3053             }
3054         }
3055
3056         doc_comment! {
3057             concat!("Calculates the modulo of Euclidean division of `self.mod_euc(rhs)`.
3058
3059 Returns a tuple of the modulo after dividing along with a boolean
3060 indicating whether an arithmetic overflow would occur. Note that for
3061 unsigned integers overflow never occurs, so the second value is
3062 always `false`.
3063
3064 # Panics
3065
3066 This function will panic if `rhs` is 0.
3067
3068 # Examples
3069
3070 Basic usage
3071
3072 ```
3073 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));", $EndFeature, "
3074 ```"),
3075             #[inline]
3076             #[unstable(feature = "euclidean_division", issue = "49048")]
3077             pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
3078                 (self % rhs, false)
3079             }
3080         }
3081
3082         doc_comment! {
3083             concat!("Negates self in an overflowing fashion.
3084
3085 Returns `!self + 1` using wrapping operations to return the value
3086 that represents the negation of this unsigned value. Note that for
3087 positive unsigned values overflow always occurs, but negating 0 does
3088 not overflow.
3089
3090 # Examples
3091
3092 Basic usage
3093
3094 ```
3095 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3096 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3097 ", true));", $EndFeature, "
3098 ```"),
3099             #[inline]
3100             #[stable(feature = "wrapping", since = "1.7.0")]
3101             pub fn overflowing_neg(self) -> (Self, bool) {
3102                 ((!self).wrapping_add(1), self != 0)
3103             }
3104         }
3105
3106         doc_comment! {
3107             concat!("Shifts self left by `rhs` bits.
3108
3109 Returns a tuple of the shifted version of self along with a boolean
3110 indicating whether the shift value was larger than or equal to the
3111 number of bits. If the shift value is too large, then value is
3112 masked (N-1) where N is the number of bits, and this value is then
3113 used to perform the shift.
3114
3115 # Examples
3116
3117 Basic usage
3118
3119 ```
3120 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3121 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3122 ```"),
3123             #[inline]
3124             #[stable(feature = "wrapping", since = "1.7.0")]
3125             pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3126                 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3127             }
3128         }
3129
3130         doc_comment! {
3131             concat!("Shifts self right by `rhs` bits.
3132
3133 Returns a tuple of the shifted version of self along with a boolean
3134 indicating whether the shift value was larger than or equal to the
3135 number of bits. If the shift value is too large, then value is
3136 masked (N-1) where N is the number of bits, and this value is then
3137 used to perform the shift.
3138
3139 # Examples
3140
3141 Basic usage
3142
3143 ```
3144 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3145 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3146 ```"),
3147             #[inline]
3148             #[stable(feature = "wrapping", since = "1.7.0")]
3149             pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3150                 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3151             }
3152         }
3153
3154         doc_comment! {
3155             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3156
3157 Returns a tuple of the exponentiation along with a bool indicating
3158 whether an overflow happened.
3159
3160 # Examples
3161
3162 Basic usage:
3163
3164 ```
3165 #![feature(no_panic_pow)]
3166 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3167 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3168 ```"),
3169             #[unstable(feature = "no_panic_pow", issue = "48320")]
3170             #[inline]
3171             pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3172                 let mut base = self;
3173                 let mut acc: Self = 1;
3174                 let mut overflown = false;
3175                 // Scratch space for storing results of overflowing_mul.
3176                 let mut r;
3177
3178                 while exp > 1 {
3179                     if (exp & 1) == 1 {
3180                         r = acc.overflowing_mul(base);
3181                         acc = r.0;
3182                         overflown |= r.1;
3183                     }
3184                     exp /= 2;
3185                     r = base.overflowing_mul(base);
3186                     base = r.0;
3187                     overflown |= r.1;
3188                 }
3189
3190                 // Deal with the final bit of the exponent separately, since
3191                 // squaring the base afterwards is not necessary and may cause a
3192                 // needless overflow.
3193                 if exp == 1 {
3194                     r = acc.overflowing_mul(base);
3195                     acc = r.0;
3196                     overflown |= r.1;
3197                 }
3198
3199                 (acc, overflown)
3200             }
3201         }
3202
3203         doc_comment! {
3204             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3205
3206 # Examples
3207
3208 Basic usage:
3209
3210 ```
3211 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3212 ```"),
3213         #[stable(feature = "rust1", since = "1.0.0")]
3214         #[inline]
3215         #[rustc_inherit_overflow_checks]
3216         pub fn pow(self, mut exp: u32) -> Self {
3217             let mut base = self;
3218             let mut acc = 1;
3219
3220             while exp > 1 {
3221                 if (exp & 1) == 1 {
3222                     acc = acc * base;
3223                 }
3224                 exp /= 2;
3225                 base = base * base;
3226             }
3227
3228             // Deal with the final bit of the exponent separately, since
3229             // squaring the base afterwards is not necessary and may cause a
3230             // needless overflow.
3231             if exp == 1 {
3232                 acc = acc * base;
3233             }
3234
3235             acc
3236         }
3237     }
3238
3239             doc_comment! {
3240             concat!("Performs Euclidean division.
3241
3242 For unsigned types, this is just the same as `self / rhs`.
3243
3244 # Examples
3245
3246 Basic usage:
3247
3248 ```
3249 ", $Feature, "assert_eq(7", stringify!($SelfT), ".div_euc(4), 1); // or any other integer type",
3250 $EndFeature, "
3251 ```"),
3252             #[unstable(feature = "euclidean_division", issue = "49048")]
3253             #[inline]
3254             #[rustc_inherit_overflow_checks]
3255             pub fn div_euc(self, rhs: Self) -> Self {
3256                 self / rhs
3257             }
3258         }
3259
3260
3261         doc_comment! {
3262             concat!("Calculates the Euclidean modulo `self mod rhs`.
3263
3264 For unsigned types, this is just the same as `self % rhs`.
3265
3266 # Examples
3267
3268 Basic usage:
3269
3270 ```
3271 ", $Feature, "assert_eq(7", stringify!($SelfT), ".mod_euc(4), 3); // or any other integer type",
3272 $EndFeature, "
3273 ```"),
3274             #[unstable(feature = "euclidean_division", issue = "49048")]
3275             #[inline]
3276             #[rustc_inherit_overflow_checks]
3277             pub fn mod_euc(self, rhs: Self) -> Self {
3278                 self % rhs
3279             }
3280         }
3281
3282         doc_comment! {
3283             concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3284
3285 # Examples
3286
3287 Basic usage:
3288
3289 ```
3290 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3291 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3292 ```"),
3293             #[stable(feature = "rust1", since = "1.0.0")]
3294             #[inline]
3295             pub fn is_power_of_two(self) -> bool {
3296                 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3297             }
3298         }
3299
3300         // Returns one less than next power of two.
3301         // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3302         //
3303         // 8u8.one_less_than_next_power_of_two() == 7
3304         // 6u8.one_less_than_next_power_of_two() == 7
3305         //
3306         // This method cannot overflow, as in the `next_power_of_two`
3307         // overflow cases it instead ends up returning the maximum value
3308         // of the type, and can return 0 for 0.
3309         #[inline]
3310         fn one_less_than_next_power_of_two(self) -> Self {
3311             if self <= 1 { return 0; }
3312
3313             // Because `p > 0`, it cannot consist entirely of leading zeros.
3314             // That means the shift is always in-bounds, and some processors
3315             // (such as intel pre-haswell) have more efficient ctlz
3316             // intrinsics when the argument is non-zero.
3317             let p = self - 1;
3318             let z = unsafe { intrinsics::ctlz_nonzero(p) };
3319             <$SelfT>::max_value() >> z
3320         }
3321
3322         doc_comment! {
3323             concat!("Returns the smallest power of two greater than or equal to `self`.
3324
3325 When return value overflows (i.e. `self > (1 << (N-1))` for type
3326 `uN`), it panics in debug mode and return value is wrapped to 0 in
3327 release mode (the only situation in which method can return 0).
3328
3329 # Examples
3330
3331 Basic usage:
3332
3333 ```
3334 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3335 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3336 ```"),
3337             #[stable(feature = "rust1", since = "1.0.0")]
3338             #[inline]
3339             pub fn next_power_of_two(self) -> Self {
3340                 // Call the trait to get overflow checks
3341                 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3342             }
3343         }
3344
3345         doc_comment! {
3346             concat!("Returns the smallest power of two greater than or equal to `n`. If
3347 the next power of two is greater than the type's maximum value,
3348 `None` is returned, otherwise the power of two is wrapped in `Some`.
3349
3350 # Examples
3351
3352 Basic usage:
3353
3354 ```
3355 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3356 ".checked_next_power_of_two(), Some(2));
3357 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3358 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3359 $EndFeature, "
3360 ```"),
3361             #[stable(feature = "rust1", since = "1.0.0")]
3362             pub fn checked_next_power_of_two(self) -> Option<Self> {
3363                 self.one_less_than_next_power_of_two().checked_add(1)
3364             }
3365         }
3366     }
3367 }
3368
3369 #[lang = "u8"]
3370 impl u8 {
3371     uint_impl! { u8, u8, 8, 255, "", "" }
3372
3373
3374     /// Checks if the value is within the ASCII range.
3375     ///
3376     /// # Examples
3377     ///
3378     /// ```
3379     /// let ascii = 97u8;
3380     /// let non_ascii = 150u8;
3381     ///
3382     /// assert!(ascii.is_ascii());
3383     /// assert!(!non_ascii.is_ascii());
3384     /// ```
3385     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3386     #[inline]
3387     pub fn is_ascii(&self) -> bool {
3388         *self & 128 == 0
3389     }
3390
3391     /// Makes a copy of the value in its ASCII upper case equivalent.
3392     ///
3393     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3394     /// but non-ASCII letters are unchanged.
3395     ///
3396     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
3397     ///
3398     /// # Examples
3399     ///
3400     /// ```
3401     /// let lowercase_a = 97u8;
3402     ///
3403     /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
3404     /// ```
3405     ///
3406     /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
3407     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3408     #[inline]
3409     pub fn to_ascii_uppercase(&self) -> u8 {
3410         ASCII_UPPERCASE_MAP[*self as usize]
3411     }
3412
3413     /// Makes a copy of the value in its ASCII lower case equivalent.
3414     ///
3415     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3416     /// but non-ASCII letters are unchanged.
3417     ///
3418     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
3419     ///
3420     /// # Examples
3421     ///
3422     /// ```
3423     /// let uppercase_a = 65u8;
3424     ///
3425     /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
3426     /// ```
3427     ///
3428     /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
3429     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3430     #[inline]
3431     pub fn to_ascii_lowercase(&self) -> u8 {
3432         ASCII_LOWERCASE_MAP[*self as usize]
3433     }
3434
3435     /// Checks that two values are an ASCII case-insensitive match.
3436     ///
3437     /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3438     ///
3439     /// # Examples
3440     ///
3441     /// ```
3442     /// let lowercase_a = 97u8;
3443     /// let uppercase_a = 65u8;
3444     ///
3445     /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3446     /// ```
3447     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3448     #[inline]
3449     pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3450         self.to_ascii_lowercase() == other.to_ascii_lowercase()
3451     }
3452
3453     /// Converts this value to its ASCII upper case equivalent in-place.
3454     ///
3455     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3456     /// but non-ASCII letters are unchanged.
3457     ///
3458     /// To return a new uppercased value without modifying the existing one, use
3459     /// [`to_ascii_uppercase`].
3460     ///
3461     /// # Examples
3462     ///
3463     /// ```
3464     /// let mut byte = b'a';
3465     ///
3466     /// byte.make_ascii_uppercase();
3467     ///
3468     /// assert_eq!(b'A', byte);
3469     /// ```
3470     ///
3471     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3472     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3473     #[inline]
3474     pub fn make_ascii_uppercase(&mut self) {
3475         *self = self.to_ascii_uppercase();
3476     }
3477
3478     /// Converts this value to its ASCII lower case equivalent in-place.
3479     ///
3480     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3481     /// but non-ASCII letters are unchanged.
3482     ///
3483     /// To return a new lowercased value without modifying the existing one, use
3484     /// [`to_ascii_lowercase`].
3485     ///
3486     /// # Examples
3487     ///
3488     /// ```
3489     /// let mut byte = b'A';
3490     ///
3491     /// byte.make_ascii_lowercase();
3492     ///
3493     /// assert_eq!(b'a', byte);
3494     /// ```
3495     ///
3496     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3497     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3498     #[inline]
3499     pub fn make_ascii_lowercase(&mut self) {
3500         *self = self.to_ascii_lowercase();
3501     }
3502
3503     /// Checks if the value is an ASCII alphabetic character:
3504     ///
3505     /// - U+0041 'A' ... U+005A 'Z', or
3506     /// - U+0061 'a' ... U+007A 'z'.
3507     ///
3508     /// # Examples
3509     ///
3510     /// ```
3511     /// #![feature(ascii_ctype)]
3512     ///
3513     /// let uppercase_a = b'A';
3514     /// let uppercase_g = b'G';
3515     /// let a = b'a';
3516     /// let g = b'g';
3517     /// let zero = b'0';
3518     /// let percent = b'%';
3519     /// let space = b' ';
3520     /// let lf = b'\n';
3521     /// let esc = 0x1b_u8;
3522     ///
3523     /// assert!(uppercase_a.is_ascii_alphabetic());
3524     /// assert!(uppercase_g.is_ascii_alphabetic());
3525     /// assert!(a.is_ascii_alphabetic());
3526     /// assert!(g.is_ascii_alphabetic());
3527     /// assert!(!zero.is_ascii_alphabetic());
3528     /// assert!(!percent.is_ascii_alphabetic());
3529     /// assert!(!space.is_ascii_alphabetic());
3530     /// assert!(!lf.is_ascii_alphabetic());
3531     /// assert!(!esc.is_ascii_alphabetic());
3532     /// ```
3533     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3534     #[inline]
3535     pub fn is_ascii_alphabetic(&self) -> bool {
3536         if *self >= 0x80 { return false; }
3537         match ASCII_CHARACTER_CLASS[*self as usize] {
3538             L | Lx | U | Ux => true,
3539             _ => false
3540         }
3541     }
3542
3543     /// Checks if the value is an ASCII uppercase character:
3544     /// U+0041 'A' ... U+005A 'Z'.
3545     ///
3546     /// # Examples
3547     ///
3548     /// ```
3549     /// #![feature(ascii_ctype)]
3550     ///
3551     /// let uppercase_a = b'A';
3552     /// let uppercase_g = b'G';
3553     /// let a = b'a';
3554     /// let g = b'g';
3555     /// let zero = b'0';
3556     /// let percent = b'%';
3557     /// let space = b' ';
3558     /// let lf = b'\n';
3559     /// let esc = 0x1b_u8;
3560     ///
3561     /// assert!(uppercase_a.is_ascii_uppercase());
3562     /// assert!(uppercase_g.is_ascii_uppercase());
3563     /// assert!(!a.is_ascii_uppercase());
3564     /// assert!(!g.is_ascii_uppercase());
3565     /// assert!(!zero.is_ascii_uppercase());
3566     /// assert!(!percent.is_ascii_uppercase());
3567     /// assert!(!space.is_ascii_uppercase());
3568     /// assert!(!lf.is_ascii_uppercase());
3569     /// assert!(!esc.is_ascii_uppercase());
3570     /// ```
3571     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3572     #[inline]
3573     pub fn is_ascii_uppercase(&self) -> bool {
3574         if *self >= 0x80 { return false }
3575         match ASCII_CHARACTER_CLASS[*self as usize] {
3576             U | Ux => true,
3577             _ => false
3578         }
3579     }
3580
3581     /// Checks if the value is an ASCII lowercase character:
3582     /// U+0061 'a' ... U+007A 'z'.
3583     ///
3584     /// # Examples
3585     ///
3586     /// ```
3587     /// #![feature(ascii_ctype)]
3588     ///
3589     /// let uppercase_a = b'A';
3590     /// let uppercase_g = b'G';
3591     /// let a = b'a';
3592     /// let g = b'g';
3593     /// let zero = b'0';
3594     /// let percent = b'%';
3595     /// let space = b' ';
3596     /// let lf = b'\n';
3597     /// let esc = 0x1b_u8;
3598     ///
3599     /// assert!(!uppercase_a.is_ascii_lowercase());
3600     /// assert!(!uppercase_g.is_ascii_lowercase());
3601     /// assert!(a.is_ascii_lowercase());
3602     /// assert!(g.is_ascii_lowercase());
3603     /// assert!(!zero.is_ascii_lowercase());
3604     /// assert!(!percent.is_ascii_lowercase());
3605     /// assert!(!space.is_ascii_lowercase());
3606     /// assert!(!lf.is_ascii_lowercase());
3607     /// assert!(!esc.is_ascii_lowercase());
3608     /// ```
3609     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3610     #[inline]
3611     pub fn is_ascii_lowercase(&self) -> bool {
3612         if *self >= 0x80 { return false }
3613         match ASCII_CHARACTER_CLASS[*self as usize] {
3614             L | Lx => true,
3615             _ => false
3616         }
3617     }
3618
3619     /// Checks if the value is an ASCII alphanumeric character:
3620     ///
3621     /// - U+0041 'A' ... U+005A 'Z', or
3622     /// - U+0061 'a' ... U+007A 'z', or
3623     /// - U+0030 '0' ... U+0039 '9'.
3624     ///
3625     /// # Examples
3626     ///
3627     /// ```
3628     /// #![feature(ascii_ctype)]
3629     ///
3630     /// let uppercase_a = b'A';
3631     /// let uppercase_g = b'G';
3632     /// let a = b'a';
3633     /// let g = b'g';
3634     /// let zero = b'0';
3635     /// let percent = b'%';
3636     /// let space = b' ';
3637     /// let lf = b'\n';
3638     /// let esc = 0x1b_u8;
3639     ///
3640     /// assert!(uppercase_a.is_ascii_alphanumeric());
3641     /// assert!(uppercase_g.is_ascii_alphanumeric());
3642     /// assert!(a.is_ascii_alphanumeric());
3643     /// assert!(g.is_ascii_alphanumeric());
3644     /// assert!(zero.is_ascii_alphanumeric());
3645     /// assert!(!percent.is_ascii_alphanumeric());
3646     /// assert!(!space.is_ascii_alphanumeric());
3647     /// assert!(!lf.is_ascii_alphanumeric());
3648     /// assert!(!esc.is_ascii_alphanumeric());
3649     /// ```
3650     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3651     #[inline]
3652     pub fn is_ascii_alphanumeric(&self) -> bool {
3653         if *self >= 0x80 { return false }
3654         match ASCII_CHARACTER_CLASS[*self as usize] {
3655             D | L | Lx | U | Ux => true,
3656             _ => false
3657         }
3658     }
3659
3660     /// Checks if the value is an ASCII decimal digit:
3661     /// U+0030 '0' ... U+0039 '9'.
3662     ///
3663     /// # Examples
3664     ///
3665     /// ```
3666     /// #![feature(ascii_ctype)]
3667     ///
3668     /// let uppercase_a = b'A';
3669     /// let uppercase_g = b'G';
3670     /// let a = b'a';
3671     /// let g = b'g';
3672     /// let zero = b'0';
3673     /// let percent = b'%';
3674     /// let space = b' ';
3675     /// let lf = b'\n';
3676     /// let esc = 0x1b_u8;
3677     ///
3678     /// assert!(!uppercase_a.is_ascii_digit());
3679     /// assert!(!uppercase_g.is_ascii_digit());
3680     /// assert!(!a.is_ascii_digit());
3681     /// assert!(!g.is_ascii_digit());
3682     /// assert!(zero.is_ascii_digit());
3683     /// assert!(!percent.is_ascii_digit());
3684     /// assert!(!space.is_ascii_digit());
3685     /// assert!(!lf.is_ascii_digit());
3686     /// assert!(!esc.is_ascii_digit());
3687     /// ```
3688     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3689     #[inline]
3690     pub fn is_ascii_digit(&self) -> bool {
3691         if *self >= 0x80 { return false }
3692         match ASCII_CHARACTER_CLASS[*self as usize] {
3693             D => true,
3694             _ => false
3695         }
3696     }
3697
3698     /// Checks if the value is an ASCII hexadecimal digit:
3699     ///
3700     /// - U+0030 '0' ... U+0039 '9', or
3701     /// - U+0041 'A' ... U+0046 'F', or
3702     /// - U+0061 'a' ... U+0066 'f'.
3703     ///
3704     /// # Examples
3705     ///
3706     /// ```
3707     /// #![feature(ascii_ctype)]
3708     ///
3709     /// let uppercase_a = b'A';
3710     /// let uppercase_g = b'G';
3711     /// let a = b'a';
3712     /// let g = b'g';
3713     /// let zero = b'0';
3714     /// let percent = b'%';
3715     /// let space = b' ';
3716     /// let lf = b'\n';
3717     /// let esc = 0x1b_u8;
3718     ///
3719     /// assert!(uppercase_a.is_ascii_hexdigit());
3720     /// assert!(!uppercase_g.is_ascii_hexdigit());
3721     /// assert!(a.is_ascii_hexdigit());
3722     /// assert!(!g.is_ascii_hexdigit());
3723     /// assert!(zero.is_ascii_hexdigit());
3724     /// assert!(!percent.is_ascii_hexdigit());
3725     /// assert!(!space.is_ascii_hexdigit());
3726     /// assert!(!lf.is_ascii_hexdigit());
3727     /// assert!(!esc.is_ascii_hexdigit());
3728     /// ```
3729     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3730     #[inline]
3731     pub fn is_ascii_hexdigit(&self) -> bool {
3732         if *self >= 0x80 { return false }
3733         match ASCII_CHARACTER_CLASS[*self as usize] {
3734             D | Lx | Ux => true,
3735             _ => false
3736         }
3737     }
3738
3739     /// Checks if the value is an ASCII punctuation character:
3740     ///
3741     /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
3742     /// - U+003A ... U+0040 `: ; < = > ? @`, or
3743     /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
3744     /// - U+007B ... U+007E `{ | } ~`
3745     ///
3746     /// # Examples
3747     ///
3748     /// ```
3749     /// #![feature(ascii_ctype)]
3750     ///
3751     /// let uppercase_a = b'A';
3752     /// let uppercase_g = b'G';
3753     /// let a = b'a';
3754     /// let g = b'g';
3755     /// let zero = b'0';
3756     /// let percent = b'%';
3757     /// let space = b' ';
3758     /// let lf = b'\n';
3759     /// let esc = 0x1b_u8;
3760     ///
3761     /// assert!(!uppercase_a.is_ascii_punctuation());
3762     /// assert!(!uppercase_g.is_ascii_punctuation());
3763     /// assert!(!a.is_ascii_punctuation());
3764     /// assert!(!g.is_ascii_punctuation());
3765     /// assert!(!zero.is_ascii_punctuation());
3766     /// assert!(percent.is_ascii_punctuation());
3767     /// assert!(!space.is_ascii_punctuation());
3768     /// assert!(!lf.is_ascii_punctuation());
3769     /// assert!(!esc.is_ascii_punctuation());
3770     /// ```
3771     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3772     #[inline]
3773     pub fn is_ascii_punctuation(&self) -> bool {
3774         if *self >= 0x80 { return false }
3775         match ASCII_CHARACTER_CLASS[*self as usize] {
3776             P => true,
3777             _ => false
3778         }
3779     }
3780
3781     /// Checks if the value is an ASCII graphic character:
3782     /// U+0021 '!' ... U+007E '~'.
3783     ///
3784     /// # Examples
3785     ///
3786     /// ```
3787     /// #![feature(ascii_ctype)]
3788     ///
3789     /// let uppercase_a = b'A';
3790     /// let uppercase_g = b'G';
3791     /// let a = b'a';
3792     /// let g = b'g';
3793     /// let zero = b'0';
3794     /// let percent = b'%';
3795     /// let space = b' ';
3796     /// let lf = b'\n';
3797     /// let esc = 0x1b_u8;
3798     ///
3799     /// assert!(uppercase_a.is_ascii_graphic());
3800     /// assert!(uppercase_g.is_ascii_graphic());
3801     /// assert!(a.is_ascii_graphic());
3802     /// assert!(g.is_ascii_graphic());
3803     /// assert!(zero.is_ascii_graphic());
3804     /// assert!(percent.is_ascii_graphic());
3805     /// assert!(!space.is_ascii_graphic());
3806     /// assert!(!lf.is_ascii_graphic());
3807     /// assert!(!esc.is_ascii_graphic());
3808     /// ```
3809     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3810     #[inline]
3811     pub fn is_ascii_graphic(&self) -> bool {
3812         if *self >= 0x80 { return false; }
3813         match ASCII_CHARACTER_CLASS[*self as usize] {
3814             Ux | U | Lx | L | D | P => true,
3815             _ => false
3816         }
3817     }
3818
3819     /// Checks if the value is an ASCII whitespace character:
3820     /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
3821     /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
3822     ///
3823     /// Rust uses the WhatWG Infra Standard's [definition of ASCII
3824     /// whitespace][infra-aw]. There are several other definitions in
3825     /// wide use. For instance, [the POSIX locale][pct] includes
3826     /// U+000B VERTICAL TAB as well as all the above characters,
3827     /// but—from the very same specification—[the default rule for
3828     /// "field splitting" in the Bourne shell][bfs] considers *only*
3829     /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
3830     ///
3831     /// If you are writing a program that will process an existing
3832     /// file format, check what that format's definition of whitespace is
3833     /// before using this function.
3834     ///
3835     /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
3836     /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
3837     /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
3838     ///
3839     /// # Examples
3840     ///
3841     /// ```
3842     /// #![feature(ascii_ctype)]
3843     ///
3844     /// let uppercase_a = b'A';
3845     /// let uppercase_g = b'G';
3846     /// let a = b'a';
3847     /// let g = b'g';
3848     /// let zero = b'0';
3849     /// let percent = b'%';
3850     /// let space = b' ';
3851     /// let lf = b'\n';
3852     /// let esc = 0x1b_u8;
3853     ///
3854     /// assert!(!uppercase_a.is_ascii_whitespace());
3855     /// assert!(!uppercase_g.is_ascii_whitespace());
3856     /// assert!(!a.is_ascii_whitespace());
3857     /// assert!(!g.is_ascii_whitespace());
3858     /// assert!(!zero.is_ascii_whitespace());
3859     /// assert!(!percent.is_ascii_whitespace());
3860     /// assert!(space.is_ascii_whitespace());
3861     /// assert!(lf.is_ascii_whitespace());
3862     /// assert!(!esc.is_ascii_whitespace());
3863     /// ```
3864     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3865     #[inline]
3866     pub fn is_ascii_whitespace(&self) -> bool {
3867         if *self >= 0x80 { return false; }
3868         match ASCII_CHARACTER_CLASS[*self as usize] {
3869             Cw | W => true,
3870             _ => false
3871         }
3872     }
3873
3874     /// Checks if the value is an ASCII control character:
3875     /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
3876     /// Note that most ASCII whitespace characters are control
3877     /// characters, but SPACE is not.
3878     ///
3879     /// # Examples
3880     ///
3881     /// ```
3882     /// #![feature(ascii_ctype)]
3883     ///
3884     /// let uppercase_a = b'A';
3885     /// let uppercase_g = b'G';
3886     /// let a = b'a';
3887     /// let g = b'g';
3888     /// let zero = b'0';
3889     /// let percent = b'%';
3890     /// let space = b' ';
3891     /// let lf = b'\n';
3892     /// let esc = 0x1b_u8;
3893     ///
3894     /// assert!(!uppercase_a.is_ascii_control());
3895     /// assert!(!uppercase_g.is_ascii_control());
3896     /// assert!(!a.is_ascii_control());
3897     /// assert!(!g.is_ascii_control());
3898     /// assert!(!zero.is_ascii_control());
3899     /// assert!(!percent.is_ascii_control());
3900     /// assert!(!space.is_ascii_control());
3901     /// assert!(lf.is_ascii_control());
3902     /// assert!(esc.is_ascii_control());
3903     /// ```
3904     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3905     #[inline]
3906     pub fn is_ascii_control(&self) -> bool {
3907         if *self >= 0x80 { return false; }
3908         match ASCII_CHARACTER_CLASS[*self as usize] {
3909             C | Cw => true,
3910             _ => false
3911         }
3912     }
3913 }
3914
3915 #[lang = "u16"]
3916 impl u16 {
3917     uint_impl! { u16, u16, 16, 65535, "", "" }
3918 }
3919
3920 #[lang = "u32"]
3921 impl u32 {
3922     uint_impl! { u32, u32, 32, 4294967295, "", "" }
3923 }
3924
3925 #[lang = "u64"]
3926 impl u64 {
3927     uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
3928 }
3929
3930 #[lang = "u128"]
3931 impl u128 {
3932     uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "#![feature(i128_type)]
3933 #![feature(i128)]
3934
3935 # fn main() {
3936 ", "
3937 # }" }
3938 }
3939
3940 #[cfg(target_pointer_width = "16")]
3941 #[lang = "usize"]
3942 impl usize {
3943     uint_impl! { usize, u16, 16, 65536, "", "" }
3944 }
3945 #[cfg(target_pointer_width = "32")]
3946 #[lang = "usize"]
3947 impl usize {
3948     uint_impl! { usize, u32, 32, 4294967295, "", "" }
3949 }
3950
3951 #[cfg(target_pointer_width = "64")]
3952 #[lang = "usize"]
3953 impl usize {
3954     uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
3955 }
3956
3957 /// A classification of floating point numbers.
3958 ///
3959 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
3960 /// their documentation for more.
3961 ///
3962 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
3963 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
3964 ///
3965 /// # Examples
3966 ///
3967 /// ```
3968 /// use std::num::FpCategory;
3969 /// use std::f32;
3970 ///
3971 /// let num = 12.4_f32;
3972 /// let inf = f32::INFINITY;
3973 /// let zero = 0f32;
3974 /// let sub: f32 = 1.1754942e-38;
3975 /// let nan = f32::NAN;
3976 ///
3977 /// assert_eq!(num.classify(), FpCategory::Normal);
3978 /// assert_eq!(inf.classify(), FpCategory::Infinite);
3979 /// assert_eq!(zero.classify(), FpCategory::Zero);
3980 /// assert_eq!(nan.classify(), FpCategory::Nan);
3981 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
3982 /// ```
3983 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
3984 #[stable(feature = "rust1", since = "1.0.0")]
3985 pub enum FpCategory {
3986     /// "Not a Number", often obtained by dividing by zero.
3987     #[stable(feature = "rust1", since = "1.0.0")]
3988     Nan,
3989
3990     /// Positive or negative infinity.
3991     #[stable(feature = "rust1", since = "1.0.0")]
3992     Infinite,
3993
3994     /// Positive or negative zero.
3995     #[stable(feature = "rust1", since = "1.0.0")]
3996     Zero,
3997
3998     /// De-normalized floating point representation (less precise than `Normal`).
3999     #[stable(feature = "rust1", since = "1.0.0")]
4000     Subnormal,
4001
4002     /// A regular floating point number.
4003     #[stable(feature = "rust1", since = "1.0.0")]
4004     Normal,
4005 }
4006
4007 /// A built-in floating point number.
4008 #[doc(hidden)]
4009 #[unstable(feature = "core_float",
4010            reason = "stable interface is via `impl f{32,64}` in later crates",
4011            issue = "32110")]
4012 pub trait Float: Sized {
4013     /// Type used by `to_bits` and `from_bits`.
4014     #[stable(feature = "core_float_bits", since = "1.25.0")]
4015     type Bits;
4016
4017     /// Returns `true` if this value is NaN and false otherwise.
4018     #[stable(feature = "core", since = "1.6.0")]
4019     fn is_nan(self) -> bool;
4020     /// Returns `true` if this value is positive infinity or negative infinity and
4021     /// false otherwise.
4022     #[stable(feature = "core", since = "1.6.0")]
4023     fn is_infinite(self) -> bool;
4024     /// Returns `true` if this number is neither infinite nor NaN.
4025     #[stable(feature = "core", since = "1.6.0")]
4026     fn is_finite(self) -> bool;
4027     /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
4028     #[stable(feature = "core", since = "1.6.0")]
4029     fn is_normal(self) -> bool;
4030     /// Returns the category that this number falls into.
4031     #[stable(feature = "core", since = "1.6.0")]
4032     fn classify(self) -> FpCategory;
4033
4034     /// Computes the absolute value of `self`. Returns `Float::nan()` if the
4035     /// number is `Float::nan()`.
4036     #[stable(feature = "core", since = "1.6.0")]
4037     fn abs(self) -> Self;
4038     /// Returns a number that represents the sign of `self`.
4039     ///
4040     /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
4041     /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
4042     /// - `Float::nan()` if the number is `Float::nan()`
4043     #[stable(feature = "core", since = "1.6.0")]
4044     fn signum(self) -> Self;
4045
4046     /// Returns `true` if `self` is positive, including `+0.0` and
4047     /// `Float::infinity()`.
4048     #[stable(feature = "core", since = "1.6.0")]
4049     fn is_sign_positive(self) -> bool;
4050     /// Returns `true` if `self` is negative, including `-0.0` and
4051     /// `Float::neg_infinity()`.
4052     #[stable(feature = "core", since = "1.6.0")]
4053     fn is_sign_negative(self) -> bool;
4054
4055     /// Take the reciprocal (inverse) of a number, `1/x`.
4056     #[stable(feature = "core", since = "1.6.0")]
4057     fn recip(self) -> Self;
4058
4059     /// Raise a number to an integer power.
4060     ///
4061     /// Using this function is generally faster than using `powf`
4062     #[stable(feature = "core", since = "1.6.0")]
4063     fn powi(self, n: i32) -> Self;
4064
4065     /// Convert radians to degrees.
4066     #[stable(feature = "deg_rad_conversions", since="1.7.0")]
4067     fn to_degrees(self) -> Self;
4068     /// Convert degrees to radians.
4069     #[stable(feature = "deg_rad_conversions", since="1.7.0")]
4070     fn to_radians(self) -> Self;
4071
4072     /// Returns the maximum of the two numbers.
4073     #[stable(feature = "core_float_min_max", since="1.20.0")]
4074     fn max(self, other: Self) -> Self;
4075     /// Returns the minimum of the two numbers.
4076     #[stable(feature = "core_float_min_max", since="1.20.0")]
4077     fn min(self, other: Self) -> Self;
4078
4079     /// Raw transmutation to integer.
4080     #[stable(feature = "core_float_bits", since="1.25.0")]
4081     fn to_bits(self) -> Self::Bits;
4082     /// Raw transmutation from integer.
4083     #[stable(feature = "core_float_bits", since="1.25.0")]
4084     fn from_bits(v: Self::Bits) -> Self;
4085 }
4086
4087 macro_rules! from_str_radix_int_impl {
4088     ($($t:ty)*) => {$(
4089         #[stable(feature = "rust1", since = "1.0.0")]
4090         impl FromStr for $t {
4091             type Err = ParseIntError;
4092             fn from_str(src: &str) -> Result<Self, ParseIntError> {
4093                 from_str_radix(src, 10)
4094             }
4095         }
4096     )*}
4097 }
4098 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4099
4100 /// The error type returned when a checked integral type conversion fails.
4101 #[unstable(feature = "try_from", issue = "33417")]
4102 #[derive(Debug, Copy, Clone)]
4103 pub struct TryFromIntError(());
4104
4105 impl TryFromIntError {
4106     #[unstable(feature = "int_error_internals",
4107                reason = "available through Error trait and this method should \
4108                          not be exposed publicly",
4109                issue = "0")]
4110     #[doc(hidden)]
4111     pub fn __description(&self) -> &str {
4112         "out of range integral type conversion attempted"
4113     }
4114 }
4115
4116 #[unstable(feature = "try_from", issue = "33417")]
4117 impl fmt::Display for TryFromIntError {
4118     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4119         self.__description().fmt(fmt)
4120     }
4121 }
4122
4123 #[unstable(feature = "try_from", issue = "33417")]
4124 impl From<!> for TryFromIntError {
4125     fn from(never: !) -> TryFromIntError {
4126         never
4127     }
4128 }
4129
4130 // no possible bounds violation
4131 macro_rules! try_from_unbounded {
4132     ($source:ty, $($target:ty),*) => {$(
4133         #[unstable(feature = "try_from", issue = "33417")]
4134         impl TryFrom<$source> for $target {
4135             type Error = !;
4136
4137             #[inline]
4138             fn try_from(value: $source) -> Result<Self, Self::Error> {
4139                 Ok(value as $target)
4140             }
4141         }
4142     )*}
4143 }
4144
4145 // only negative bounds
4146 macro_rules! try_from_lower_bounded {
4147     ($source:ty, $($target:ty),*) => {$(
4148         #[unstable(feature = "try_from", issue = "33417")]
4149         impl TryFrom<$source> for $target {
4150             type Error = TryFromIntError;
4151
4152             #[inline]
4153             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4154                 if u >= 0 {
4155                     Ok(u as $target)
4156                 } else {
4157                     Err(TryFromIntError(()))
4158                 }
4159             }
4160         }
4161     )*}
4162 }
4163
4164 // unsigned to signed (only positive bound)
4165 macro_rules! try_from_upper_bounded {
4166     ($source:ty, $($target:ty),*) => {$(
4167         #[unstable(feature = "try_from", issue = "33417")]
4168         impl TryFrom<$source> for $target {
4169             type Error = TryFromIntError;
4170
4171             #[inline]
4172             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4173                 if u > (<$target>::max_value() as $source) {
4174                     Err(TryFromIntError(()))
4175                 } else {
4176                     Ok(u as $target)
4177                 }
4178             }
4179         }
4180     )*}
4181 }
4182
4183 // all other cases
4184 macro_rules! try_from_both_bounded {
4185     ($source:ty, $($target:ty),*) => {$(
4186         #[unstable(feature = "try_from", issue = "33417")]
4187         impl TryFrom<$source> for $target {
4188             type Error = TryFromIntError;
4189
4190             #[inline]
4191             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4192                 let min = <$target>::min_value() as $source;
4193                 let max = <$target>::max_value() as $source;
4194                 if u < min || u > max {
4195                     Err(TryFromIntError(()))
4196                 } else {
4197                     Ok(u as $target)
4198                 }
4199             }
4200         }
4201     )*}
4202 }
4203
4204 macro_rules! rev {
4205     ($mac:ident, $source:ty, $($target:ty),*) => {$(
4206         $mac!($target, $source);
4207     )*}
4208 }
4209
4210 /// intra-sign conversions
4211 try_from_upper_bounded!(u16, u8);
4212 try_from_upper_bounded!(u32, u16, u8);
4213 try_from_upper_bounded!(u64, u32, u16, u8);
4214 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4215
4216 try_from_both_bounded!(i16, i8);
4217 try_from_both_bounded!(i32, i16, i8);
4218 try_from_both_bounded!(i64, i32, i16, i8);
4219 try_from_both_bounded!(i128, i64, i32, i16, i8);
4220
4221 // unsigned-to-signed
4222 try_from_upper_bounded!(u8, i8);
4223 try_from_upper_bounded!(u16, i8, i16);
4224 try_from_upper_bounded!(u32, i8, i16, i32);
4225 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4226 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4227
4228 // signed-to-unsigned
4229 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4230 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4231 try_from_lower_bounded!(i32, u32, u64, u128);
4232 try_from_lower_bounded!(i64, u64, u128);
4233 try_from_lower_bounded!(i128, u128);
4234 try_from_both_bounded!(i16, u8);
4235 try_from_both_bounded!(i32, u16, u8);
4236 try_from_both_bounded!(i64, u32, u16, u8);
4237 try_from_both_bounded!(i128, u64, u32, u16, u8);
4238
4239 // usize/isize
4240 try_from_upper_bounded!(usize, isize);
4241 try_from_lower_bounded!(isize, usize);
4242
4243 #[cfg(target_pointer_width = "16")]
4244 mod ptr_try_from_impls {
4245     use super::TryFromIntError;
4246     use convert::TryFrom;
4247
4248     try_from_upper_bounded!(usize, u8);
4249     try_from_unbounded!(usize, u16, u32, u64, u128);
4250     try_from_upper_bounded!(usize, i8, i16);
4251     try_from_unbounded!(usize, i32, i64, i128);
4252
4253     try_from_both_bounded!(isize, u8);
4254     try_from_lower_bounded!(isize, u16, u32, u64, u128);
4255     try_from_both_bounded!(isize, i8);
4256     try_from_unbounded!(isize, i16, i32, i64, i128);
4257
4258     rev!(try_from_unbounded, usize, u16);
4259     rev!(try_from_upper_bounded, usize, u32, u64, u128);
4260     rev!(try_from_lower_bounded, usize, i8, i16);
4261     rev!(try_from_both_bounded, usize, i32, i64, i128);
4262
4263     rev!(try_from_unbounded, isize, u8);
4264     rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4265     rev!(try_from_unbounded, isize, i16);
4266     rev!(try_from_both_bounded, isize, i32, i64, i128);
4267 }
4268
4269 #[cfg(target_pointer_width = "32")]
4270 mod ptr_try_from_impls {
4271     use super::TryFromIntError;
4272     use convert::TryFrom;
4273
4274     try_from_upper_bounded!(usize, u8, u16);
4275     try_from_unbounded!(usize, u32, u64, u128);
4276     try_from_upper_bounded!(usize, i8, i16, i32);
4277     try_from_unbounded!(usize, i64, i128);
4278
4279     try_from_both_bounded!(isize, u8, u16);
4280     try_from_lower_bounded!(isize, u32, u64, u128);
4281     try_from_both_bounded!(isize, i8, i16);
4282     try_from_unbounded!(isize, i32, i64, i128);
4283
4284     rev!(try_from_unbounded, usize, u16, u32);
4285     rev!(try_from_upper_bounded, usize, u64, u128);
4286     rev!(try_from_lower_bounded, usize, i8, i16, i32);
4287     rev!(try_from_both_bounded, usize, i64, i128);
4288
4289     rev!(try_from_unbounded, isize, u8, u16);
4290     rev!(try_from_upper_bounded, isize, u32, u64, u128);
4291     rev!(try_from_unbounded, isize, i16, i32);
4292     rev!(try_from_both_bounded, isize, i64, i128);
4293 }
4294
4295 #[cfg(target_pointer_width = "64")]
4296 mod ptr_try_from_impls {
4297     use super::TryFromIntError;
4298     use convert::TryFrom;
4299
4300     try_from_upper_bounded!(usize, u8, u16, u32);
4301     try_from_unbounded!(usize, u64, u128);
4302     try_from_upper_bounded!(usize, i8, i16, i32, i64);
4303     try_from_unbounded!(usize, i128);
4304
4305     try_from_both_bounded!(isize, u8, u16, u32);
4306     try_from_lower_bounded!(isize, u64, u128);
4307     try_from_both_bounded!(isize, i8, i16, i32);
4308     try_from_unbounded!(isize, i64, i128);
4309
4310     rev!(try_from_unbounded, usize, u16, u32, u64);
4311     rev!(try_from_upper_bounded, usize, u128);
4312     rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4313     rev!(try_from_both_bounded, usize, i128);
4314
4315     rev!(try_from_unbounded, isize, u8, u16, u32);
4316     rev!(try_from_upper_bounded, isize, u64, u128);
4317     rev!(try_from_unbounded, isize, i16, i32, i64);
4318     rev!(try_from_both_bounded, isize, i128);
4319 }
4320
4321 #[doc(hidden)]
4322 trait FromStrRadixHelper: PartialOrd + Copy {
4323     fn min_value() -> Self;
4324     fn max_value() -> Self;
4325     fn from_u32(u: u32) -> Self;
4326     fn checked_mul(&self, other: u32) -> Option<Self>;
4327     fn checked_sub(&self, other: u32) -> Option<Self>;
4328     fn checked_add(&self, other: u32) -> Option<Self>;
4329 }
4330
4331 macro_rules! doit {
4332     ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4333         #[inline]
4334         fn min_value() -> Self { Self::min_value() }
4335         #[inline]
4336         fn max_value() -> Self { Self::max_value() }
4337         #[inline]
4338         fn from_u32(u: u32) -> Self { u as Self }
4339         #[inline]
4340         fn checked_mul(&self, other: u32) -> Option<Self> {
4341             Self::checked_mul(*self, other as Self)
4342         }
4343         #[inline]
4344         fn checked_sub(&self, other: u32) -> Option<Self> {
4345             Self::checked_sub(*self, other as Self)
4346         }
4347         #[inline]
4348         fn checked_add(&self, other: u32) -> Option<Self> {
4349             Self::checked_add(*self, other as Self)
4350         }
4351     })*)
4352 }
4353 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4354
4355 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4356     use self::IntErrorKind::*;
4357     use self::ParseIntError as PIE;
4358
4359     assert!(radix >= 2 && radix <= 36,
4360            "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4361            radix);
4362
4363     if src.is_empty() {
4364         return Err(PIE { kind: Empty });
4365     }
4366
4367     let is_signed_ty = T::from_u32(0) > T::min_value();
4368
4369     // all valid digits are ascii, so we will just iterate over the utf8 bytes
4370     // and cast them to chars. .to_digit() will safely return None for anything
4371     // other than a valid ascii digit for the given radix, including the first-byte
4372     // of multi-byte sequences
4373     let src = src.as_bytes();
4374
4375     let (is_positive, digits) = match src[0] {
4376         b'+' => (true, &src[1..]),
4377         b'-' if is_signed_ty => (false, &src[1..]),
4378         _ => (true, src),
4379     };
4380
4381     if digits.is_empty() {
4382         return Err(PIE { kind: Empty });
4383     }
4384
4385     let mut result = T::from_u32(0);
4386     if is_positive {
4387         // The number is positive
4388         for &c in digits {
4389             let x = match (c as char).to_digit(radix) {
4390                 Some(x) => x,
4391                 None => return Err(PIE { kind: InvalidDigit }),
4392             };
4393             result = match result.checked_mul(radix) {
4394                 Some(result) => result,
4395                 None => return Err(PIE { kind: Overflow }),
4396             };
4397             result = match result.checked_add(x) {
4398                 Some(result) => result,
4399                 None => return Err(PIE { kind: Overflow }),
4400             };
4401         }
4402     } else {
4403         // The number is negative
4404         for &c in digits {
4405             let x = match (c as char).to_digit(radix) {
4406                 Some(x) => x,
4407                 None => return Err(PIE { kind: InvalidDigit }),
4408             };
4409             result = match result.checked_mul(radix) {
4410                 Some(result) => result,
4411                 None => return Err(PIE { kind: Underflow }),
4412             };
4413             result = match result.checked_sub(x) {
4414                 Some(result) => result,
4415                 None => return Err(PIE { kind: Underflow }),
4416             };
4417         }
4418     }
4419     Ok(result)
4420 }
4421
4422 /// An error which can be returned when parsing an integer.
4423 ///
4424 /// This error is used as the error type for the `from_str_radix()` functions
4425 /// on the primitive integer types, such as [`i8::from_str_radix`].
4426 ///
4427 /// # Potential causes
4428 ///
4429 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
4430 /// in the string e.g. when it is obtained from the standard input.
4431 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
4432 ///
4433 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
4434 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
4435 #[derive(Debug, Clone, PartialEq, Eq)]
4436 #[stable(feature = "rust1", since = "1.0.0")]
4437 pub struct ParseIntError {
4438     kind: IntErrorKind,
4439 }
4440
4441 #[derive(Debug, Clone, PartialEq, Eq)]
4442 enum IntErrorKind {
4443     Empty,
4444     InvalidDigit,
4445     Overflow,
4446     Underflow,
4447 }
4448
4449 impl ParseIntError {
4450     #[unstable(feature = "int_error_internals",
4451                reason = "available through Error trait and this method should \
4452                          not be exposed publicly",
4453                issue = "0")]
4454     #[doc(hidden)]
4455     pub fn __description(&self) -> &str {
4456         match self.kind {
4457             IntErrorKind::Empty => "cannot parse integer from empty string",
4458             IntErrorKind::InvalidDigit => "invalid digit found in string",
4459             IntErrorKind::Overflow => "number too large to fit in target type",
4460             IntErrorKind::Underflow => "number too small to fit in target type",
4461         }
4462     }
4463 }
4464
4465 #[stable(feature = "rust1", since = "1.0.0")]
4466 impl fmt::Display for ParseIntError {
4467     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4468         self.__description().fmt(f)
4469     }
4470 }
4471
4472 #[stable(feature = "rust1", since = "1.0.0")]
4473 pub use num::dec2flt::ParseFloatError;
4474
4475 // Conversion traits for primitive integer and float types
4476 // Conversions T -> T are covered by a blanket impl and therefore excluded
4477 // Some conversions from and to usize/isize are not implemented due to portability concerns
4478 macro_rules! impl_from {
4479     ($Small: ty, $Large: ty, #[$attr:meta]) => {
4480         #[$attr]
4481         impl From<$Small> for $Large {
4482             #[inline]
4483             fn from(small: $Small) -> $Large {
4484                 small as $Large
4485             }
4486         }
4487     }
4488 }
4489
4490 // Unsigned -> Unsigned
4491 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4492 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4493 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4494 impl_from! { u8, u128, #[unstable(feature = "i128", issue = "35118")] }
4495 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4496 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4497 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4498 impl_from! { u16, u128, #[unstable(feature = "i128", issue = "35118")] }
4499 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4500 impl_from! { u32, u128, #[unstable(feature = "i128", issue = "35118")] }
4501 impl_from! { u64, u128, #[unstable(feature = "i128", issue = "35118")] }
4502
4503 // Signed -> Signed
4504 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4505 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4506 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4507 impl_from! { i8, i128, #[unstable(feature = "i128", issue = "35118")] }
4508 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4509 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4510 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4511 impl_from! { i16, i128, #[unstable(feature = "i128", issue = "35118")] }
4512 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4513 impl_from! { i32, i128, #[unstable(feature = "i128", issue = "35118")] }
4514 impl_from! { i64, i128, #[unstable(feature = "i128", issue = "35118")] }
4515
4516 // Unsigned -> Signed
4517 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4518 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4519 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4520 impl_from! { u8, i128, #[unstable(feature = "i128", issue = "35118")] }
4521 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4522 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4523 impl_from! { u16, i128, #[unstable(feature = "i128", issue = "35118")] }
4524 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4525 impl_from! { u32, i128, #[unstable(feature = "i128", issue = "35118")] }
4526 impl_from! { u64, i128, #[unstable(feature = "i128", issue = "35118")] }
4527
4528 // Note: integers can only be represented with full precision in a float if
4529 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4530 // Lossy float conversions are not implemented at this time.
4531
4532 // Signed -> Float
4533 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4534 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4535 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4536 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4537 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4538
4539 // Unsigned -> Float
4540 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4541 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4542 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4543 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4544 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4545
4546 // Float -> Float
4547 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4548
4549 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4550     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4551     0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4552     0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4553     0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4554     b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4555     b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4556     b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4557     b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4558     b'@',
4559
4560           b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4561     b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4562     b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4563     b'x', b'y', b'z',
4564
4565                       b'[', b'\\', b']', b'^', b'_',
4566     b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4567     b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4568     b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4569     b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4570     0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4571     0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4572     0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4573     0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4574     0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4575     0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4576     0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4577     0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4578     0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4579     0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4580     0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4581     0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4582     0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4583     0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4584     0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4585     0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4586 ];
4587
4588 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4589     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4590     0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4591     0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4592     0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4593     b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4594     b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4595     b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4596     b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4597     b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4598     b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4599     b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4600     b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4601     b'`',
4602
4603           b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4604     b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4605     b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4606     b'X', b'Y', b'Z',
4607
4608                       b'{', b'|', b'}', b'~', 0x7f,
4609     0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4610     0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4611     0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4612     0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4613     0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4614     0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4615     0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4616     0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4617     0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4618     0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4619     0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4620     0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4621     0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4622     0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4623     0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4624     0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4625 ];
4626
4627 enum AsciiCharacterClass {
4628     C,  // control
4629     Cw, // control whitespace
4630     W,  // whitespace
4631     D,  // digit
4632     L,  // lowercase
4633     Lx, // lowercase hex digit
4634     U,  // uppercase
4635     Ux, // uppercase hex digit
4636     P,  // punctuation
4637 }
4638 use self::AsciiCharacterClass::*;
4639
4640 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4641 //  _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4642     C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4643     C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4644     W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4645     D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4646     P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4647     U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4648     P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4649     L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_
4650 ];