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