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")]
15 use convert::{Infallible, TryFrom};
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>());
49 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
50 pub struct $Ty(NonZero<$Int>);
53 /// Create a non-zero without checking the value.
57 /// The value must not be zero.
60 pub const unsafe fn new_unchecked(n: $Int) -> Self {
64 /// Create a non-zero if the given value is not zero.
67 pub fn new(n: $Int) -> Option<Self> {
75 /// Returns the value as a primitive type.
78 pub fn get(self) -> $Int {
86 (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
93 #[unstable(feature = "nonzero", issue = "27730")]
94 NonZeroU8(u8); NonZeroI8(i8);
95 NonZeroU16(u16); NonZeroI16(i16);
96 NonZeroU32(u32); NonZeroI32(i32);
97 NonZeroU64(u64); NonZeroI64(i64);
98 NonZeroUsize(usize); NonZeroIsize(isize);
102 // Change this to `#[unstable(feature = "i128", issue = "35118")]`
103 // if other NonZero* integer types are stabilizied before 128-bit integers
104 #[unstable(feature = "nonzero", issue = "27730")]
105 NonZeroU128(u128); NonZeroI128(i128);
108 /// Provides intentionally-wrapped arithmetic on `T`.
110 /// Operations like `+` on `u32` values is intended to never overflow,
111 /// and in some debug configurations overflow is detected and results
112 /// in a panic. While most arithmetic falls into this category, some
113 /// code explicitly expects and relies upon modular arithmetic (e.g.,
116 /// Wrapping arithmetic can be achieved either through methods like
117 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
118 /// all standard arithmetic operations on the underlying value are
119 /// intended to have wrapping semantics.
124 /// use std::num::Wrapping;
126 /// let zero = Wrapping(0u32);
127 /// let one = Wrapping(1u32);
129 /// assert_eq!(std::u32::MAX, (zero - one).0);
131 #[stable(feature = "rust1", since = "1.0.0")]
132 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
133 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
136 #[stable(feature = "rust1", since = "1.0.0")]
137 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
138 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
143 #[stable(feature = "wrapping_display", since = "1.10.0")]
144 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
145 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
151 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
152 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
158 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
159 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
164 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
165 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
166 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
172 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
173 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
180 // All these modules are technically private and only exposed for coretests:
186 macro_rules! doc_comment {
187 ($x:expr, $($tt:tt)*) => {
193 // `Int` + `SignedInt` implemented for signed integers
194 macro_rules! int_impl {
195 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
196 $EndFeature:expr) => {
198 concat!("Returns the smallest value that can be represented by this integer type.
205 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
208 #[stable(feature = "rust1", since = "1.0.0")]
210 pub const fn min_value() -> Self {
211 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
216 concat!("Returns the largest value that can be represented by this integer type.
223 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
226 #[stable(feature = "rust1", since = "1.0.0")]
228 pub const fn max_value() -> Self {
234 concat!("Converts a string slice in a given base to an integer.
236 The string is expected to be an optional `+` or `-` sign followed by digits.
237 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
238 depending on `radix`:
246 This function panics if `radix` is not in the range from 2 to 36.
253 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
256 #[stable(feature = "rust1", since = "1.0.0")]
257 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
258 from_str_radix(src, radix)
263 concat!("Returns the number of ones in the binary representation of `self`.
270 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
272 assert_eq!(n.count_ones(), 1);",
276 #[stable(feature = "rust1", since = "1.0.0")]
278 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
282 concat!("Returns the number of zeros in the binary representation of `self`.
289 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
291 #[stable(feature = "rust1", since = "1.0.0")]
293 pub fn count_zeros(self) -> u32 {
299 concat!("Returns the number of leading zeros in the binary representation of `self`.
306 ", $Feature, "let n = -1", stringify!($SelfT), ";
308 assert_eq!(n.leading_zeros(), 0);",
311 #[stable(feature = "rust1", since = "1.0.0")]
313 pub fn leading_zeros(self) -> u32 {
314 (self as $UnsignedT).leading_zeros()
319 concat!("Returns the number of trailing zeros in the binary representation of `self`.
326 ", $Feature, "let n = -4", stringify!($SelfT), ";
328 assert_eq!(n.trailing_zeros(), 2);",
331 #[stable(feature = "rust1", since = "1.0.0")]
333 pub fn trailing_zeros(self) -> u32 {
334 (self as $UnsignedT).trailing_zeros()
338 /// Shifts the bits to the left by a specified amount, `n`,
339 /// wrapping the truncated bits to the end of the resulting integer.
341 /// Please note this isn't the same operation as `<<`!
345 /// Please note that this example is shared between integer types.
346 /// Which explains why `i64` is used here.
351 /// let n = 0x0123456789ABCDEFi64;
352 /// let m = -0x76543210FEDCBA99i64;
354 /// assert_eq!(n.rotate_left(32), m);
356 #[stable(feature = "rust1", since = "1.0.0")]
358 pub fn rotate_left(self, n: u32) -> Self {
359 (self as $UnsignedT).rotate_left(n) as Self
362 /// Shifts the bits to the right by a specified amount, `n`,
363 /// wrapping the truncated bits to the beginning of the resulting
366 /// Please note this isn't the same operation as `>>`!
370 /// Please note that this example is shared between integer types.
371 /// Which explains why `i64` is used here.
376 /// let n = 0x0123456789ABCDEFi64;
377 /// let m = -0xFEDCBA987654322i64;
379 /// assert_eq!(n.rotate_right(4), m);
381 #[stable(feature = "rust1", since = "1.0.0")]
383 pub fn rotate_right(self, n: u32) -> Self {
384 (self as $UnsignedT).rotate_right(n) as Self
387 /// Reverses the byte order of the integer.
391 /// Please note that this example is shared between integer types.
392 /// Which explains why `i16` is used here.
397 /// let n: i16 = 0b0000000_01010101;
398 /// assert_eq!(n, 85);
400 /// let m = n.swap_bytes();
402 /// assert_eq!(m, 0b01010101_00000000);
403 /// assert_eq!(m, 21760);
405 #[stable(feature = "rust1", since = "1.0.0")]
407 pub fn swap_bytes(self) -> Self {
408 (self as $UnsignedT).swap_bytes() as Self
411 /// Reverses the bit pattern of the integer.
415 /// Please note that this example is shared between integer types.
416 /// Which explains why `i16` is used here.
421 /// #![feature(reverse_bits)]
423 /// let n: i16 = 0b0000000_01010101;
424 /// assert_eq!(n, 85);
426 /// let m = n.reverse_bits();
428 /// assert_eq!(m as u16, 0b10101010_00000000);
429 /// assert_eq!(m, -22016);
431 #[unstable(feature = "reverse_bits", issue = "48763")]
434 pub fn reverse_bits(self) -> Self {
435 (self as $UnsignedT).reverse_bits() as Self
439 concat!("Converts an integer from big endian to the target's endianness.
441 On big endian this is a no-op. On little endian the bytes are swapped.
448 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
450 if cfg!(target_endian = \"big\") {
451 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
453 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
457 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn from_be(x: Self) -> Self {
460 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
465 concat!("Converts an integer from little endian to the target's endianness.
467 On little endian this is a no-op. On big endian the bytes are swapped.
474 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
476 if cfg!(target_endian = \"little\") {
477 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
479 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
483 #[stable(feature = "rust1", since = "1.0.0")]
485 pub fn from_le(x: Self) -> Self {
486 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
491 concat!("Converts `self` to big endian from the target's endianness.
493 On big endian this is a no-op. On little endian the bytes are swapped.
500 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
502 if cfg!(target_endian = \"big\") {
503 assert_eq!(n.to_be(), n)
505 assert_eq!(n.to_be(), n.swap_bytes())
509 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn to_be(self) -> Self { // or not to be?
512 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
517 concat!("Converts `self` to little endian from the target's endianness.
519 On little endian this is a no-op. On big endian the bytes are swapped.
526 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
528 if cfg!(target_endian = \"little\") {
529 assert_eq!(n.to_le(), n)
531 assert_eq!(n.to_le(), n.swap_bytes())
535 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn to_le(self) -> Self {
538 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
543 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
544 if overflow occurred.
551 ", $Feature, "assert_eq!((", stringify!($SelfT),
552 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
553 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
556 #[stable(feature = "rust1", since = "1.0.0")]
558 pub fn checked_add(self, rhs: Self) -> Option<Self> {
559 let (a, b) = self.overflowing_add(rhs);
560 if b {None} else {Some(a)}
565 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
573 ", $Feature, "assert_eq!((", stringify!($SelfT),
574 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
575 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
578 #[stable(feature = "rust1", since = "1.0.0")]
580 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
581 let (a, b) = self.overflowing_sub(rhs);
582 if b {None} else {Some(a)}
587 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
595 ", $Feature, "assert_eq!(", stringify!($SelfT),
596 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
597 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
600 #[stable(feature = "rust1", since = "1.0.0")]
602 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
603 let (a, b) = self.overflowing_mul(rhs);
604 if b {None} else {Some(a)}
609 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
610 or the division results in overflow.
617 ", $Feature, "assert_eq!((", stringify!($SelfT),
618 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
619 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
620 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
623 #[stable(feature = "rust1", since = "1.0.0")]
625 pub fn checked_div(self, rhs: Self) -> Option<Self> {
626 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
629 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
635 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
636 `rhs == 0` or the division results in overflow.
643 ", $Feature, "use std::", stringify!($SelfT), ";
645 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
646 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
647 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
650 #[stable(feature = "wrapping", since = "1.7.0")]
652 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
653 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
656 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
662 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
669 ", $Feature, "use std::", stringify!($SelfT), ";
671 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
672 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
675 #[stable(feature = "wrapping", since = "1.7.0")]
677 pub fn checked_neg(self) -> Option<Self> {
678 let (a, b) = self.overflowing_neg();
679 if b {None} else {Some(a)}
684 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
685 than or equal to the number of bits in `self`.
692 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
693 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
696 #[stable(feature = "wrapping", since = "1.7.0")]
698 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
699 let (a, b) = self.overflowing_shl(rhs);
700 if b {None} else {Some(a)}
705 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
706 larger than or equal to the number of bits in `self`.
713 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
714 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
717 #[stable(feature = "wrapping", since = "1.7.0")]
719 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
720 let (a, b) = self.overflowing_shr(rhs);
721 if b {None} else {Some(a)}
726 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
734 ", $Feature, "use std::", stringify!($SelfT), ";
736 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
737 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
740 #[stable(feature = "no_panic_abs", since = "1.13.0")]
742 pub fn checked_abs(self) -> Option<Self> {
743 if self.is_negative() {
752 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
760 #![feature(no_panic_pow)]
761 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
762 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
766 #[unstable(feature = "no_panic_pow", issue = "48320")]
768 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
770 let mut acc: Self = 1;
774 acc = acc.checked_mul(base)?;
777 base = base.checked_mul(base)?;
780 // Deal with the final bit of the exponent separately, since
781 // squaring the base afterwards is not necessary and may cause a
782 // needless overflow.
784 acc = acc.checked_mul(base)?;
792 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
793 bounds instead of overflowing.
800 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
801 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
805 #[stable(feature = "rust1", since = "1.0.0")]
807 pub fn saturating_add(self, rhs: Self) -> Self {
808 match self.checked_add(rhs) {
810 None if rhs >= 0 => Self::max_value(),
811 None => Self::min_value(),
817 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
818 numeric bounds instead of overflowing.
825 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
826 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
830 #[stable(feature = "rust1", since = "1.0.0")]
832 pub fn saturating_sub(self, rhs: Self) -> Self {
833 match self.checked_sub(rhs) {
835 None if rhs >= 0 => Self::min_value(),
836 None => Self::max_value(),
842 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
843 numeric bounds instead of overflowing.
850 ", $Feature, "use std::", stringify!($SelfT), ";
852 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
853 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
854 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
857 #[stable(feature = "wrapping", since = "1.7.0")]
859 pub fn saturating_mul(self, rhs: Self) -> Self {
860 self.checked_mul(rhs).unwrap_or_else(|| {
861 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
871 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
872 saturating at the numeric bounds instead of overflowing.
879 #![feature(no_panic_pow)]
880 ", $Feature, "use std::", stringify!($SelfT), ";
882 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
883 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
884 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
887 #[unstable(feature = "no_panic_pow", issue = "48320")]
889 pub fn saturating_pow(self, exp: u32) -> Self {
890 match self.checked_pow(exp) {
892 None if self < 0 && exp % 2 == 1 => Self::min_value(),
893 None => Self::max_value(),
899 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
900 boundary of the type.
907 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
908 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
909 "::min_value() + 1);",
912 #[stable(feature = "rust1", since = "1.0.0")]
914 pub fn wrapping_add(self, rhs: Self) -> Self {
916 intrinsics::overflowing_add(self, rhs)
922 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
923 boundary of the type.
930 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
931 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
932 stringify!($SelfT), "::max_value());",
935 #[stable(feature = "rust1", since = "1.0.0")]
937 pub fn wrapping_sub(self, rhs: Self) -> Self {
939 intrinsics::overflowing_sub(self, rhs)
945 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
946 the boundary of the type.
953 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
954 assert_eq!(11i8.wrapping_mul(12), -124);",
957 #[stable(feature = "rust1", since = "1.0.0")]
959 pub fn wrapping_mul(self, rhs: Self) -> Self {
961 intrinsics::overflowing_mul(self, rhs)
967 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
968 boundary of the type.
970 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
971 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
972 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
976 This function will panic if `rhs` is 0.
983 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
984 assert_eq!((-128i8).wrapping_div(-1), -128);",
987 #[stable(feature = "num_wrapping", since = "1.2.0")]
989 pub fn wrapping_div(self, rhs: Self) -> Self {
990 self.overflowing_div(rhs).0
995 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
996 boundary of the type.
998 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
999 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1000 this function returns `0`.
1004 This function will panic if `rhs` is 0.
1011 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1012 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1015 #[stable(feature = "num_wrapping", since = "1.2.0")]
1017 pub fn wrapping_rem(self, rhs: Self) -> Self {
1018 self.overflowing_rem(rhs).0
1023 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1026 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1027 is the negative minimal value for the type); this is a positive value that is too large to represent
1028 in the type. In such a case, this function returns `MIN` itself.
1035 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1036 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1040 #[stable(feature = "num_wrapping", since = "1.2.0")]
1042 pub fn wrapping_neg(self) -> Self {
1043 self.overflowing_neg().0
1048 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1049 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1051 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1052 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1053 The primitive integer types all implement a `rotate_left` function, which may be what you want
1061 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1062 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1065 #[stable(feature = "num_wrapping", since = "1.2.0")]
1067 pub fn wrapping_shl(self, rhs: u32) -> Self {
1069 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1075 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1076 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1078 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1079 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1080 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1088 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1089 assert_eq!((-128i16).wrapping_shr(64), -128);",
1092 #[stable(feature = "num_wrapping", since = "1.2.0")]
1094 pub fn wrapping_shr(self, rhs: u32) -> Self {
1096 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1102 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1103 the boundary of the type.
1105 The only case where such wrapping can occur is when one takes the absolute value of the negative
1106 minimal value for the type this is a positive value that is too large to represent in the type. In
1107 such a case, this function returns `MIN` itself.
1114 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1115 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1116 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1118 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1121 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1123 pub fn wrapping_abs(self) -> Self {
1124 if self.is_negative() {
1133 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1134 wrapping around at the boundary of the type.
1141 #![feature(no_panic_pow)]
1142 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1143 assert_eq!(3i8.wrapping_pow(5), -13);
1144 assert_eq!(3i8.wrapping_pow(6), -39);",
1147 #[unstable(feature = "no_panic_pow", issue = "48320")]
1149 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1150 let mut base = self;
1151 let mut acc: Self = 1;
1155 acc = acc.wrapping_mul(base);
1158 base = base.wrapping_mul(base);
1161 // Deal with the final bit of the exponent separately, since
1162 // squaring the base afterwards is not necessary and may cause a
1163 // needless overflow.
1165 acc = acc.wrapping_mul(base);
1173 concat!("Calculates `self` + `rhs`
1175 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1176 occur. If an overflow would have occurred then the wrapped value is returned.
1183 ", $Feature, "use std::", stringify!($SelfT), ";
1185 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1186 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1187 "::MIN, true));", $EndFeature, "
1190 #[stable(feature = "wrapping", since = "1.7.0")]
1191 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1192 let (a, b) = unsafe {
1193 intrinsics::add_with_overflow(self as $ActualT,
1201 concat!("Calculates `self` - `rhs`
1203 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1204 would occur. If an overflow would have occurred then the wrapped value is returned.
1211 ", $Feature, "use std::", stringify!($SelfT), ";
1213 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1214 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1215 "::MAX, true));", $EndFeature, "
1218 #[stable(feature = "wrapping", since = "1.7.0")]
1219 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1220 let (a, b) = unsafe {
1221 intrinsics::sub_with_overflow(self as $ActualT,
1229 concat!("Calculates the multiplication of `self` and `rhs`.
1231 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1232 would occur. If an overflow would have occurred then the wrapped value is returned.
1239 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1240 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1244 #[stable(feature = "wrapping", since = "1.7.0")]
1245 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1246 let (a, b) = unsafe {
1247 intrinsics::mul_with_overflow(self as $ActualT,
1255 concat!("Calculates the divisor when `self` is divided by `rhs`.
1257 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1258 occur. If an overflow would occur then self is returned.
1262 This function will panic if `rhs` is 0.
1269 ", $Feature, "use std::", stringify!($SelfT), ";
1271 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1272 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1277 #[stable(feature = "wrapping", since = "1.7.0")]
1278 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1279 if self == Self::min_value() && rhs == -1 {
1288 concat!("Calculates the remainder when `self` is divided by `rhs`.
1290 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1291 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1295 This function will panic if `rhs` is 0.
1302 ", $Feature, "use std::", stringify!($SelfT), ";
1304 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1305 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1309 #[stable(feature = "wrapping", since = "1.7.0")]
1310 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1311 if self == Self::min_value() && rhs == -1 {
1320 concat!("Negates self, overflowing if this is equal to the minimum value.
1322 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1323 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1324 minimum value will be returned again and `true` will be returned for an overflow happening.
1331 ", $Feature, "use std::", stringify!($SelfT), ";
1333 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1334 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1335 "::MIN, true));", $EndFeature, "
1338 #[stable(feature = "wrapping", since = "1.7.0")]
1339 pub fn overflowing_neg(self) -> (Self, bool) {
1340 if self == Self::min_value() {
1341 (Self::min_value(), true)
1349 concat!("Shifts self left by `rhs` bits.
1351 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1352 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1353 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1360 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1361 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1365 #[stable(feature = "wrapping", since = "1.7.0")]
1366 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1367 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1372 concat!("Shifts self right by `rhs` bits.
1374 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1375 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1376 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1383 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1384 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1388 #[stable(feature = "wrapping", since = "1.7.0")]
1389 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1390 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1395 concat!("Computes the absolute value of `self`.
1397 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1398 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1399 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1400 for an overflow happening.
1407 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1408 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1409 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1410 "::min_value(), true));",
1413 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1415 pub fn overflowing_abs(self) -> (Self, bool) {
1416 if self.is_negative() {
1417 self.overflowing_neg()
1425 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1427 Returns a tuple of the exponentiation along with a bool indicating
1428 whether an overflow happened.
1435 #![feature(no_panic_pow)]
1436 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1437 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1440 #[unstable(feature = "no_panic_pow", issue = "48320")]
1442 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1443 let mut base = self;
1444 let mut acc: Self = 1;
1445 let mut overflown = false;
1446 // Scratch space for storing results of overflowing_mul.
1451 r = acc.overflowing_mul(base);
1456 r = base.overflowing_mul(base);
1461 // Deal with the final bit of the exponent separately, since
1462 // squaring the base afterwards is not necessary and may cause a
1463 // needless overflow.
1465 r = acc.overflowing_mul(base);
1475 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1482 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1484 assert_eq!(x.pow(5), 32);",
1487 #[stable(feature = "rust1", since = "1.0.0")]
1489 #[rustc_inherit_overflow_checks]
1490 pub fn pow(self, mut exp: u32) -> Self {
1491 let mut base = self;
1502 // Deal with the final bit of the exponent separately, since
1503 // squaring the base afterwards is not necessary and may cause a
1504 // needless overflow.
1514 concat!("Computes the absolute value of `self`.
1518 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1519 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1520 code in debug mode will trigger a panic on this case and optimized code will return `",
1521 stringify!($SelfT), "::min_value()` without a panic.
1528 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1529 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1532 #[stable(feature = "rust1", since = "1.0.0")]
1534 #[rustc_inherit_overflow_checks]
1535 pub fn abs(self) -> Self {
1536 if self.is_negative() {
1537 // Note that the #[inline] above means that the overflow
1538 // semantics of this negation depend on the crate we're being
1548 concat!("Returns a number representing sign of `self`.
1550 - `0` if the number is zero
1551 - `1` if the number is positive
1552 - `-1` if the number is negative
1559 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1560 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1561 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1564 #[stable(feature = "rust1", since = "1.0.0")]
1566 pub fn signum(self) -> Self {
1576 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1584 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1585 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1588 #[stable(feature = "rust1", since = "1.0.0")]
1590 pub fn is_positive(self) -> bool { self > 0 }
1594 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1602 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1603 assert!(!10", stringify!($SelfT), ".is_negative());",
1606 #[stable(feature = "rust1", since = "1.0.0")]
1608 pub fn is_negative(self) -> bool { self < 0 }
1615 int_impl! { i8, i8, u8, 8, -128, 127, "", "" }
1620 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "" }
1625 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "" }
1630 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1635 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
1636 170141183460469231731687303715884105727, "#![feature(i128_type)]
1643 #[cfg(target_pointer_width = "16")]
1646 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "" }
1649 #[cfg(target_pointer_width = "32")]
1652 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "" }
1655 #[cfg(target_pointer_width = "64")]
1658 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1661 // `Int` + `UnsignedInt` implemented for unsigned integers
1662 macro_rules! uint_impl {
1663 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr) => {
1665 concat!("Returns the smallest value that can be represented by this integer type.
1672 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
1674 #[stable(feature = "rust1", since = "1.0.0")]
1676 pub const fn min_value() -> Self { 0 }
1680 concat!("Returns the largest value that can be represented by this integer type.
1687 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
1688 stringify!($MaxV), ");", $EndFeature, "
1690 #[stable(feature = "rust1", since = "1.0.0")]
1692 pub const fn max_value() -> Self { !0 }
1696 concat!("Converts a string slice in a given base to an integer.
1698 The string is expected to be an optional `+` sign
1700 Leading and trailing whitespace represent an error.
1701 Digits are a subset of these characters, depending on `radix`:
1709 This function panics if `radix` is not in the range from 2 to 36.
1716 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
1719 #[stable(feature = "rust1", since = "1.0.0")]
1720 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1721 from_str_radix(src, radix)
1726 concat!("Returns the number of ones in the binary representation of `self`.
1733 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
1735 assert_eq!(n.count_ones(), 3);", $EndFeature, "
1737 #[stable(feature = "rust1", since = "1.0.0")]
1739 pub fn count_ones(self) -> u32 {
1740 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
1745 concat!("Returns the number of zeros in the binary representation of `self`.
1752 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
1754 #[stable(feature = "rust1", since = "1.0.0")]
1756 pub fn count_zeros(self) -> u32 {
1757 (!self).count_ones()
1762 concat!("Returns the number of leading zeros in the binary representation of `self`.
1769 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
1771 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
1773 #[stable(feature = "rust1", since = "1.0.0")]
1775 pub fn leading_zeros(self) -> u32 {
1776 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
1781 concat!("Returns the number of trailing zeros in the binary representation
1789 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
1791 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
1793 #[stable(feature = "rust1", since = "1.0.0")]
1795 pub fn trailing_zeros(self) -> u32 {
1796 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1797 // emits two conditional moves on x86_64. By promoting the value to
1798 // u16 and setting bit 8, we get better code without any conditional
1800 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1801 // pending, remove this workaround once LLVM generates better code
1805 intrinsics::cttz(self as u16 | 0x100) as u32
1807 intrinsics::cttz(self) as u32
1813 /// Shifts the bits to the left by a specified amount, `n`,
1814 /// wrapping the truncated bits to the end of the resulting integer.
1816 /// Please note this isn't the same operation as `<<`!
1822 /// Please note that this example is shared between integer types.
1823 /// Which explains why `u64` is used here.
1826 /// let n = 0x0123456789ABCDEFu64;
1827 /// let m = 0x3456789ABCDEF012u64;
1829 /// assert_eq!(n.rotate_left(12), m);
1831 #[stable(feature = "rust1", since = "1.0.0")]
1833 pub fn rotate_left(self, n: u32) -> Self {
1834 // Protect against undefined behaviour for over-long bit shifts
1836 (self << n) | (self >> (($BITS - n) % $BITS))
1839 /// Shifts the bits to the right by a specified amount, `n`,
1840 /// wrapping the truncated bits to the beginning of the resulting
1843 /// Please note this isn't the same operation as `>>`!
1849 /// Please note that this example is shared between integer types.
1850 /// Which explains why `u64` is used here.
1853 /// let n = 0x0123456789ABCDEFu64;
1854 /// let m = 0xDEF0123456789ABCu64;
1856 /// assert_eq!(n.rotate_right(12), m);
1858 #[stable(feature = "rust1", since = "1.0.0")]
1860 pub fn rotate_right(self, n: u32) -> Self {
1861 // Protect against undefined behaviour for over-long bit shifts
1863 (self >> n) | (self << (($BITS - n) % $BITS))
1866 /// Reverses the byte order of the integer.
1872 /// Please note that this example is shared between integer types.
1873 /// Which explains why `u16` is used here.
1876 /// let n: u16 = 0b0000000_01010101;
1877 /// assert_eq!(n, 85);
1879 /// let m = n.swap_bytes();
1881 /// assert_eq!(m, 0b01010101_00000000);
1882 /// assert_eq!(m, 21760);
1884 #[stable(feature = "rust1", since = "1.0.0")]
1886 pub fn swap_bytes(self) -> Self {
1887 unsafe { intrinsics::bswap(self as $ActualT) as Self }
1890 /// Reverses the bit pattern of the integer.
1896 /// Please note that this example is shared between integer types.
1897 /// Which explains why `u16` is used here.
1900 /// #![feature(reverse_bits)]
1902 /// let n: u16 = 0b0000000_01010101;
1903 /// assert_eq!(n, 85);
1905 /// let m = n.reverse_bits();
1907 /// assert_eq!(m, 0b10101010_00000000);
1908 /// assert_eq!(m, 43520);
1910 #[unstable(feature = "reverse_bits", issue = "48763")]
1913 pub fn reverse_bits(self) -> Self {
1914 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
1918 concat!("Converts an integer from big endian to the target's endianness.
1920 On big endian this is a no-op. On little endian the bytes are
1928 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1930 if cfg!(target_endian = \"big\") {
1931 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
1933 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
1936 #[stable(feature = "rust1", since = "1.0.0")]
1938 pub fn from_be(x: Self) -> Self {
1939 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1944 concat!("Converts an integer from little endian to the target's endianness.
1946 On little endian this is a no-op. On big endian the bytes are
1954 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1956 if cfg!(target_endian = \"little\") {
1957 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
1959 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
1962 #[stable(feature = "rust1", since = "1.0.0")]
1964 pub fn from_le(x: Self) -> Self {
1965 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1970 concat!("Converts `self` to big endian from the target's endianness.
1972 On big endian this is a no-op. On little endian the bytes are
1980 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1982 if cfg!(target_endian = \"big\") {
1983 assert_eq!(n.to_be(), n)
1985 assert_eq!(n.to_be(), n.swap_bytes())
1988 #[stable(feature = "rust1", since = "1.0.0")]
1990 pub fn to_be(self) -> Self { // or not to be?
1991 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1996 concat!("Converts `self` to little endian from the target's endianness.
1998 On little endian this is a no-op. On big endian the bytes are
2006 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2008 if cfg!(target_endian = \"little\") {
2009 assert_eq!(n.to_le(), n)
2011 assert_eq!(n.to_le(), n.swap_bytes())
2014 #[stable(feature = "rust1", since = "1.0.0")]
2016 pub fn to_le(self) -> Self {
2017 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
2022 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2023 if overflow occurred.
2030 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2031 "Some(", stringify!($SelfT), "::max_value() - 1));
2032 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3),None);", $EndFeature, "
2034 #[stable(feature = "rust1", since = "1.0.0")]
2036 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2037 let (a, b) = self.overflowing_add(rhs);
2038 if b {None} else {Some(a)}
2043 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2044 `None` if overflow occurred.
2051 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2052 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2054 #[stable(feature = "rust1", since = "1.0.0")]
2056 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2057 let (a, b) = self.overflowing_sub(rhs);
2058 if b {None} else {Some(a)}
2063 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2064 `None` if overflow occurred.
2071 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2072 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2074 #[stable(feature = "rust1", since = "1.0.0")]
2076 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2077 let (a, b) = self.overflowing_mul(rhs);
2078 if b {None} else {Some(a)}
2083 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2091 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2092 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2094 #[stable(feature = "rust1", since = "1.0.0")]
2096 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2099 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2105 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2113 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2114 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2116 #[stable(feature = "wrapping", since = "1.7.0")]
2118 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2122 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2128 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2131 Note that negating any positive integer will overflow.
2138 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2139 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2141 #[stable(feature = "wrapping", since = "1.7.0")]
2143 pub fn checked_neg(self) -> Option<Self> {
2144 let (a, b) = self.overflowing_neg();
2145 if b {None} else {Some(a)}
2150 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2151 if `rhs` is larger than or equal to the number of bits in `self`.
2158 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2159 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2161 #[stable(feature = "wrapping", since = "1.7.0")]
2163 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2164 let (a, b) = self.overflowing_shl(rhs);
2165 if b {None} else {Some(a)}
2170 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2171 if `rhs` is larger than or equal to the number of bits in `self`.
2178 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2179 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2181 #[stable(feature = "wrapping", since = "1.7.0")]
2183 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2184 let (a, b) = self.overflowing_shr(rhs);
2185 if b {None} else {Some(a)}
2190 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2198 #![feature(no_panic_pow)]
2199 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2200 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2202 #[unstable(feature = "no_panic_pow", issue = "48320")]
2204 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2205 let mut base = self;
2206 let mut acc: Self = 1;
2210 acc = acc.checked_mul(base)?;
2213 base = base.checked_mul(base)?;
2216 // Deal with the final bit of the exponent separately, since
2217 // squaring the base afterwards is not necessary and may cause a
2218 // needless overflow.
2220 acc = acc.checked_mul(base)?;
2228 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2229 the numeric bounds instead of overflowing.
2236 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2237 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2239 #[stable(feature = "rust1", since = "1.0.0")]
2241 pub fn saturating_add(self, rhs: Self) -> Self {
2242 match self.checked_add(rhs) {
2244 None => Self::max_value(),
2250 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2251 at the numeric bounds instead of overflowing.
2258 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2259 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2261 #[stable(feature = "rust1", since = "1.0.0")]
2263 pub fn saturating_sub(self, rhs: Self) -> Self {
2264 match self.checked_sub(rhs) {
2266 None => Self::min_value(),
2272 concat!("Saturating integer multiplication. Computes `self * rhs`,
2273 saturating at the numeric bounds instead of overflowing.
2280 ", $Feature, "use std::", stringify!($SelfT), ";
2282 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2283 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2284 "::MAX);", $EndFeature, "
2286 #[stable(feature = "wrapping", since = "1.7.0")]
2288 pub fn saturating_mul(self, rhs: Self) -> Self {
2289 self.checked_mul(rhs).unwrap_or(Self::max_value())
2294 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2295 saturating at the numeric bounds instead of overflowing.
2302 #![feature(no_panic_pow)]
2303 ", $Feature, "use std::", stringify!($SelfT), ";
2305 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2306 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2309 #[unstable(feature = "no_panic_pow", issue = "48320")]
2311 pub fn saturating_pow(self, exp: u32) -> Self {
2312 match self.checked_pow(exp) {
2314 None => Self::max_value(),
2320 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2321 wrapping around at the boundary of the type.
2328 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2329 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2332 #[stable(feature = "rust1", since = "1.0.0")]
2334 pub fn wrapping_add(self, rhs: Self) -> Self {
2336 intrinsics::overflowing_add(self, rhs)
2342 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2343 wrapping around at the boundary of the type.
2350 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2351 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2354 #[stable(feature = "rust1", since = "1.0.0")]
2356 pub fn wrapping_sub(self, rhs: Self) -> Self {
2358 intrinsics::overflowing_sub(self, rhs)
2363 /// Wrapping (modular) multiplication. Computes `self *
2364 /// rhs`, wrapping around at the boundary of the type.
2370 /// Please note that this example is shared between integer types.
2371 /// Which explains why `u8` is used here.
2374 /// assert_eq!(10u8.wrapping_mul(12), 120);
2375 /// assert_eq!(25u8.wrapping_mul(12), 44);
2377 #[stable(feature = "rust1", since = "1.0.0")]
2379 pub fn wrapping_mul(self, rhs: Self) -> Self {
2381 intrinsics::overflowing_mul(self, rhs)
2386 concat!("Wrapping (modular) division. Computes `self / rhs`.
2387 Wrapped division on unsigned types is just normal division.
2388 There's no way wrapping could ever happen.
2389 This function exists, so that all operations
2390 are accounted for in the wrapping operations.
2397 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2399 #[stable(feature = "num_wrapping", since = "1.2.0")]
2401 pub fn wrapping_div(self, rhs: Self) -> Self {
2407 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2408 Wrapped remainder calculation on unsigned types is
2409 just the regular remainder calculation.
2410 There's no way wrapping could ever happen.
2411 This function exists, so that all operations
2412 are accounted for in the wrapping operations.
2419 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2421 #[stable(feature = "num_wrapping", since = "1.2.0")]
2423 pub fn wrapping_rem(self, rhs: Self) -> Self {
2428 /// Wrapping (modular) negation. Computes `-self`,
2429 /// wrapping around at the boundary of the type.
2431 /// Since unsigned types do not have negative equivalents
2432 /// all applications of this function will wrap (except for `-0`).
2433 /// For values smaller than the corresponding signed type's maximum
2434 /// the result is the same as casting the corresponding signed value.
2435 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2436 /// `MAX` is the corresponding signed type's maximum.
2442 /// Please note that this example is shared between integer types.
2443 /// Which explains why `i8` is used here.
2446 /// assert_eq!(100i8.wrapping_neg(), -100);
2447 /// assert_eq!((-128i8).wrapping_neg(), -128);
2449 #[stable(feature = "num_wrapping", since = "1.2.0")]
2451 pub fn wrapping_neg(self) -> Self {
2452 self.overflowing_neg().0
2456 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2457 where `mask` removes any high-order bits of `rhs` that
2458 would cause the shift to exceed the bitwidth of the type.
2460 Note that this is *not* the same as a rotate-left; the
2461 RHS of a wrapping shift-left is restricted to the range
2462 of the type, rather than the bits shifted out of the LHS
2463 being returned to the other end. The primitive integer
2464 types all implement a `rotate_left` function, which may
2465 be what you want instead.
2472 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2473 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2475 #[stable(feature = "num_wrapping", since = "1.2.0")]
2477 pub fn wrapping_shl(self, rhs: u32) -> Self {
2479 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
2485 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2486 where `mask` removes any high-order bits of `rhs` that
2487 would cause the shift to exceed the bitwidth of the type.
2489 Note that this is *not* the same as a rotate-right; the
2490 RHS of a wrapping shift-right is restricted to the range
2491 of the type, rather than the bits shifted out of the LHS
2492 being returned to the other end. The primitive integer
2493 types all implement a `rotate_right` function, which may
2494 be what you want instead.
2501 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
2502 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
2504 #[stable(feature = "num_wrapping", since = "1.2.0")]
2506 pub fn wrapping_shr(self, rhs: u32) -> Self {
2508 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
2514 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2515 wrapping around at the boundary of the type.
2522 #![feature(no_panic_pow)]
2523 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
2524 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
2526 #[unstable(feature = "no_panic_pow", issue = "48320")]
2528 pub fn wrapping_pow(self, mut exp: u32) -> Self {
2529 let mut base = self;
2530 let mut acc: Self = 1;
2534 acc = acc.wrapping_mul(base);
2537 base = base.wrapping_mul(base);
2540 // Deal with the final bit of the exponent separately, since
2541 // squaring the base afterwards is not necessary and may cause a
2542 // needless overflow.
2544 acc = acc.wrapping_mul(base);
2552 concat!("Calculates `self` + `rhs`
2554 Returns a tuple of the addition along with a boolean indicating
2555 whether an arithmetic overflow would occur. If an overflow would
2556 have occurred then the wrapped value is returned.
2563 ", $Feature, "use std::", stringify!($SelfT), ";
2565 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
2566 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
2569 #[stable(feature = "wrapping", since = "1.7.0")]
2570 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2571 let (a, b) = unsafe {
2572 intrinsics::add_with_overflow(self as $ActualT,
2580 concat!("Calculates `self` - `rhs`
2582 Returns a tuple of the subtraction along with a boolean indicating
2583 whether an arithmetic overflow would occur. If an overflow would
2584 have occurred then the wrapped value is returned.
2591 ", $Feature, "use std::", stringify!($SelfT), ";
2593 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
2594 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
2598 #[stable(feature = "wrapping", since = "1.7.0")]
2599 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2600 let (a, b) = unsafe {
2601 intrinsics::sub_with_overflow(self as $ActualT,
2608 /// Calculates the multiplication of `self` and `rhs`.
2610 /// Returns a tuple of the multiplication along with a boolean
2611 /// indicating whether an arithmetic overflow would occur. If an
2612 /// overflow would have occurred then the wrapped value is returned.
2618 /// Please note that this example is shared between integer types.
2619 /// Which explains why `u32` is used here.
2622 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2623 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2626 #[stable(feature = "wrapping", since = "1.7.0")]
2627 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2628 let (a, b) = unsafe {
2629 intrinsics::mul_with_overflow(self as $ActualT,
2636 concat!("Calculates the divisor when `self` is divided by `rhs`.
2638 Returns a tuple of the divisor along with a boolean indicating
2639 whether an arithmetic overflow would occur. Note that for unsigned
2640 integers overflow never occurs, so the second value is always
2645 This function will panic if `rhs` is 0.
2652 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
2655 #[stable(feature = "wrapping", since = "1.7.0")]
2656 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2662 concat!("Calculates the remainder when `self` is divided by `rhs`.
2664 Returns a tuple of the remainder after dividing along with a boolean
2665 indicating whether an arithmetic overflow would occur. Note that for
2666 unsigned integers overflow never occurs, so the second value is
2671 This function will panic if `rhs` is 0.
2678 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
2681 #[stable(feature = "wrapping", since = "1.7.0")]
2682 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2688 concat!("Negates self in an overflowing fashion.
2690 Returns `!self + 1` using wrapping operations to return the value
2691 that represents the negation of this unsigned value. Note that for
2692 positive unsigned values overflow always occurs, but negating 0 does
2700 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
2701 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
2702 ", true));", $EndFeature, "
2705 #[stable(feature = "wrapping", since = "1.7.0")]
2706 pub fn overflowing_neg(self) -> (Self, bool) {
2707 ((!self).wrapping_add(1), self != 0)
2712 concat!("Shifts self left by `rhs` bits.
2714 Returns a tuple of the shifted version of self along with a boolean
2715 indicating whether the shift value was larger than or equal to the
2716 number of bits. If the shift value is too large, then value is
2717 masked (N-1) where N is the number of bits, and this value is then
2718 used to perform the shift.
2725 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
2726 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
2729 #[stable(feature = "wrapping", since = "1.7.0")]
2730 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2731 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
2736 concat!("Shifts self right by `rhs` bits.
2738 Returns a tuple of the shifted version of self along with a boolean
2739 indicating whether the shift value was larger than or equal to the
2740 number of bits. If the shift value is too large, then value is
2741 masked (N-1) where N is the number of bits, and this value is then
2742 used to perform the shift.
2749 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
2750 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
2753 #[stable(feature = "wrapping", since = "1.7.0")]
2754 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2755 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
2760 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2762 Returns a tuple of the exponentiation along with a bool indicating
2763 whether an overflow happened.
2770 #![feature(no_panic_pow)]
2771 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
2772 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
2774 #[unstable(feature = "no_panic_pow", issue = "48320")]
2776 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
2777 let mut base = self;
2778 let mut acc: Self = 1;
2779 let mut overflown = false;
2780 // Scratch space for storing results of overflowing_mul.
2785 r = acc.overflowing_mul(base);
2790 r = base.overflowing_mul(base);
2795 // Deal with the final bit of the exponent separately, since
2796 // squaring the base afterwards is not necessary and may cause a
2797 // needless overflow.
2799 r = acc.overflowing_mul(base);
2809 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2816 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
2818 #[stable(feature = "rust1", since = "1.0.0")]
2820 #[rustc_inherit_overflow_checks]
2821 pub fn pow(self, mut exp: u32) -> Self {
2822 let mut base = self;
2833 // Deal with the final bit of the exponent separately, since
2834 // squaring the base afterwards is not necessary and may cause a
2835 // needless overflow.
2845 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
2852 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
2853 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
2855 #[stable(feature = "rust1", since = "1.0.0")]
2857 pub fn is_power_of_two(self) -> bool {
2858 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2862 // Returns one less than next power of two.
2863 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2865 // 8u8.one_less_than_next_power_of_two() == 7
2866 // 6u8.one_less_than_next_power_of_two() == 7
2868 // This method cannot overflow, as in the `next_power_of_two`
2869 // overflow cases it instead ends up returning the maximum value
2870 // of the type, and can return 0 for 0.
2872 fn one_less_than_next_power_of_two(self) -> Self {
2873 if self <= 1 { return 0; }
2875 // Because `p > 0`, it cannot consist entirely of leading zeros.
2876 // That means the shift is always in-bounds, and some processors
2877 // (such as intel pre-haswell) have more efficient ctlz
2878 // intrinsics when the argument is non-zero.
2880 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2881 <$SelfT>::max_value() >> z
2885 concat!("Returns the smallest power of two greater than or equal to `self`.
2887 When return value overflows (i.e. `self > (1 << (N-1))` for type
2888 `uN`), it panics in debug mode and return value is wrapped to 0 in
2889 release mode (the only situation in which method can return 0).
2896 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
2897 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
2899 #[stable(feature = "rust1", since = "1.0.0")]
2901 pub fn next_power_of_two(self) -> Self {
2902 // Call the trait to get overflow checks
2903 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
2908 concat!("Returns the smallest power of two greater than or equal to `n`. If
2909 the next power of two is greater than the type's maximum value,
2910 `None` is returned, otherwise the power of two is wrapped in `Some`.
2917 ", $Feature, "assert_eq!(2", stringify!($SelfT),
2918 ".checked_next_power_of_two(), Some(2));
2919 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
2920 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
2923 #[stable(feature = "rust1", since = "1.0.0")]
2924 pub fn checked_next_power_of_two(self) -> Option<Self> {
2925 self.one_less_than_next_power_of_two().checked_add(1)
2933 uint_impl! { u8, u8, 8, 255, "", "" }
2936 /// Checks if the value is within the ASCII range.
2941 /// let ascii = 97u8;
2942 /// let non_ascii = 150u8;
2944 /// assert!(ascii.is_ascii());
2945 /// assert!(!non_ascii.is_ascii());
2947 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2949 pub fn is_ascii(&self) -> bool {
2953 /// Makes a copy of the value in its ASCII upper case equivalent.
2955 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2956 /// but non-ASCII letters are unchanged.
2958 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
2963 /// let lowercase_a = 97u8;
2965 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
2968 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
2969 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2971 pub fn to_ascii_uppercase(&self) -> u8 {
2972 ASCII_UPPERCASE_MAP[*self as usize]
2975 /// Makes a copy of the value in its ASCII lower case equivalent.
2977 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2978 /// but non-ASCII letters are unchanged.
2980 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
2985 /// let uppercase_a = 65u8;
2987 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
2990 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
2991 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2993 pub fn to_ascii_lowercase(&self) -> u8 {
2994 ASCII_LOWERCASE_MAP[*self as usize]
2997 /// Checks that two values are an ASCII case-insensitive match.
2999 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3004 /// let lowercase_a = 97u8;
3005 /// let uppercase_a = 65u8;
3007 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3009 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3011 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3012 self.to_ascii_lowercase() == other.to_ascii_lowercase()
3015 /// Converts this value to its ASCII upper case equivalent in-place.
3017 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3018 /// but non-ASCII letters are unchanged.
3020 /// To return a new uppercased value without modifying the existing one, use
3021 /// [`to_ascii_uppercase`].
3026 /// let mut byte = b'a';
3028 /// byte.make_ascii_uppercase();
3030 /// assert_eq!(b'A', byte);
3033 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3034 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3036 pub fn make_ascii_uppercase(&mut self) {
3037 *self = self.to_ascii_uppercase();
3040 /// Converts this value to its ASCII lower case equivalent in-place.
3042 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3043 /// but non-ASCII letters are unchanged.
3045 /// To return a new lowercased value without modifying the existing one, use
3046 /// [`to_ascii_lowercase`].
3051 /// let mut byte = b'A';
3053 /// byte.make_ascii_lowercase();
3055 /// assert_eq!(b'a', byte);
3058 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3059 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3061 pub fn make_ascii_lowercase(&mut self) {
3062 *self = self.to_ascii_lowercase();
3065 /// Checks if the value is an ASCII alphabetic character:
3067 /// - U+0041 'A' ... U+005A 'Z', or
3068 /// - U+0061 'a' ... U+007A 'z'.
3073 /// #![feature(ascii_ctype)]
3075 /// let uppercase_a = b'A';
3076 /// let uppercase_g = b'G';
3079 /// let zero = b'0';
3080 /// let percent = b'%';
3081 /// let space = b' ';
3083 /// let esc = 0x1b_u8;
3085 /// assert!(uppercase_a.is_ascii_alphabetic());
3086 /// assert!(uppercase_g.is_ascii_alphabetic());
3087 /// assert!(a.is_ascii_alphabetic());
3088 /// assert!(g.is_ascii_alphabetic());
3089 /// assert!(!zero.is_ascii_alphabetic());
3090 /// assert!(!percent.is_ascii_alphabetic());
3091 /// assert!(!space.is_ascii_alphabetic());
3092 /// assert!(!lf.is_ascii_alphabetic());
3093 /// assert!(!esc.is_ascii_alphabetic());
3095 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3097 pub fn is_ascii_alphabetic(&self) -> bool {
3098 if *self >= 0x80 { return false; }
3099 match ASCII_CHARACTER_CLASS[*self as usize] {
3100 L | Lx | U | Ux => true,
3105 /// Checks if the value is an ASCII uppercase character:
3106 /// U+0041 'A' ... U+005A 'Z'.
3111 /// #![feature(ascii_ctype)]
3113 /// let uppercase_a = b'A';
3114 /// let uppercase_g = b'G';
3117 /// let zero = b'0';
3118 /// let percent = b'%';
3119 /// let space = b' ';
3121 /// let esc = 0x1b_u8;
3123 /// assert!(uppercase_a.is_ascii_uppercase());
3124 /// assert!(uppercase_g.is_ascii_uppercase());
3125 /// assert!(!a.is_ascii_uppercase());
3126 /// assert!(!g.is_ascii_uppercase());
3127 /// assert!(!zero.is_ascii_uppercase());
3128 /// assert!(!percent.is_ascii_uppercase());
3129 /// assert!(!space.is_ascii_uppercase());
3130 /// assert!(!lf.is_ascii_uppercase());
3131 /// assert!(!esc.is_ascii_uppercase());
3133 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3135 pub fn is_ascii_uppercase(&self) -> bool {
3136 if *self >= 0x80 { return false }
3137 match ASCII_CHARACTER_CLASS[*self as usize] {
3143 /// Checks if the value is an ASCII lowercase character:
3144 /// U+0061 'a' ... U+007A 'z'.
3149 /// #![feature(ascii_ctype)]
3151 /// let uppercase_a = b'A';
3152 /// let uppercase_g = b'G';
3155 /// let zero = b'0';
3156 /// let percent = b'%';
3157 /// let space = b' ';
3159 /// let esc = 0x1b_u8;
3161 /// assert!(!uppercase_a.is_ascii_lowercase());
3162 /// assert!(!uppercase_g.is_ascii_lowercase());
3163 /// assert!(a.is_ascii_lowercase());
3164 /// assert!(g.is_ascii_lowercase());
3165 /// assert!(!zero.is_ascii_lowercase());
3166 /// assert!(!percent.is_ascii_lowercase());
3167 /// assert!(!space.is_ascii_lowercase());
3168 /// assert!(!lf.is_ascii_lowercase());
3169 /// assert!(!esc.is_ascii_lowercase());
3171 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3173 pub fn is_ascii_lowercase(&self) -> bool {
3174 if *self >= 0x80 { return false }
3175 match ASCII_CHARACTER_CLASS[*self as usize] {
3181 /// Checks if the value is an ASCII alphanumeric character:
3183 /// - U+0041 'A' ... U+005A 'Z', or
3184 /// - U+0061 'a' ... U+007A 'z', or
3185 /// - U+0030 '0' ... U+0039 '9'.
3190 /// #![feature(ascii_ctype)]
3192 /// let uppercase_a = b'A';
3193 /// let uppercase_g = b'G';
3196 /// let zero = b'0';
3197 /// let percent = b'%';
3198 /// let space = b' ';
3200 /// let esc = 0x1b_u8;
3202 /// assert!(uppercase_a.is_ascii_alphanumeric());
3203 /// assert!(uppercase_g.is_ascii_alphanumeric());
3204 /// assert!(a.is_ascii_alphanumeric());
3205 /// assert!(g.is_ascii_alphanumeric());
3206 /// assert!(zero.is_ascii_alphanumeric());
3207 /// assert!(!percent.is_ascii_alphanumeric());
3208 /// assert!(!space.is_ascii_alphanumeric());
3209 /// assert!(!lf.is_ascii_alphanumeric());
3210 /// assert!(!esc.is_ascii_alphanumeric());
3212 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3214 pub fn is_ascii_alphanumeric(&self) -> bool {
3215 if *self >= 0x80 { return false }
3216 match ASCII_CHARACTER_CLASS[*self as usize] {
3217 D | L | Lx | U | Ux => true,
3222 /// Checks if the value is an ASCII decimal digit:
3223 /// U+0030 '0' ... U+0039 '9'.
3228 /// #![feature(ascii_ctype)]
3230 /// let uppercase_a = b'A';
3231 /// let uppercase_g = b'G';
3234 /// let zero = b'0';
3235 /// let percent = b'%';
3236 /// let space = b' ';
3238 /// let esc = 0x1b_u8;
3240 /// assert!(!uppercase_a.is_ascii_digit());
3241 /// assert!(!uppercase_g.is_ascii_digit());
3242 /// assert!(!a.is_ascii_digit());
3243 /// assert!(!g.is_ascii_digit());
3244 /// assert!(zero.is_ascii_digit());
3245 /// assert!(!percent.is_ascii_digit());
3246 /// assert!(!space.is_ascii_digit());
3247 /// assert!(!lf.is_ascii_digit());
3248 /// assert!(!esc.is_ascii_digit());
3250 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3252 pub fn is_ascii_digit(&self) -> bool {
3253 if *self >= 0x80 { return false }
3254 match ASCII_CHARACTER_CLASS[*self as usize] {
3260 /// Checks if the value is an ASCII hexadecimal digit:
3262 /// - U+0030 '0' ... U+0039 '9', or
3263 /// - U+0041 'A' ... U+0046 'F', or
3264 /// - U+0061 'a' ... U+0066 'f'.
3269 /// #![feature(ascii_ctype)]
3271 /// let uppercase_a = b'A';
3272 /// let uppercase_g = b'G';
3275 /// let zero = b'0';
3276 /// let percent = b'%';
3277 /// let space = b' ';
3279 /// let esc = 0x1b_u8;
3281 /// assert!(uppercase_a.is_ascii_hexdigit());
3282 /// assert!(!uppercase_g.is_ascii_hexdigit());
3283 /// assert!(a.is_ascii_hexdigit());
3284 /// assert!(!g.is_ascii_hexdigit());
3285 /// assert!(zero.is_ascii_hexdigit());
3286 /// assert!(!percent.is_ascii_hexdigit());
3287 /// assert!(!space.is_ascii_hexdigit());
3288 /// assert!(!lf.is_ascii_hexdigit());
3289 /// assert!(!esc.is_ascii_hexdigit());
3291 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3293 pub fn is_ascii_hexdigit(&self) -> bool {
3294 if *self >= 0x80 { return false }
3295 match ASCII_CHARACTER_CLASS[*self as usize] {
3296 D | Lx | Ux => true,
3301 /// Checks if the value is an ASCII punctuation character:
3303 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
3304 /// - U+003A ... U+0040 `: ; < = > ? @`, or
3305 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
3306 /// - U+007B ... U+007E `{ | } ~`
3311 /// #![feature(ascii_ctype)]
3313 /// let uppercase_a = b'A';
3314 /// let uppercase_g = b'G';
3317 /// let zero = b'0';
3318 /// let percent = b'%';
3319 /// let space = b' ';
3321 /// let esc = 0x1b_u8;
3323 /// assert!(!uppercase_a.is_ascii_punctuation());
3324 /// assert!(!uppercase_g.is_ascii_punctuation());
3325 /// assert!(!a.is_ascii_punctuation());
3326 /// assert!(!g.is_ascii_punctuation());
3327 /// assert!(!zero.is_ascii_punctuation());
3328 /// assert!(percent.is_ascii_punctuation());
3329 /// assert!(!space.is_ascii_punctuation());
3330 /// assert!(!lf.is_ascii_punctuation());
3331 /// assert!(!esc.is_ascii_punctuation());
3333 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3335 pub fn is_ascii_punctuation(&self) -> bool {
3336 if *self >= 0x80 { return false }
3337 match ASCII_CHARACTER_CLASS[*self as usize] {
3343 /// Checks if the value is an ASCII graphic character:
3344 /// U+0021 '!' ... U+007E '~'.
3349 /// #![feature(ascii_ctype)]
3351 /// let uppercase_a = b'A';
3352 /// let uppercase_g = b'G';
3355 /// let zero = b'0';
3356 /// let percent = b'%';
3357 /// let space = b' ';
3359 /// let esc = 0x1b_u8;
3361 /// assert!(uppercase_a.is_ascii_graphic());
3362 /// assert!(uppercase_g.is_ascii_graphic());
3363 /// assert!(a.is_ascii_graphic());
3364 /// assert!(g.is_ascii_graphic());
3365 /// assert!(zero.is_ascii_graphic());
3366 /// assert!(percent.is_ascii_graphic());
3367 /// assert!(!space.is_ascii_graphic());
3368 /// assert!(!lf.is_ascii_graphic());
3369 /// assert!(!esc.is_ascii_graphic());
3371 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3373 pub fn is_ascii_graphic(&self) -> bool {
3374 if *self >= 0x80 { return false; }
3375 match ASCII_CHARACTER_CLASS[*self as usize] {
3376 Ux | U | Lx | L | D | P => true,
3381 /// Checks if the value is an ASCII whitespace character:
3382 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
3383 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
3385 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
3386 /// whitespace][infra-aw]. There are several other definitions in
3387 /// wide use. For instance, [the POSIX locale][pct] includes
3388 /// U+000B VERTICAL TAB as well as all the above characters,
3389 /// but—from the very same specification—[the default rule for
3390 /// "field splitting" in the Bourne shell][bfs] considers *only*
3391 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
3393 /// If you are writing a program that will process an existing
3394 /// file format, check what that format's definition of whitespace is
3395 /// before using this function.
3397 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
3398 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
3399 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
3404 /// #![feature(ascii_ctype)]
3406 /// let uppercase_a = b'A';
3407 /// let uppercase_g = b'G';
3410 /// let zero = b'0';
3411 /// let percent = b'%';
3412 /// let space = b' ';
3414 /// let esc = 0x1b_u8;
3416 /// assert!(!uppercase_a.is_ascii_whitespace());
3417 /// assert!(!uppercase_g.is_ascii_whitespace());
3418 /// assert!(!a.is_ascii_whitespace());
3419 /// assert!(!g.is_ascii_whitespace());
3420 /// assert!(!zero.is_ascii_whitespace());
3421 /// assert!(!percent.is_ascii_whitespace());
3422 /// assert!(space.is_ascii_whitespace());
3423 /// assert!(lf.is_ascii_whitespace());
3424 /// assert!(!esc.is_ascii_whitespace());
3426 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3428 pub fn is_ascii_whitespace(&self) -> bool {
3429 if *self >= 0x80 { return false; }
3430 match ASCII_CHARACTER_CLASS[*self as usize] {
3436 /// Checks if the value is an ASCII control character:
3437 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
3438 /// Note that most ASCII whitespace characters are control
3439 /// characters, but SPACE is not.
3444 /// #![feature(ascii_ctype)]
3446 /// let uppercase_a = b'A';
3447 /// let uppercase_g = b'G';
3450 /// let zero = b'0';
3451 /// let percent = b'%';
3452 /// let space = b' ';
3454 /// let esc = 0x1b_u8;
3456 /// assert!(!uppercase_a.is_ascii_control());
3457 /// assert!(!uppercase_g.is_ascii_control());
3458 /// assert!(!a.is_ascii_control());
3459 /// assert!(!g.is_ascii_control());
3460 /// assert!(!zero.is_ascii_control());
3461 /// assert!(!percent.is_ascii_control());
3462 /// assert!(!space.is_ascii_control());
3463 /// assert!(lf.is_ascii_control());
3464 /// assert!(esc.is_ascii_control());
3466 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3468 pub fn is_ascii_control(&self) -> bool {
3469 if *self >= 0x80 { return false; }
3470 match ASCII_CHARACTER_CLASS[*self as usize] {
3479 uint_impl! { u16, u16, 16, 65535, "", "" }
3484 uint_impl! { u32, u32, 32, 4294967295, "", "" }
3489 uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
3494 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "#![feature(i128_type)]
3502 #[cfg(target_pointer_width = "16")]
3505 uint_impl! { usize, u16, 16, 65536, "", "" }
3507 #[cfg(target_pointer_width = "32")]
3510 uint_impl! { usize, u32, 32, 4294967295, "", "" }
3513 #[cfg(target_pointer_width = "64")]
3516 uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
3519 /// A classification of floating point numbers.
3521 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
3522 /// their documentation for more.
3524 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
3525 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
3530 /// use std::num::FpCategory;
3533 /// let num = 12.4_f32;
3534 /// let inf = f32::INFINITY;
3535 /// let zero = 0f32;
3536 /// let sub: f32 = 1.1754942e-38;
3537 /// let nan = f32::NAN;
3539 /// assert_eq!(num.classify(), FpCategory::Normal);
3540 /// assert_eq!(inf.classify(), FpCategory::Infinite);
3541 /// assert_eq!(zero.classify(), FpCategory::Zero);
3542 /// assert_eq!(nan.classify(), FpCategory::Nan);
3543 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
3545 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
3546 #[stable(feature = "rust1", since = "1.0.0")]
3547 pub enum FpCategory {
3548 /// "Not a Number", often obtained by dividing by zero.
3549 #[stable(feature = "rust1", since = "1.0.0")]
3552 /// Positive or negative infinity.
3553 #[stable(feature = "rust1", since = "1.0.0")]
3556 /// Positive or negative zero.
3557 #[stable(feature = "rust1", since = "1.0.0")]
3560 /// De-normalized floating point representation (less precise than `Normal`).
3561 #[stable(feature = "rust1", since = "1.0.0")]
3564 /// A regular floating point number.
3565 #[stable(feature = "rust1", since = "1.0.0")]
3569 /// A built-in floating point number.
3571 #[unstable(feature = "core_float",
3572 reason = "stable interface is via `impl f{32,64}` in later crates",
3574 pub trait Float: Sized {
3575 /// Type used by `to_bits` and `from_bits`.
3576 #[stable(feature = "core_float_bits", since = "1.25.0")]
3579 /// Returns `true` if this value is NaN and false otherwise.
3580 #[stable(feature = "core", since = "1.6.0")]
3581 fn is_nan(self) -> bool;
3582 /// Returns `true` if this value is positive infinity or negative infinity and
3583 /// false otherwise.
3584 #[stable(feature = "core", since = "1.6.0")]
3585 fn is_infinite(self) -> bool;
3586 /// Returns `true` if this number is neither infinite nor NaN.
3587 #[stable(feature = "core", since = "1.6.0")]
3588 fn is_finite(self) -> bool;
3589 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
3590 #[stable(feature = "core", since = "1.6.0")]
3591 fn is_normal(self) -> bool;
3592 /// Returns the category that this number falls into.
3593 #[stable(feature = "core", since = "1.6.0")]
3594 fn classify(self) -> FpCategory;
3596 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
3597 /// number is `Float::nan()`.
3598 #[stable(feature = "core", since = "1.6.0")]
3599 fn abs(self) -> Self;
3600 /// Returns a number that represents the sign of `self`.
3602 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
3603 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
3604 /// - `Float::nan()` if the number is `Float::nan()`
3605 #[stable(feature = "core", since = "1.6.0")]
3606 fn signum(self) -> Self;
3608 /// Returns `true` if `self` is positive, including `+0.0` and
3609 /// `Float::infinity()`.
3610 #[stable(feature = "core", since = "1.6.0")]
3611 fn is_sign_positive(self) -> bool;
3612 /// Returns `true` if `self` is negative, including `-0.0` and
3613 /// `Float::neg_infinity()`.
3614 #[stable(feature = "core", since = "1.6.0")]
3615 fn is_sign_negative(self) -> bool;
3617 /// Take the reciprocal (inverse) of a number, `1/x`.
3618 #[stable(feature = "core", since = "1.6.0")]
3619 fn recip(self) -> Self;
3621 /// Raise a number to an integer power.
3623 /// Using this function is generally faster than using `powf`
3624 #[stable(feature = "core", since = "1.6.0")]
3625 fn powi(self, n: i32) -> Self;
3627 /// Convert radians to degrees.
3628 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3629 fn to_degrees(self) -> Self;
3630 /// Convert degrees to radians.
3631 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3632 fn to_radians(self) -> Self;
3634 /// Returns the maximum of the two numbers.
3635 #[stable(feature = "core_float_min_max", since="1.20.0")]
3636 fn max(self, other: Self) -> Self;
3637 /// Returns the minimum of the two numbers.
3638 #[stable(feature = "core_float_min_max", since="1.20.0")]
3639 fn min(self, other: Self) -> Self;
3641 /// Raw transmutation to integer.
3642 #[stable(feature = "core_float_bits", since="1.25.0")]
3643 fn to_bits(self) -> Self::Bits;
3644 /// Raw transmutation from integer.
3645 #[stable(feature = "core_float_bits", since="1.25.0")]
3646 fn from_bits(v: Self::Bits) -> Self;
3649 macro_rules! from_str_radix_int_impl {
3651 #[stable(feature = "rust1", since = "1.0.0")]
3652 impl FromStr for $t {
3653 type Err = ParseIntError;
3654 fn from_str(src: &str) -> Result<Self, ParseIntError> {
3655 from_str_radix(src, 10)
3660 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
3662 /// The error type returned when a checked integral type conversion fails.
3663 #[unstable(feature = "try_from", issue = "33417")]
3664 #[derive(Debug, Copy, Clone)]
3665 pub struct TryFromIntError(());
3667 impl TryFromIntError {
3668 #[unstable(feature = "int_error_internals",
3669 reason = "available through Error trait and this method should \
3670 not be exposed publicly",
3673 pub fn __description(&self) -> &str {
3674 "out of range integral type conversion attempted"
3678 #[unstable(feature = "try_from", issue = "33417")]
3679 impl fmt::Display for TryFromIntError {
3680 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3681 self.__description().fmt(fmt)
3685 #[unstable(feature = "try_from", issue = "33417")]
3686 impl From<Infallible> for TryFromIntError {
3687 fn from(infallible: Infallible) -> TryFromIntError {
3693 // no possible bounds violation
3694 macro_rules! try_from_unbounded {
3695 ($source:ty, $($target:ty),*) => {$(
3696 #[unstable(feature = "try_from", issue = "33417")]
3697 impl TryFrom<$source> for $target {
3698 type Error = Infallible;
3701 fn try_from(value: $source) -> Result<Self, Self::Error> {
3702 Ok(value as $target)
3708 // only negative bounds
3709 macro_rules! try_from_lower_bounded {
3710 ($source:ty, $($target:ty),*) => {$(
3711 #[unstable(feature = "try_from", issue = "33417")]
3712 impl TryFrom<$source> for $target {
3713 type Error = TryFromIntError;
3716 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3720 Err(TryFromIntError(()))
3727 // unsigned to signed (only positive bound)
3728 macro_rules! try_from_upper_bounded {
3729 ($source:ty, $($target:ty),*) => {$(
3730 #[unstable(feature = "try_from", issue = "33417")]
3731 impl TryFrom<$source> for $target {
3732 type Error = TryFromIntError;
3735 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3736 if u > (<$target>::max_value() as $source) {
3737 Err(TryFromIntError(()))
3747 macro_rules! try_from_both_bounded {
3748 ($source:ty, $($target:ty),*) => {$(
3749 #[unstable(feature = "try_from", issue = "33417")]
3750 impl TryFrom<$source> for $target {
3751 type Error = TryFromIntError;
3754 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3755 let min = <$target>::min_value() as $source;
3756 let max = <$target>::max_value() as $source;
3757 if u < min || u > max {
3758 Err(TryFromIntError(()))
3768 ($mac:ident, $source:ty, $($target:ty),*) => {$(
3769 $mac!($target, $source);
3773 /// intra-sign conversions
3774 try_from_upper_bounded!(u16, u8);
3775 try_from_upper_bounded!(u32, u16, u8);
3776 try_from_upper_bounded!(u64, u32, u16, u8);
3777 try_from_upper_bounded!(u128, u64, u32, u16, u8);
3779 try_from_both_bounded!(i16, i8);
3780 try_from_both_bounded!(i32, i16, i8);
3781 try_from_both_bounded!(i64, i32, i16, i8);
3782 try_from_both_bounded!(i128, i64, i32, i16, i8);
3784 // unsigned-to-signed
3785 try_from_upper_bounded!(u8, i8);
3786 try_from_upper_bounded!(u16, i8, i16);
3787 try_from_upper_bounded!(u32, i8, i16, i32);
3788 try_from_upper_bounded!(u64, i8, i16, i32, i64);
3789 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
3791 // signed-to-unsigned
3792 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
3793 try_from_lower_bounded!(i16, u16, u32, u64, u128);
3794 try_from_lower_bounded!(i32, u32, u64, u128);
3795 try_from_lower_bounded!(i64, u64, u128);
3796 try_from_lower_bounded!(i128, u128);
3797 try_from_both_bounded!(i16, u8);
3798 try_from_both_bounded!(i32, u16, u8);
3799 try_from_both_bounded!(i64, u32, u16, u8);
3800 try_from_both_bounded!(i128, u64, u32, u16, u8);
3803 try_from_upper_bounded!(usize, isize);
3804 try_from_lower_bounded!(isize, usize);
3806 #[cfg(target_pointer_width = "16")]
3807 mod ptr_try_from_impls {
3808 use super::TryFromIntError;
3809 use convert::{Infallible, TryFrom};
3811 try_from_upper_bounded!(usize, u8);
3812 try_from_unbounded!(usize, u16, u32, u64, u128);
3813 try_from_upper_bounded!(usize, i8, i16);
3814 try_from_unbounded!(usize, i32, i64, i128);
3816 try_from_both_bounded!(isize, u8);
3817 try_from_lower_bounded!(isize, u16, u32, u64, u128);
3818 try_from_both_bounded!(isize, i8);
3819 try_from_unbounded!(isize, i16, i32, i64, i128);
3821 rev!(try_from_unbounded, usize, u16);
3822 rev!(try_from_upper_bounded, usize, u32, u64, u128);
3823 rev!(try_from_lower_bounded, usize, i8, i16);
3824 rev!(try_from_both_bounded, usize, i32, i64, i128);
3826 rev!(try_from_unbounded, isize, u8);
3827 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
3828 rev!(try_from_unbounded, isize, i16);
3829 rev!(try_from_both_bounded, isize, i32, i64, i128);
3832 #[cfg(target_pointer_width = "32")]
3833 mod ptr_try_from_impls {
3834 use super::TryFromIntError;
3835 use convert::{Infallible, TryFrom};
3837 try_from_upper_bounded!(usize, u8, u16);
3838 try_from_unbounded!(usize, u32, u64, u128);
3839 try_from_upper_bounded!(usize, i8, i16, i32);
3840 try_from_unbounded!(usize, i64, i128);
3842 try_from_both_bounded!(isize, u8, u16);
3843 try_from_lower_bounded!(isize, u32, u64, u128);
3844 try_from_both_bounded!(isize, i8, i16);
3845 try_from_unbounded!(isize, i32, i64, i128);
3847 rev!(try_from_unbounded, usize, u16, u32);
3848 rev!(try_from_upper_bounded, usize, u64, u128);
3849 rev!(try_from_lower_bounded, usize, i8, i16, i32);
3850 rev!(try_from_both_bounded, usize, i64, i128);
3852 rev!(try_from_unbounded, isize, u8, u16);
3853 rev!(try_from_upper_bounded, isize, u32, u64, u128);
3854 rev!(try_from_unbounded, isize, i16, i32);
3855 rev!(try_from_both_bounded, isize, i64, i128);
3858 #[cfg(target_pointer_width = "64")]
3859 mod ptr_try_from_impls {
3860 use super::TryFromIntError;
3861 use convert::{Infallible, TryFrom};
3863 try_from_upper_bounded!(usize, u8, u16, u32);
3864 try_from_unbounded!(usize, u64, u128);
3865 try_from_upper_bounded!(usize, i8, i16, i32, i64);
3866 try_from_unbounded!(usize, i128);
3868 try_from_both_bounded!(isize, u8, u16, u32);
3869 try_from_lower_bounded!(isize, u64, u128);
3870 try_from_both_bounded!(isize, i8, i16, i32);
3871 try_from_unbounded!(isize, i64, i128);
3873 rev!(try_from_unbounded, usize, u16, u32, u64);
3874 rev!(try_from_upper_bounded, usize, u128);
3875 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
3876 rev!(try_from_both_bounded, usize, i128);
3878 rev!(try_from_unbounded, isize, u8, u16, u32);
3879 rev!(try_from_upper_bounded, isize, u64, u128);
3880 rev!(try_from_unbounded, isize, i16, i32, i64);
3881 rev!(try_from_both_bounded, isize, i128);
3885 trait FromStrRadixHelper: PartialOrd + Copy {
3886 fn min_value() -> Self;
3887 fn max_value() -> Self;
3888 fn from_u32(u: u32) -> Self;
3889 fn checked_mul(&self, other: u32) -> Option<Self>;
3890 fn checked_sub(&self, other: u32) -> Option<Self>;
3891 fn checked_add(&self, other: u32) -> Option<Self>;
3895 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
3897 fn min_value() -> Self { Self::min_value() }
3899 fn max_value() -> Self { Self::max_value() }
3901 fn from_u32(u: u32) -> Self { u as Self }
3903 fn checked_mul(&self, other: u32) -> Option<Self> {
3904 Self::checked_mul(*self, other as Self)
3907 fn checked_sub(&self, other: u32) -> Option<Self> {
3908 Self::checked_sub(*self, other as Self)
3911 fn checked_add(&self, other: u32) -> Option<Self> {
3912 Self::checked_add(*self, other as Self)
3916 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
3918 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
3919 use self::IntErrorKind::*;
3920 use self::ParseIntError as PIE;
3922 assert!(radix >= 2 && radix <= 36,
3923 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
3927 return Err(PIE { kind: Empty });
3930 let is_signed_ty = T::from_u32(0) > T::min_value();
3932 // all valid digits are ascii, so we will just iterate over the utf8 bytes
3933 // and cast them to chars. .to_digit() will safely return None for anything
3934 // other than a valid ascii digit for the given radix, including the first-byte
3935 // of multi-byte sequences
3936 let src = src.as_bytes();
3938 let (is_positive, digits) = match src[0] {
3939 b'+' => (true, &src[1..]),
3940 b'-' if is_signed_ty => (false, &src[1..]),
3944 if digits.is_empty() {
3945 return Err(PIE { kind: Empty });
3948 let mut result = T::from_u32(0);
3950 // The number is positive
3952 let x = match (c as char).to_digit(radix) {
3954 None => return Err(PIE { kind: InvalidDigit }),
3956 result = match result.checked_mul(radix) {
3957 Some(result) => result,
3958 None => return Err(PIE { kind: Overflow }),
3960 result = match result.checked_add(x) {
3961 Some(result) => result,
3962 None => return Err(PIE { kind: Overflow }),
3966 // The number is negative
3968 let x = match (c as char).to_digit(radix) {
3970 None => return Err(PIE { kind: InvalidDigit }),
3972 result = match result.checked_mul(radix) {
3973 Some(result) => result,
3974 None => return Err(PIE { kind: Underflow }),
3976 result = match result.checked_sub(x) {
3977 Some(result) => result,
3978 None => return Err(PIE { kind: Underflow }),
3985 /// An error which can be returned when parsing an integer.
3987 /// This error is used as the error type for the `from_str_radix()` functions
3988 /// on the primitive integer types, such as [`i8::from_str_radix`].
3990 /// # Potential causes
3992 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
3993 /// in the string e.g. when it is obtained from the standard input.
3994 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
3996 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
3997 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
3998 #[derive(Debug, Clone, PartialEq, Eq)]
3999 #[stable(feature = "rust1", since = "1.0.0")]
4000 pub struct ParseIntError {
4004 #[derive(Debug, Clone, PartialEq, Eq)]
4012 impl ParseIntError {
4013 #[unstable(feature = "int_error_internals",
4014 reason = "available through Error trait and this method should \
4015 not be exposed publicly",
4018 pub fn __description(&self) -> &str {
4020 IntErrorKind::Empty => "cannot parse integer from empty string",
4021 IntErrorKind::InvalidDigit => "invalid digit found in string",
4022 IntErrorKind::Overflow => "number too large to fit in target type",
4023 IntErrorKind::Underflow => "number too small to fit in target type",
4028 #[stable(feature = "rust1", since = "1.0.0")]
4029 impl fmt::Display for ParseIntError {
4030 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4031 self.__description().fmt(f)
4035 #[stable(feature = "rust1", since = "1.0.0")]
4036 pub use num::dec2flt::ParseFloatError;
4038 // Conversion traits for primitive integer and float types
4039 // Conversions T -> T are covered by a blanket impl and therefore excluded
4040 // Some conversions from and to usize/isize are not implemented due to portability concerns
4041 macro_rules! impl_from {
4042 ($Small: ty, $Large: ty, #[$attr:meta]) => {
4044 impl From<$Small> for $Large {
4046 fn from(small: $Small) -> $Large {
4053 // Unsigned -> Unsigned
4054 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4055 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4056 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4057 impl_from! { u8, u128, #[unstable(feature = "i128", issue = "35118")] }
4058 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4059 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4060 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4061 impl_from! { u16, u128, #[unstable(feature = "i128", issue = "35118")] }
4062 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4063 impl_from! { u32, u128, #[unstable(feature = "i128", issue = "35118")] }
4064 impl_from! { u64, u128, #[unstable(feature = "i128", issue = "35118")] }
4067 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4068 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4069 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4070 impl_from! { i8, i128, #[unstable(feature = "i128", issue = "35118")] }
4071 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4072 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4073 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4074 impl_from! { i16, i128, #[unstable(feature = "i128", issue = "35118")] }
4075 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4076 impl_from! { i32, i128, #[unstable(feature = "i128", issue = "35118")] }
4077 impl_from! { i64, i128, #[unstable(feature = "i128", issue = "35118")] }
4079 // Unsigned -> Signed
4080 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4081 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4082 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4083 impl_from! { u8, i128, #[unstable(feature = "i128", issue = "35118")] }
4084 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4085 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4086 impl_from! { u16, i128, #[unstable(feature = "i128", issue = "35118")] }
4087 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4088 impl_from! { u32, i128, #[unstable(feature = "i128", issue = "35118")] }
4089 impl_from! { u64, i128, #[unstable(feature = "i128", issue = "35118")] }
4091 // Note: integers can only be represented with full precision in a float if
4092 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4093 // Lossy float conversions are not implemented at this time.
4096 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4097 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4098 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4099 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4100 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4102 // Unsigned -> Float
4103 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4104 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4105 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4106 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4107 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4110 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4112 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4113 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4114 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4115 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4116 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4117 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4118 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4119 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4120 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4123 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4124 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4125 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4128 b'[', b'\\', b']', b'^', b'_',
4129 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4130 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4131 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4132 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4133 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4134 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4135 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4136 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4137 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4138 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4139 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4140 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4141 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4142 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4143 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4144 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4145 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4146 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4147 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4148 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4151 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4152 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4153 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4154 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4155 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4156 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4157 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4158 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4159 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4160 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4161 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4162 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4163 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4166 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4167 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4168 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4171 b'{', b'|', b'}', b'~', 0x7f,
4172 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4173 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4174 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4175 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4176 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4177 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4178 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4179 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4180 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4181 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4182 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4183 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4184 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4185 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4186 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4187 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4190 enum AsciiCharacterClass {
4192 Cw, // control whitespace
4196 Lx, // lowercase hex digit
4198 Ux, // uppercase hex digit
4201 use self::AsciiCharacterClass::*;
4203 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4204 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4205 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4206 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4207 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4208 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4209 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4210 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4211 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4212 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_