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