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