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