]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
Fix missed i128 feature gates
[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, "", "" }
1639 }
1640
1641 #[cfg(target_pointer_width = "16")]
1642 #[lang = "isize"]
1643 impl isize {
1644     int_impl! { isize, i16, u16, 16, -32768, 32767, "", "" }
1645 }
1646
1647 #[cfg(target_pointer_width = "32")]
1648 #[lang = "isize"]
1649 impl isize {
1650     int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "" }
1651 }
1652
1653 #[cfg(target_pointer_width = "64")]
1654 #[lang = "isize"]
1655 impl isize {
1656     int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1657 }
1658
1659 // `Int` + `UnsignedInt` implemented for unsigned integers
1660 macro_rules! uint_impl {
1661     ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr) => {
1662         doc_comment! {
1663             concat!("Returns the smallest value that can be represented by this integer type.
1664
1665 # Examples
1666
1667 Basic usage:
1668
1669 ```
1670 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
1671 ```"),
1672             #[stable(feature = "rust1", since = "1.0.0")]
1673             #[inline]
1674             pub const fn min_value() -> Self { 0 }
1675         }
1676
1677         doc_comment! {
1678             concat!("Returns the largest value that can be represented by this integer type.
1679
1680 # Examples
1681
1682 Basic usage:
1683
1684 ```
1685 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
1686 stringify!($MaxV), ");", $EndFeature, "
1687 ```"),
1688             #[stable(feature = "rust1", since = "1.0.0")]
1689             #[inline]
1690             pub const fn max_value() -> Self { !0 }
1691         }
1692
1693         doc_comment! {
1694             concat!("Converts a string slice in a given base to an integer.
1695
1696 The string is expected to be an optional `+` sign
1697 followed by digits.
1698 Leading and trailing whitespace represent an error.
1699 Digits are a subset of these characters, depending on `radix`:
1700
1701 * `0-9`
1702 * `a-z`
1703 * `A-Z`
1704
1705 # Panics
1706
1707 This function panics if `radix` is not in the range from 2 to 36.
1708
1709 # Examples
1710
1711 Basic usage:
1712
1713 ```
1714 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
1715 $EndFeature, "
1716 ```"),
1717             #[stable(feature = "rust1", since = "1.0.0")]
1718             pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1719                 from_str_radix(src, radix)
1720             }
1721         }
1722
1723         doc_comment! {
1724             concat!("Returns the number of ones in the binary representation of `self`.
1725
1726 # Examples
1727
1728 Basic usage:
1729
1730 ```
1731 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
1732
1733 assert_eq!(n.count_ones(), 3);", $EndFeature, "
1734 ```"),
1735             #[stable(feature = "rust1", since = "1.0.0")]
1736             #[inline]
1737             pub fn count_ones(self) -> u32 {
1738                 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
1739             }
1740         }
1741
1742         doc_comment! {
1743             concat!("Returns the number of zeros in the binary representation of `self`.
1744
1745 # Examples
1746
1747 Basic usage:
1748
1749 ```
1750 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
1751 ```"),
1752             #[stable(feature = "rust1", since = "1.0.0")]
1753             #[inline]
1754             pub fn count_zeros(self) -> u32 {
1755                 (!self).count_ones()
1756             }
1757         }
1758
1759         doc_comment! {
1760             concat!("Returns the number of leading zeros in the binary representation of `self`.
1761
1762 # Examples
1763
1764 Basic usage:
1765
1766 ```
1767 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
1768
1769 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
1770 ```"),
1771             #[stable(feature = "rust1", since = "1.0.0")]
1772             #[inline]
1773             pub fn leading_zeros(self) -> u32 {
1774                 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
1775             }
1776         }
1777
1778         doc_comment! {
1779             concat!("Returns the number of trailing zeros in the binary representation
1780 of `self`.
1781
1782 # Examples
1783
1784 Basic usage:
1785
1786 ```
1787 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
1788
1789 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
1790 ```"),
1791             #[stable(feature = "rust1", since = "1.0.0")]
1792             #[inline]
1793             pub fn trailing_zeros(self) -> u32 {
1794                 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1795                 // emits two conditional moves on x86_64. By promoting the value to
1796                 // u16 and setting bit 8, we get better code without any conditional
1797                 // operations.
1798                 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1799                 // pending, remove this workaround once LLVM generates better code
1800                 // for cttz8.
1801                 unsafe {
1802                     if $BITS == 8 {
1803                         intrinsics::cttz(self as u16 | 0x100) as u32
1804                     } else {
1805                         intrinsics::cttz(self) as u32
1806                     }
1807                 }
1808             }
1809         }
1810
1811         /// Shifts the bits to the left by a specified amount, `n`,
1812         /// wrapping the truncated bits to the end of the resulting integer.
1813         ///
1814         /// Please note this isn't the same operation as `<<`!
1815         ///
1816         /// # Examples
1817         ///
1818         /// Basic usage:
1819         ///
1820         /// Please note that this example is shared between integer types.
1821         /// Which explains why `u64` is used here.
1822         ///
1823         /// ```
1824         /// let n = 0x0123456789ABCDEFu64;
1825         /// let m = 0x3456789ABCDEF012u64;
1826         ///
1827         /// assert_eq!(n.rotate_left(12), m);
1828         /// ```
1829         #[stable(feature = "rust1", since = "1.0.0")]
1830         #[inline]
1831         pub fn rotate_left(self, n: u32) -> Self {
1832             // Protect against undefined behaviour for over-long bit shifts
1833             let n = n % $BITS;
1834             (self << n) | (self >> (($BITS - n) % $BITS))
1835         }
1836
1837         /// Shifts the bits to the right by a specified amount, `n`,
1838         /// wrapping the truncated bits to the beginning of the resulting
1839         /// integer.
1840         ///
1841         /// Please note this isn't the same operation as `>>`!
1842         ///
1843         /// # Examples
1844         ///
1845         /// Basic usage:
1846         ///
1847         /// Please note that this example is shared between integer types.
1848         /// Which explains why `u64` is used here.
1849         ///
1850         /// ```
1851         /// let n = 0x0123456789ABCDEFu64;
1852         /// let m = 0xDEF0123456789ABCu64;
1853         ///
1854         /// assert_eq!(n.rotate_right(12), m);
1855         /// ```
1856         #[stable(feature = "rust1", since = "1.0.0")]
1857         #[inline]
1858         pub fn rotate_right(self, n: u32) -> Self {
1859             // Protect against undefined behaviour for over-long bit shifts
1860             let n = n % $BITS;
1861             (self >> n) | (self << (($BITS - n) % $BITS))
1862         }
1863
1864         /// Reverses the byte order of the integer.
1865         ///
1866         /// # Examples
1867         ///
1868         /// Basic usage:
1869         ///
1870         /// Please note that this example is shared between integer types.
1871         /// Which explains why `u16` is used here.
1872         ///
1873         /// ```
1874         /// let n: u16 = 0b0000000_01010101;
1875         /// assert_eq!(n, 85);
1876         ///
1877         /// let m = n.swap_bytes();
1878         ///
1879         /// assert_eq!(m, 0b01010101_00000000);
1880         /// assert_eq!(m, 21760);
1881         /// ```
1882         #[stable(feature = "rust1", since = "1.0.0")]
1883         #[inline]
1884         pub fn swap_bytes(self) -> Self {
1885             unsafe { intrinsics::bswap(self as $ActualT) as Self }
1886         }
1887
1888         /// Reverses the bit pattern of the integer.
1889         ///
1890         /// # Examples
1891         ///
1892         /// Basic usage:
1893         ///
1894         /// Please note that this example is shared between integer types.
1895         /// Which explains why `u16` is used here.
1896         ///
1897         /// ```
1898         /// #![feature(reverse_bits)]
1899         ///
1900         /// let n: u16 = 0b0000000_01010101;
1901         /// assert_eq!(n, 85);
1902         ///
1903         /// let m = n.reverse_bits();
1904         ///
1905         /// assert_eq!(m, 0b10101010_00000000);
1906         /// assert_eq!(m, 43520);
1907         /// ```
1908         #[unstable(feature = "reverse_bits", issue = "48763")]
1909         #[cfg(not(stage0))]
1910         #[inline]
1911         pub fn reverse_bits(self) -> Self {
1912             unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
1913         }
1914
1915         doc_comment! {
1916             concat!("Converts an integer from big endian to the target's endianness.
1917
1918 On big endian this is a no-op. On little endian the bytes are
1919 swapped.
1920
1921 # Examples
1922
1923 Basic usage:
1924
1925 ```
1926 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1927
1928 if cfg!(target_endian = \"big\") {
1929     assert_eq!(", stringify!($SelfT), "::from_be(n), n)
1930 } else {
1931     assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
1932 }", $EndFeature, "
1933 ```"),
1934             #[stable(feature = "rust1", since = "1.0.0")]
1935             #[inline]
1936             pub fn from_be(x: Self) -> Self {
1937                 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1938             }
1939         }
1940
1941         doc_comment! {
1942             concat!("Converts an integer from little endian to the target's endianness.
1943
1944 On little endian this is a no-op. On big endian the bytes are
1945 swapped.
1946
1947 # Examples
1948
1949 Basic usage:
1950
1951 ```
1952 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1953
1954 if cfg!(target_endian = \"little\") {
1955     assert_eq!(", stringify!($SelfT), "::from_le(n), n)
1956 } else {
1957     assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
1958 }", $EndFeature, "
1959 ```"),
1960             #[stable(feature = "rust1", since = "1.0.0")]
1961             #[inline]
1962             pub fn from_le(x: Self) -> Self {
1963                 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1964             }
1965         }
1966
1967         doc_comment! {
1968             concat!("Converts `self` to big endian from the target's endianness.
1969
1970 On big endian this is a no-op. On little endian the bytes are
1971 swapped.
1972
1973 # Examples
1974
1975 Basic usage:
1976
1977 ```
1978 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1979
1980 if cfg!(target_endian = \"big\") {
1981     assert_eq!(n.to_be(), n)
1982 } else {
1983     assert_eq!(n.to_be(), n.swap_bytes())
1984 }", $EndFeature, "
1985 ```"),
1986             #[stable(feature = "rust1", since = "1.0.0")]
1987             #[inline]
1988             pub fn to_be(self) -> Self { // or not to be?
1989                 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1990             }
1991         }
1992
1993         doc_comment! {
1994             concat!("Converts `self` to little endian from the target's endianness.
1995
1996 On little endian this is a no-op. On big endian the bytes are
1997 swapped.
1998
1999 # Examples
2000
2001 Basic usage:
2002
2003 ```
2004 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2005
2006 if cfg!(target_endian = \"little\") {
2007     assert_eq!(n.to_le(), n)
2008 } else {
2009     assert_eq!(n.to_le(), n.swap_bytes())
2010 }", $EndFeature, "
2011 ```"),
2012             #[stable(feature = "rust1", since = "1.0.0")]
2013             #[inline]
2014             pub fn to_le(self) -> Self {
2015                 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
2016             }
2017         }
2018
2019         doc_comment! {
2020             concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2021 if overflow occurred.
2022
2023 # Examples
2024
2025 Basic usage:
2026
2027 ```
2028 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2029 "Some(", stringify!($SelfT), "::max_value() - 1));
2030 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3),None);", $EndFeature, "
2031 ```"),
2032             #[stable(feature = "rust1", since = "1.0.0")]
2033             #[inline]
2034             pub fn checked_add(self, rhs: Self) -> Option<Self> {
2035                 let (a, b) = self.overflowing_add(rhs);
2036                 if b {None} else {Some(a)}
2037             }
2038         }
2039
2040         doc_comment! {
2041             concat!("Checked integer subtraction. Computes `self - rhs`, returning
2042 `None` if overflow occurred.
2043
2044 # Examples
2045
2046 Basic usage:
2047
2048 ```
2049 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2050 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2051 ```"),
2052             #[stable(feature = "rust1", since = "1.0.0")]
2053             #[inline]
2054             pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2055                 let (a, b) = self.overflowing_sub(rhs);
2056                 if b {None} else {Some(a)}
2057             }
2058         }
2059
2060         doc_comment! {
2061             concat!("Checked integer multiplication. Computes `self * rhs`, returning
2062 `None` if overflow occurred.
2063
2064 # Examples
2065
2066 Basic usage:
2067
2068 ```
2069 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2070 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2071 ```"),
2072             #[stable(feature = "rust1", since = "1.0.0")]
2073             #[inline]
2074             pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2075                 let (a, b) = self.overflowing_mul(rhs);
2076                 if b {None} else {Some(a)}
2077             }
2078         }
2079
2080         doc_comment! {
2081             concat!("Checked integer division. Computes `self / rhs`, returning `None`
2082 if `rhs == 0`.
2083
2084 # Examples
2085
2086 Basic usage:
2087
2088 ```
2089 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2090 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2091 ```"),
2092             #[stable(feature = "rust1", since = "1.0.0")]
2093             #[inline]
2094             pub fn checked_div(self, rhs: Self) -> Option<Self> {
2095                 match rhs {
2096                     0 => None,
2097                     rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2098                 }
2099             }
2100         }
2101
2102         doc_comment! {
2103             concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2104 if `rhs == 0`.
2105
2106 # Examples
2107
2108 Basic usage:
2109
2110 ```
2111 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2112 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2113 ```"),
2114             #[stable(feature = "wrapping", since = "1.7.0")]
2115             #[inline]
2116             pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2117                 if rhs == 0 {
2118                     None
2119                 } else {
2120                     Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2121                 }
2122             }
2123         }
2124
2125         doc_comment! {
2126             concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2127 0`.
2128
2129 Note that negating any positive integer will overflow.
2130
2131 # Examples
2132
2133 Basic usage:
2134
2135 ```
2136 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2137 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2138 ```"),
2139             #[stable(feature = "wrapping", since = "1.7.0")]
2140             #[inline]
2141             pub fn checked_neg(self) -> Option<Self> {
2142                 let (a, b) = self.overflowing_neg();
2143                 if b {None} else {Some(a)}
2144             }
2145         }
2146
2147         doc_comment! {
2148             concat!("Checked shift left. Computes `self << rhs`, returning `None`
2149 if `rhs` is larger than or equal to the number of bits in `self`.
2150
2151 # Examples
2152
2153 Basic usage:
2154
2155 ```
2156 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2157 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2158 ```"),
2159             #[stable(feature = "wrapping", since = "1.7.0")]
2160             #[inline]
2161             pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2162                 let (a, b) = self.overflowing_shl(rhs);
2163                 if b {None} else {Some(a)}
2164             }
2165         }
2166
2167         doc_comment! {
2168             concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2169 if `rhs` is larger than or equal to the number of bits in `self`.
2170
2171 # Examples
2172
2173 Basic usage:
2174
2175 ```
2176 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2177 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2178 ```"),
2179             #[stable(feature = "wrapping", since = "1.7.0")]
2180             #[inline]
2181             pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2182                 let (a, b) = self.overflowing_shr(rhs);
2183                 if b {None} else {Some(a)}
2184             }
2185         }
2186
2187         doc_comment! {
2188             concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2189 overflow occurred.
2190
2191 # Examples
2192
2193 Basic usage:
2194
2195 ```
2196 #![feature(no_panic_pow)]
2197 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2198 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2199 ```"),
2200             #[unstable(feature = "no_panic_pow", issue = "48320")]
2201             #[inline]
2202             pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2203                 let mut base = self;
2204                 let mut acc: Self = 1;
2205
2206                 while exp > 1 {
2207                     if (exp & 1) == 1 {
2208                         acc = acc.checked_mul(base)?;
2209                     }
2210                     exp /= 2;
2211                     base = base.checked_mul(base)?;
2212                 }
2213
2214                 // Deal with the final bit of the exponent separately, since
2215                 // squaring the base afterwards is not necessary and may cause a
2216                 // needless overflow.
2217                 if exp == 1 {
2218                     acc = acc.checked_mul(base)?;
2219                 }
2220
2221                 Some(acc)
2222             }
2223         }
2224
2225         doc_comment! {
2226             concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2227 the numeric bounds instead of overflowing.
2228
2229 # Examples
2230
2231 Basic usage:
2232
2233 ```
2234 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2235 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2236 ```"),
2237             #[stable(feature = "rust1", since = "1.0.0")]
2238             #[inline]
2239             pub fn saturating_add(self, rhs: Self) -> Self {
2240                 match self.checked_add(rhs) {
2241                     Some(x) => x,
2242                     None => Self::max_value(),
2243                 }
2244             }
2245         }
2246
2247         doc_comment! {
2248             concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2249 at the numeric bounds instead of overflowing.
2250
2251 # Examples
2252
2253 Basic usage:
2254
2255 ```
2256 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2257 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2258 ```"),
2259             #[stable(feature = "rust1", since = "1.0.0")]
2260             #[inline]
2261             pub fn saturating_sub(self, rhs: Self) -> Self {
2262                 match self.checked_sub(rhs) {
2263                     Some(x) => x,
2264                     None => Self::min_value(),
2265                 }
2266             }
2267         }
2268
2269         doc_comment! {
2270             concat!("Saturating integer multiplication. Computes `self * rhs`,
2271 saturating at the numeric bounds instead of overflowing.
2272
2273 # Examples
2274
2275 Basic usage:
2276
2277 ```
2278 ", $Feature, "use std::", stringify!($SelfT), ";
2279
2280 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2281 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2282 "::MAX);", $EndFeature, "
2283 ```"),
2284             #[stable(feature = "wrapping", since = "1.7.0")]
2285             #[inline]
2286             pub fn saturating_mul(self, rhs: Self) -> Self {
2287                 self.checked_mul(rhs).unwrap_or(Self::max_value())
2288             }
2289         }
2290
2291         doc_comment! {
2292             concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2293 saturating at the numeric bounds instead of overflowing.
2294
2295 # Examples
2296
2297 Basic usage:
2298
2299 ```
2300 #![feature(no_panic_pow)]
2301 ", $Feature, "use std::", stringify!($SelfT), ";
2302
2303 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2304 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2305 $EndFeature, "
2306 ```"),
2307             #[unstable(feature = "no_panic_pow", issue = "48320")]
2308             #[inline]
2309             pub fn saturating_pow(self, exp: u32) -> Self {
2310                 match self.checked_pow(exp) {
2311                     Some(x) => x,
2312                     None => Self::max_value(),
2313                 }
2314             }
2315         }
2316
2317         doc_comment! {
2318             concat!("Wrapping (modular) addition. Computes `self + rhs`,
2319 wrapping around at the boundary of the type.
2320
2321 # Examples
2322
2323 Basic usage:
2324
2325 ```
2326 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2327 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2328 $EndFeature, "
2329 ```"),
2330             #[stable(feature = "rust1", since = "1.0.0")]
2331             #[inline]
2332             pub fn wrapping_add(self, rhs: Self) -> Self {
2333                 unsafe {
2334                     intrinsics::overflowing_add(self, rhs)
2335                 }
2336             }
2337         }
2338
2339         doc_comment! {
2340             concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2341 wrapping around at the boundary of the type.
2342
2343 # Examples
2344
2345 Basic usage:
2346
2347 ```
2348 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2349 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2350 $EndFeature, "
2351 ```"),
2352             #[stable(feature = "rust1", since = "1.0.0")]
2353             #[inline]
2354             pub fn wrapping_sub(self, rhs: Self) -> Self {
2355                 unsafe {
2356                     intrinsics::overflowing_sub(self, rhs)
2357                 }
2358             }
2359         }
2360
2361         /// Wrapping (modular) multiplication. Computes `self *
2362         /// rhs`, wrapping around at the boundary of the type.
2363         ///
2364         /// # Examples
2365         ///
2366         /// Basic usage:
2367         ///
2368         /// Please note that this example is shared between integer types.
2369         /// Which explains why `u8` is used here.
2370         ///
2371         /// ```
2372         /// assert_eq!(10u8.wrapping_mul(12), 120);
2373         /// assert_eq!(25u8.wrapping_mul(12), 44);
2374         /// ```
2375         #[stable(feature = "rust1", since = "1.0.0")]
2376         #[inline]
2377         pub fn wrapping_mul(self, rhs: Self) -> Self {
2378             unsafe {
2379                 intrinsics::overflowing_mul(self, rhs)
2380             }
2381         }
2382
2383         doc_comment! {
2384             concat!("Wrapping (modular) division. Computes `self / rhs`.
2385 Wrapped division on unsigned types is just normal division.
2386 There's no way wrapping could ever happen.
2387 This function exists, so that all operations
2388 are accounted for in the wrapping operations.
2389
2390 # Examples
2391
2392 Basic usage:
2393
2394 ```
2395 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2396 ```"),
2397             #[stable(feature = "num_wrapping", since = "1.2.0")]
2398             #[inline]
2399             pub fn wrapping_div(self, rhs: Self) -> Self {
2400                 self / rhs
2401             }
2402         }
2403
2404         doc_comment! {
2405             concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2406 Wrapped remainder calculation on unsigned types is
2407 just the regular remainder calculation.
2408 There's no way wrapping could ever happen.
2409 This function exists, so that all operations
2410 are accounted for in the wrapping operations.
2411
2412 # Examples
2413
2414 Basic usage:
2415
2416 ```
2417 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2418 ```"),
2419             #[stable(feature = "num_wrapping", since = "1.2.0")]
2420             #[inline]
2421             pub fn wrapping_rem(self, rhs: Self) -> Self {
2422                 self % rhs
2423             }
2424         }
2425
2426         /// Wrapping (modular) negation. Computes `-self`,
2427         /// wrapping around at the boundary of the type.
2428         ///
2429         /// Since unsigned types do not have negative equivalents
2430         /// all applications of this function will wrap (except for `-0`).
2431         /// For values smaller than the corresponding signed type's maximum
2432         /// the result is the same as casting the corresponding signed value.
2433         /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2434         /// `MAX` is the corresponding signed type's maximum.
2435         ///
2436         /// # Examples
2437         ///
2438         /// Basic usage:
2439         ///
2440         /// Please note that this example is shared between integer types.
2441         /// Which explains why `i8` is used here.
2442         ///
2443         /// ```
2444         /// assert_eq!(100i8.wrapping_neg(), -100);
2445         /// assert_eq!((-128i8).wrapping_neg(), -128);
2446         /// ```
2447         #[stable(feature = "num_wrapping", since = "1.2.0")]
2448         #[inline]
2449         pub fn wrapping_neg(self) -> Self {
2450             self.overflowing_neg().0
2451         }
2452
2453         doc_comment! {
2454             concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2455 where `mask` removes any high-order bits of `rhs` that
2456 would cause the shift to exceed the bitwidth of the type.
2457
2458 Note that this is *not* the same as a rotate-left; the
2459 RHS of a wrapping shift-left is restricted to the range
2460 of the type, rather than the bits shifted out of the LHS
2461 being returned to the other end. The primitive integer
2462 types all implement a `rotate_left` function, which may
2463 be what you want instead.
2464
2465 # Examples
2466
2467 Basic usage:
2468
2469 ```
2470 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2471 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2472 ```"),
2473             #[stable(feature = "num_wrapping", since = "1.2.0")]
2474             #[inline]
2475             pub fn wrapping_shl(self, rhs: u32) -> Self {
2476                 unsafe {
2477                     intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
2478                 }
2479             }
2480         }
2481
2482         doc_comment! {
2483             concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2484 where `mask` removes any high-order bits of `rhs` that
2485 would cause the shift to exceed the bitwidth of the type.
2486
2487 Note that this is *not* the same as a rotate-right; the
2488 RHS of a wrapping shift-right is restricted to the range
2489 of the type, rather than the bits shifted out of the LHS
2490 being returned to the other end. The primitive integer
2491 types all implement a `rotate_right` function, which may
2492 be what you want instead.
2493
2494 # Examples
2495
2496 Basic usage:
2497
2498 ```
2499 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
2500 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
2501 ```"),
2502             #[stable(feature = "num_wrapping", since = "1.2.0")]
2503             #[inline]
2504             pub fn wrapping_shr(self, rhs: u32) -> Self {
2505                 unsafe {
2506                     intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
2507                 }
2508             }
2509         }
2510
2511         doc_comment! {
2512             concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2513 wrapping around at the boundary of the type.
2514
2515 # Examples
2516
2517 Basic usage:
2518
2519 ```
2520 #![feature(no_panic_pow)]
2521 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
2522 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
2523 ```"),
2524             #[unstable(feature = "no_panic_pow", issue = "48320")]
2525             #[inline]
2526             pub fn wrapping_pow(self, mut exp: u32) -> Self {
2527                 let mut base = self;
2528                 let mut acc: Self = 1;
2529
2530                 while exp > 1 {
2531                     if (exp & 1) == 1 {
2532                         acc = acc.wrapping_mul(base);
2533                     }
2534                     exp /= 2;
2535                     base = base.wrapping_mul(base);
2536                 }
2537
2538                 // Deal with the final bit of the exponent separately, since
2539                 // squaring the base afterwards is not necessary and may cause a
2540                 // needless overflow.
2541                 if exp == 1 {
2542                     acc = acc.wrapping_mul(base);
2543                 }
2544
2545                 acc
2546             }
2547         }
2548
2549         doc_comment! {
2550             concat!("Calculates `self` + `rhs`
2551
2552 Returns a tuple of the addition along with a boolean indicating
2553 whether an arithmetic overflow would occur. If an overflow would
2554 have occurred then the wrapped value is returned.
2555
2556 # Examples
2557
2558 Basic usage
2559
2560 ```
2561 ", $Feature, "use std::", stringify!($SelfT), ";
2562
2563 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
2564 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
2565 ```"),
2566             #[inline]
2567             #[stable(feature = "wrapping", since = "1.7.0")]
2568             pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2569                 let (a, b) = unsafe {
2570                     intrinsics::add_with_overflow(self as $ActualT,
2571                                                   rhs as $ActualT)
2572                 };
2573                 (a as Self, b)
2574             }
2575         }
2576
2577         doc_comment! {
2578             concat!("Calculates `self` - `rhs`
2579
2580 Returns a tuple of the subtraction along with a boolean indicating
2581 whether an arithmetic overflow would occur. If an overflow would
2582 have occurred then the wrapped value is returned.
2583
2584 # Examples
2585
2586 Basic usage
2587
2588 ```
2589 ", $Feature, "use std::", stringify!($SelfT), ";
2590
2591 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
2592 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
2593 $EndFeature, "
2594 ```"),
2595             #[inline]
2596             #[stable(feature = "wrapping", since = "1.7.0")]
2597             pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2598                 let (a, b) = unsafe {
2599                     intrinsics::sub_with_overflow(self as $ActualT,
2600                                                   rhs as $ActualT)
2601                 };
2602                 (a as Self, b)
2603             }
2604         }
2605
2606         /// Calculates the multiplication of `self` and `rhs`.
2607         ///
2608         /// Returns a tuple of the multiplication along with a boolean
2609         /// indicating whether an arithmetic overflow would occur. If an
2610         /// overflow would have occurred then the wrapped value is returned.
2611         ///
2612         /// # Examples
2613         ///
2614         /// Basic usage:
2615         ///
2616         /// Please note that this example is shared between integer types.
2617         /// Which explains why `u32` is used here.
2618         ///
2619         /// ```
2620         /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2621         /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2622         /// ```
2623         #[inline]
2624         #[stable(feature = "wrapping", since = "1.7.0")]
2625         pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2626             let (a, b) = unsafe {
2627                 intrinsics::mul_with_overflow(self as $ActualT,
2628                                               rhs as $ActualT)
2629             };
2630             (a as Self, b)
2631         }
2632
2633         doc_comment! {
2634             concat!("Calculates the divisor when `self` is divided by `rhs`.
2635
2636 Returns a tuple of the divisor along with a boolean indicating
2637 whether an arithmetic overflow would occur. Note that for unsigned
2638 integers overflow never occurs, so the second value is always
2639 `false`.
2640
2641 # Panics
2642
2643 This function will panic if `rhs` is 0.
2644
2645 # Examples
2646
2647 Basic usage
2648
2649 ```
2650 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
2651 ```"),
2652             #[inline]
2653             #[stable(feature = "wrapping", since = "1.7.0")]
2654             pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2655                 (self / rhs, false)
2656             }
2657         }
2658
2659         doc_comment! {
2660             concat!("Calculates the remainder when `self` is divided by `rhs`.
2661
2662 Returns a tuple of the remainder after dividing along with a boolean
2663 indicating whether an arithmetic overflow would occur. Note that for
2664 unsigned integers overflow never occurs, so the second value is
2665 always `false`.
2666
2667 # Panics
2668
2669 This function will panic if `rhs` is 0.
2670
2671 # Examples
2672
2673 Basic usage
2674
2675 ```
2676 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
2677 ```"),
2678             #[inline]
2679             #[stable(feature = "wrapping", since = "1.7.0")]
2680             pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2681                 (self % rhs, false)
2682             }
2683         }
2684
2685         doc_comment! {
2686             concat!("Negates self in an overflowing fashion.
2687
2688 Returns `!self + 1` using wrapping operations to return the value
2689 that represents the negation of this unsigned value. Note that for
2690 positive unsigned values overflow always occurs, but negating 0 does
2691 not overflow.
2692
2693 # Examples
2694
2695 Basic usage
2696
2697 ```
2698 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
2699 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
2700 ", true));", $EndFeature, "
2701 ```"),
2702             #[inline]
2703             #[stable(feature = "wrapping", since = "1.7.0")]
2704             pub fn overflowing_neg(self) -> (Self, bool) {
2705                 ((!self).wrapping_add(1), self != 0)
2706             }
2707         }
2708
2709         doc_comment! {
2710             concat!("Shifts self left by `rhs` bits.
2711
2712 Returns a tuple of the shifted version of self along with a boolean
2713 indicating whether the shift value was larger than or equal to the
2714 number of bits. If the shift value is too large, then value is
2715 masked (N-1) where N is the number of bits, and this value is then
2716 used to perform the shift.
2717
2718 # Examples
2719
2720 Basic usage
2721
2722 ```
2723 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
2724 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
2725 ```"),
2726             #[inline]
2727             #[stable(feature = "wrapping", since = "1.7.0")]
2728             pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2729                 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
2730             }
2731         }
2732
2733         doc_comment! {
2734             concat!("Shifts self right by `rhs` bits.
2735
2736 Returns a tuple of the shifted version of self along with a boolean
2737 indicating whether the shift value was larger than or equal to the
2738 number of bits. If the shift value is too large, then value is
2739 masked (N-1) where N is the number of bits, and this value is then
2740 used to perform the shift.
2741
2742 # Examples
2743
2744 Basic usage
2745
2746 ```
2747 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
2748 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
2749 ```"),
2750             #[inline]
2751             #[stable(feature = "wrapping", since = "1.7.0")]
2752             pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2753                 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
2754             }
2755         }
2756
2757         doc_comment! {
2758             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2759
2760 Returns a tuple of the exponentiation along with a bool indicating
2761 whether an overflow happened.
2762
2763 # Examples
2764
2765 Basic usage:
2766
2767 ```
2768 #![feature(no_panic_pow)]
2769 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
2770 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
2771 ```"),
2772             #[unstable(feature = "no_panic_pow", issue = "48320")]
2773             #[inline]
2774             pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
2775                 let mut base = self;
2776                 let mut acc: Self = 1;
2777                 let mut overflown = false;
2778                 // Scratch space for storing results of overflowing_mul.
2779                 let mut r;
2780
2781                 while exp > 1 {
2782                     if (exp & 1) == 1 {
2783                         r = acc.overflowing_mul(base);
2784                         acc = r.0;
2785                         overflown |= r.1;
2786                     }
2787                     exp /= 2;
2788                     r = base.overflowing_mul(base);
2789                     base = r.0;
2790                     overflown |= r.1;
2791                 }
2792
2793                 // Deal with the final bit of the exponent separately, since
2794                 // squaring the base afterwards is not necessary and may cause a
2795                 // needless overflow.
2796                 if exp == 1 {
2797                     r = acc.overflowing_mul(base);
2798                     acc = r.0;
2799                     overflown |= r.1;
2800                 }
2801
2802                 (acc, overflown)
2803             }
2804         }
2805
2806         doc_comment! {
2807             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2808
2809 # Examples
2810
2811 Basic usage:
2812
2813 ```
2814 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
2815 ```"),
2816         #[stable(feature = "rust1", since = "1.0.0")]
2817         #[inline]
2818         #[rustc_inherit_overflow_checks]
2819         pub fn pow(self, mut exp: u32) -> Self {
2820             let mut base = self;
2821             let mut acc = 1;
2822
2823             while exp > 1 {
2824                 if (exp & 1) == 1 {
2825                     acc = acc * base;
2826                 }
2827                 exp /= 2;
2828                 base = base * base;
2829             }
2830
2831             // Deal with the final bit of the exponent separately, since
2832             // squaring the base afterwards is not necessary and may cause a
2833             // needless overflow.
2834             if exp == 1 {
2835                 acc = acc * base;
2836             }
2837
2838             acc
2839         }
2840     }
2841
2842         doc_comment! {
2843             concat!("Returns `true` if and only if `self == 2^k` for some `k`.
2844
2845 # Examples
2846
2847 Basic usage:
2848
2849 ```
2850 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
2851 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
2852 ```"),
2853             #[stable(feature = "rust1", since = "1.0.0")]
2854             #[inline]
2855             pub fn is_power_of_two(self) -> bool {
2856                 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2857             }
2858         }
2859
2860         // Returns one less than next power of two.
2861         // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2862         //
2863         // 8u8.one_less_than_next_power_of_two() == 7
2864         // 6u8.one_less_than_next_power_of_two() == 7
2865         //
2866         // This method cannot overflow, as in the `next_power_of_two`
2867         // overflow cases it instead ends up returning the maximum value
2868         // of the type, and can return 0 for 0.
2869         #[inline]
2870         fn one_less_than_next_power_of_two(self) -> Self {
2871             if self <= 1 { return 0; }
2872
2873             // Because `p > 0`, it cannot consist entirely of leading zeros.
2874             // That means the shift is always in-bounds, and some processors
2875             // (such as intel pre-haswell) have more efficient ctlz
2876             // intrinsics when the argument is non-zero.
2877             let p = self - 1;
2878             let z = unsafe { intrinsics::ctlz_nonzero(p) };
2879             <$SelfT>::max_value() >> z
2880         }
2881
2882         doc_comment! {
2883             concat!("Returns the smallest power of two greater than or equal to `self`.
2884
2885 When return value overflows (i.e. `self > (1 << (N-1))` for type
2886 `uN`), it panics in debug mode and return value is wrapped to 0 in
2887 release mode (the only situation in which method can return 0).
2888
2889 # Examples
2890
2891 Basic usage:
2892
2893 ```
2894 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
2895 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
2896 ```"),
2897             #[stable(feature = "rust1", since = "1.0.0")]
2898             #[inline]
2899             pub fn next_power_of_two(self) -> Self {
2900                 // Call the trait to get overflow checks
2901                 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
2902             }
2903         }
2904
2905         doc_comment! {
2906             concat!("Returns the smallest power of two greater than or equal to `n`. If
2907 the next power of two is greater than the type's maximum value,
2908 `None` is returned, otherwise the power of two is wrapped in `Some`.
2909
2910 # Examples
2911
2912 Basic usage:
2913
2914 ```
2915 ", $Feature, "assert_eq!(2", stringify!($SelfT),
2916 ".checked_next_power_of_two(), Some(2));
2917 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
2918 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
2919 $EndFeature, "
2920 ```"),
2921             #[stable(feature = "rust1", since = "1.0.0")]
2922             pub fn checked_next_power_of_two(self) -> Option<Self> {
2923                 self.one_less_than_next_power_of_two().checked_add(1)
2924             }
2925         }
2926     }
2927 }
2928
2929 #[lang = "u8"]
2930 impl u8 {
2931     uint_impl! { u8, u8, 8, 255, "", "" }
2932
2933
2934     /// Checks if the value is within the ASCII range.
2935     ///
2936     /// # Examples
2937     ///
2938     /// ```
2939     /// let ascii = 97u8;
2940     /// let non_ascii = 150u8;
2941     ///
2942     /// assert!(ascii.is_ascii());
2943     /// assert!(!non_ascii.is_ascii());
2944     /// ```
2945     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2946     #[inline]
2947     pub fn is_ascii(&self) -> bool {
2948         *self & 128 == 0
2949     }
2950
2951     /// Makes a copy of the value in its ASCII upper case equivalent.
2952     ///
2953     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2954     /// but non-ASCII letters are unchanged.
2955     ///
2956     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
2957     ///
2958     /// # Examples
2959     ///
2960     /// ```
2961     /// let lowercase_a = 97u8;
2962     ///
2963     /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
2964     /// ```
2965     ///
2966     /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
2967     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2968     #[inline]
2969     pub fn to_ascii_uppercase(&self) -> u8 {
2970         ASCII_UPPERCASE_MAP[*self as usize]
2971     }
2972
2973     /// Makes a copy of the value in its ASCII lower case equivalent.
2974     ///
2975     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2976     /// but non-ASCII letters are unchanged.
2977     ///
2978     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
2979     ///
2980     /// # Examples
2981     ///
2982     /// ```
2983     /// let uppercase_a = 65u8;
2984     ///
2985     /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
2986     /// ```
2987     ///
2988     /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
2989     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2990     #[inline]
2991     pub fn to_ascii_lowercase(&self) -> u8 {
2992         ASCII_LOWERCASE_MAP[*self as usize]
2993     }
2994
2995     /// Checks that two values are an ASCII case-insensitive match.
2996     ///
2997     /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
2998     ///
2999     /// # Examples
3000     ///
3001     /// ```
3002     /// let lowercase_a = 97u8;
3003     /// let uppercase_a = 65u8;
3004     ///
3005     /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3006     /// ```
3007     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3008     #[inline]
3009     pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3010         self.to_ascii_lowercase() == other.to_ascii_lowercase()
3011     }
3012
3013     /// Converts this value to its ASCII upper case equivalent in-place.
3014     ///
3015     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3016     /// but non-ASCII letters are unchanged.
3017     ///
3018     /// To return a new uppercased value without modifying the existing one, use
3019     /// [`to_ascii_uppercase`].
3020     ///
3021     /// # Examples
3022     ///
3023     /// ```
3024     /// let mut byte = b'a';
3025     ///
3026     /// byte.make_ascii_uppercase();
3027     ///
3028     /// assert_eq!(b'A', byte);
3029     /// ```
3030     ///
3031     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3032     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3033     #[inline]
3034     pub fn make_ascii_uppercase(&mut self) {
3035         *self = self.to_ascii_uppercase();
3036     }
3037
3038     /// Converts this value to its ASCII lower case equivalent in-place.
3039     ///
3040     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3041     /// but non-ASCII letters are unchanged.
3042     ///
3043     /// To return a new lowercased value without modifying the existing one, use
3044     /// [`to_ascii_lowercase`].
3045     ///
3046     /// # Examples
3047     ///
3048     /// ```
3049     /// let mut byte = b'A';
3050     ///
3051     /// byte.make_ascii_lowercase();
3052     ///
3053     /// assert_eq!(b'a', byte);
3054     /// ```
3055     ///
3056     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3057     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3058     #[inline]
3059     pub fn make_ascii_lowercase(&mut self) {
3060         *self = self.to_ascii_lowercase();
3061     }
3062
3063     /// Checks if the value is an ASCII alphabetic character:
3064     ///
3065     /// - U+0041 'A' ... U+005A 'Z', or
3066     /// - U+0061 'a' ... U+007A 'z'.
3067     ///
3068     /// # Examples
3069     ///
3070     /// ```
3071     /// #![feature(ascii_ctype)]
3072     ///
3073     /// let uppercase_a = b'A';
3074     /// let uppercase_g = b'G';
3075     /// let a = b'a';
3076     /// let g = b'g';
3077     /// let zero = b'0';
3078     /// let percent = b'%';
3079     /// let space = b' ';
3080     /// let lf = b'\n';
3081     /// let esc = 0x1b_u8;
3082     ///
3083     /// assert!(uppercase_a.is_ascii_alphabetic());
3084     /// assert!(uppercase_g.is_ascii_alphabetic());
3085     /// assert!(a.is_ascii_alphabetic());
3086     /// assert!(g.is_ascii_alphabetic());
3087     /// assert!(!zero.is_ascii_alphabetic());
3088     /// assert!(!percent.is_ascii_alphabetic());
3089     /// assert!(!space.is_ascii_alphabetic());
3090     /// assert!(!lf.is_ascii_alphabetic());
3091     /// assert!(!esc.is_ascii_alphabetic());
3092     /// ```
3093     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3094     #[inline]
3095     pub fn is_ascii_alphabetic(&self) -> bool {
3096         if *self >= 0x80 { return false; }
3097         match ASCII_CHARACTER_CLASS[*self as usize] {
3098             L | Lx | U | Ux => true,
3099             _ => false
3100         }
3101     }
3102
3103     /// Checks if the value is an ASCII uppercase character:
3104     /// U+0041 'A' ... U+005A 'Z'.
3105     ///
3106     /// # Examples
3107     ///
3108     /// ```
3109     /// #![feature(ascii_ctype)]
3110     ///
3111     /// let uppercase_a = b'A';
3112     /// let uppercase_g = b'G';
3113     /// let a = b'a';
3114     /// let g = b'g';
3115     /// let zero = b'0';
3116     /// let percent = b'%';
3117     /// let space = b' ';
3118     /// let lf = b'\n';
3119     /// let esc = 0x1b_u8;
3120     ///
3121     /// assert!(uppercase_a.is_ascii_uppercase());
3122     /// assert!(uppercase_g.is_ascii_uppercase());
3123     /// assert!(!a.is_ascii_uppercase());
3124     /// assert!(!g.is_ascii_uppercase());
3125     /// assert!(!zero.is_ascii_uppercase());
3126     /// assert!(!percent.is_ascii_uppercase());
3127     /// assert!(!space.is_ascii_uppercase());
3128     /// assert!(!lf.is_ascii_uppercase());
3129     /// assert!(!esc.is_ascii_uppercase());
3130     /// ```
3131     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3132     #[inline]
3133     pub fn is_ascii_uppercase(&self) -> bool {
3134         if *self >= 0x80 { return false }
3135         match ASCII_CHARACTER_CLASS[*self as usize] {
3136             U | Ux => true,
3137             _ => false
3138         }
3139     }
3140
3141     /// Checks if the value is an ASCII lowercase character:
3142     /// U+0061 'a' ... U+007A 'z'.
3143     ///
3144     /// # Examples
3145     ///
3146     /// ```
3147     /// #![feature(ascii_ctype)]
3148     ///
3149     /// let uppercase_a = b'A';
3150     /// let uppercase_g = b'G';
3151     /// let a = b'a';
3152     /// let g = b'g';
3153     /// let zero = b'0';
3154     /// let percent = b'%';
3155     /// let space = b' ';
3156     /// let lf = b'\n';
3157     /// let esc = 0x1b_u8;
3158     ///
3159     /// assert!(!uppercase_a.is_ascii_lowercase());
3160     /// assert!(!uppercase_g.is_ascii_lowercase());
3161     /// assert!(a.is_ascii_lowercase());
3162     /// assert!(g.is_ascii_lowercase());
3163     /// assert!(!zero.is_ascii_lowercase());
3164     /// assert!(!percent.is_ascii_lowercase());
3165     /// assert!(!space.is_ascii_lowercase());
3166     /// assert!(!lf.is_ascii_lowercase());
3167     /// assert!(!esc.is_ascii_lowercase());
3168     /// ```
3169     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3170     #[inline]
3171     pub fn is_ascii_lowercase(&self) -> bool {
3172         if *self >= 0x80 { return false }
3173         match ASCII_CHARACTER_CLASS[*self as usize] {
3174             L | Lx => true,
3175             _ => false
3176         }
3177     }
3178
3179     /// Checks if the value is an ASCII alphanumeric character:
3180     ///
3181     /// - U+0041 'A' ... U+005A 'Z', or
3182     /// - U+0061 'a' ... U+007A 'z', or
3183     /// - U+0030 '0' ... U+0039 '9'.
3184     ///
3185     /// # Examples
3186     ///
3187     /// ```
3188     /// #![feature(ascii_ctype)]
3189     ///
3190     /// let uppercase_a = b'A';
3191     /// let uppercase_g = b'G';
3192     /// let a = b'a';
3193     /// let g = b'g';
3194     /// let zero = b'0';
3195     /// let percent = b'%';
3196     /// let space = b' ';
3197     /// let lf = b'\n';
3198     /// let esc = 0x1b_u8;
3199     ///
3200     /// assert!(uppercase_a.is_ascii_alphanumeric());
3201     /// assert!(uppercase_g.is_ascii_alphanumeric());
3202     /// assert!(a.is_ascii_alphanumeric());
3203     /// assert!(g.is_ascii_alphanumeric());
3204     /// assert!(zero.is_ascii_alphanumeric());
3205     /// assert!(!percent.is_ascii_alphanumeric());
3206     /// assert!(!space.is_ascii_alphanumeric());
3207     /// assert!(!lf.is_ascii_alphanumeric());
3208     /// assert!(!esc.is_ascii_alphanumeric());
3209     /// ```
3210     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3211     #[inline]
3212     pub fn is_ascii_alphanumeric(&self) -> bool {
3213         if *self >= 0x80 { return false }
3214         match ASCII_CHARACTER_CLASS[*self as usize] {
3215             D | L | Lx | U | Ux => true,
3216             _ => false
3217         }
3218     }
3219
3220     /// Checks if the value is an ASCII decimal digit:
3221     /// U+0030 '0' ... U+0039 '9'.
3222     ///
3223     /// # Examples
3224     ///
3225     /// ```
3226     /// #![feature(ascii_ctype)]
3227     ///
3228     /// let uppercase_a = b'A';
3229     /// let uppercase_g = b'G';
3230     /// let a = b'a';
3231     /// let g = b'g';
3232     /// let zero = b'0';
3233     /// let percent = b'%';
3234     /// let space = b' ';
3235     /// let lf = b'\n';
3236     /// let esc = 0x1b_u8;
3237     ///
3238     /// assert!(!uppercase_a.is_ascii_digit());
3239     /// assert!(!uppercase_g.is_ascii_digit());
3240     /// assert!(!a.is_ascii_digit());
3241     /// assert!(!g.is_ascii_digit());
3242     /// assert!(zero.is_ascii_digit());
3243     /// assert!(!percent.is_ascii_digit());
3244     /// assert!(!space.is_ascii_digit());
3245     /// assert!(!lf.is_ascii_digit());
3246     /// assert!(!esc.is_ascii_digit());
3247     /// ```
3248     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3249     #[inline]
3250     pub fn is_ascii_digit(&self) -> bool {
3251         if *self >= 0x80 { return false }
3252         match ASCII_CHARACTER_CLASS[*self as usize] {
3253             D => true,
3254             _ => false
3255         }
3256     }
3257
3258     /// Checks if the value is an ASCII hexadecimal digit:
3259     ///
3260     /// - U+0030 '0' ... U+0039 '9', or
3261     /// - U+0041 'A' ... U+0046 'F', or
3262     /// - U+0061 'a' ... U+0066 'f'.
3263     ///
3264     /// # Examples
3265     ///
3266     /// ```
3267     /// #![feature(ascii_ctype)]
3268     ///
3269     /// let uppercase_a = b'A';
3270     /// let uppercase_g = b'G';
3271     /// let a = b'a';
3272     /// let g = b'g';
3273     /// let zero = b'0';
3274     /// let percent = b'%';
3275     /// let space = b' ';
3276     /// let lf = b'\n';
3277     /// let esc = 0x1b_u8;
3278     ///
3279     /// assert!(uppercase_a.is_ascii_hexdigit());
3280     /// assert!(!uppercase_g.is_ascii_hexdigit());
3281     /// assert!(a.is_ascii_hexdigit());
3282     /// assert!(!g.is_ascii_hexdigit());
3283     /// assert!(zero.is_ascii_hexdigit());
3284     /// assert!(!percent.is_ascii_hexdigit());
3285     /// assert!(!space.is_ascii_hexdigit());
3286     /// assert!(!lf.is_ascii_hexdigit());
3287     /// assert!(!esc.is_ascii_hexdigit());
3288     /// ```
3289     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3290     #[inline]
3291     pub fn is_ascii_hexdigit(&self) -> bool {
3292         if *self >= 0x80 { return false }
3293         match ASCII_CHARACTER_CLASS[*self as usize] {
3294             D | Lx | Ux => true,
3295             _ => false
3296         }
3297     }
3298
3299     /// Checks if the value is an ASCII punctuation character:
3300     ///
3301     /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
3302     /// - U+003A ... U+0040 `: ; < = > ? @`, or
3303     /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
3304     /// - U+007B ... U+007E `{ | } ~`
3305     ///
3306     /// # Examples
3307     ///
3308     /// ```
3309     /// #![feature(ascii_ctype)]
3310     ///
3311     /// let uppercase_a = b'A';
3312     /// let uppercase_g = b'G';
3313     /// let a = b'a';
3314     /// let g = b'g';
3315     /// let zero = b'0';
3316     /// let percent = b'%';
3317     /// let space = b' ';
3318     /// let lf = b'\n';
3319     /// let esc = 0x1b_u8;
3320     ///
3321     /// assert!(!uppercase_a.is_ascii_punctuation());
3322     /// assert!(!uppercase_g.is_ascii_punctuation());
3323     /// assert!(!a.is_ascii_punctuation());
3324     /// assert!(!g.is_ascii_punctuation());
3325     /// assert!(!zero.is_ascii_punctuation());
3326     /// assert!(percent.is_ascii_punctuation());
3327     /// assert!(!space.is_ascii_punctuation());
3328     /// assert!(!lf.is_ascii_punctuation());
3329     /// assert!(!esc.is_ascii_punctuation());
3330     /// ```
3331     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3332     #[inline]
3333     pub fn is_ascii_punctuation(&self) -> bool {
3334         if *self >= 0x80 { return false }
3335         match ASCII_CHARACTER_CLASS[*self as usize] {
3336             P => true,
3337             _ => false
3338         }
3339     }
3340
3341     /// Checks if the value is an ASCII graphic character:
3342     /// U+0021 '!' ... U+007E '~'.
3343     ///
3344     /// # Examples
3345     ///
3346     /// ```
3347     /// #![feature(ascii_ctype)]
3348     ///
3349     /// let uppercase_a = b'A';
3350     /// let uppercase_g = b'G';
3351     /// let a = b'a';
3352     /// let g = b'g';
3353     /// let zero = b'0';
3354     /// let percent = b'%';
3355     /// let space = b' ';
3356     /// let lf = b'\n';
3357     /// let esc = 0x1b_u8;
3358     ///
3359     /// assert!(uppercase_a.is_ascii_graphic());
3360     /// assert!(uppercase_g.is_ascii_graphic());
3361     /// assert!(a.is_ascii_graphic());
3362     /// assert!(g.is_ascii_graphic());
3363     /// assert!(zero.is_ascii_graphic());
3364     /// assert!(percent.is_ascii_graphic());
3365     /// assert!(!space.is_ascii_graphic());
3366     /// assert!(!lf.is_ascii_graphic());
3367     /// assert!(!esc.is_ascii_graphic());
3368     /// ```
3369     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3370     #[inline]
3371     pub fn is_ascii_graphic(&self) -> bool {
3372         if *self >= 0x80 { return false; }
3373         match ASCII_CHARACTER_CLASS[*self as usize] {
3374             Ux | U | Lx | L | D | P => true,
3375             _ => false
3376         }
3377     }
3378
3379     /// Checks if the value is an ASCII whitespace character:
3380     /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
3381     /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
3382     ///
3383     /// Rust uses the WhatWG Infra Standard's [definition of ASCII
3384     /// whitespace][infra-aw]. There are several other definitions in
3385     /// wide use. For instance, [the POSIX locale][pct] includes
3386     /// U+000B VERTICAL TAB as well as all the above characters,
3387     /// but—from the very same specification—[the default rule for
3388     /// "field splitting" in the Bourne shell][bfs] considers *only*
3389     /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
3390     ///
3391     /// If you are writing a program that will process an existing
3392     /// file format, check what that format's definition of whitespace is
3393     /// before using this function.
3394     ///
3395     /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
3396     /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
3397     /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
3398     ///
3399     /// # Examples
3400     ///
3401     /// ```
3402     /// #![feature(ascii_ctype)]
3403     ///
3404     /// let uppercase_a = b'A';
3405     /// let uppercase_g = b'G';
3406     /// let a = b'a';
3407     /// let g = b'g';
3408     /// let zero = b'0';
3409     /// let percent = b'%';
3410     /// let space = b' ';
3411     /// let lf = b'\n';
3412     /// let esc = 0x1b_u8;
3413     ///
3414     /// assert!(!uppercase_a.is_ascii_whitespace());
3415     /// assert!(!uppercase_g.is_ascii_whitespace());
3416     /// assert!(!a.is_ascii_whitespace());
3417     /// assert!(!g.is_ascii_whitespace());
3418     /// assert!(!zero.is_ascii_whitespace());
3419     /// assert!(!percent.is_ascii_whitespace());
3420     /// assert!(space.is_ascii_whitespace());
3421     /// assert!(lf.is_ascii_whitespace());
3422     /// assert!(!esc.is_ascii_whitespace());
3423     /// ```
3424     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3425     #[inline]
3426     pub fn is_ascii_whitespace(&self) -> bool {
3427         if *self >= 0x80 { return false; }
3428         match ASCII_CHARACTER_CLASS[*self as usize] {
3429             Cw | W => true,
3430             _ => false
3431         }
3432     }
3433
3434     /// Checks if the value is an ASCII control character:
3435     /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
3436     /// Note that most ASCII whitespace characters are control
3437     /// characters, but SPACE is not.
3438     ///
3439     /// # Examples
3440     ///
3441     /// ```
3442     /// #![feature(ascii_ctype)]
3443     ///
3444     /// let uppercase_a = b'A';
3445     /// let uppercase_g = b'G';
3446     /// let a = b'a';
3447     /// let g = b'g';
3448     /// let zero = b'0';
3449     /// let percent = b'%';
3450     /// let space = b' ';
3451     /// let lf = b'\n';
3452     /// let esc = 0x1b_u8;
3453     ///
3454     /// assert!(!uppercase_a.is_ascii_control());
3455     /// assert!(!uppercase_g.is_ascii_control());
3456     /// assert!(!a.is_ascii_control());
3457     /// assert!(!g.is_ascii_control());
3458     /// assert!(!zero.is_ascii_control());
3459     /// assert!(!percent.is_ascii_control());
3460     /// assert!(!space.is_ascii_control());
3461     /// assert!(lf.is_ascii_control());
3462     /// assert!(esc.is_ascii_control());
3463     /// ```
3464     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3465     #[inline]
3466     pub fn is_ascii_control(&self) -> bool {
3467         if *self >= 0x80 { return false; }
3468         match ASCII_CHARACTER_CLASS[*self as usize] {
3469             C | Cw => true,
3470             _ => false
3471         }
3472     }
3473 }
3474
3475 #[lang = "u16"]
3476 impl u16 {
3477     uint_impl! { u16, u16, 16, 65535, "", "" }
3478 }
3479
3480 #[lang = "u32"]
3481 impl u32 {
3482     uint_impl! { u32, u32, 32, 4294967295, "", "" }
3483 }
3484
3485 #[lang = "u64"]
3486 impl u64 {
3487     uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
3488 }
3489
3490 #[lang = "u128"]
3491 impl u128 {
3492     uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "" }
3493 }
3494
3495 #[cfg(target_pointer_width = "16")]
3496 #[lang = "usize"]
3497 impl usize {
3498     uint_impl! { usize, u16, 16, 65536, "", "" }
3499 }
3500 #[cfg(target_pointer_width = "32")]
3501 #[lang = "usize"]
3502 impl usize {
3503     uint_impl! { usize, u32, 32, 4294967295, "", "" }
3504 }
3505
3506 #[cfg(target_pointer_width = "64")]
3507 #[lang = "usize"]
3508 impl usize {
3509     uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
3510 }
3511
3512 /// A classification of floating point numbers.
3513 ///
3514 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
3515 /// their documentation for more.
3516 ///
3517 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
3518 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
3519 ///
3520 /// # Examples
3521 ///
3522 /// ```
3523 /// use std::num::FpCategory;
3524 /// use std::f32;
3525 ///
3526 /// let num = 12.4_f32;
3527 /// let inf = f32::INFINITY;
3528 /// let zero = 0f32;
3529 /// let sub: f32 = 1.1754942e-38;
3530 /// let nan = f32::NAN;
3531 ///
3532 /// assert_eq!(num.classify(), FpCategory::Normal);
3533 /// assert_eq!(inf.classify(), FpCategory::Infinite);
3534 /// assert_eq!(zero.classify(), FpCategory::Zero);
3535 /// assert_eq!(nan.classify(), FpCategory::Nan);
3536 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
3537 /// ```
3538 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
3539 #[stable(feature = "rust1", since = "1.0.0")]
3540 pub enum FpCategory {
3541     /// "Not a Number", often obtained by dividing by zero.
3542     #[stable(feature = "rust1", since = "1.0.0")]
3543     Nan,
3544
3545     /// Positive or negative infinity.
3546     #[stable(feature = "rust1", since = "1.0.0")]
3547     Infinite,
3548
3549     /// Positive or negative zero.
3550     #[stable(feature = "rust1", since = "1.0.0")]
3551     Zero,
3552
3553     /// De-normalized floating point representation (less precise than `Normal`).
3554     #[stable(feature = "rust1", since = "1.0.0")]
3555     Subnormal,
3556
3557     /// A regular floating point number.
3558     #[stable(feature = "rust1", since = "1.0.0")]
3559     Normal,
3560 }
3561
3562 /// A built-in floating point number.
3563 #[doc(hidden)]
3564 #[unstable(feature = "core_float",
3565            reason = "stable interface is via `impl f{32,64}` in later crates",
3566            issue = "32110")]
3567 pub trait Float: Sized {
3568     /// Type used by `to_bits` and `from_bits`.
3569     #[stable(feature = "core_float_bits", since = "1.25.0")]
3570     type Bits;
3571
3572     /// Returns `true` if this value is NaN and false otherwise.
3573     #[stable(feature = "core", since = "1.6.0")]
3574     fn is_nan(self) -> bool;
3575     /// Returns `true` if this value is positive infinity or negative infinity and
3576     /// false otherwise.
3577     #[stable(feature = "core", since = "1.6.0")]
3578     fn is_infinite(self) -> bool;
3579     /// Returns `true` if this number is neither infinite nor NaN.
3580     #[stable(feature = "core", since = "1.6.0")]
3581     fn is_finite(self) -> bool;
3582     /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
3583     #[stable(feature = "core", since = "1.6.0")]
3584     fn is_normal(self) -> bool;
3585     /// Returns the category that this number falls into.
3586     #[stable(feature = "core", since = "1.6.0")]
3587     fn classify(self) -> FpCategory;
3588
3589     /// Computes the absolute value of `self`. Returns `Float::nan()` if the
3590     /// number is `Float::nan()`.
3591     #[stable(feature = "core", since = "1.6.0")]
3592     fn abs(self) -> Self;
3593     /// Returns a number that represents the sign of `self`.
3594     ///
3595     /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
3596     /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
3597     /// - `Float::nan()` if the number is `Float::nan()`
3598     #[stable(feature = "core", since = "1.6.0")]
3599     fn signum(self) -> Self;
3600
3601     /// Returns `true` if `self` is positive, including `+0.0` and
3602     /// `Float::infinity()`.
3603     #[stable(feature = "core", since = "1.6.0")]
3604     fn is_sign_positive(self) -> bool;
3605     /// Returns `true` if `self` is negative, including `-0.0` and
3606     /// `Float::neg_infinity()`.
3607     #[stable(feature = "core", since = "1.6.0")]
3608     fn is_sign_negative(self) -> bool;
3609
3610     /// Take the reciprocal (inverse) of a number, `1/x`.
3611     #[stable(feature = "core", since = "1.6.0")]
3612     fn recip(self) -> Self;
3613
3614     /// Raise a number to an integer power.
3615     ///
3616     /// Using this function is generally faster than using `powf`
3617     #[stable(feature = "core", since = "1.6.0")]
3618     fn powi(self, n: i32) -> Self;
3619
3620     /// Convert radians to degrees.
3621     #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3622     fn to_degrees(self) -> Self;
3623     /// Convert degrees to radians.
3624     #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3625     fn to_radians(self) -> Self;
3626
3627     /// Returns the maximum of the two numbers.
3628     #[stable(feature = "core_float_min_max", since="1.20.0")]
3629     fn max(self, other: Self) -> Self;
3630     /// Returns the minimum of the two numbers.
3631     #[stable(feature = "core_float_min_max", since="1.20.0")]
3632     fn min(self, other: Self) -> Self;
3633
3634     /// Raw transmutation to integer.
3635     #[stable(feature = "core_float_bits", since="1.25.0")]
3636     fn to_bits(self) -> Self::Bits;
3637     /// Raw transmutation from integer.
3638     #[stable(feature = "core_float_bits", since="1.25.0")]
3639     fn from_bits(v: Self::Bits) -> Self;
3640 }
3641
3642 macro_rules! from_str_radix_int_impl {
3643     ($($t:ty)*) => {$(
3644         #[stable(feature = "rust1", since = "1.0.0")]
3645         impl FromStr for $t {
3646             type Err = ParseIntError;
3647             fn from_str(src: &str) -> Result<Self, ParseIntError> {
3648                 from_str_radix(src, 10)
3649             }
3650         }
3651     )*}
3652 }
3653 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
3654
3655 /// The error type returned when a checked integral type conversion fails.
3656 #[unstable(feature = "try_from", issue = "33417")]
3657 #[derive(Debug, Copy, Clone)]
3658 pub struct TryFromIntError(());
3659
3660 impl TryFromIntError {
3661     #[unstable(feature = "int_error_internals",
3662                reason = "available through Error trait and this method should \
3663                          not be exposed publicly",
3664                issue = "0")]
3665     #[doc(hidden)]
3666     pub fn __description(&self) -> &str {
3667         "out of range integral type conversion attempted"
3668     }
3669 }
3670
3671 #[unstable(feature = "try_from", issue = "33417")]
3672 impl fmt::Display for TryFromIntError {
3673     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3674         self.__description().fmt(fmt)
3675     }
3676 }
3677
3678 #[unstable(feature = "try_from", issue = "33417")]
3679 impl From<!> for TryFromIntError {
3680     fn from(never: !) -> TryFromIntError {
3681         never
3682     }
3683 }
3684
3685 // no possible bounds violation
3686 macro_rules! try_from_unbounded {
3687     ($source:ty, $($target:ty),*) => {$(
3688         #[unstable(feature = "try_from", issue = "33417")]
3689         impl TryFrom<$source> for $target {
3690             type Error = !;
3691
3692             #[inline]
3693             fn try_from(value: $source) -> Result<Self, Self::Error> {
3694                 Ok(value as $target)
3695             }
3696         }
3697     )*}
3698 }
3699
3700 // only negative bounds
3701 macro_rules! try_from_lower_bounded {
3702     ($source:ty, $($target:ty),*) => {$(
3703         #[unstable(feature = "try_from", issue = "33417")]
3704         impl TryFrom<$source> for $target {
3705             type Error = TryFromIntError;
3706
3707             #[inline]
3708             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3709                 if u >= 0 {
3710                     Ok(u as $target)
3711                 } else {
3712                     Err(TryFromIntError(()))
3713                 }
3714             }
3715         }
3716     )*}
3717 }
3718
3719 // unsigned to signed (only positive bound)
3720 macro_rules! try_from_upper_bounded {
3721     ($source:ty, $($target:ty),*) => {$(
3722         #[unstable(feature = "try_from", issue = "33417")]
3723         impl TryFrom<$source> for $target {
3724             type Error = TryFromIntError;
3725
3726             #[inline]
3727             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3728                 if u > (<$target>::max_value() as $source) {
3729                     Err(TryFromIntError(()))
3730                 } else {
3731                     Ok(u as $target)
3732                 }
3733             }
3734         }
3735     )*}
3736 }
3737
3738 // all other cases
3739 macro_rules! try_from_both_bounded {
3740     ($source:ty, $($target:ty),*) => {$(
3741         #[unstable(feature = "try_from", issue = "33417")]
3742         impl TryFrom<$source> for $target {
3743             type Error = TryFromIntError;
3744
3745             #[inline]
3746             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3747                 let min = <$target>::min_value() as $source;
3748                 let max = <$target>::max_value() as $source;
3749                 if u < min || u > max {
3750                     Err(TryFromIntError(()))
3751                 } else {
3752                     Ok(u as $target)
3753                 }
3754             }
3755         }
3756     )*}
3757 }
3758
3759 macro_rules! rev {
3760     ($mac:ident, $source:ty, $($target:ty),*) => {$(
3761         $mac!($target, $source);
3762     )*}
3763 }
3764
3765 /// intra-sign conversions
3766 try_from_upper_bounded!(u16, u8);
3767 try_from_upper_bounded!(u32, u16, u8);
3768 try_from_upper_bounded!(u64, u32, u16, u8);
3769 try_from_upper_bounded!(u128, u64, u32, u16, u8);
3770
3771 try_from_both_bounded!(i16, i8);
3772 try_from_both_bounded!(i32, i16, i8);
3773 try_from_both_bounded!(i64, i32, i16, i8);
3774 try_from_both_bounded!(i128, i64, i32, i16, i8);
3775
3776 // unsigned-to-signed
3777 try_from_upper_bounded!(u8, i8);
3778 try_from_upper_bounded!(u16, i8, i16);
3779 try_from_upper_bounded!(u32, i8, i16, i32);
3780 try_from_upper_bounded!(u64, i8, i16, i32, i64);
3781 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
3782
3783 // signed-to-unsigned
3784 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
3785 try_from_lower_bounded!(i16, u16, u32, u64, u128);
3786 try_from_lower_bounded!(i32, u32, u64, u128);
3787 try_from_lower_bounded!(i64, u64, u128);
3788 try_from_lower_bounded!(i128, u128);
3789 try_from_both_bounded!(i16, u8);
3790 try_from_both_bounded!(i32, u16, u8);
3791 try_from_both_bounded!(i64, u32, u16, u8);
3792 try_from_both_bounded!(i128, u64, u32, u16, u8);
3793
3794 // usize/isize
3795 try_from_upper_bounded!(usize, isize);
3796 try_from_lower_bounded!(isize, usize);
3797
3798 #[cfg(target_pointer_width = "16")]
3799 mod ptr_try_from_impls {
3800     use super::TryFromIntError;
3801     use convert::TryFrom;
3802
3803     try_from_upper_bounded!(usize, u8);
3804     try_from_unbounded!(usize, u16, u32, u64, u128);
3805     try_from_upper_bounded!(usize, i8, i16);
3806     try_from_unbounded!(usize, i32, i64, i128);
3807
3808     try_from_both_bounded!(isize, u8);
3809     try_from_lower_bounded!(isize, u16, u32, u64, u128);
3810     try_from_both_bounded!(isize, i8);
3811     try_from_unbounded!(isize, i16, i32, i64, i128);
3812
3813     rev!(try_from_unbounded, usize, u16);
3814     rev!(try_from_upper_bounded, usize, u32, u64, u128);
3815     rev!(try_from_lower_bounded, usize, i8, i16);
3816     rev!(try_from_both_bounded, usize, i32, i64, i128);
3817
3818     rev!(try_from_unbounded, isize, u8);
3819     rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
3820     rev!(try_from_unbounded, isize, i16);
3821     rev!(try_from_both_bounded, isize, i32, i64, i128);
3822 }
3823
3824 #[cfg(target_pointer_width = "32")]
3825 mod ptr_try_from_impls {
3826     use super::TryFromIntError;
3827     use convert::TryFrom;
3828
3829     try_from_upper_bounded!(usize, u8, u16);
3830     try_from_unbounded!(usize, u32, u64, u128);
3831     try_from_upper_bounded!(usize, i8, i16, i32);
3832     try_from_unbounded!(usize, i64, i128);
3833
3834     try_from_both_bounded!(isize, u8, u16);
3835     try_from_lower_bounded!(isize, u32, u64, u128);
3836     try_from_both_bounded!(isize, i8, i16);
3837     try_from_unbounded!(isize, i32, i64, i128);
3838
3839     rev!(try_from_unbounded, usize, u16, u32);
3840     rev!(try_from_upper_bounded, usize, u64, u128);
3841     rev!(try_from_lower_bounded, usize, i8, i16, i32);
3842     rev!(try_from_both_bounded, usize, i64, i128);
3843
3844     rev!(try_from_unbounded, isize, u8, u16);
3845     rev!(try_from_upper_bounded, isize, u32, u64, u128);
3846     rev!(try_from_unbounded, isize, i16, i32);
3847     rev!(try_from_both_bounded, isize, i64, i128);
3848 }
3849
3850 #[cfg(target_pointer_width = "64")]
3851 mod ptr_try_from_impls {
3852     use super::TryFromIntError;
3853     use convert::TryFrom;
3854
3855     try_from_upper_bounded!(usize, u8, u16, u32);
3856     try_from_unbounded!(usize, u64, u128);
3857     try_from_upper_bounded!(usize, i8, i16, i32, i64);
3858     try_from_unbounded!(usize, i128);
3859
3860     try_from_both_bounded!(isize, u8, u16, u32);
3861     try_from_lower_bounded!(isize, u64, u128);
3862     try_from_both_bounded!(isize, i8, i16, i32);
3863     try_from_unbounded!(isize, i64, i128);
3864
3865     rev!(try_from_unbounded, usize, u16, u32, u64);
3866     rev!(try_from_upper_bounded, usize, u128);
3867     rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
3868     rev!(try_from_both_bounded, usize, i128);
3869
3870     rev!(try_from_unbounded, isize, u8, u16, u32);
3871     rev!(try_from_upper_bounded, isize, u64, u128);
3872     rev!(try_from_unbounded, isize, i16, i32, i64);
3873     rev!(try_from_both_bounded, isize, i128);
3874 }
3875
3876 #[doc(hidden)]
3877 trait FromStrRadixHelper: PartialOrd + Copy {
3878     fn min_value() -> Self;
3879     fn max_value() -> Self;
3880     fn from_u32(u: u32) -> Self;
3881     fn checked_mul(&self, other: u32) -> Option<Self>;
3882     fn checked_sub(&self, other: u32) -> Option<Self>;
3883     fn checked_add(&self, other: u32) -> Option<Self>;
3884 }
3885
3886 macro_rules! doit {
3887     ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
3888         #[inline]
3889         fn min_value() -> Self { Self::min_value() }
3890         #[inline]
3891         fn max_value() -> Self { Self::max_value() }
3892         #[inline]
3893         fn from_u32(u: u32) -> Self { u as Self }
3894         #[inline]
3895         fn checked_mul(&self, other: u32) -> Option<Self> {
3896             Self::checked_mul(*self, other as Self)
3897         }
3898         #[inline]
3899         fn checked_sub(&self, other: u32) -> Option<Self> {
3900             Self::checked_sub(*self, other as Self)
3901         }
3902         #[inline]
3903         fn checked_add(&self, other: u32) -> Option<Self> {
3904             Self::checked_add(*self, other as Self)
3905         }
3906     })*)
3907 }
3908 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
3909
3910 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
3911     use self::IntErrorKind::*;
3912     use self::ParseIntError as PIE;
3913
3914     assert!(radix >= 2 && radix <= 36,
3915            "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
3916            radix);
3917
3918     if src.is_empty() {
3919         return Err(PIE { kind: Empty });
3920     }
3921
3922     let is_signed_ty = T::from_u32(0) > T::min_value();
3923
3924     // all valid digits are ascii, so we will just iterate over the utf8 bytes
3925     // and cast them to chars. .to_digit() will safely return None for anything
3926     // other than a valid ascii digit for the given radix, including the first-byte
3927     // of multi-byte sequences
3928     let src = src.as_bytes();
3929
3930     let (is_positive, digits) = match src[0] {
3931         b'+' => (true, &src[1..]),
3932         b'-' if is_signed_ty => (false, &src[1..]),
3933         _ => (true, src),
3934     };
3935
3936     if digits.is_empty() {
3937         return Err(PIE { kind: Empty });
3938     }
3939
3940     let mut result = T::from_u32(0);
3941     if is_positive {
3942         // The number is positive
3943         for &c in digits {
3944             let x = match (c as char).to_digit(radix) {
3945                 Some(x) => x,
3946                 None => return Err(PIE { kind: InvalidDigit }),
3947             };
3948             result = match result.checked_mul(radix) {
3949                 Some(result) => result,
3950                 None => return Err(PIE { kind: Overflow }),
3951             };
3952             result = match result.checked_add(x) {
3953                 Some(result) => result,
3954                 None => return Err(PIE { kind: Overflow }),
3955             };
3956         }
3957     } else {
3958         // The number is negative
3959         for &c in digits {
3960             let x = match (c as char).to_digit(radix) {
3961                 Some(x) => x,
3962                 None => return Err(PIE { kind: InvalidDigit }),
3963             };
3964             result = match result.checked_mul(radix) {
3965                 Some(result) => result,
3966                 None => return Err(PIE { kind: Underflow }),
3967             };
3968             result = match result.checked_sub(x) {
3969                 Some(result) => result,
3970                 None => return Err(PIE { kind: Underflow }),
3971             };
3972         }
3973     }
3974     Ok(result)
3975 }
3976
3977 /// An error which can be returned when parsing an integer.
3978 ///
3979 /// This error is used as the error type for the `from_str_radix()` functions
3980 /// on the primitive integer types, such as [`i8::from_str_radix`].
3981 ///
3982 /// # Potential causes
3983 ///
3984 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
3985 /// in the string e.g. when it is obtained from the standard input.
3986 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
3987 ///
3988 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
3989 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
3990 #[derive(Debug, Clone, PartialEq, Eq)]
3991 #[stable(feature = "rust1", since = "1.0.0")]
3992 pub struct ParseIntError {
3993     kind: IntErrorKind,
3994 }
3995
3996 #[derive(Debug, Clone, PartialEq, Eq)]
3997 enum IntErrorKind {
3998     Empty,
3999     InvalidDigit,
4000     Overflow,
4001     Underflow,
4002 }
4003
4004 impl ParseIntError {
4005     #[unstable(feature = "int_error_internals",
4006                reason = "available through Error trait and this method should \
4007                          not be exposed publicly",
4008                issue = "0")]
4009     #[doc(hidden)]
4010     pub fn __description(&self) -> &str {
4011         match self.kind {
4012             IntErrorKind::Empty => "cannot parse integer from empty string",
4013             IntErrorKind::InvalidDigit => "invalid digit found in string",
4014             IntErrorKind::Overflow => "number too large to fit in target type",
4015             IntErrorKind::Underflow => "number too small to fit in target type",
4016         }
4017     }
4018 }
4019
4020 #[stable(feature = "rust1", since = "1.0.0")]
4021 impl fmt::Display for ParseIntError {
4022     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4023         self.__description().fmt(f)
4024     }
4025 }
4026
4027 #[stable(feature = "rust1", since = "1.0.0")]
4028 pub use num::dec2flt::ParseFloatError;
4029
4030 // Conversion traits for primitive integer and float types
4031 // Conversions T -> T are covered by a blanket impl and therefore excluded
4032 // Some conversions from and to usize/isize are not implemented due to portability concerns
4033 macro_rules! impl_from {
4034     ($Small: ty, $Large: ty, #[$attr:meta]) => {
4035         #[$attr]
4036         impl From<$Small> for $Large {
4037             #[inline]
4038             fn from(small: $Small) -> $Large {
4039                 small as $Large
4040             }
4041         }
4042     }
4043 }
4044
4045 // Unsigned -> Unsigned
4046 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4047 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4048 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4049 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
4050 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4051 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4052 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4053 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
4054 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4055 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
4056 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
4057
4058 // Signed -> Signed
4059 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4060 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4061 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4062 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4063 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4064 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4065 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4066 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4067 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4068 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4069 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4070
4071 // Unsigned -> Signed
4072 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4073 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4074 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4075 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4076 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4077 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4078 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4079 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4080 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4081 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4082
4083 // Note: integers can only be represented with full precision in a float if
4084 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4085 // Lossy float conversions are not implemented at this time.
4086
4087 // Signed -> Float
4088 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4089 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4090 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4091 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4092 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4093
4094 // Unsigned -> Float
4095 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4096 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4097 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4098 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4099 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4100
4101 // Float -> Float
4102 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4103
4104 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4105     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4106     0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4107     0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4108     0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4109     b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4110     b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4111     b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4112     b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4113     b'@',
4114
4115           b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4116     b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4117     b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4118     b'x', b'y', b'z',
4119
4120                       b'[', b'\\', b']', b'^', b'_',
4121     b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4122     b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4123     b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4124     b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4125     0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4126     0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4127     0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4128     0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4129     0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4130     0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4131     0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4132     0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4133     0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4134     0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4135     0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4136     0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4137     0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4138     0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4139     0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4140     0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4141 ];
4142
4143 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4144     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4145     0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4146     0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4147     0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4148     b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4149     b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4150     b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4151     b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4152     b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4153     b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4154     b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4155     b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4156     b'`',
4157
4158           b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4159     b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4160     b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4161     b'X', b'Y', b'Z',
4162
4163                       b'{', b'|', b'}', b'~', 0x7f,
4164     0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4165     0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4166     0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4167     0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4168     0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4169     0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4170     0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4171     0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4172     0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4173     0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4174     0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4175     0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4176     0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4177     0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4178     0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4179     0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4180 ];
4181
4182 enum AsciiCharacterClass {
4183     C,  // control
4184     Cw, // control whitespace
4185     W,  // whitespace
4186     D,  // digit
4187     L,  // lowercase
4188     Lx, // lowercase hex digit
4189     U,  // uppercase
4190     Ux, // uppercase hex digit
4191     P,  // punctuation
4192 }
4193 use self::AsciiCharacterClass::*;
4194
4195 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4196 //  _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4197     C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4198     C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4199     W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4200     D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4201     P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4202     U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4203     P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4204     L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_
4205 ];