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.
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.
11 //! Numeric traits and functions for the built-in numeric types.
13 #![stable(feature = "rust1", since = "1.0.0")]
18 #[allow(deprecated)] use nonzero::NonZero;
22 macro_rules! impl_nonzero_fmt {
23 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
26 impl fmt::$Trait for $Ty {
28 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36 macro_rules! nonzero_integers {
37 ( #[$stability: meta] $( $Ty: ident($Int: ty); )+ ) => {
39 /// An integer that is known not to equal zero.
41 /// This may enable some memory layout optimization such as:
44 /// # #![feature(nonzero)]
45 /// use std::mem::size_of;
46 /// assert_eq!(size_of::<Option<std::num::NonZeroU32>>(), size_of::<u32>());
50 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
51 pub struct $Ty(NonZero<$Int>);
55 /// Create a non-zero without checking the value.
59 /// The value must not be zero.
62 pub const unsafe fn new_unchecked(n: $Int) -> Self {
66 /// Create a non-zero if the given value is not zero.
69 pub fn new(n: $Int) -> Option<Self> {
77 /// Returns the value as a primitive type.
80 pub fn get(self) -> $Int {
88 (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
95 #[unstable(feature = "nonzero", issue = "49137")]
96 NonZeroU8(u8); NonZeroI8(i8);
97 NonZeroU16(u16); NonZeroI16(i16);
98 NonZeroU32(u32); NonZeroI32(i32);
99 NonZeroU64(u64); NonZeroI64(i64);
100 NonZeroUsize(usize); NonZeroIsize(isize);
104 // Change this to `#[unstable(feature = "i128", issue = "35118")]`
105 // if other NonZero* integer types are stabilizied before 128-bit integers
106 #[unstable(feature = "nonzero", issue = "49137")]
107 NonZeroU128(u128); NonZeroI128(i128);
110 /// Provides intentionally-wrapped arithmetic on `T`.
112 /// Operations like `+` on `u32` values is intended to never overflow,
113 /// and in some debug configurations overflow is detected and results
114 /// in a panic. While most arithmetic falls into this category, some
115 /// code explicitly expects and relies upon modular arithmetic (e.g.,
118 /// Wrapping arithmetic can be achieved either through methods like
119 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
120 /// all standard arithmetic operations on the underlying value are
121 /// intended to have wrapping semantics.
126 /// use std::num::Wrapping;
128 /// let zero = Wrapping(0u32);
129 /// let one = Wrapping(1u32);
131 /// assert_eq!(std::u32::MAX, (zero - one).0);
133 #[stable(feature = "rust1", since = "1.0.0")]
134 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
135 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
138 #[stable(feature = "rust1", since = "1.0.0")]
139 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
140 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
145 #[stable(feature = "wrapping_display", since = "1.10.0")]
146 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
147 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
152 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
153 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
154 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
159 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
160 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
161 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
166 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
167 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
168 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
173 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
174 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
175 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
182 // All these modules are technically private and only exposed for coretests:
188 macro_rules! doc_comment {
189 ($x:expr, $($tt:tt)*) => {
195 // `Int` + `SignedInt` implemented for signed integers
196 macro_rules! int_impl {
197 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
198 $EndFeature:expr) => {
200 concat!("Returns the smallest value that can be represented by this integer type.
207 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
210 #[stable(feature = "rust1", since = "1.0.0")]
212 pub const fn min_value() -> Self {
213 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
218 concat!("Returns the largest value that can be represented by this integer type.
225 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
228 #[stable(feature = "rust1", since = "1.0.0")]
230 pub const fn max_value() -> Self {
236 concat!("Converts a string slice in a given base to an integer.
238 The string is expected to be an optional `+` or `-` sign followed by digits.
239 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
240 depending on `radix`:
248 This function panics if `radix` is not in the range from 2 to 36.
255 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
258 #[stable(feature = "rust1", since = "1.0.0")]
259 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
260 from_str_radix(src, radix)
265 concat!("Returns the number of ones in the binary representation of `self`.
272 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
274 assert_eq!(n.count_ones(), 1);",
278 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
284 concat!("Returns the number of zeros in the binary representation of `self`.
291 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
293 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn count_zeros(self) -> u32 {
301 concat!("Returns the number of leading zeros in the binary representation of `self`.
308 ", $Feature, "let n = -1", stringify!($SelfT), ";
310 assert_eq!(n.leading_zeros(), 0);",
313 #[stable(feature = "rust1", since = "1.0.0")]
315 pub fn leading_zeros(self) -> u32 {
316 (self as $UnsignedT).leading_zeros()
321 concat!("Returns the number of trailing zeros in the binary representation of `self`.
328 ", $Feature, "let n = -4", stringify!($SelfT), ";
330 assert_eq!(n.trailing_zeros(), 2);",
333 #[stable(feature = "rust1", since = "1.0.0")]
335 pub fn trailing_zeros(self) -> u32 {
336 (self as $UnsignedT).trailing_zeros()
340 /// Shifts the bits to the left by a specified amount, `n`,
341 /// wrapping the truncated bits to the end of the resulting integer.
343 /// Please note this isn't the same operation as `<<`!
347 /// Please note that this example is shared between integer types.
348 /// Which explains why `i64` is used here.
353 /// let n = 0x0123456789ABCDEFi64;
354 /// let m = -0x76543210FEDCBA99i64;
356 /// assert_eq!(n.rotate_left(32), m);
358 #[stable(feature = "rust1", since = "1.0.0")]
360 pub fn rotate_left(self, n: u32) -> Self {
361 (self as $UnsignedT).rotate_left(n) as Self
364 /// Shifts the bits to the right by a specified amount, `n`,
365 /// wrapping the truncated bits to the beginning of the resulting
368 /// Please note this isn't the same operation as `>>`!
372 /// Please note that this example is shared between integer types.
373 /// Which explains why `i64` is used here.
378 /// let n = 0x0123456789ABCDEFi64;
379 /// let m = -0xFEDCBA987654322i64;
381 /// assert_eq!(n.rotate_right(4), m);
383 #[stable(feature = "rust1", since = "1.0.0")]
385 pub fn rotate_right(self, n: u32) -> Self {
386 (self as $UnsignedT).rotate_right(n) as Self
389 /// Reverses the byte order of the integer.
393 /// Please note that this example is shared between integer types.
394 /// Which explains why `i16` is used here.
399 /// let n: i16 = 0b0000000_01010101;
400 /// assert_eq!(n, 85);
402 /// let m = n.swap_bytes();
404 /// assert_eq!(m, 0b01010101_00000000);
405 /// assert_eq!(m, 21760);
407 #[stable(feature = "rust1", since = "1.0.0")]
409 pub fn swap_bytes(self) -> Self {
410 (self as $UnsignedT).swap_bytes() as Self
413 /// Reverses the bit pattern of the integer.
417 /// Please note that this example is shared between integer types.
418 /// Which explains why `i16` is used here.
423 /// #![feature(reverse_bits)]
425 /// let n: i16 = 0b0000000_01010101;
426 /// assert_eq!(n, 85);
428 /// let m = n.reverse_bits();
430 /// assert_eq!(m as u16, 0b10101010_00000000);
431 /// assert_eq!(m, -22016);
433 #[unstable(feature = "reverse_bits", issue = "48763")]
436 pub fn reverse_bits(self) -> Self {
437 (self as $UnsignedT).reverse_bits() as Self
441 concat!("Converts an integer from big endian to the target's endianness.
443 On big endian this is a no-op. On little endian the bytes are swapped.
450 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
452 if cfg!(target_endian = \"big\") {
453 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
455 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
459 #[stable(feature = "rust1", since = "1.0.0")]
461 pub fn from_be(x: Self) -> Self {
462 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
467 concat!("Converts an integer from little endian to the target's endianness.
469 On little endian this is a no-op. On big endian the bytes are swapped.
476 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
478 if cfg!(target_endian = \"little\") {
479 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
481 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
485 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn from_le(x: Self) -> Self {
488 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
493 concat!("Converts `self` to big endian from the target's endianness.
495 On big endian this is a no-op. On little endian the bytes are swapped.
502 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
504 if cfg!(target_endian = \"big\") {
505 assert_eq!(n.to_be(), n)
507 assert_eq!(n.to_be(), n.swap_bytes())
511 #[stable(feature = "rust1", since = "1.0.0")]
513 pub fn to_be(self) -> Self { // or not to be?
514 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
519 concat!("Converts `self` to little endian from the target's endianness.
521 On little endian this is a no-op. On big endian the bytes are swapped.
528 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
530 if cfg!(target_endian = \"little\") {
531 assert_eq!(n.to_le(), n)
533 assert_eq!(n.to_le(), n.swap_bytes())
537 #[stable(feature = "rust1", since = "1.0.0")]
539 pub fn to_le(self) -> Self {
540 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
545 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
546 if overflow occurred.
553 ", $Feature, "assert_eq!((", stringify!($SelfT),
554 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
555 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
558 #[stable(feature = "rust1", since = "1.0.0")]
560 pub fn checked_add(self, rhs: Self) -> Option<Self> {
561 let (a, b) = self.overflowing_add(rhs);
562 if b {None} else {Some(a)}
567 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
575 ", $Feature, "assert_eq!((", stringify!($SelfT),
576 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
577 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
580 #[stable(feature = "rust1", since = "1.0.0")]
582 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
583 let (a, b) = self.overflowing_sub(rhs);
584 if b {None} else {Some(a)}
589 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
597 ", $Feature, "assert_eq!(", stringify!($SelfT),
598 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
599 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
602 #[stable(feature = "rust1", since = "1.0.0")]
604 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
605 let (a, b) = self.overflowing_mul(rhs);
606 if b {None} else {Some(a)}
611 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
612 or the division results in overflow.
619 ", $Feature, "assert_eq!((", stringify!($SelfT),
620 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
621 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
622 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
625 #[stable(feature = "rust1", since = "1.0.0")]
627 pub fn checked_div(self, rhs: Self) -> Option<Self> {
628 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
631 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
637 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
638 `rhs == 0` or the division results in overflow.
645 ", $Feature, "use std::", stringify!($SelfT), ";
647 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
648 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
649 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
652 #[stable(feature = "wrapping", since = "1.7.0")]
654 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
655 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
658 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
664 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
671 ", $Feature, "use std::", stringify!($SelfT), ";
673 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
674 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
677 #[stable(feature = "wrapping", since = "1.7.0")]
679 pub fn checked_neg(self) -> Option<Self> {
680 let (a, b) = self.overflowing_neg();
681 if b {None} else {Some(a)}
686 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
687 than or equal to the number of bits in `self`.
694 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
695 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
698 #[stable(feature = "wrapping", since = "1.7.0")]
700 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
701 let (a, b) = self.overflowing_shl(rhs);
702 if b {None} else {Some(a)}
707 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
708 larger than or equal to the number of bits in `self`.
715 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
716 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
719 #[stable(feature = "wrapping", since = "1.7.0")]
721 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
722 let (a, b) = self.overflowing_shr(rhs);
723 if b {None} else {Some(a)}
728 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
736 ", $Feature, "use std::", stringify!($SelfT), ";
738 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
739 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
742 #[stable(feature = "no_panic_abs", since = "1.13.0")]
744 pub fn checked_abs(self) -> Option<Self> {
745 if self.is_negative() {
754 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
762 #![feature(no_panic_pow)]
763 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
764 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
768 #[unstable(feature = "no_panic_pow", issue = "48320")]
770 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
772 let mut acc: Self = 1;
776 acc = acc.checked_mul(base)?;
779 base = base.checked_mul(base)?;
782 // Deal with the final bit of the exponent separately, since
783 // squaring the base afterwards is not necessary and may cause a
784 // needless overflow.
786 acc = acc.checked_mul(base)?;
794 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
795 bounds instead of overflowing.
802 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
803 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
807 #[stable(feature = "rust1", since = "1.0.0")]
809 pub fn saturating_add(self, rhs: Self) -> Self {
810 match self.checked_add(rhs) {
812 None if rhs >= 0 => Self::max_value(),
813 None => Self::min_value(),
819 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
820 numeric bounds instead of overflowing.
827 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
828 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
832 #[stable(feature = "rust1", since = "1.0.0")]
834 pub fn saturating_sub(self, rhs: Self) -> Self {
835 match self.checked_sub(rhs) {
837 None if rhs >= 0 => Self::min_value(),
838 None => Self::max_value(),
844 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
845 numeric bounds instead of overflowing.
852 ", $Feature, "use std::", stringify!($SelfT), ";
854 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
855 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
856 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
859 #[stable(feature = "wrapping", since = "1.7.0")]
861 pub fn saturating_mul(self, rhs: Self) -> Self {
862 self.checked_mul(rhs).unwrap_or_else(|| {
863 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
873 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
874 saturating at the numeric bounds instead of overflowing.
881 #![feature(no_panic_pow)]
882 ", $Feature, "use std::", stringify!($SelfT), ";
884 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
885 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
886 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
889 #[unstable(feature = "no_panic_pow", issue = "48320")]
891 pub fn saturating_pow(self, exp: u32) -> Self {
892 match self.checked_pow(exp) {
894 None if self < 0 && exp % 2 == 1 => Self::min_value(),
895 None => Self::max_value(),
901 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
902 boundary of the type.
909 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
910 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
911 "::min_value() + 1);",
914 #[stable(feature = "rust1", since = "1.0.0")]
916 pub fn wrapping_add(self, rhs: Self) -> Self {
918 intrinsics::overflowing_add(self, rhs)
924 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
925 boundary of the type.
932 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
933 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
934 stringify!($SelfT), "::max_value());",
937 #[stable(feature = "rust1", since = "1.0.0")]
939 pub fn wrapping_sub(self, rhs: Self) -> Self {
941 intrinsics::overflowing_sub(self, rhs)
947 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
948 the boundary of the type.
955 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
956 assert_eq!(11i8.wrapping_mul(12), -124);",
959 #[stable(feature = "rust1", since = "1.0.0")]
961 pub fn wrapping_mul(self, rhs: Self) -> Self {
963 intrinsics::overflowing_mul(self, rhs)
969 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
970 boundary of the type.
972 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
973 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
974 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
978 This function will panic if `rhs` is 0.
985 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
986 assert_eq!((-128i8).wrapping_div(-1), -128);",
989 #[stable(feature = "num_wrapping", since = "1.2.0")]
991 pub fn wrapping_div(self, rhs: Self) -> Self {
992 self.overflowing_div(rhs).0
997 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
998 boundary of the type.
1000 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1001 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1002 this function returns `0`.
1006 This function will panic if `rhs` is 0.
1013 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1014 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1017 #[stable(feature = "num_wrapping", since = "1.2.0")]
1019 pub fn wrapping_rem(self, rhs: Self) -> Self {
1020 self.overflowing_rem(rhs).0
1025 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1028 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1029 is the negative minimal value for the type); this is a positive value that is too large to represent
1030 in the type. In such a case, this function returns `MIN` itself.
1037 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1038 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1042 #[stable(feature = "num_wrapping", since = "1.2.0")]
1044 pub fn wrapping_neg(self) -> Self {
1045 self.overflowing_neg().0
1050 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1051 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1053 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1054 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1055 The primitive integer types all implement a `rotate_left` function, which may be what you want
1063 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1064 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1067 #[stable(feature = "num_wrapping", since = "1.2.0")]
1069 pub fn wrapping_shl(self, rhs: u32) -> Self {
1071 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1077 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1078 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1080 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1081 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1082 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1090 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1091 assert_eq!((-128i16).wrapping_shr(64), -128);",
1094 #[stable(feature = "num_wrapping", since = "1.2.0")]
1096 pub fn wrapping_shr(self, rhs: u32) -> Self {
1098 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1104 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1105 the boundary of the type.
1107 The only case where such wrapping can occur is when one takes the absolute value of the negative
1108 minimal value for the type this is a positive value that is too large to represent in the type. In
1109 such a case, this function returns `MIN` itself.
1116 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1117 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1118 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1120 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1123 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1125 pub fn wrapping_abs(self) -> Self {
1126 if self.is_negative() {
1135 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1136 wrapping around at the boundary of the type.
1143 #![feature(no_panic_pow)]
1144 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1145 assert_eq!(3i8.wrapping_pow(5), -13);
1146 assert_eq!(3i8.wrapping_pow(6), -39);",
1149 #[unstable(feature = "no_panic_pow", issue = "48320")]
1151 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1152 let mut base = self;
1153 let mut acc: Self = 1;
1157 acc = acc.wrapping_mul(base);
1160 base = base.wrapping_mul(base);
1163 // Deal with the final bit of the exponent separately, since
1164 // squaring the base afterwards is not necessary and may cause a
1165 // needless overflow.
1167 acc = acc.wrapping_mul(base);
1175 concat!("Calculates `self` + `rhs`
1177 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1178 occur. If an overflow would have occurred then the wrapped value is returned.
1185 ", $Feature, "use std::", stringify!($SelfT), ";
1187 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1188 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1189 "::MIN, true));", $EndFeature, "
1192 #[stable(feature = "wrapping", since = "1.7.0")]
1193 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1194 let (a, b) = unsafe {
1195 intrinsics::add_with_overflow(self as $ActualT,
1203 concat!("Calculates `self` - `rhs`
1205 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1206 would occur. If an overflow would have occurred then the wrapped value is returned.
1213 ", $Feature, "use std::", stringify!($SelfT), ";
1215 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1216 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1217 "::MAX, true));", $EndFeature, "
1220 #[stable(feature = "wrapping", since = "1.7.0")]
1221 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1222 let (a, b) = unsafe {
1223 intrinsics::sub_with_overflow(self as $ActualT,
1231 concat!("Calculates the multiplication of `self` and `rhs`.
1233 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1234 would occur. If an overflow would have occurred then the wrapped value is returned.
1241 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1242 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1246 #[stable(feature = "wrapping", since = "1.7.0")]
1247 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1248 let (a, b) = unsafe {
1249 intrinsics::mul_with_overflow(self as $ActualT,
1257 concat!("Calculates the divisor when `self` is divided by `rhs`.
1259 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1260 occur. If an overflow would occur then self is returned.
1264 This function will panic if `rhs` is 0.
1271 ", $Feature, "use std::", stringify!($SelfT), ";
1273 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1274 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1279 #[stable(feature = "wrapping", since = "1.7.0")]
1280 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1281 if self == Self::min_value() && rhs == -1 {
1290 concat!("Calculates the remainder when `self` is divided by `rhs`.
1292 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1293 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1297 This function will panic if `rhs` is 0.
1304 ", $Feature, "use std::", stringify!($SelfT), ";
1306 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1307 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1311 #[stable(feature = "wrapping", since = "1.7.0")]
1312 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1313 if self == Self::min_value() && rhs == -1 {
1322 concat!("Negates self, overflowing if this is equal to the minimum value.
1324 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1325 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1326 minimum value will be returned again and `true` will be returned for an overflow happening.
1333 ", $Feature, "use std::", stringify!($SelfT), ";
1335 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1336 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1337 "::MIN, true));", $EndFeature, "
1340 #[stable(feature = "wrapping", since = "1.7.0")]
1341 pub fn overflowing_neg(self) -> (Self, bool) {
1342 if self == Self::min_value() {
1343 (Self::min_value(), true)
1351 concat!("Shifts self left by `rhs` bits.
1353 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1354 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1355 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1362 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1363 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1367 #[stable(feature = "wrapping", since = "1.7.0")]
1368 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1369 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1374 concat!("Shifts self right by `rhs` bits.
1376 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1377 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1378 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1385 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1386 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1390 #[stable(feature = "wrapping", since = "1.7.0")]
1391 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1392 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1397 concat!("Computes the absolute value of `self`.
1399 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1400 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1401 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1402 for an overflow happening.
1409 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1410 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1411 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1412 "::min_value(), true));",
1415 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1417 pub fn overflowing_abs(self) -> (Self, bool) {
1418 if self.is_negative() {
1419 self.overflowing_neg()
1427 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1429 Returns a tuple of the exponentiation along with a bool indicating
1430 whether an overflow happened.
1437 #![feature(no_panic_pow)]
1438 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1439 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1442 #[unstable(feature = "no_panic_pow", issue = "48320")]
1444 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1445 let mut base = self;
1446 let mut acc: Self = 1;
1447 let mut overflown = false;
1448 // Scratch space for storing results of overflowing_mul.
1453 r = acc.overflowing_mul(base);
1458 r = base.overflowing_mul(base);
1463 // Deal with the final bit of the exponent separately, since
1464 // squaring the base afterwards is not necessary and may cause a
1465 // needless overflow.
1467 r = acc.overflowing_mul(base);
1477 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1484 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1486 assert_eq!(x.pow(5), 32);",
1489 #[stable(feature = "rust1", since = "1.0.0")]
1491 #[rustc_inherit_overflow_checks]
1492 pub fn pow(self, mut exp: u32) -> Self {
1493 let mut base = self;
1504 // Deal with the final bit of the exponent separately, since
1505 // squaring the base afterwards is not necessary and may cause a
1506 // needless overflow.
1516 concat!("Computes the absolute value of `self`.
1520 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1521 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1522 code in debug mode will trigger a panic on this case and optimized code will return `",
1523 stringify!($SelfT), "::min_value()` without a panic.
1530 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1531 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1534 #[stable(feature = "rust1", since = "1.0.0")]
1536 #[rustc_inherit_overflow_checks]
1537 pub fn abs(self) -> Self {
1538 if self.is_negative() {
1539 // Note that the #[inline] above means that the overflow
1540 // semantics of this negation depend on the crate we're being
1550 concat!("Returns a number representing sign of `self`.
1552 - `0` if the number is zero
1553 - `1` if the number is positive
1554 - `-1` if the number is negative
1561 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1562 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1563 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1566 #[stable(feature = "rust1", since = "1.0.0")]
1568 pub fn signum(self) -> Self {
1578 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1586 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1587 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1590 #[stable(feature = "rust1", since = "1.0.0")]
1592 pub fn is_positive(self) -> bool { self > 0 }
1596 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1604 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1605 assert!(!10", stringify!($SelfT), ".is_negative());",
1608 #[stable(feature = "rust1", since = "1.0.0")]
1610 pub fn is_negative(self) -> bool { self < 0 }
1617 int_impl! { i8, i8, u8, 8, -128, 127, "", "" }
1622 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "" }
1627 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "" }
1632 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1637 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
1638 170141183460469231731687303715884105727, "#![feature(i128_type)]
1645 #[cfg(target_pointer_width = "16")]
1648 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "" }
1651 #[cfg(target_pointer_width = "32")]
1654 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "" }
1657 #[cfg(target_pointer_width = "64")]
1660 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1663 // `Int` + `UnsignedInt` implemented for unsigned integers
1664 macro_rules! uint_impl {
1665 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr) => {
1667 concat!("Returns the smallest value that can be represented by this integer type.
1674 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
1676 #[stable(feature = "rust1", since = "1.0.0")]
1678 pub const fn min_value() -> Self { 0 }
1682 concat!("Returns the largest value that can be represented by this integer type.
1689 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
1690 stringify!($MaxV), ");", $EndFeature, "
1692 #[stable(feature = "rust1", since = "1.0.0")]
1694 pub const fn max_value() -> Self { !0 }
1698 concat!("Converts a string slice in a given base to an integer.
1700 The string is expected to be an optional `+` sign
1702 Leading and trailing whitespace represent an error.
1703 Digits are a subset of these characters, depending on `radix`:
1711 This function panics if `radix` is not in the range from 2 to 36.
1718 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1723 from_str_radix(src, radix)
1728 concat!("Returns the number of ones in the binary representation of `self`.
1735 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
1737 assert_eq!(n.count_ones(), 3);", $EndFeature, "
1739 #[stable(feature = "rust1", since = "1.0.0")]
1741 pub fn count_ones(self) -> u32 {
1742 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
1747 concat!("Returns the number of zeros in the binary representation of `self`.
1754 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
1756 #[stable(feature = "rust1", since = "1.0.0")]
1758 pub fn count_zeros(self) -> u32 {
1759 (!self).count_ones()
1764 concat!("Returns the number of leading zeros in the binary representation of `self`.
1771 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
1773 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
1775 #[stable(feature = "rust1", since = "1.0.0")]
1777 pub fn leading_zeros(self) -> u32 {
1778 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
1783 concat!("Returns the number of trailing zeros in the binary representation
1791 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
1793 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
1795 #[stable(feature = "rust1", since = "1.0.0")]
1797 pub fn trailing_zeros(self) -> u32 {
1798 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1799 // emits two conditional moves on x86_64. By promoting the value to
1800 // u16 and setting bit 8, we get better code without any conditional
1802 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1803 // pending, remove this workaround once LLVM generates better code
1807 intrinsics::cttz(self as u16 | 0x100) as u32
1809 intrinsics::cttz(self) as u32
1815 /// Shifts the bits to the left by a specified amount, `n`,
1816 /// wrapping the truncated bits to the end of the resulting integer.
1818 /// Please note this isn't the same operation as `<<`!
1824 /// Please note that this example is shared between integer types.
1825 /// Which explains why `u64` is used here.
1828 /// let n = 0x0123456789ABCDEFu64;
1829 /// let m = 0x3456789ABCDEF012u64;
1831 /// assert_eq!(n.rotate_left(12), m);
1833 #[stable(feature = "rust1", since = "1.0.0")]
1835 pub fn rotate_left(self, n: u32) -> Self {
1836 // Protect against undefined behaviour for over-long bit shifts
1838 (self << n) | (self >> (($BITS - n) % $BITS))
1841 /// Shifts the bits to the right by a specified amount, `n`,
1842 /// wrapping the truncated bits to the beginning of the resulting
1845 /// Please note this isn't the same operation as `>>`!
1851 /// Please note that this example is shared between integer types.
1852 /// Which explains why `u64` is used here.
1855 /// let n = 0x0123456789ABCDEFu64;
1856 /// let m = 0xDEF0123456789ABCu64;
1858 /// assert_eq!(n.rotate_right(12), m);
1860 #[stable(feature = "rust1", since = "1.0.0")]
1862 pub fn rotate_right(self, n: u32) -> Self {
1863 // Protect against undefined behaviour for over-long bit shifts
1865 (self >> n) | (self << (($BITS - n) % $BITS))
1868 /// Reverses the byte order of the integer.
1874 /// Please note that this example is shared between integer types.
1875 /// Which explains why `u16` is used here.
1878 /// let n: u16 = 0b0000000_01010101;
1879 /// assert_eq!(n, 85);
1881 /// let m = n.swap_bytes();
1883 /// assert_eq!(m, 0b01010101_00000000);
1884 /// assert_eq!(m, 21760);
1886 #[stable(feature = "rust1", since = "1.0.0")]
1888 pub fn swap_bytes(self) -> Self {
1889 unsafe { intrinsics::bswap(self as $ActualT) as Self }
1892 /// Reverses the bit pattern of the integer.
1898 /// Please note that this example is shared between integer types.
1899 /// Which explains why `u16` is used here.
1902 /// #![feature(reverse_bits)]
1904 /// let n: u16 = 0b0000000_01010101;
1905 /// assert_eq!(n, 85);
1907 /// let m = n.reverse_bits();
1909 /// assert_eq!(m, 0b10101010_00000000);
1910 /// assert_eq!(m, 43520);
1912 #[unstable(feature = "reverse_bits", issue = "48763")]
1915 pub fn reverse_bits(self) -> Self {
1916 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
1920 concat!("Converts an integer from big endian to the target's endianness.
1922 On big endian this is a no-op. On little endian the bytes are
1930 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1932 if cfg!(target_endian = \"big\") {
1933 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
1935 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
1938 #[stable(feature = "rust1", since = "1.0.0")]
1940 pub fn from_be(x: Self) -> Self {
1941 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1946 concat!("Converts an integer from little endian to the target's endianness.
1948 On little endian this is a no-op. On big endian the bytes are
1956 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1958 if cfg!(target_endian = \"little\") {
1959 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
1961 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
1964 #[stable(feature = "rust1", since = "1.0.0")]
1966 pub fn from_le(x: Self) -> Self {
1967 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1972 concat!("Converts `self` to big endian from the target's endianness.
1974 On big endian this is a no-op. On little endian the bytes are
1982 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1984 if cfg!(target_endian = \"big\") {
1985 assert_eq!(n.to_be(), n)
1987 assert_eq!(n.to_be(), n.swap_bytes())
1990 #[stable(feature = "rust1", since = "1.0.0")]
1992 pub fn to_be(self) -> Self { // or not to be?
1993 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1998 concat!("Converts `self` to little endian from the target's endianness.
2000 On little endian this is a no-op. On big endian the bytes are
2008 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2010 if cfg!(target_endian = \"little\") {
2011 assert_eq!(n.to_le(), n)
2013 assert_eq!(n.to_le(), n.swap_bytes())
2016 #[stable(feature = "rust1", since = "1.0.0")]
2018 pub fn to_le(self) -> Self {
2019 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
2024 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2025 if overflow occurred.
2032 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2033 "Some(", stringify!($SelfT), "::max_value() - 1));
2034 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3),None);", $EndFeature, "
2036 #[stable(feature = "rust1", since = "1.0.0")]
2038 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2039 let (a, b) = self.overflowing_add(rhs);
2040 if b {None} else {Some(a)}
2045 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2046 `None` if overflow occurred.
2053 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2054 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2056 #[stable(feature = "rust1", since = "1.0.0")]
2058 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2059 let (a, b) = self.overflowing_sub(rhs);
2060 if b {None} else {Some(a)}
2065 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2066 `None` if overflow occurred.
2073 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2074 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2076 #[stable(feature = "rust1", since = "1.0.0")]
2078 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2079 let (a, b) = self.overflowing_mul(rhs);
2080 if b {None} else {Some(a)}
2085 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2093 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2094 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2096 #[stable(feature = "rust1", since = "1.0.0")]
2098 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2101 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2107 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2115 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2116 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2118 #[stable(feature = "wrapping", since = "1.7.0")]
2120 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2124 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2130 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2133 Note that negating any positive integer will overflow.
2140 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2141 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2143 #[stable(feature = "wrapping", since = "1.7.0")]
2145 pub fn checked_neg(self) -> Option<Self> {
2146 let (a, b) = self.overflowing_neg();
2147 if b {None} else {Some(a)}
2152 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2153 if `rhs` is larger than or equal to the number of bits in `self`.
2160 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2161 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2163 #[stable(feature = "wrapping", since = "1.7.0")]
2165 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2166 let (a, b) = self.overflowing_shl(rhs);
2167 if b {None} else {Some(a)}
2172 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2173 if `rhs` is larger than or equal to the number of bits in `self`.
2180 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2181 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2183 #[stable(feature = "wrapping", since = "1.7.0")]
2185 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2186 let (a, b) = self.overflowing_shr(rhs);
2187 if b {None} else {Some(a)}
2192 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2200 #![feature(no_panic_pow)]
2201 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2202 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2204 #[unstable(feature = "no_panic_pow", issue = "48320")]
2206 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2207 let mut base = self;
2208 let mut acc: Self = 1;
2212 acc = acc.checked_mul(base)?;
2215 base = base.checked_mul(base)?;
2218 // Deal with the final bit of the exponent separately, since
2219 // squaring the base afterwards is not necessary and may cause a
2220 // needless overflow.
2222 acc = acc.checked_mul(base)?;
2230 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2231 the numeric bounds instead of overflowing.
2238 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2239 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2241 #[stable(feature = "rust1", since = "1.0.0")]
2243 pub fn saturating_add(self, rhs: Self) -> Self {
2244 match self.checked_add(rhs) {
2246 None => Self::max_value(),
2252 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2253 at the numeric bounds instead of overflowing.
2260 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2261 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2263 #[stable(feature = "rust1", since = "1.0.0")]
2265 pub fn saturating_sub(self, rhs: Self) -> Self {
2266 match self.checked_sub(rhs) {
2268 None => Self::min_value(),
2274 concat!("Saturating integer multiplication. Computes `self * rhs`,
2275 saturating at the numeric bounds instead of overflowing.
2282 ", $Feature, "use std::", stringify!($SelfT), ";
2284 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2285 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2286 "::MAX);", $EndFeature, "
2288 #[stable(feature = "wrapping", since = "1.7.0")]
2290 pub fn saturating_mul(self, rhs: Self) -> Self {
2291 self.checked_mul(rhs).unwrap_or(Self::max_value())
2296 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2297 saturating at the numeric bounds instead of overflowing.
2304 #![feature(no_panic_pow)]
2305 ", $Feature, "use std::", stringify!($SelfT), ";
2307 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2308 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2311 #[unstable(feature = "no_panic_pow", issue = "48320")]
2313 pub fn saturating_pow(self, exp: u32) -> Self {
2314 match self.checked_pow(exp) {
2316 None => Self::max_value(),
2322 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2323 wrapping around at the boundary of the type.
2330 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2331 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2334 #[stable(feature = "rust1", since = "1.0.0")]
2336 pub fn wrapping_add(self, rhs: Self) -> Self {
2338 intrinsics::overflowing_add(self, rhs)
2344 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2345 wrapping around at the boundary of the type.
2352 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2353 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2356 #[stable(feature = "rust1", since = "1.0.0")]
2358 pub fn wrapping_sub(self, rhs: Self) -> Self {
2360 intrinsics::overflowing_sub(self, rhs)
2365 /// Wrapping (modular) multiplication. Computes `self *
2366 /// rhs`, wrapping around at the boundary of the type.
2372 /// Please note that this example is shared between integer types.
2373 /// Which explains why `u8` is used here.
2376 /// assert_eq!(10u8.wrapping_mul(12), 120);
2377 /// assert_eq!(25u8.wrapping_mul(12), 44);
2379 #[stable(feature = "rust1", since = "1.0.0")]
2381 pub fn wrapping_mul(self, rhs: Self) -> Self {
2383 intrinsics::overflowing_mul(self, rhs)
2388 concat!("Wrapping (modular) division. Computes `self / rhs`.
2389 Wrapped division on unsigned types is just normal division.
2390 There's no way wrapping could ever happen.
2391 This function exists, so that all operations
2392 are accounted for in the wrapping operations.
2399 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2401 #[stable(feature = "num_wrapping", since = "1.2.0")]
2403 pub fn wrapping_div(self, rhs: Self) -> Self {
2409 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2410 Wrapped remainder calculation on unsigned types is
2411 just the regular remainder calculation.
2412 There's no way wrapping could ever happen.
2413 This function exists, so that all operations
2414 are accounted for in the wrapping operations.
2421 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2423 #[stable(feature = "num_wrapping", since = "1.2.0")]
2425 pub fn wrapping_rem(self, rhs: Self) -> Self {
2430 /// Wrapping (modular) negation. Computes `-self`,
2431 /// wrapping around at the boundary of the type.
2433 /// Since unsigned types do not have negative equivalents
2434 /// all applications of this function will wrap (except for `-0`).
2435 /// For values smaller than the corresponding signed type's maximum
2436 /// the result is the same as casting the corresponding signed value.
2437 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2438 /// `MAX` is the corresponding signed type's maximum.
2444 /// Please note that this example is shared between integer types.
2445 /// Which explains why `i8` is used here.
2448 /// assert_eq!(100i8.wrapping_neg(), -100);
2449 /// assert_eq!((-128i8).wrapping_neg(), -128);
2451 #[stable(feature = "num_wrapping", since = "1.2.0")]
2453 pub fn wrapping_neg(self) -> Self {
2454 self.overflowing_neg().0
2458 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2459 where `mask` removes any high-order bits of `rhs` that
2460 would cause the shift to exceed the bitwidth of the type.
2462 Note that this is *not* the same as a rotate-left; the
2463 RHS of a wrapping shift-left is restricted to the range
2464 of the type, rather than the bits shifted out of the LHS
2465 being returned to the other end. The primitive integer
2466 types all implement a `rotate_left` function, which may
2467 be what you want instead.
2474 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2475 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2477 #[stable(feature = "num_wrapping", since = "1.2.0")]
2479 pub fn wrapping_shl(self, rhs: u32) -> Self {
2481 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
2487 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2488 where `mask` removes any high-order bits of `rhs` that
2489 would cause the shift to exceed the bitwidth of the type.
2491 Note that this is *not* the same as a rotate-right; the
2492 RHS of a wrapping shift-right is restricted to the range
2493 of the type, rather than the bits shifted out of the LHS
2494 being returned to the other end. The primitive integer
2495 types all implement a `rotate_right` function, which may
2496 be what you want instead.
2503 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
2504 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
2506 #[stable(feature = "num_wrapping", since = "1.2.0")]
2508 pub fn wrapping_shr(self, rhs: u32) -> Self {
2510 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
2516 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2517 wrapping around at the boundary of the type.
2524 #![feature(no_panic_pow)]
2525 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
2526 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
2528 #[unstable(feature = "no_panic_pow", issue = "48320")]
2530 pub fn wrapping_pow(self, mut exp: u32) -> Self {
2531 let mut base = self;
2532 let mut acc: Self = 1;
2536 acc = acc.wrapping_mul(base);
2539 base = base.wrapping_mul(base);
2542 // Deal with the final bit of the exponent separately, since
2543 // squaring the base afterwards is not necessary and may cause a
2544 // needless overflow.
2546 acc = acc.wrapping_mul(base);
2554 concat!("Calculates `self` + `rhs`
2556 Returns a tuple of the addition along with a boolean indicating
2557 whether an arithmetic overflow would occur. If an overflow would
2558 have occurred then the wrapped value is returned.
2565 ", $Feature, "use std::", stringify!($SelfT), ";
2567 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
2568 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
2571 #[stable(feature = "wrapping", since = "1.7.0")]
2572 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2573 let (a, b) = unsafe {
2574 intrinsics::add_with_overflow(self as $ActualT,
2582 concat!("Calculates `self` - `rhs`
2584 Returns a tuple of the subtraction along with a boolean indicating
2585 whether an arithmetic overflow would occur. If an overflow would
2586 have occurred then the wrapped value is returned.
2593 ", $Feature, "use std::", stringify!($SelfT), ";
2595 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
2596 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
2600 #[stable(feature = "wrapping", since = "1.7.0")]
2601 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2602 let (a, b) = unsafe {
2603 intrinsics::sub_with_overflow(self as $ActualT,
2610 /// Calculates the multiplication of `self` and `rhs`.
2612 /// Returns a tuple of the multiplication along with a boolean
2613 /// indicating whether an arithmetic overflow would occur. If an
2614 /// overflow would have occurred then the wrapped value is returned.
2620 /// Please note that this example is shared between integer types.
2621 /// Which explains why `u32` is used here.
2624 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2625 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2628 #[stable(feature = "wrapping", since = "1.7.0")]
2629 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2630 let (a, b) = unsafe {
2631 intrinsics::mul_with_overflow(self as $ActualT,
2638 concat!("Calculates the divisor when `self` is divided by `rhs`.
2640 Returns a tuple of the divisor along with a boolean indicating
2641 whether an arithmetic overflow would occur. Note that for unsigned
2642 integers overflow never occurs, so the second value is always
2647 This function will panic if `rhs` is 0.
2654 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
2657 #[stable(feature = "wrapping", since = "1.7.0")]
2658 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2664 concat!("Calculates the remainder when `self` is divided by `rhs`.
2666 Returns a tuple of the remainder after dividing along with a boolean
2667 indicating whether an arithmetic overflow would occur. Note that for
2668 unsigned integers overflow never occurs, so the second value is
2673 This function will panic if `rhs` is 0.
2680 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
2683 #[stable(feature = "wrapping", since = "1.7.0")]
2684 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2690 concat!("Negates self in an overflowing fashion.
2692 Returns `!self + 1` using wrapping operations to return the value
2693 that represents the negation of this unsigned value. Note that for
2694 positive unsigned values overflow always occurs, but negating 0 does
2702 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
2703 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
2704 ", true));", $EndFeature, "
2707 #[stable(feature = "wrapping", since = "1.7.0")]
2708 pub fn overflowing_neg(self) -> (Self, bool) {
2709 ((!self).wrapping_add(1), self != 0)
2714 concat!("Shifts self left by `rhs` bits.
2716 Returns a tuple of the shifted version of self along with a boolean
2717 indicating whether the shift value was larger than or equal to the
2718 number of bits. If the shift value is too large, then value is
2719 masked (N-1) where N is the number of bits, and this value is then
2720 used to perform the shift.
2727 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
2728 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
2731 #[stable(feature = "wrapping", since = "1.7.0")]
2732 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2733 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
2738 concat!("Shifts self right by `rhs` bits.
2740 Returns a tuple of the shifted version of self along with a boolean
2741 indicating whether the shift value was larger than or equal to the
2742 number of bits. If the shift value is too large, then value is
2743 masked (N-1) where N is the number of bits, and this value is then
2744 used to perform the shift.
2751 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
2752 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
2755 #[stable(feature = "wrapping", since = "1.7.0")]
2756 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2757 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
2762 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2764 Returns a tuple of the exponentiation along with a bool indicating
2765 whether an overflow happened.
2772 #![feature(no_panic_pow)]
2773 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
2774 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
2776 #[unstable(feature = "no_panic_pow", issue = "48320")]
2778 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
2779 let mut base = self;
2780 let mut acc: Self = 1;
2781 let mut overflown = false;
2782 // Scratch space for storing results of overflowing_mul.
2787 r = acc.overflowing_mul(base);
2792 r = base.overflowing_mul(base);
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.
2801 r = acc.overflowing_mul(base);
2811 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2818 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
2820 #[stable(feature = "rust1", since = "1.0.0")]
2822 #[rustc_inherit_overflow_checks]
2823 pub fn pow(self, mut exp: u32) -> Self {
2824 let mut base = self;
2835 // Deal with the final bit of the exponent separately, since
2836 // squaring the base afterwards is not necessary and may cause a
2837 // needless overflow.
2847 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
2854 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
2855 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
2857 #[stable(feature = "rust1", since = "1.0.0")]
2859 pub fn is_power_of_two(self) -> bool {
2860 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2864 // Returns one less than next power of two.
2865 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2867 // 8u8.one_less_than_next_power_of_two() == 7
2868 // 6u8.one_less_than_next_power_of_two() == 7
2870 // This method cannot overflow, as in the `next_power_of_two`
2871 // overflow cases it instead ends up returning the maximum value
2872 // of the type, and can return 0 for 0.
2874 fn one_less_than_next_power_of_two(self) -> Self {
2875 if self <= 1 { return 0; }
2877 // Because `p > 0`, it cannot consist entirely of leading zeros.
2878 // That means the shift is always in-bounds, and some processors
2879 // (such as intel pre-haswell) have more efficient ctlz
2880 // intrinsics when the argument is non-zero.
2882 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2883 <$SelfT>::max_value() >> z
2887 concat!("Returns the smallest power of two greater than or equal to `self`.
2889 When return value overflows (i.e. `self > (1 << (N-1))` for type
2890 `uN`), it panics in debug mode and return value is wrapped to 0 in
2891 release mode (the only situation in which method can return 0).
2898 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
2899 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
2901 #[stable(feature = "rust1", since = "1.0.0")]
2903 pub fn next_power_of_two(self) -> Self {
2904 // Call the trait to get overflow checks
2905 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
2910 concat!("Returns the smallest power of two greater than or equal to `n`. If
2911 the next power of two is greater than the type's maximum value,
2912 `None` is returned, otherwise the power of two is wrapped in `Some`.
2919 ", $Feature, "assert_eq!(2", stringify!($SelfT),
2920 ".checked_next_power_of_two(), Some(2));
2921 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
2922 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
2925 #[stable(feature = "rust1", since = "1.0.0")]
2926 pub fn checked_next_power_of_two(self) -> Option<Self> {
2927 self.one_less_than_next_power_of_two().checked_add(1)
2935 uint_impl! { u8, u8, 8, 255, "", "" }
2938 /// Checks if the value is within the ASCII range.
2943 /// let ascii = 97u8;
2944 /// let non_ascii = 150u8;
2946 /// assert!(ascii.is_ascii());
2947 /// assert!(!non_ascii.is_ascii());
2949 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2951 pub fn is_ascii(&self) -> bool {
2955 /// Makes a copy of the value in its ASCII upper case equivalent.
2957 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2958 /// but non-ASCII letters are unchanged.
2960 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
2965 /// let lowercase_a = 97u8;
2967 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
2970 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
2971 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2973 pub fn to_ascii_uppercase(&self) -> u8 {
2974 ASCII_UPPERCASE_MAP[*self as usize]
2977 /// Makes a copy of the value in its ASCII lower case equivalent.
2979 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2980 /// but non-ASCII letters are unchanged.
2982 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
2987 /// let uppercase_a = 65u8;
2989 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
2992 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
2993 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2995 pub fn to_ascii_lowercase(&self) -> u8 {
2996 ASCII_LOWERCASE_MAP[*self as usize]
2999 /// Checks that two values are an ASCII case-insensitive match.
3001 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3006 /// let lowercase_a = 97u8;
3007 /// let uppercase_a = 65u8;
3009 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3011 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3013 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3014 self.to_ascii_lowercase() == other.to_ascii_lowercase()
3017 /// Converts this value to its ASCII upper case equivalent in-place.
3019 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3020 /// but non-ASCII letters are unchanged.
3022 /// To return a new uppercased value without modifying the existing one, use
3023 /// [`to_ascii_uppercase`].
3028 /// let mut byte = b'a';
3030 /// byte.make_ascii_uppercase();
3032 /// assert_eq!(b'A', byte);
3035 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3036 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3038 pub fn make_ascii_uppercase(&mut self) {
3039 *self = self.to_ascii_uppercase();
3042 /// Converts this value to its ASCII lower case equivalent in-place.
3044 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3045 /// but non-ASCII letters are unchanged.
3047 /// To return a new lowercased value without modifying the existing one, use
3048 /// [`to_ascii_lowercase`].
3053 /// let mut byte = b'A';
3055 /// byte.make_ascii_lowercase();
3057 /// assert_eq!(b'a', byte);
3060 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3061 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3063 pub fn make_ascii_lowercase(&mut self) {
3064 *self = self.to_ascii_lowercase();
3067 /// Checks if the value is an ASCII alphabetic character:
3069 /// - U+0041 'A' ... U+005A 'Z', or
3070 /// - U+0061 'a' ... U+007A 'z'.
3075 /// #![feature(ascii_ctype)]
3077 /// let uppercase_a = b'A';
3078 /// let uppercase_g = b'G';
3081 /// let zero = b'0';
3082 /// let percent = b'%';
3083 /// let space = b' ';
3085 /// let esc = 0x1b_u8;
3087 /// assert!(uppercase_a.is_ascii_alphabetic());
3088 /// assert!(uppercase_g.is_ascii_alphabetic());
3089 /// assert!(a.is_ascii_alphabetic());
3090 /// assert!(g.is_ascii_alphabetic());
3091 /// assert!(!zero.is_ascii_alphabetic());
3092 /// assert!(!percent.is_ascii_alphabetic());
3093 /// assert!(!space.is_ascii_alphabetic());
3094 /// assert!(!lf.is_ascii_alphabetic());
3095 /// assert!(!esc.is_ascii_alphabetic());
3097 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3099 pub fn is_ascii_alphabetic(&self) -> bool {
3100 if *self >= 0x80 { return false; }
3101 match ASCII_CHARACTER_CLASS[*self as usize] {
3102 L | Lx | U | Ux => true,
3107 /// Checks if the value is an ASCII uppercase character:
3108 /// U+0041 'A' ... U+005A 'Z'.
3113 /// #![feature(ascii_ctype)]
3115 /// let uppercase_a = b'A';
3116 /// let uppercase_g = b'G';
3119 /// let zero = b'0';
3120 /// let percent = b'%';
3121 /// let space = b' ';
3123 /// let esc = 0x1b_u8;
3125 /// assert!(uppercase_a.is_ascii_uppercase());
3126 /// assert!(uppercase_g.is_ascii_uppercase());
3127 /// assert!(!a.is_ascii_uppercase());
3128 /// assert!(!g.is_ascii_uppercase());
3129 /// assert!(!zero.is_ascii_uppercase());
3130 /// assert!(!percent.is_ascii_uppercase());
3131 /// assert!(!space.is_ascii_uppercase());
3132 /// assert!(!lf.is_ascii_uppercase());
3133 /// assert!(!esc.is_ascii_uppercase());
3135 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3137 pub fn is_ascii_uppercase(&self) -> bool {
3138 if *self >= 0x80 { return false }
3139 match ASCII_CHARACTER_CLASS[*self as usize] {
3145 /// Checks if the value is an ASCII lowercase character:
3146 /// U+0061 'a' ... U+007A 'z'.
3151 /// #![feature(ascii_ctype)]
3153 /// let uppercase_a = b'A';
3154 /// let uppercase_g = b'G';
3157 /// let zero = b'0';
3158 /// let percent = b'%';
3159 /// let space = b' ';
3161 /// let esc = 0x1b_u8;
3163 /// assert!(!uppercase_a.is_ascii_lowercase());
3164 /// assert!(!uppercase_g.is_ascii_lowercase());
3165 /// assert!(a.is_ascii_lowercase());
3166 /// assert!(g.is_ascii_lowercase());
3167 /// assert!(!zero.is_ascii_lowercase());
3168 /// assert!(!percent.is_ascii_lowercase());
3169 /// assert!(!space.is_ascii_lowercase());
3170 /// assert!(!lf.is_ascii_lowercase());
3171 /// assert!(!esc.is_ascii_lowercase());
3173 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3175 pub fn is_ascii_lowercase(&self) -> bool {
3176 if *self >= 0x80 { return false }
3177 match ASCII_CHARACTER_CLASS[*self as usize] {
3183 /// Checks if the value is an ASCII alphanumeric character:
3185 /// - U+0041 'A' ... U+005A 'Z', or
3186 /// - U+0061 'a' ... U+007A 'z', or
3187 /// - U+0030 '0' ... U+0039 '9'.
3192 /// #![feature(ascii_ctype)]
3194 /// let uppercase_a = b'A';
3195 /// let uppercase_g = b'G';
3198 /// let zero = b'0';
3199 /// let percent = b'%';
3200 /// let space = b' ';
3202 /// let esc = 0x1b_u8;
3204 /// assert!(uppercase_a.is_ascii_alphanumeric());
3205 /// assert!(uppercase_g.is_ascii_alphanumeric());
3206 /// assert!(a.is_ascii_alphanumeric());
3207 /// assert!(g.is_ascii_alphanumeric());
3208 /// assert!(zero.is_ascii_alphanumeric());
3209 /// assert!(!percent.is_ascii_alphanumeric());
3210 /// assert!(!space.is_ascii_alphanumeric());
3211 /// assert!(!lf.is_ascii_alphanumeric());
3212 /// assert!(!esc.is_ascii_alphanumeric());
3214 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3216 pub fn is_ascii_alphanumeric(&self) -> bool {
3217 if *self >= 0x80 { return false }
3218 match ASCII_CHARACTER_CLASS[*self as usize] {
3219 D | L | Lx | U | Ux => true,
3224 /// Checks if the value is an ASCII decimal digit:
3225 /// U+0030 '0' ... U+0039 '9'.
3230 /// #![feature(ascii_ctype)]
3232 /// let uppercase_a = b'A';
3233 /// let uppercase_g = b'G';
3236 /// let zero = b'0';
3237 /// let percent = b'%';
3238 /// let space = b' ';
3240 /// let esc = 0x1b_u8;
3242 /// assert!(!uppercase_a.is_ascii_digit());
3243 /// assert!(!uppercase_g.is_ascii_digit());
3244 /// assert!(!a.is_ascii_digit());
3245 /// assert!(!g.is_ascii_digit());
3246 /// assert!(zero.is_ascii_digit());
3247 /// assert!(!percent.is_ascii_digit());
3248 /// assert!(!space.is_ascii_digit());
3249 /// assert!(!lf.is_ascii_digit());
3250 /// assert!(!esc.is_ascii_digit());
3252 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3254 pub fn is_ascii_digit(&self) -> bool {
3255 if *self >= 0x80 { return false }
3256 match ASCII_CHARACTER_CLASS[*self as usize] {
3262 /// Checks if the value is an ASCII hexadecimal digit:
3264 /// - U+0030 '0' ... U+0039 '9', or
3265 /// - U+0041 'A' ... U+0046 'F', or
3266 /// - U+0061 'a' ... U+0066 'f'.
3271 /// #![feature(ascii_ctype)]
3273 /// let uppercase_a = b'A';
3274 /// let uppercase_g = b'G';
3277 /// let zero = b'0';
3278 /// let percent = b'%';
3279 /// let space = b' ';
3281 /// let esc = 0x1b_u8;
3283 /// assert!(uppercase_a.is_ascii_hexdigit());
3284 /// assert!(!uppercase_g.is_ascii_hexdigit());
3285 /// assert!(a.is_ascii_hexdigit());
3286 /// assert!(!g.is_ascii_hexdigit());
3287 /// assert!(zero.is_ascii_hexdigit());
3288 /// assert!(!percent.is_ascii_hexdigit());
3289 /// assert!(!space.is_ascii_hexdigit());
3290 /// assert!(!lf.is_ascii_hexdigit());
3291 /// assert!(!esc.is_ascii_hexdigit());
3293 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3295 pub fn is_ascii_hexdigit(&self) -> bool {
3296 if *self >= 0x80 { return false }
3297 match ASCII_CHARACTER_CLASS[*self as usize] {
3298 D | Lx | Ux => true,
3303 /// Checks if the value is an ASCII punctuation character:
3305 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
3306 /// - U+003A ... U+0040 `: ; < = > ? @`, or
3307 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
3308 /// - U+007B ... U+007E `{ | } ~`
3313 /// #![feature(ascii_ctype)]
3315 /// let uppercase_a = b'A';
3316 /// let uppercase_g = b'G';
3319 /// let zero = b'0';
3320 /// let percent = b'%';
3321 /// let space = b' ';
3323 /// let esc = 0x1b_u8;
3325 /// assert!(!uppercase_a.is_ascii_punctuation());
3326 /// assert!(!uppercase_g.is_ascii_punctuation());
3327 /// assert!(!a.is_ascii_punctuation());
3328 /// assert!(!g.is_ascii_punctuation());
3329 /// assert!(!zero.is_ascii_punctuation());
3330 /// assert!(percent.is_ascii_punctuation());
3331 /// assert!(!space.is_ascii_punctuation());
3332 /// assert!(!lf.is_ascii_punctuation());
3333 /// assert!(!esc.is_ascii_punctuation());
3335 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3337 pub fn is_ascii_punctuation(&self) -> bool {
3338 if *self >= 0x80 { return false }
3339 match ASCII_CHARACTER_CLASS[*self as usize] {
3345 /// Checks if the value is an ASCII graphic character:
3346 /// U+0021 '!' ... U+007E '~'.
3351 /// #![feature(ascii_ctype)]
3353 /// let uppercase_a = b'A';
3354 /// let uppercase_g = b'G';
3357 /// let zero = b'0';
3358 /// let percent = b'%';
3359 /// let space = b' ';
3361 /// let esc = 0x1b_u8;
3363 /// assert!(uppercase_a.is_ascii_graphic());
3364 /// assert!(uppercase_g.is_ascii_graphic());
3365 /// assert!(a.is_ascii_graphic());
3366 /// assert!(g.is_ascii_graphic());
3367 /// assert!(zero.is_ascii_graphic());
3368 /// assert!(percent.is_ascii_graphic());
3369 /// assert!(!space.is_ascii_graphic());
3370 /// assert!(!lf.is_ascii_graphic());
3371 /// assert!(!esc.is_ascii_graphic());
3373 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3375 pub fn is_ascii_graphic(&self) -> bool {
3376 if *self >= 0x80 { return false; }
3377 match ASCII_CHARACTER_CLASS[*self as usize] {
3378 Ux | U | Lx | L | D | P => true,
3383 /// Checks if the value is an ASCII whitespace character:
3384 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
3385 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
3387 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
3388 /// whitespace][infra-aw]. There are several other definitions in
3389 /// wide use. For instance, [the POSIX locale][pct] includes
3390 /// U+000B VERTICAL TAB as well as all the above characters,
3391 /// but—from the very same specification—[the default rule for
3392 /// "field splitting" in the Bourne shell][bfs] considers *only*
3393 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
3395 /// If you are writing a program that will process an existing
3396 /// file format, check what that format's definition of whitespace is
3397 /// before using this function.
3399 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
3400 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
3401 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
3406 /// #![feature(ascii_ctype)]
3408 /// let uppercase_a = b'A';
3409 /// let uppercase_g = b'G';
3412 /// let zero = b'0';
3413 /// let percent = b'%';
3414 /// let space = b' ';
3416 /// let esc = 0x1b_u8;
3418 /// assert!(!uppercase_a.is_ascii_whitespace());
3419 /// assert!(!uppercase_g.is_ascii_whitespace());
3420 /// assert!(!a.is_ascii_whitespace());
3421 /// assert!(!g.is_ascii_whitespace());
3422 /// assert!(!zero.is_ascii_whitespace());
3423 /// assert!(!percent.is_ascii_whitespace());
3424 /// assert!(space.is_ascii_whitespace());
3425 /// assert!(lf.is_ascii_whitespace());
3426 /// assert!(!esc.is_ascii_whitespace());
3428 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3430 pub fn is_ascii_whitespace(&self) -> bool {
3431 if *self >= 0x80 { return false; }
3432 match ASCII_CHARACTER_CLASS[*self as usize] {
3438 /// Checks if the value is an ASCII control character:
3439 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
3440 /// Note that most ASCII whitespace characters are control
3441 /// characters, but SPACE is not.
3446 /// #![feature(ascii_ctype)]
3448 /// let uppercase_a = b'A';
3449 /// let uppercase_g = b'G';
3452 /// let zero = b'0';
3453 /// let percent = b'%';
3454 /// let space = b' ';
3456 /// let esc = 0x1b_u8;
3458 /// assert!(!uppercase_a.is_ascii_control());
3459 /// assert!(!uppercase_g.is_ascii_control());
3460 /// assert!(!a.is_ascii_control());
3461 /// assert!(!g.is_ascii_control());
3462 /// assert!(!zero.is_ascii_control());
3463 /// assert!(!percent.is_ascii_control());
3464 /// assert!(!space.is_ascii_control());
3465 /// assert!(lf.is_ascii_control());
3466 /// assert!(esc.is_ascii_control());
3468 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3470 pub fn is_ascii_control(&self) -> bool {
3471 if *self >= 0x80 { return false; }
3472 match ASCII_CHARACTER_CLASS[*self as usize] {
3481 uint_impl! { u16, u16, 16, 65535, "", "" }
3486 uint_impl! { u32, u32, 32, 4294967295, "", "" }
3491 uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
3496 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "#![feature(i128_type)]
3504 #[cfg(target_pointer_width = "16")]
3507 uint_impl! { usize, u16, 16, 65536, "", "" }
3509 #[cfg(target_pointer_width = "32")]
3512 uint_impl! { usize, u32, 32, 4294967295, "", "" }
3515 #[cfg(target_pointer_width = "64")]
3518 uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
3521 /// A classification of floating point numbers.
3523 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
3524 /// their documentation for more.
3526 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
3527 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
3532 /// use std::num::FpCategory;
3535 /// let num = 12.4_f32;
3536 /// let inf = f32::INFINITY;
3537 /// let zero = 0f32;
3538 /// let sub: f32 = 1.1754942e-38;
3539 /// let nan = f32::NAN;
3541 /// assert_eq!(num.classify(), FpCategory::Normal);
3542 /// assert_eq!(inf.classify(), FpCategory::Infinite);
3543 /// assert_eq!(zero.classify(), FpCategory::Zero);
3544 /// assert_eq!(nan.classify(), FpCategory::Nan);
3545 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
3547 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
3548 #[stable(feature = "rust1", since = "1.0.0")]
3549 pub enum FpCategory {
3550 /// "Not a Number", often obtained by dividing by zero.
3551 #[stable(feature = "rust1", since = "1.0.0")]
3554 /// Positive or negative infinity.
3555 #[stable(feature = "rust1", since = "1.0.0")]
3558 /// Positive or negative zero.
3559 #[stable(feature = "rust1", since = "1.0.0")]
3562 /// De-normalized floating point representation (less precise than `Normal`).
3563 #[stable(feature = "rust1", since = "1.0.0")]
3566 /// A regular floating point number.
3567 #[stable(feature = "rust1", since = "1.0.0")]
3571 /// A built-in floating point number.
3573 #[unstable(feature = "core_float",
3574 reason = "stable interface is via `impl f{32,64}` in later crates",
3576 pub trait Float: Sized {
3577 /// Type used by `to_bits` and `from_bits`.
3578 #[stable(feature = "core_float_bits", since = "1.25.0")]
3581 /// Returns `true` if this value is NaN and false otherwise.
3582 #[stable(feature = "core", since = "1.6.0")]
3583 fn is_nan(self) -> bool;
3584 /// Returns `true` if this value is positive infinity or negative infinity and
3585 /// false otherwise.
3586 #[stable(feature = "core", since = "1.6.0")]
3587 fn is_infinite(self) -> bool;
3588 /// Returns `true` if this number is neither infinite nor NaN.
3589 #[stable(feature = "core", since = "1.6.0")]
3590 fn is_finite(self) -> bool;
3591 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
3592 #[stable(feature = "core", since = "1.6.0")]
3593 fn is_normal(self) -> bool;
3594 /// Returns the category that this number falls into.
3595 #[stable(feature = "core", since = "1.6.0")]
3596 fn classify(self) -> FpCategory;
3598 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
3599 /// number is `Float::nan()`.
3600 #[stable(feature = "core", since = "1.6.0")]
3601 fn abs(self) -> Self;
3602 /// Returns a number that represents the sign of `self`.
3604 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
3605 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
3606 /// - `Float::nan()` if the number is `Float::nan()`
3607 #[stable(feature = "core", since = "1.6.0")]
3608 fn signum(self) -> Self;
3610 /// Returns `true` if `self` is positive, including `+0.0` and
3611 /// `Float::infinity()`.
3612 #[stable(feature = "core", since = "1.6.0")]
3613 fn is_sign_positive(self) -> bool;
3614 /// Returns `true` if `self` is negative, including `-0.0` and
3615 /// `Float::neg_infinity()`.
3616 #[stable(feature = "core", since = "1.6.0")]
3617 fn is_sign_negative(self) -> bool;
3619 /// Take the reciprocal (inverse) of a number, `1/x`.
3620 #[stable(feature = "core", since = "1.6.0")]
3621 fn recip(self) -> Self;
3623 /// Raise a number to an integer power.
3625 /// Using this function is generally faster than using `powf`
3626 #[stable(feature = "core", since = "1.6.0")]
3627 fn powi(self, n: i32) -> Self;
3629 /// Convert radians to degrees.
3630 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3631 fn to_degrees(self) -> Self;
3632 /// Convert degrees to radians.
3633 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3634 fn to_radians(self) -> Self;
3636 /// Returns the maximum of the two numbers.
3637 #[stable(feature = "core_float_min_max", since="1.20.0")]
3638 fn max(self, other: Self) -> Self;
3639 /// Returns the minimum of the two numbers.
3640 #[stable(feature = "core_float_min_max", since="1.20.0")]
3641 fn min(self, other: Self) -> Self;
3643 /// Raw transmutation to integer.
3644 #[stable(feature = "core_float_bits", since="1.25.0")]
3645 fn to_bits(self) -> Self::Bits;
3646 /// Raw transmutation from integer.
3647 #[stable(feature = "core_float_bits", since="1.25.0")]
3648 fn from_bits(v: Self::Bits) -> Self;
3651 macro_rules! from_str_radix_int_impl {
3653 #[stable(feature = "rust1", since = "1.0.0")]
3654 impl FromStr for $t {
3655 type Err = ParseIntError;
3656 fn from_str(src: &str) -> Result<Self, ParseIntError> {
3657 from_str_radix(src, 10)
3662 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
3664 /// The error type returned when a checked integral type conversion fails.
3665 #[unstable(feature = "try_from", issue = "33417")]
3666 #[derive(Debug, Copy, Clone)]
3667 pub struct TryFromIntError(());
3669 impl TryFromIntError {
3670 #[unstable(feature = "int_error_internals",
3671 reason = "available through Error trait and this method should \
3672 not be exposed publicly",
3675 pub fn __description(&self) -> &str {
3676 "out of range integral type conversion attempted"
3680 #[unstable(feature = "try_from", issue = "33417")]
3681 impl fmt::Display for TryFromIntError {
3682 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3683 self.__description().fmt(fmt)
3687 #[unstable(feature = "try_from", issue = "33417")]
3688 impl From<!> for TryFromIntError {
3689 fn from(never: !) -> TryFromIntError {
3694 // no possible bounds violation
3695 macro_rules! try_from_unbounded {
3696 ($source:ty, $($target:ty),*) => {$(
3697 #[unstable(feature = "try_from", issue = "33417")]
3698 impl TryFrom<$source> for $target {
3702 fn try_from(value: $source) -> Result<Self, Self::Error> {
3703 Ok(value as $target)
3709 // only negative bounds
3710 macro_rules! try_from_lower_bounded {
3711 ($source:ty, $($target:ty),*) => {$(
3712 #[unstable(feature = "try_from", issue = "33417")]
3713 impl TryFrom<$source> for $target {
3714 type Error = TryFromIntError;
3717 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3721 Err(TryFromIntError(()))
3728 // unsigned to signed (only positive bound)
3729 macro_rules! try_from_upper_bounded {
3730 ($source:ty, $($target:ty),*) => {$(
3731 #[unstable(feature = "try_from", issue = "33417")]
3732 impl TryFrom<$source> for $target {
3733 type Error = TryFromIntError;
3736 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3737 if u > (<$target>::max_value() as $source) {
3738 Err(TryFromIntError(()))
3748 macro_rules! try_from_both_bounded {
3749 ($source:ty, $($target:ty),*) => {$(
3750 #[unstable(feature = "try_from", issue = "33417")]
3751 impl TryFrom<$source> for $target {
3752 type Error = TryFromIntError;
3755 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3756 let min = <$target>::min_value() as $source;
3757 let max = <$target>::max_value() as $source;
3758 if u < min || u > max {
3759 Err(TryFromIntError(()))
3769 ($mac:ident, $source:ty, $($target:ty),*) => {$(
3770 $mac!($target, $source);
3774 /// intra-sign conversions
3775 try_from_upper_bounded!(u16, u8);
3776 try_from_upper_bounded!(u32, u16, u8);
3777 try_from_upper_bounded!(u64, u32, u16, u8);
3778 try_from_upper_bounded!(u128, u64, u32, u16, u8);
3780 try_from_both_bounded!(i16, i8);
3781 try_from_both_bounded!(i32, i16, i8);
3782 try_from_both_bounded!(i64, i32, i16, i8);
3783 try_from_both_bounded!(i128, i64, i32, i16, i8);
3785 // unsigned-to-signed
3786 try_from_upper_bounded!(u8, i8);
3787 try_from_upper_bounded!(u16, i8, i16);
3788 try_from_upper_bounded!(u32, i8, i16, i32);
3789 try_from_upper_bounded!(u64, i8, i16, i32, i64);
3790 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
3792 // signed-to-unsigned
3793 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
3794 try_from_lower_bounded!(i16, u16, u32, u64, u128);
3795 try_from_lower_bounded!(i32, u32, u64, u128);
3796 try_from_lower_bounded!(i64, u64, u128);
3797 try_from_lower_bounded!(i128, u128);
3798 try_from_both_bounded!(i16, u8);
3799 try_from_both_bounded!(i32, u16, u8);
3800 try_from_both_bounded!(i64, u32, u16, u8);
3801 try_from_both_bounded!(i128, u64, u32, u16, u8);
3804 try_from_upper_bounded!(usize, isize);
3805 try_from_lower_bounded!(isize, usize);
3807 #[cfg(target_pointer_width = "16")]
3808 mod ptr_try_from_impls {
3809 use super::TryFromIntError;
3810 use convert::TryFrom;
3812 try_from_upper_bounded!(usize, u8);
3813 try_from_unbounded!(usize, u16, u32, u64, u128);
3814 try_from_upper_bounded!(usize, i8, i16);
3815 try_from_unbounded!(usize, i32, i64, i128);
3817 try_from_both_bounded!(isize, u8);
3818 try_from_lower_bounded!(isize, u16, u32, u64, u128);
3819 try_from_both_bounded!(isize, i8);
3820 try_from_unbounded!(isize, i16, i32, i64, i128);
3822 rev!(try_from_unbounded, usize, u16);
3823 rev!(try_from_upper_bounded, usize, u32, u64, u128);
3824 rev!(try_from_lower_bounded, usize, i8, i16);
3825 rev!(try_from_both_bounded, usize, i32, i64, i128);
3827 rev!(try_from_unbounded, isize, u8);
3828 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
3829 rev!(try_from_unbounded, isize, i16);
3830 rev!(try_from_both_bounded, isize, i32, i64, i128);
3833 #[cfg(target_pointer_width = "32")]
3834 mod ptr_try_from_impls {
3835 use super::TryFromIntError;
3836 use convert::TryFrom;
3838 try_from_upper_bounded!(usize, u8, u16);
3839 try_from_unbounded!(usize, u32, u64, u128);
3840 try_from_upper_bounded!(usize, i8, i16, i32);
3841 try_from_unbounded!(usize, i64, i128);
3843 try_from_both_bounded!(isize, u8, u16);
3844 try_from_lower_bounded!(isize, u32, u64, u128);
3845 try_from_both_bounded!(isize, i8, i16);
3846 try_from_unbounded!(isize, i32, i64, i128);
3848 rev!(try_from_unbounded, usize, u16, u32);
3849 rev!(try_from_upper_bounded, usize, u64, u128);
3850 rev!(try_from_lower_bounded, usize, i8, i16, i32);
3851 rev!(try_from_both_bounded, usize, i64, i128);
3853 rev!(try_from_unbounded, isize, u8, u16);
3854 rev!(try_from_upper_bounded, isize, u32, u64, u128);
3855 rev!(try_from_unbounded, isize, i16, i32);
3856 rev!(try_from_both_bounded, isize, i64, i128);
3859 #[cfg(target_pointer_width = "64")]
3860 mod ptr_try_from_impls {
3861 use super::TryFromIntError;
3862 use convert::TryFrom;
3864 try_from_upper_bounded!(usize, u8, u16, u32);
3865 try_from_unbounded!(usize, u64, u128);
3866 try_from_upper_bounded!(usize, i8, i16, i32, i64);
3867 try_from_unbounded!(usize, i128);
3869 try_from_both_bounded!(isize, u8, u16, u32);
3870 try_from_lower_bounded!(isize, u64, u128);
3871 try_from_both_bounded!(isize, i8, i16, i32);
3872 try_from_unbounded!(isize, i64, i128);
3874 rev!(try_from_unbounded, usize, u16, u32, u64);
3875 rev!(try_from_upper_bounded, usize, u128);
3876 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
3877 rev!(try_from_both_bounded, usize, i128);
3879 rev!(try_from_unbounded, isize, u8, u16, u32);
3880 rev!(try_from_upper_bounded, isize, u64, u128);
3881 rev!(try_from_unbounded, isize, i16, i32, i64);
3882 rev!(try_from_both_bounded, isize, i128);
3886 trait FromStrRadixHelper: PartialOrd + Copy {
3887 fn min_value() -> Self;
3888 fn max_value() -> Self;
3889 fn from_u32(u: u32) -> Self;
3890 fn checked_mul(&self, other: u32) -> Option<Self>;
3891 fn checked_sub(&self, other: u32) -> Option<Self>;
3892 fn checked_add(&self, other: u32) -> Option<Self>;
3896 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
3898 fn min_value() -> Self { Self::min_value() }
3900 fn max_value() -> Self { Self::max_value() }
3902 fn from_u32(u: u32) -> Self { u as Self }
3904 fn checked_mul(&self, other: u32) -> Option<Self> {
3905 Self::checked_mul(*self, other as Self)
3908 fn checked_sub(&self, other: u32) -> Option<Self> {
3909 Self::checked_sub(*self, other as Self)
3912 fn checked_add(&self, other: u32) -> Option<Self> {
3913 Self::checked_add(*self, other as Self)
3917 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
3919 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
3920 use self::IntErrorKind::*;
3921 use self::ParseIntError as PIE;
3923 assert!(radix >= 2 && radix <= 36,
3924 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
3928 return Err(PIE { kind: Empty });
3931 let is_signed_ty = T::from_u32(0) > T::min_value();
3933 // all valid digits are ascii, so we will just iterate over the utf8 bytes
3934 // and cast them to chars. .to_digit() will safely return None for anything
3935 // other than a valid ascii digit for the given radix, including the first-byte
3936 // of multi-byte sequences
3937 let src = src.as_bytes();
3939 let (is_positive, digits) = match src[0] {
3940 b'+' => (true, &src[1..]),
3941 b'-' if is_signed_ty => (false, &src[1..]),
3945 if digits.is_empty() {
3946 return Err(PIE { kind: Empty });
3949 let mut result = T::from_u32(0);
3951 // The number is positive
3953 let x = match (c as char).to_digit(radix) {
3955 None => return Err(PIE { kind: InvalidDigit }),
3957 result = match result.checked_mul(radix) {
3958 Some(result) => result,
3959 None => return Err(PIE { kind: Overflow }),
3961 result = match result.checked_add(x) {
3962 Some(result) => result,
3963 None => return Err(PIE { kind: Overflow }),
3967 // The number is negative
3969 let x = match (c as char).to_digit(radix) {
3971 None => return Err(PIE { kind: InvalidDigit }),
3973 result = match result.checked_mul(radix) {
3974 Some(result) => result,
3975 None => return Err(PIE { kind: Underflow }),
3977 result = match result.checked_sub(x) {
3978 Some(result) => result,
3979 None => return Err(PIE { kind: Underflow }),
3986 /// An error which can be returned when parsing an integer.
3988 /// This error is used as the error type for the `from_str_radix()` functions
3989 /// on the primitive integer types, such as [`i8::from_str_radix`].
3991 /// # Potential causes
3993 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
3994 /// in the string e.g. when it is obtained from the standard input.
3995 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
3997 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
3998 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
3999 #[derive(Debug, Clone, PartialEq, Eq)]
4000 #[stable(feature = "rust1", since = "1.0.0")]
4001 pub struct ParseIntError {
4005 #[derive(Debug, Clone, PartialEq, Eq)]
4013 impl ParseIntError {
4014 #[unstable(feature = "int_error_internals",
4015 reason = "available through Error trait and this method should \
4016 not be exposed publicly",
4019 pub fn __description(&self) -> &str {
4021 IntErrorKind::Empty => "cannot parse integer from empty string",
4022 IntErrorKind::InvalidDigit => "invalid digit found in string",
4023 IntErrorKind::Overflow => "number too large to fit in target type",
4024 IntErrorKind::Underflow => "number too small to fit in target type",
4029 #[stable(feature = "rust1", since = "1.0.0")]
4030 impl fmt::Display for ParseIntError {
4031 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4032 self.__description().fmt(f)
4036 #[stable(feature = "rust1", since = "1.0.0")]
4037 pub use num::dec2flt::ParseFloatError;
4039 // Conversion traits for primitive integer and float types
4040 // Conversions T -> T are covered by a blanket impl and therefore excluded
4041 // Some conversions from and to usize/isize are not implemented due to portability concerns
4042 macro_rules! impl_from {
4043 ($Small: ty, $Large: ty, #[$attr:meta]) => {
4045 impl From<$Small> for $Large {
4047 fn from(small: $Small) -> $Large {
4054 // Unsigned -> Unsigned
4055 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4056 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4057 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4058 impl_from! { u8, u128, #[unstable(feature = "i128", issue = "35118")] }
4059 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4060 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4061 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4062 impl_from! { u16, u128, #[unstable(feature = "i128", issue = "35118")] }
4063 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4064 impl_from! { u32, u128, #[unstable(feature = "i128", issue = "35118")] }
4065 impl_from! { u64, u128, #[unstable(feature = "i128", issue = "35118")] }
4068 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4069 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4070 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4071 impl_from! { i8, i128, #[unstable(feature = "i128", issue = "35118")] }
4072 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4073 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4074 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4075 impl_from! { i16, i128, #[unstable(feature = "i128", issue = "35118")] }
4076 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4077 impl_from! { i32, i128, #[unstable(feature = "i128", issue = "35118")] }
4078 impl_from! { i64, i128, #[unstable(feature = "i128", issue = "35118")] }
4080 // Unsigned -> Signed
4081 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4082 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4083 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4084 impl_from! { u8, i128, #[unstable(feature = "i128", issue = "35118")] }
4085 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4086 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4087 impl_from! { u16, i128, #[unstable(feature = "i128", issue = "35118")] }
4088 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4089 impl_from! { u32, i128, #[unstable(feature = "i128", issue = "35118")] }
4090 impl_from! { u64, i128, #[unstable(feature = "i128", issue = "35118")] }
4092 // Note: integers can only be represented with full precision in a float if
4093 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4094 // Lossy float conversions are not implemented at this time.
4097 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4098 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4099 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4100 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4101 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4103 // Unsigned -> Float
4104 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4105 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4106 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4107 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4108 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4111 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4113 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4114 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4115 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4116 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4117 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4118 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4119 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4120 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4121 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4124 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4125 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4126 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4129 b'[', b'\\', b']', b'^', b'_',
4130 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4131 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4132 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4133 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4134 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4135 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4136 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4137 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4138 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4139 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4140 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4141 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4142 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4143 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4144 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4145 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4146 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4147 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4148 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4149 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4152 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4153 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4154 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4155 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4156 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4157 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4158 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4159 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4160 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4161 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4162 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4163 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4164 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4167 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4168 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4169 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4172 b'{', b'|', b'}', b'~', 0x7f,
4173 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4174 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4175 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4176 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4177 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4178 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4179 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4180 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4181 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4182 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4183 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4184 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4185 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4186 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4187 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4188 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4191 enum AsciiCharacterClass {
4193 Cw, // control whitespace
4197 Lx, // lowercase hex digit
4199 Ux, // uppercase hex digit
4202 use self::AsciiCharacterClass::*;
4204 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4205 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4206 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4207 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4208 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4209 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4210 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4211 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4212 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4213 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_