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