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