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