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