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