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