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, "", "" }
1641 #[cfg(target_pointer_width = "16")]
1644 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "" }
1647 #[cfg(target_pointer_width = "32")]
1650 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "" }
1653 #[cfg(target_pointer_width = "64")]
1656 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1659 // `Int` + `UnsignedInt` implemented for unsigned integers
1660 macro_rules! uint_impl {
1661 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr) => {
1663 concat!("Returns the smallest value that can be represented by this integer type.
1670 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
1672 #[stable(feature = "rust1", since = "1.0.0")]
1674 pub const fn min_value() -> Self { 0 }
1678 concat!("Returns the largest value that can be represented by this integer type.
1685 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
1686 stringify!($MaxV), ");", $EndFeature, "
1688 #[stable(feature = "rust1", since = "1.0.0")]
1690 pub const fn max_value() -> Self { !0 }
1694 concat!("Converts a string slice in a given base to an integer.
1696 The string is expected to be an optional `+` sign
1698 Leading and trailing whitespace represent an error.
1699 Digits are a subset of these characters, depending on `radix`:
1707 This function panics if `radix` is not in the range from 2 to 36.
1714 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
1717 #[stable(feature = "rust1", since = "1.0.0")]
1718 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1719 from_str_radix(src, radix)
1724 concat!("Returns the number of ones in the binary representation of `self`.
1731 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
1733 assert_eq!(n.count_ones(), 3);", $EndFeature, "
1735 #[stable(feature = "rust1", since = "1.0.0")]
1737 pub fn count_ones(self) -> u32 {
1738 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
1743 concat!("Returns the number of zeros in the binary representation of `self`.
1750 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
1752 #[stable(feature = "rust1", since = "1.0.0")]
1754 pub fn count_zeros(self) -> u32 {
1755 (!self).count_ones()
1760 concat!("Returns the number of leading zeros in the binary representation of `self`.
1767 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
1769 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
1771 #[stable(feature = "rust1", since = "1.0.0")]
1773 pub fn leading_zeros(self) -> u32 {
1774 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
1779 concat!("Returns the number of trailing zeros in the binary representation
1787 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
1789 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
1791 #[stable(feature = "rust1", since = "1.0.0")]
1793 pub fn trailing_zeros(self) -> u32 {
1794 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1795 // emits two conditional moves on x86_64. By promoting the value to
1796 // u16 and setting bit 8, we get better code without any conditional
1798 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1799 // pending, remove this workaround once LLVM generates better code
1803 intrinsics::cttz(self as u16 | 0x100) as u32
1805 intrinsics::cttz(self) as u32
1811 /// Shifts the bits to the left by a specified amount, `n`,
1812 /// wrapping the truncated bits to the end of the resulting integer.
1814 /// Please note this isn't the same operation as `<<`!
1820 /// Please note that this example is shared between integer types.
1821 /// Which explains why `u64` is used here.
1824 /// let n = 0x0123456789ABCDEFu64;
1825 /// let m = 0x3456789ABCDEF012u64;
1827 /// assert_eq!(n.rotate_left(12), m);
1829 #[stable(feature = "rust1", since = "1.0.0")]
1831 pub fn rotate_left(self, n: u32) -> Self {
1832 // Protect against undefined behaviour for over-long bit shifts
1834 (self << n) | (self >> (($BITS - n) % $BITS))
1837 /// Shifts the bits to the right by a specified amount, `n`,
1838 /// wrapping the truncated bits to the beginning of the resulting
1841 /// Please note this isn't the same operation as `>>`!
1847 /// Please note that this example is shared between integer types.
1848 /// Which explains why `u64` is used here.
1851 /// let n = 0x0123456789ABCDEFu64;
1852 /// let m = 0xDEF0123456789ABCu64;
1854 /// assert_eq!(n.rotate_right(12), m);
1856 #[stable(feature = "rust1", since = "1.0.0")]
1858 pub fn rotate_right(self, n: u32) -> Self {
1859 // Protect against undefined behaviour for over-long bit shifts
1861 (self >> n) | (self << (($BITS - n) % $BITS))
1864 /// Reverses the byte order of the integer.
1870 /// Please note that this example is shared between integer types.
1871 /// Which explains why `u16` is used here.
1874 /// let n: u16 = 0b0000000_01010101;
1875 /// assert_eq!(n, 85);
1877 /// let m = n.swap_bytes();
1879 /// assert_eq!(m, 0b01010101_00000000);
1880 /// assert_eq!(m, 21760);
1882 #[stable(feature = "rust1", since = "1.0.0")]
1884 pub fn swap_bytes(self) -> Self {
1885 unsafe { intrinsics::bswap(self as $ActualT) as Self }
1888 /// Reverses the bit pattern of the integer.
1894 /// Please note that this example is shared between integer types.
1895 /// Which explains why `u16` is used here.
1898 /// #![feature(reverse_bits)]
1900 /// let n: u16 = 0b0000000_01010101;
1901 /// assert_eq!(n, 85);
1903 /// let m = n.reverse_bits();
1905 /// assert_eq!(m, 0b10101010_00000000);
1906 /// assert_eq!(m, 43520);
1908 #[unstable(feature = "reverse_bits", issue = "48763")]
1911 pub fn reverse_bits(self) -> Self {
1912 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
1916 concat!("Converts an integer from big endian to the target's endianness.
1918 On big endian this is a no-op. On little endian the bytes are
1926 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1928 if cfg!(target_endian = \"big\") {
1929 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
1931 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
1934 #[stable(feature = "rust1", since = "1.0.0")]
1936 pub fn from_be(x: Self) -> Self {
1937 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1942 concat!("Converts an integer from little endian to the target's endianness.
1944 On little endian this is a no-op. On big endian the bytes are
1952 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1954 if cfg!(target_endian = \"little\") {
1955 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
1957 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
1960 #[stable(feature = "rust1", since = "1.0.0")]
1962 pub fn from_le(x: Self) -> Self {
1963 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1968 concat!("Converts `self` to big endian from the target's endianness.
1970 On big endian this is a no-op. On little endian the bytes are
1978 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1980 if cfg!(target_endian = \"big\") {
1981 assert_eq!(n.to_be(), n)
1983 assert_eq!(n.to_be(), n.swap_bytes())
1986 #[stable(feature = "rust1", since = "1.0.0")]
1988 pub fn to_be(self) -> Self { // or not to be?
1989 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1994 concat!("Converts `self` to little endian from the target's endianness.
1996 On little endian this is a no-op. On big endian the bytes are
2004 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2006 if cfg!(target_endian = \"little\") {
2007 assert_eq!(n.to_le(), n)
2009 assert_eq!(n.to_le(), n.swap_bytes())
2012 #[stable(feature = "rust1", since = "1.0.0")]
2014 pub fn to_le(self) -> Self {
2015 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
2020 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2021 if overflow occurred.
2028 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2029 "Some(", stringify!($SelfT), "::max_value() - 1));
2030 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3),None);", $EndFeature, "
2032 #[stable(feature = "rust1", since = "1.0.0")]
2034 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2035 let (a, b) = self.overflowing_add(rhs);
2036 if b {None} else {Some(a)}
2041 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2042 `None` if overflow occurred.
2049 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2050 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2052 #[stable(feature = "rust1", since = "1.0.0")]
2054 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2055 let (a, b) = self.overflowing_sub(rhs);
2056 if b {None} else {Some(a)}
2061 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2062 `None` if overflow occurred.
2069 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2070 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2072 #[stable(feature = "rust1", since = "1.0.0")]
2074 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2075 let (a, b) = self.overflowing_mul(rhs);
2076 if b {None} else {Some(a)}
2081 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2089 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2090 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2092 #[stable(feature = "rust1", since = "1.0.0")]
2094 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2097 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2103 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2111 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2112 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2114 #[stable(feature = "wrapping", since = "1.7.0")]
2116 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2120 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2126 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2129 Note that negating any positive integer will overflow.
2136 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2137 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2139 #[stable(feature = "wrapping", since = "1.7.0")]
2141 pub fn checked_neg(self) -> Option<Self> {
2142 let (a, b) = self.overflowing_neg();
2143 if b {None} else {Some(a)}
2148 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2149 if `rhs` is larger than or equal to the number of bits in `self`.
2156 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2157 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2159 #[stable(feature = "wrapping", since = "1.7.0")]
2161 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2162 let (a, b) = self.overflowing_shl(rhs);
2163 if b {None} else {Some(a)}
2168 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2169 if `rhs` is larger than or equal to the number of bits in `self`.
2176 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2177 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2179 #[stable(feature = "wrapping", since = "1.7.0")]
2181 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2182 let (a, b) = self.overflowing_shr(rhs);
2183 if b {None} else {Some(a)}
2188 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2196 #![feature(no_panic_pow)]
2197 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2198 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2200 #[unstable(feature = "no_panic_pow", issue = "48320")]
2202 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2203 let mut base = self;
2204 let mut acc: Self = 1;
2208 acc = acc.checked_mul(base)?;
2211 base = base.checked_mul(base)?;
2214 // Deal with the final bit of the exponent separately, since
2215 // squaring the base afterwards is not necessary and may cause a
2216 // needless overflow.
2218 acc = acc.checked_mul(base)?;
2226 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2227 the numeric bounds instead of overflowing.
2234 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2235 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2237 #[stable(feature = "rust1", since = "1.0.0")]
2239 pub fn saturating_add(self, rhs: Self) -> Self {
2240 match self.checked_add(rhs) {
2242 None => Self::max_value(),
2248 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2249 at the numeric bounds instead of overflowing.
2256 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2257 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2259 #[stable(feature = "rust1", since = "1.0.0")]
2261 pub fn saturating_sub(self, rhs: Self) -> Self {
2262 match self.checked_sub(rhs) {
2264 None => Self::min_value(),
2270 concat!("Saturating integer multiplication. Computes `self * rhs`,
2271 saturating at the numeric bounds instead of overflowing.
2278 ", $Feature, "use std::", stringify!($SelfT), ";
2280 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2281 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2282 "::MAX);", $EndFeature, "
2284 #[stable(feature = "wrapping", since = "1.7.0")]
2286 pub fn saturating_mul(self, rhs: Self) -> Self {
2287 self.checked_mul(rhs).unwrap_or(Self::max_value())
2292 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2293 saturating at the numeric bounds instead of overflowing.
2300 #![feature(no_panic_pow)]
2301 ", $Feature, "use std::", stringify!($SelfT), ";
2303 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2304 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2307 #[unstable(feature = "no_panic_pow", issue = "48320")]
2309 pub fn saturating_pow(self, exp: u32) -> Self {
2310 match self.checked_pow(exp) {
2312 None => Self::max_value(),
2318 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2319 wrapping around at the boundary of the type.
2326 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2327 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2330 #[stable(feature = "rust1", since = "1.0.0")]
2332 pub fn wrapping_add(self, rhs: Self) -> Self {
2334 intrinsics::overflowing_add(self, rhs)
2340 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2341 wrapping around at the boundary of the type.
2348 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2349 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2352 #[stable(feature = "rust1", since = "1.0.0")]
2354 pub fn wrapping_sub(self, rhs: Self) -> Self {
2356 intrinsics::overflowing_sub(self, rhs)
2361 /// Wrapping (modular) multiplication. Computes `self *
2362 /// rhs`, wrapping around at the boundary of the type.
2368 /// Please note that this example is shared between integer types.
2369 /// Which explains why `u8` is used here.
2372 /// assert_eq!(10u8.wrapping_mul(12), 120);
2373 /// assert_eq!(25u8.wrapping_mul(12), 44);
2375 #[stable(feature = "rust1", since = "1.0.0")]
2377 pub fn wrapping_mul(self, rhs: Self) -> Self {
2379 intrinsics::overflowing_mul(self, rhs)
2384 concat!("Wrapping (modular) division. Computes `self / rhs`.
2385 Wrapped division on unsigned types is just normal division.
2386 There's no way wrapping could ever happen.
2387 This function exists, so that all operations
2388 are accounted for in the wrapping operations.
2395 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2397 #[stable(feature = "num_wrapping", since = "1.2.0")]
2399 pub fn wrapping_div(self, rhs: Self) -> Self {
2405 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2406 Wrapped remainder calculation on unsigned types is
2407 just the regular remainder calculation.
2408 There's no way wrapping could ever happen.
2409 This function exists, so that all operations
2410 are accounted for in the wrapping operations.
2417 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2419 #[stable(feature = "num_wrapping", since = "1.2.0")]
2421 pub fn wrapping_rem(self, rhs: Self) -> Self {
2426 /// Wrapping (modular) negation. Computes `-self`,
2427 /// wrapping around at the boundary of the type.
2429 /// Since unsigned types do not have negative equivalents
2430 /// all applications of this function will wrap (except for `-0`).
2431 /// For values smaller than the corresponding signed type's maximum
2432 /// the result is the same as casting the corresponding signed value.
2433 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2434 /// `MAX` is the corresponding signed type's maximum.
2440 /// Please note that this example is shared between integer types.
2441 /// Which explains why `i8` is used here.
2444 /// assert_eq!(100i8.wrapping_neg(), -100);
2445 /// assert_eq!((-128i8).wrapping_neg(), -128);
2447 #[stable(feature = "num_wrapping", since = "1.2.0")]
2449 pub fn wrapping_neg(self) -> Self {
2450 self.overflowing_neg().0
2454 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2455 where `mask` removes any high-order bits of `rhs` that
2456 would cause the shift to exceed the bitwidth of the type.
2458 Note that this is *not* the same as a rotate-left; the
2459 RHS of a wrapping shift-left is restricted to the range
2460 of the type, rather than the bits shifted out of the LHS
2461 being returned to the other end. The primitive integer
2462 types all implement a `rotate_left` function, which may
2463 be what you want instead.
2470 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2471 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2473 #[stable(feature = "num_wrapping", since = "1.2.0")]
2475 pub fn wrapping_shl(self, rhs: u32) -> Self {
2477 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
2483 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2484 where `mask` removes any high-order bits of `rhs` that
2485 would cause the shift to exceed the bitwidth of the type.
2487 Note that this is *not* the same as a rotate-right; the
2488 RHS of a wrapping shift-right is restricted to the range
2489 of the type, rather than the bits shifted out of the LHS
2490 being returned to the other end. The primitive integer
2491 types all implement a `rotate_right` function, which may
2492 be what you want instead.
2499 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
2500 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
2502 #[stable(feature = "num_wrapping", since = "1.2.0")]
2504 pub fn wrapping_shr(self, rhs: u32) -> Self {
2506 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
2512 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2513 wrapping around at the boundary of the type.
2520 #![feature(no_panic_pow)]
2521 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
2522 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
2524 #[unstable(feature = "no_panic_pow", issue = "48320")]
2526 pub fn wrapping_pow(self, mut exp: u32) -> Self {
2527 let mut base = self;
2528 let mut acc: Self = 1;
2532 acc = acc.wrapping_mul(base);
2535 base = base.wrapping_mul(base);
2538 // Deal with the final bit of the exponent separately, since
2539 // squaring the base afterwards is not necessary and may cause a
2540 // needless overflow.
2542 acc = acc.wrapping_mul(base);
2550 concat!("Calculates `self` + `rhs`
2552 Returns a tuple of the addition along with a boolean indicating
2553 whether an arithmetic overflow would occur. If an overflow would
2554 have occurred then the wrapped value is returned.
2561 ", $Feature, "use std::", stringify!($SelfT), ";
2563 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
2564 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
2567 #[stable(feature = "wrapping", since = "1.7.0")]
2568 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2569 let (a, b) = unsafe {
2570 intrinsics::add_with_overflow(self as $ActualT,
2578 concat!("Calculates `self` - `rhs`
2580 Returns a tuple of the subtraction along with a boolean indicating
2581 whether an arithmetic overflow would occur. If an overflow would
2582 have occurred then the wrapped value is returned.
2589 ", $Feature, "use std::", stringify!($SelfT), ";
2591 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
2592 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
2596 #[stable(feature = "wrapping", since = "1.7.0")]
2597 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2598 let (a, b) = unsafe {
2599 intrinsics::sub_with_overflow(self as $ActualT,
2606 /// Calculates the multiplication of `self` and `rhs`.
2608 /// Returns a tuple of the multiplication along with a boolean
2609 /// indicating whether an arithmetic overflow would occur. If an
2610 /// overflow would have occurred then the wrapped value is returned.
2616 /// Please note that this example is shared between integer types.
2617 /// Which explains why `u32` is used here.
2620 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2621 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2624 #[stable(feature = "wrapping", since = "1.7.0")]
2625 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2626 let (a, b) = unsafe {
2627 intrinsics::mul_with_overflow(self as $ActualT,
2634 concat!("Calculates the divisor when `self` is divided by `rhs`.
2636 Returns a tuple of the divisor along with a boolean indicating
2637 whether an arithmetic overflow would occur. Note that for unsigned
2638 integers overflow never occurs, so the second value is always
2643 This function will panic if `rhs` is 0.
2650 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
2653 #[stable(feature = "wrapping", since = "1.7.0")]
2654 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2660 concat!("Calculates the remainder when `self` is divided by `rhs`.
2662 Returns a tuple of the remainder after dividing along with a boolean
2663 indicating whether an arithmetic overflow would occur. Note that for
2664 unsigned integers overflow never occurs, so the second value is
2669 This function will panic if `rhs` is 0.
2676 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
2679 #[stable(feature = "wrapping", since = "1.7.0")]
2680 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2686 concat!("Negates self in an overflowing fashion.
2688 Returns `!self + 1` using wrapping operations to return the value
2689 that represents the negation of this unsigned value. Note that for
2690 positive unsigned values overflow always occurs, but negating 0 does
2698 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
2699 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
2700 ", true));", $EndFeature, "
2703 #[stable(feature = "wrapping", since = "1.7.0")]
2704 pub fn overflowing_neg(self) -> (Self, bool) {
2705 ((!self).wrapping_add(1), self != 0)
2710 concat!("Shifts self left by `rhs` bits.
2712 Returns a tuple of the shifted version of self along with a boolean
2713 indicating whether the shift value was larger than or equal to the
2714 number of bits. If the shift value is too large, then value is
2715 masked (N-1) where N is the number of bits, and this value is then
2716 used to perform the shift.
2723 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
2724 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
2727 #[stable(feature = "wrapping", since = "1.7.0")]
2728 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2729 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
2734 concat!("Shifts self right by `rhs` bits.
2736 Returns a tuple of the shifted version of self along with a boolean
2737 indicating whether the shift value was larger than or equal to the
2738 number of bits. If the shift value is too large, then value is
2739 masked (N-1) where N is the number of bits, and this value is then
2740 used to perform the shift.
2747 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
2748 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
2751 #[stable(feature = "wrapping", since = "1.7.0")]
2752 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2753 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
2758 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2760 Returns a tuple of the exponentiation along with a bool indicating
2761 whether an overflow happened.
2768 #![feature(no_panic_pow)]
2769 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
2770 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
2772 #[unstable(feature = "no_panic_pow", issue = "48320")]
2774 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
2775 let mut base = self;
2776 let mut acc: Self = 1;
2777 let mut overflown = false;
2778 // Scratch space for storing results of overflowing_mul.
2783 r = acc.overflowing_mul(base);
2788 r = base.overflowing_mul(base);
2793 // Deal with the final bit of the exponent separately, since
2794 // squaring the base afterwards is not necessary and may cause a
2795 // needless overflow.
2797 r = acc.overflowing_mul(base);
2807 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2814 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
2816 #[stable(feature = "rust1", since = "1.0.0")]
2818 #[rustc_inherit_overflow_checks]
2819 pub fn pow(self, mut exp: u32) -> Self {
2820 let mut base = self;
2831 // Deal with the final bit of the exponent separately, since
2832 // squaring the base afterwards is not necessary and may cause a
2833 // needless overflow.
2843 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
2850 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
2851 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
2853 #[stable(feature = "rust1", since = "1.0.0")]
2855 pub fn is_power_of_two(self) -> bool {
2856 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2860 // Returns one less than next power of two.
2861 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2863 // 8u8.one_less_than_next_power_of_two() == 7
2864 // 6u8.one_less_than_next_power_of_two() == 7
2866 // This method cannot overflow, as in the `next_power_of_two`
2867 // overflow cases it instead ends up returning the maximum value
2868 // of the type, and can return 0 for 0.
2870 fn one_less_than_next_power_of_two(self) -> Self {
2871 if self <= 1 { return 0; }
2873 // Because `p > 0`, it cannot consist entirely of leading zeros.
2874 // That means the shift is always in-bounds, and some processors
2875 // (such as intel pre-haswell) have more efficient ctlz
2876 // intrinsics when the argument is non-zero.
2878 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2879 <$SelfT>::max_value() >> z
2883 concat!("Returns the smallest power of two greater than or equal to `self`.
2885 When return value overflows (i.e. `self > (1 << (N-1))` for type
2886 `uN`), it panics in debug mode and return value is wrapped to 0 in
2887 release mode (the only situation in which method can return 0).
2894 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
2895 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
2897 #[stable(feature = "rust1", since = "1.0.0")]
2899 pub fn next_power_of_two(self) -> Self {
2900 // Call the trait to get overflow checks
2901 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
2906 concat!("Returns the smallest power of two greater than or equal to `n`. If
2907 the next power of two is greater than the type's maximum value,
2908 `None` is returned, otherwise the power of two is wrapped in `Some`.
2915 ", $Feature, "assert_eq!(2", stringify!($SelfT),
2916 ".checked_next_power_of_two(), Some(2));
2917 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
2918 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
2921 #[stable(feature = "rust1", since = "1.0.0")]
2922 pub fn checked_next_power_of_two(self) -> Option<Self> {
2923 self.one_less_than_next_power_of_two().checked_add(1)
2931 uint_impl! { u8, u8, 8, 255, "", "" }
2934 /// Checks if the value is within the ASCII range.
2939 /// let ascii = 97u8;
2940 /// let non_ascii = 150u8;
2942 /// assert!(ascii.is_ascii());
2943 /// assert!(!non_ascii.is_ascii());
2945 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2947 pub fn is_ascii(&self) -> bool {
2951 /// Makes a copy of the value in its ASCII upper case equivalent.
2953 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2954 /// but non-ASCII letters are unchanged.
2956 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
2961 /// let lowercase_a = 97u8;
2963 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
2966 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
2967 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2969 pub fn to_ascii_uppercase(&self) -> u8 {
2970 ASCII_UPPERCASE_MAP[*self as usize]
2973 /// Makes a copy of the value in its ASCII lower case equivalent.
2975 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2976 /// but non-ASCII letters are unchanged.
2978 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
2983 /// let uppercase_a = 65u8;
2985 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
2988 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
2989 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2991 pub fn to_ascii_lowercase(&self) -> u8 {
2992 ASCII_LOWERCASE_MAP[*self as usize]
2995 /// Checks that two values are an ASCII case-insensitive match.
2997 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3002 /// let lowercase_a = 97u8;
3003 /// let uppercase_a = 65u8;
3005 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3007 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3009 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3010 self.to_ascii_lowercase() == other.to_ascii_lowercase()
3013 /// Converts this value to its ASCII upper case equivalent in-place.
3015 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3016 /// but non-ASCII letters are unchanged.
3018 /// To return a new uppercased value without modifying the existing one, use
3019 /// [`to_ascii_uppercase`].
3024 /// let mut byte = b'a';
3026 /// byte.make_ascii_uppercase();
3028 /// assert_eq!(b'A', byte);
3031 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3032 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3034 pub fn make_ascii_uppercase(&mut self) {
3035 *self = self.to_ascii_uppercase();
3038 /// Converts this value to its ASCII lower case equivalent in-place.
3040 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3041 /// but non-ASCII letters are unchanged.
3043 /// To return a new lowercased value without modifying the existing one, use
3044 /// [`to_ascii_lowercase`].
3049 /// let mut byte = b'A';
3051 /// byte.make_ascii_lowercase();
3053 /// assert_eq!(b'a', byte);
3056 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3057 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3059 pub fn make_ascii_lowercase(&mut self) {
3060 *self = self.to_ascii_lowercase();
3063 /// Checks if the value is an ASCII alphabetic character:
3065 /// - U+0041 'A' ... U+005A 'Z', or
3066 /// - U+0061 'a' ... U+007A 'z'.
3071 /// #![feature(ascii_ctype)]
3073 /// let uppercase_a = b'A';
3074 /// let uppercase_g = b'G';
3077 /// let zero = b'0';
3078 /// let percent = b'%';
3079 /// let space = b' ';
3081 /// let esc = 0x1b_u8;
3083 /// assert!(uppercase_a.is_ascii_alphabetic());
3084 /// assert!(uppercase_g.is_ascii_alphabetic());
3085 /// assert!(a.is_ascii_alphabetic());
3086 /// assert!(g.is_ascii_alphabetic());
3087 /// assert!(!zero.is_ascii_alphabetic());
3088 /// assert!(!percent.is_ascii_alphabetic());
3089 /// assert!(!space.is_ascii_alphabetic());
3090 /// assert!(!lf.is_ascii_alphabetic());
3091 /// assert!(!esc.is_ascii_alphabetic());
3093 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3095 pub fn is_ascii_alphabetic(&self) -> bool {
3096 if *self >= 0x80 { return false; }
3097 match ASCII_CHARACTER_CLASS[*self as usize] {
3098 L | Lx | U | Ux => true,
3103 /// Checks if the value is an ASCII uppercase character:
3104 /// U+0041 'A' ... U+005A 'Z'.
3109 /// #![feature(ascii_ctype)]
3111 /// let uppercase_a = b'A';
3112 /// let uppercase_g = b'G';
3115 /// let zero = b'0';
3116 /// let percent = b'%';
3117 /// let space = b' ';
3119 /// let esc = 0x1b_u8;
3121 /// assert!(uppercase_a.is_ascii_uppercase());
3122 /// assert!(uppercase_g.is_ascii_uppercase());
3123 /// assert!(!a.is_ascii_uppercase());
3124 /// assert!(!g.is_ascii_uppercase());
3125 /// assert!(!zero.is_ascii_uppercase());
3126 /// assert!(!percent.is_ascii_uppercase());
3127 /// assert!(!space.is_ascii_uppercase());
3128 /// assert!(!lf.is_ascii_uppercase());
3129 /// assert!(!esc.is_ascii_uppercase());
3131 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3133 pub fn is_ascii_uppercase(&self) -> bool {
3134 if *self >= 0x80 { return false }
3135 match ASCII_CHARACTER_CLASS[*self as usize] {
3141 /// Checks if the value is an ASCII lowercase character:
3142 /// U+0061 'a' ... U+007A 'z'.
3147 /// #![feature(ascii_ctype)]
3149 /// let uppercase_a = b'A';
3150 /// let uppercase_g = b'G';
3153 /// let zero = b'0';
3154 /// let percent = b'%';
3155 /// let space = b' ';
3157 /// let esc = 0x1b_u8;
3159 /// assert!(!uppercase_a.is_ascii_lowercase());
3160 /// assert!(!uppercase_g.is_ascii_lowercase());
3161 /// assert!(a.is_ascii_lowercase());
3162 /// assert!(g.is_ascii_lowercase());
3163 /// assert!(!zero.is_ascii_lowercase());
3164 /// assert!(!percent.is_ascii_lowercase());
3165 /// assert!(!space.is_ascii_lowercase());
3166 /// assert!(!lf.is_ascii_lowercase());
3167 /// assert!(!esc.is_ascii_lowercase());
3169 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3171 pub fn is_ascii_lowercase(&self) -> bool {
3172 if *self >= 0x80 { return false }
3173 match ASCII_CHARACTER_CLASS[*self as usize] {
3179 /// Checks if the value is an ASCII alphanumeric character:
3181 /// - U+0041 'A' ... U+005A 'Z', or
3182 /// - U+0061 'a' ... U+007A 'z', or
3183 /// - U+0030 '0' ... U+0039 '9'.
3188 /// #![feature(ascii_ctype)]
3190 /// let uppercase_a = b'A';
3191 /// let uppercase_g = b'G';
3194 /// let zero = b'0';
3195 /// let percent = b'%';
3196 /// let space = b' ';
3198 /// let esc = 0x1b_u8;
3200 /// assert!(uppercase_a.is_ascii_alphanumeric());
3201 /// assert!(uppercase_g.is_ascii_alphanumeric());
3202 /// assert!(a.is_ascii_alphanumeric());
3203 /// assert!(g.is_ascii_alphanumeric());
3204 /// assert!(zero.is_ascii_alphanumeric());
3205 /// assert!(!percent.is_ascii_alphanumeric());
3206 /// assert!(!space.is_ascii_alphanumeric());
3207 /// assert!(!lf.is_ascii_alphanumeric());
3208 /// assert!(!esc.is_ascii_alphanumeric());
3210 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3212 pub fn is_ascii_alphanumeric(&self) -> bool {
3213 if *self >= 0x80 { return false }
3214 match ASCII_CHARACTER_CLASS[*self as usize] {
3215 D | L | Lx | U | Ux => true,
3220 /// Checks if the value is an ASCII decimal digit:
3221 /// U+0030 '0' ... U+0039 '9'.
3226 /// #![feature(ascii_ctype)]
3228 /// let uppercase_a = b'A';
3229 /// let uppercase_g = b'G';
3232 /// let zero = b'0';
3233 /// let percent = b'%';
3234 /// let space = b' ';
3236 /// let esc = 0x1b_u8;
3238 /// assert!(!uppercase_a.is_ascii_digit());
3239 /// assert!(!uppercase_g.is_ascii_digit());
3240 /// assert!(!a.is_ascii_digit());
3241 /// assert!(!g.is_ascii_digit());
3242 /// assert!(zero.is_ascii_digit());
3243 /// assert!(!percent.is_ascii_digit());
3244 /// assert!(!space.is_ascii_digit());
3245 /// assert!(!lf.is_ascii_digit());
3246 /// assert!(!esc.is_ascii_digit());
3248 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3250 pub fn is_ascii_digit(&self) -> bool {
3251 if *self >= 0x80 { return false }
3252 match ASCII_CHARACTER_CLASS[*self as usize] {
3258 /// Checks if the value is an ASCII hexadecimal digit:
3260 /// - U+0030 '0' ... U+0039 '9', or
3261 /// - U+0041 'A' ... U+0046 'F', or
3262 /// - U+0061 'a' ... U+0066 'f'.
3267 /// #![feature(ascii_ctype)]
3269 /// let uppercase_a = b'A';
3270 /// let uppercase_g = b'G';
3273 /// let zero = b'0';
3274 /// let percent = b'%';
3275 /// let space = b' ';
3277 /// let esc = 0x1b_u8;
3279 /// assert!(uppercase_a.is_ascii_hexdigit());
3280 /// assert!(!uppercase_g.is_ascii_hexdigit());
3281 /// assert!(a.is_ascii_hexdigit());
3282 /// assert!(!g.is_ascii_hexdigit());
3283 /// assert!(zero.is_ascii_hexdigit());
3284 /// assert!(!percent.is_ascii_hexdigit());
3285 /// assert!(!space.is_ascii_hexdigit());
3286 /// assert!(!lf.is_ascii_hexdigit());
3287 /// assert!(!esc.is_ascii_hexdigit());
3289 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3291 pub fn is_ascii_hexdigit(&self) -> bool {
3292 if *self >= 0x80 { return false }
3293 match ASCII_CHARACTER_CLASS[*self as usize] {
3294 D | Lx | Ux => true,
3299 /// Checks if the value is an ASCII punctuation character:
3301 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
3302 /// - U+003A ... U+0040 `: ; < = > ? @`, or
3303 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
3304 /// - U+007B ... U+007E `{ | } ~`
3309 /// #![feature(ascii_ctype)]
3311 /// let uppercase_a = b'A';
3312 /// let uppercase_g = b'G';
3315 /// let zero = b'0';
3316 /// let percent = b'%';
3317 /// let space = b' ';
3319 /// let esc = 0x1b_u8;
3321 /// assert!(!uppercase_a.is_ascii_punctuation());
3322 /// assert!(!uppercase_g.is_ascii_punctuation());
3323 /// assert!(!a.is_ascii_punctuation());
3324 /// assert!(!g.is_ascii_punctuation());
3325 /// assert!(!zero.is_ascii_punctuation());
3326 /// assert!(percent.is_ascii_punctuation());
3327 /// assert!(!space.is_ascii_punctuation());
3328 /// assert!(!lf.is_ascii_punctuation());
3329 /// assert!(!esc.is_ascii_punctuation());
3331 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3333 pub fn is_ascii_punctuation(&self) -> bool {
3334 if *self >= 0x80 { return false }
3335 match ASCII_CHARACTER_CLASS[*self as usize] {
3341 /// Checks if the value is an ASCII graphic character:
3342 /// U+0021 '!' ... U+007E '~'.
3347 /// #![feature(ascii_ctype)]
3349 /// let uppercase_a = b'A';
3350 /// let uppercase_g = b'G';
3353 /// let zero = b'0';
3354 /// let percent = b'%';
3355 /// let space = b' ';
3357 /// let esc = 0x1b_u8;
3359 /// assert!(uppercase_a.is_ascii_graphic());
3360 /// assert!(uppercase_g.is_ascii_graphic());
3361 /// assert!(a.is_ascii_graphic());
3362 /// assert!(g.is_ascii_graphic());
3363 /// assert!(zero.is_ascii_graphic());
3364 /// assert!(percent.is_ascii_graphic());
3365 /// assert!(!space.is_ascii_graphic());
3366 /// assert!(!lf.is_ascii_graphic());
3367 /// assert!(!esc.is_ascii_graphic());
3369 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3371 pub fn is_ascii_graphic(&self) -> bool {
3372 if *self >= 0x80 { return false; }
3373 match ASCII_CHARACTER_CLASS[*self as usize] {
3374 Ux | U | Lx | L | D | P => true,
3379 /// Checks if the value is an ASCII whitespace character:
3380 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
3381 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
3383 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
3384 /// whitespace][infra-aw]. There are several other definitions in
3385 /// wide use. For instance, [the POSIX locale][pct] includes
3386 /// U+000B VERTICAL TAB as well as all the above characters,
3387 /// but—from the very same specification—[the default rule for
3388 /// "field splitting" in the Bourne shell][bfs] considers *only*
3389 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
3391 /// If you are writing a program that will process an existing
3392 /// file format, check what that format's definition of whitespace is
3393 /// before using this function.
3395 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
3396 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
3397 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
3402 /// #![feature(ascii_ctype)]
3404 /// let uppercase_a = b'A';
3405 /// let uppercase_g = b'G';
3408 /// let zero = b'0';
3409 /// let percent = b'%';
3410 /// let space = b' ';
3412 /// let esc = 0x1b_u8;
3414 /// assert!(!uppercase_a.is_ascii_whitespace());
3415 /// assert!(!uppercase_g.is_ascii_whitespace());
3416 /// assert!(!a.is_ascii_whitespace());
3417 /// assert!(!g.is_ascii_whitespace());
3418 /// assert!(!zero.is_ascii_whitespace());
3419 /// assert!(!percent.is_ascii_whitespace());
3420 /// assert!(space.is_ascii_whitespace());
3421 /// assert!(lf.is_ascii_whitespace());
3422 /// assert!(!esc.is_ascii_whitespace());
3424 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3426 pub fn is_ascii_whitespace(&self) -> bool {
3427 if *self >= 0x80 { return false; }
3428 match ASCII_CHARACTER_CLASS[*self as usize] {
3434 /// Checks if the value is an ASCII control character:
3435 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
3436 /// Note that most ASCII whitespace characters are control
3437 /// characters, but SPACE is not.
3442 /// #![feature(ascii_ctype)]
3444 /// let uppercase_a = b'A';
3445 /// let uppercase_g = b'G';
3448 /// let zero = b'0';
3449 /// let percent = b'%';
3450 /// let space = b' ';
3452 /// let esc = 0x1b_u8;
3454 /// assert!(!uppercase_a.is_ascii_control());
3455 /// assert!(!uppercase_g.is_ascii_control());
3456 /// assert!(!a.is_ascii_control());
3457 /// assert!(!g.is_ascii_control());
3458 /// assert!(!zero.is_ascii_control());
3459 /// assert!(!percent.is_ascii_control());
3460 /// assert!(!space.is_ascii_control());
3461 /// assert!(lf.is_ascii_control());
3462 /// assert!(esc.is_ascii_control());
3464 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3466 pub fn is_ascii_control(&self) -> bool {
3467 if *self >= 0x80 { return false; }
3468 match ASCII_CHARACTER_CLASS[*self as usize] {
3477 uint_impl! { u16, u16, 16, 65535, "", "" }
3482 uint_impl! { u32, u32, 32, 4294967295, "", "" }
3487 uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
3492 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "" }
3495 #[cfg(target_pointer_width = "16")]
3498 uint_impl! { usize, u16, 16, 65536, "", "" }
3500 #[cfg(target_pointer_width = "32")]
3503 uint_impl! { usize, u32, 32, 4294967295, "", "" }
3506 #[cfg(target_pointer_width = "64")]
3509 uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
3512 /// A classification of floating point numbers.
3514 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
3515 /// their documentation for more.
3517 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
3518 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
3523 /// use std::num::FpCategory;
3526 /// let num = 12.4_f32;
3527 /// let inf = f32::INFINITY;
3528 /// let zero = 0f32;
3529 /// let sub: f32 = 1.1754942e-38;
3530 /// let nan = f32::NAN;
3532 /// assert_eq!(num.classify(), FpCategory::Normal);
3533 /// assert_eq!(inf.classify(), FpCategory::Infinite);
3534 /// assert_eq!(zero.classify(), FpCategory::Zero);
3535 /// assert_eq!(nan.classify(), FpCategory::Nan);
3536 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
3538 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
3539 #[stable(feature = "rust1", since = "1.0.0")]
3540 pub enum FpCategory {
3541 /// "Not a Number", often obtained by dividing by zero.
3542 #[stable(feature = "rust1", since = "1.0.0")]
3545 /// Positive or negative infinity.
3546 #[stable(feature = "rust1", since = "1.0.0")]
3549 /// Positive or negative zero.
3550 #[stable(feature = "rust1", since = "1.0.0")]
3553 /// De-normalized floating point representation (less precise than `Normal`).
3554 #[stable(feature = "rust1", since = "1.0.0")]
3557 /// A regular floating point number.
3558 #[stable(feature = "rust1", since = "1.0.0")]
3562 /// A built-in floating point number.
3564 #[unstable(feature = "core_float",
3565 reason = "stable interface is via `impl f{32,64}` in later crates",
3567 pub trait Float: Sized {
3568 /// Type used by `to_bits` and `from_bits`.
3569 #[stable(feature = "core_float_bits", since = "1.25.0")]
3572 /// Returns `true` if this value is NaN and false otherwise.
3573 #[stable(feature = "core", since = "1.6.0")]
3574 fn is_nan(self) -> bool;
3575 /// Returns `true` if this value is positive infinity or negative infinity and
3576 /// false otherwise.
3577 #[stable(feature = "core", since = "1.6.0")]
3578 fn is_infinite(self) -> bool;
3579 /// Returns `true` if this number is neither infinite nor NaN.
3580 #[stable(feature = "core", since = "1.6.0")]
3581 fn is_finite(self) -> bool;
3582 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
3583 #[stable(feature = "core", since = "1.6.0")]
3584 fn is_normal(self) -> bool;
3585 /// Returns the category that this number falls into.
3586 #[stable(feature = "core", since = "1.6.0")]
3587 fn classify(self) -> FpCategory;
3589 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
3590 /// number is `Float::nan()`.
3591 #[stable(feature = "core", since = "1.6.0")]
3592 fn abs(self) -> Self;
3593 /// Returns a number that represents the sign of `self`.
3595 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
3596 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
3597 /// - `Float::nan()` if the number is `Float::nan()`
3598 #[stable(feature = "core", since = "1.6.0")]
3599 fn signum(self) -> Self;
3601 /// Returns `true` if `self` is positive, including `+0.0` and
3602 /// `Float::infinity()`.
3603 #[stable(feature = "core", since = "1.6.0")]
3604 fn is_sign_positive(self) -> bool;
3605 /// Returns `true` if `self` is negative, including `-0.0` and
3606 /// `Float::neg_infinity()`.
3607 #[stable(feature = "core", since = "1.6.0")]
3608 fn is_sign_negative(self) -> bool;
3610 /// Take the reciprocal (inverse) of a number, `1/x`.
3611 #[stable(feature = "core", since = "1.6.0")]
3612 fn recip(self) -> Self;
3614 /// Raise a number to an integer power.
3616 /// Using this function is generally faster than using `powf`
3617 #[stable(feature = "core", since = "1.6.0")]
3618 fn powi(self, n: i32) -> Self;
3620 /// Convert radians to degrees.
3621 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3622 fn to_degrees(self) -> Self;
3623 /// Convert degrees to radians.
3624 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3625 fn to_radians(self) -> Self;
3627 /// Returns the maximum of the two numbers.
3628 #[stable(feature = "core_float_min_max", since="1.20.0")]
3629 fn max(self, other: Self) -> Self;
3630 /// Returns the minimum of the two numbers.
3631 #[stable(feature = "core_float_min_max", since="1.20.0")]
3632 fn min(self, other: Self) -> Self;
3634 /// Raw transmutation to integer.
3635 #[stable(feature = "core_float_bits", since="1.25.0")]
3636 fn to_bits(self) -> Self::Bits;
3637 /// Raw transmutation from integer.
3638 #[stable(feature = "core_float_bits", since="1.25.0")]
3639 fn from_bits(v: Self::Bits) -> Self;
3642 macro_rules! from_str_radix_int_impl {
3644 #[stable(feature = "rust1", since = "1.0.0")]
3645 impl FromStr for $t {
3646 type Err = ParseIntError;
3647 fn from_str(src: &str) -> Result<Self, ParseIntError> {
3648 from_str_radix(src, 10)
3653 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
3655 /// The error type returned when a checked integral type conversion fails.
3656 #[unstable(feature = "try_from", issue = "33417")]
3657 #[derive(Debug, Copy, Clone)]
3658 pub struct TryFromIntError(());
3660 impl TryFromIntError {
3661 #[unstable(feature = "int_error_internals",
3662 reason = "available through Error trait and this method should \
3663 not be exposed publicly",
3666 pub fn __description(&self) -> &str {
3667 "out of range integral type conversion attempted"
3671 #[unstable(feature = "try_from", issue = "33417")]
3672 impl fmt::Display for TryFromIntError {
3673 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3674 self.__description().fmt(fmt)
3678 #[unstable(feature = "try_from", issue = "33417")]
3679 impl From<!> for TryFromIntError {
3680 fn from(never: !) -> TryFromIntError {
3685 // no possible bounds violation
3686 macro_rules! try_from_unbounded {
3687 ($source:ty, $($target:ty),*) => {$(
3688 #[unstable(feature = "try_from", issue = "33417")]
3689 impl TryFrom<$source> for $target {
3693 fn try_from(value: $source) -> Result<Self, Self::Error> {
3694 Ok(value as $target)
3700 // only negative bounds
3701 macro_rules! try_from_lower_bounded {
3702 ($source:ty, $($target:ty),*) => {$(
3703 #[unstable(feature = "try_from", issue = "33417")]
3704 impl TryFrom<$source> for $target {
3705 type Error = TryFromIntError;
3708 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3712 Err(TryFromIntError(()))
3719 // unsigned to signed (only positive bound)
3720 macro_rules! try_from_upper_bounded {
3721 ($source:ty, $($target:ty),*) => {$(
3722 #[unstable(feature = "try_from", issue = "33417")]
3723 impl TryFrom<$source> for $target {
3724 type Error = TryFromIntError;
3727 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3728 if u > (<$target>::max_value() as $source) {
3729 Err(TryFromIntError(()))
3739 macro_rules! try_from_both_bounded {
3740 ($source:ty, $($target:ty),*) => {$(
3741 #[unstable(feature = "try_from", issue = "33417")]
3742 impl TryFrom<$source> for $target {
3743 type Error = TryFromIntError;
3746 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3747 let min = <$target>::min_value() as $source;
3748 let max = <$target>::max_value() as $source;
3749 if u < min || u > max {
3750 Err(TryFromIntError(()))
3760 ($mac:ident, $source:ty, $($target:ty),*) => {$(
3761 $mac!($target, $source);
3765 /// intra-sign conversions
3766 try_from_upper_bounded!(u16, u8);
3767 try_from_upper_bounded!(u32, u16, u8);
3768 try_from_upper_bounded!(u64, u32, u16, u8);
3769 try_from_upper_bounded!(u128, u64, u32, u16, u8);
3771 try_from_both_bounded!(i16, i8);
3772 try_from_both_bounded!(i32, i16, i8);
3773 try_from_both_bounded!(i64, i32, i16, i8);
3774 try_from_both_bounded!(i128, i64, i32, i16, i8);
3776 // unsigned-to-signed
3777 try_from_upper_bounded!(u8, i8);
3778 try_from_upper_bounded!(u16, i8, i16);
3779 try_from_upper_bounded!(u32, i8, i16, i32);
3780 try_from_upper_bounded!(u64, i8, i16, i32, i64);
3781 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
3783 // signed-to-unsigned
3784 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
3785 try_from_lower_bounded!(i16, u16, u32, u64, u128);
3786 try_from_lower_bounded!(i32, u32, u64, u128);
3787 try_from_lower_bounded!(i64, u64, u128);
3788 try_from_lower_bounded!(i128, u128);
3789 try_from_both_bounded!(i16, u8);
3790 try_from_both_bounded!(i32, u16, u8);
3791 try_from_both_bounded!(i64, u32, u16, u8);
3792 try_from_both_bounded!(i128, u64, u32, u16, u8);
3795 try_from_upper_bounded!(usize, isize);
3796 try_from_lower_bounded!(isize, usize);
3798 #[cfg(target_pointer_width = "16")]
3799 mod ptr_try_from_impls {
3800 use super::TryFromIntError;
3801 use convert::TryFrom;
3803 try_from_upper_bounded!(usize, u8);
3804 try_from_unbounded!(usize, u16, u32, u64, u128);
3805 try_from_upper_bounded!(usize, i8, i16);
3806 try_from_unbounded!(usize, i32, i64, i128);
3808 try_from_both_bounded!(isize, u8);
3809 try_from_lower_bounded!(isize, u16, u32, u64, u128);
3810 try_from_both_bounded!(isize, i8);
3811 try_from_unbounded!(isize, i16, i32, i64, i128);
3813 rev!(try_from_unbounded, usize, u16);
3814 rev!(try_from_upper_bounded, usize, u32, u64, u128);
3815 rev!(try_from_lower_bounded, usize, i8, i16);
3816 rev!(try_from_both_bounded, usize, i32, i64, i128);
3818 rev!(try_from_unbounded, isize, u8);
3819 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
3820 rev!(try_from_unbounded, isize, i16);
3821 rev!(try_from_both_bounded, isize, i32, i64, i128);
3824 #[cfg(target_pointer_width = "32")]
3825 mod ptr_try_from_impls {
3826 use super::TryFromIntError;
3827 use convert::TryFrom;
3829 try_from_upper_bounded!(usize, u8, u16);
3830 try_from_unbounded!(usize, u32, u64, u128);
3831 try_from_upper_bounded!(usize, i8, i16, i32);
3832 try_from_unbounded!(usize, i64, i128);
3834 try_from_both_bounded!(isize, u8, u16);
3835 try_from_lower_bounded!(isize, u32, u64, u128);
3836 try_from_both_bounded!(isize, i8, i16);
3837 try_from_unbounded!(isize, i32, i64, i128);
3839 rev!(try_from_unbounded, usize, u16, u32);
3840 rev!(try_from_upper_bounded, usize, u64, u128);
3841 rev!(try_from_lower_bounded, usize, i8, i16, i32);
3842 rev!(try_from_both_bounded, usize, i64, i128);
3844 rev!(try_from_unbounded, isize, u8, u16);
3845 rev!(try_from_upper_bounded, isize, u32, u64, u128);
3846 rev!(try_from_unbounded, isize, i16, i32);
3847 rev!(try_from_both_bounded, isize, i64, i128);
3850 #[cfg(target_pointer_width = "64")]
3851 mod ptr_try_from_impls {
3852 use super::TryFromIntError;
3853 use convert::TryFrom;
3855 try_from_upper_bounded!(usize, u8, u16, u32);
3856 try_from_unbounded!(usize, u64, u128);
3857 try_from_upper_bounded!(usize, i8, i16, i32, i64);
3858 try_from_unbounded!(usize, i128);
3860 try_from_both_bounded!(isize, u8, u16, u32);
3861 try_from_lower_bounded!(isize, u64, u128);
3862 try_from_both_bounded!(isize, i8, i16, i32);
3863 try_from_unbounded!(isize, i64, i128);
3865 rev!(try_from_unbounded, usize, u16, u32, u64);
3866 rev!(try_from_upper_bounded, usize, u128);
3867 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
3868 rev!(try_from_both_bounded, usize, i128);
3870 rev!(try_from_unbounded, isize, u8, u16, u32);
3871 rev!(try_from_upper_bounded, isize, u64, u128);
3872 rev!(try_from_unbounded, isize, i16, i32, i64);
3873 rev!(try_from_both_bounded, isize, i128);
3877 trait FromStrRadixHelper: PartialOrd + Copy {
3878 fn min_value() -> Self;
3879 fn max_value() -> Self;
3880 fn from_u32(u: u32) -> Self;
3881 fn checked_mul(&self, other: u32) -> Option<Self>;
3882 fn checked_sub(&self, other: u32) -> Option<Self>;
3883 fn checked_add(&self, other: u32) -> Option<Self>;
3887 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
3889 fn min_value() -> Self { Self::min_value() }
3891 fn max_value() -> Self { Self::max_value() }
3893 fn from_u32(u: u32) -> Self { u as Self }
3895 fn checked_mul(&self, other: u32) -> Option<Self> {
3896 Self::checked_mul(*self, other as Self)
3899 fn checked_sub(&self, other: u32) -> Option<Self> {
3900 Self::checked_sub(*self, other as Self)
3903 fn checked_add(&self, other: u32) -> Option<Self> {
3904 Self::checked_add(*self, other as Self)
3908 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
3910 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
3911 use self::IntErrorKind::*;
3912 use self::ParseIntError as PIE;
3914 assert!(radix >= 2 && radix <= 36,
3915 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
3919 return Err(PIE { kind: Empty });
3922 let is_signed_ty = T::from_u32(0) > T::min_value();
3924 // all valid digits are ascii, so we will just iterate over the utf8 bytes
3925 // and cast them to chars. .to_digit() will safely return None for anything
3926 // other than a valid ascii digit for the given radix, including the first-byte
3927 // of multi-byte sequences
3928 let src = src.as_bytes();
3930 let (is_positive, digits) = match src[0] {
3931 b'+' => (true, &src[1..]),
3932 b'-' if is_signed_ty => (false, &src[1..]),
3936 if digits.is_empty() {
3937 return Err(PIE { kind: Empty });
3940 let mut result = T::from_u32(0);
3942 // The number is positive
3944 let x = match (c as char).to_digit(radix) {
3946 None => return Err(PIE { kind: InvalidDigit }),
3948 result = match result.checked_mul(radix) {
3949 Some(result) => result,
3950 None => return Err(PIE { kind: Overflow }),
3952 result = match result.checked_add(x) {
3953 Some(result) => result,
3954 None => return Err(PIE { kind: Overflow }),
3958 // The number is negative
3960 let x = match (c as char).to_digit(radix) {
3962 None => return Err(PIE { kind: InvalidDigit }),
3964 result = match result.checked_mul(radix) {
3965 Some(result) => result,
3966 None => return Err(PIE { kind: Underflow }),
3968 result = match result.checked_sub(x) {
3969 Some(result) => result,
3970 None => return Err(PIE { kind: Underflow }),
3977 /// An error which can be returned when parsing an integer.
3979 /// This error is used as the error type for the `from_str_radix()` functions
3980 /// on the primitive integer types, such as [`i8::from_str_radix`].
3982 /// # Potential causes
3984 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
3985 /// in the string e.g. when it is obtained from the standard input.
3986 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
3988 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
3989 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
3990 #[derive(Debug, Clone, PartialEq, Eq)]
3991 #[stable(feature = "rust1", since = "1.0.0")]
3992 pub struct ParseIntError {
3996 #[derive(Debug, Clone, PartialEq, Eq)]
4004 impl ParseIntError {
4005 #[unstable(feature = "int_error_internals",
4006 reason = "available through Error trait and this method should \
4007 not be exposed publicly",
4010 pub fn __description(&self) -> &str {
4012 IntErrorKind::Empty => "cannot parse integer from empty string",
4013 IntErrorKind::InvalidDigit => "invalid digit found in string",
4014 IntErrorKind::Overflow => "number too large to fit in target type",
4015 IntErrorKind::Underflow => "number too small to fit in target type",
4020 #[stable(feature = "rust1", since = "1.0.0")]
4021 impl fmt::Display for ParseIntError {
4022 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4023 self.__description().fmt(f)
4027 #[stable(feature = "rust1", since = "1.0.0")]
4028 pub use num::dec2flt::ParseFloatError;
4030 // Conversion traits for primitive integer and float types
4031 // Conversions T -> T are covered by a blanket impl and therefore excluded
4032 // Some conversions from and to usize/isize are not implemented due to portability concerns
4033 macro_rules! impl_from {
4034 ($Small: ty, $Large: ty, #[$attr:meta]) => {
4036 impl From<$Small> for $Large {
4038 fn from(small: $Small) -> $Large {
4045 // Unsigned -> Unsigned
4046 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4047 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4048 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4049 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
4050 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4051 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4052 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4053 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
4054 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4055 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
4056 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
4059 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4060 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4061 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4062 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4063 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4064 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4065 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4066 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4067 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4068 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4069 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4071 // Unsigned -> Signed
4072 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4073 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4074 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4075 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4076 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4077 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4078 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4079 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4080 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4081 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4083 // Note: integers can only be represented with full precision in a float if
4084 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4085 // Lossy float conversions are not implemented at this time.
4088 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4089 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4090 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4091 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4092 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4094 // Unsigned -> Float
4095 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4096 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4097 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4098 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4099 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4102 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4104 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4105 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4106 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4107 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4108 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4109 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4110 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4111 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4112 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4115 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4116 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4117 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4120 b'[', b'\\', b']', b'^', b'_',
4121 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4122 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4123 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4124 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4125 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4126 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4127 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4128 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4129 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4130 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4131 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4132 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4133 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4134 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4135 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4136 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4137 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4138 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4139 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4140 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4143 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4144 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4145 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4146 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4147 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4148 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4149 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4150 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4151 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4152 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4153 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4154 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4155 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4158 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4159 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4160 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4163 b'{', b'|', b'}', b'~', 0x7f,
4164 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4165 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4166 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4167 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4168 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4169 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4170 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4171 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4172 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4173 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4174 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4175 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4176 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4177 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4178 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4179 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4182 enum AsciiCharacterClass {
4184 Cw, // control whitespace
4188 Lx, // lowercase hex digit
4190 Ux, // uppercase hex digit
4193 use self::AsciiCharacterClass::*;
4195 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4196 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4197 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4198 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4199 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4200 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4201 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4202 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4203 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4204 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_