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")]
23 macro_rules! impl_nonzero_fmt {
24 ( ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
26 #[stable(feature = "nonzero", since = "1.28.0")]
27 impl fmt::$Trait for $Ty {
29 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37 macro_rules! doc_comment {
38 ($x:expr, $($tt:tt)*) => {
44 macro_rules! nonzero_integers {
45 ( $( $Ty: ident($Int: ty); )+ ) => {
48 concat!("An integer that is known not to equal zero.
50 This enables some memory layout optimization.
51 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
54 use std::mem::size_of;
55 assert_eq!(size_of::<Option<std::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
58 #[stable(feature = "nonzero", since = "1.28.0")]
59 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
61 pub struct $Ty(NonZero<$Int>);
65 /// Create a non-zero without checking the value.
69 /// The value must not be zero.
70 #[stable(feature = "nonzero", since = "1.28.0")]
72 pub const unsafe fn new_unchecked(n: $Int) -> Self {
76 /// Create a non-zero if the given value is not zero.
77 #[stable(feature = "nonzero", since = "1.28.0")]
79 pub fn new(n: $Int) -> Option<Self> {
87 /// Returns the value as a primitive type.
88 #[stable(feature = "nonzero", since = "1.28.0")]
90 pub fn get(self) -> $Int {
96 #[stable(feature = "from_nonzero", since = "1.31.0")]
97 impl From<$Ty> for $Int {
98 fn from(nonzero: $Ty) -> Self {
104 (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
119 /// Provides intentionally-wrapped arithmetic on `T`.
121 /// Operations like `+` on `u32` values is intended to never overflow,
122 /// and in some debug configurations overflow is detected and results
123 /// in a panic. While most arithmetic falls into this category, some
124 /// code explicitly expects and relies upon modular arithmetic (e.g.,
127 /// Wrapping arithmetic can be achieved either through methods like
128 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
129 /// all standard arithmetic operations on the underlying value are
130 /// intended to have wrapping semantics.
132 /// The underlying value can be retrieved through the `.0` index of the
133 /// `Wrapping` tuple.
138 /// use std::num::Wrapping;
140 /// let zero = Wrapping(0u32);
141 /// let one = Wrapping(1u32);
143 /// assert_eq!(std::u32::MAX, (zero - one).0);
145 #[stable(feature = "rust1", since = "1.0.0")]
146 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
148 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
151 #[stable(feature = "rust1", since = "1.0.0")]
152 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158 #[stable(feature = "wrapping_display", since = "1.10.0")]
159 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
160 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
165 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
166 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
172 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
173 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
174 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
179 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
180 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
181 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
186 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
187 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
188 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
193 // All these modules are technically private and only exposed for coretests:
201 // `Int` + `SignedInt` implemented for signed integers
202 macro_rules! int_impl {
203 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
204 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
205 $reversed:expr, $le_bytes:expr, $be_bytes:expr) => {
207 concat!("Returns the smallest value that can be represented by this integer type.
214 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
217 #[stable(feature = "rust1", since = "1.0.0")]
220 pub const fn min_value() -> Self {
221 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
226 concat!("Returns the largest value that can be represented by this integer type.
233 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
236 #[stable(feature = "rust1", since = "1.0.0")]
239 pub const fn max_value() -> Self {
245 concat!("Converts a string slice in a given base to an integer.
247 The string is expected to be an optional `+` or `-` sign followed by digits.
248 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
249 depending on `radix`:
257 This function panics if `radix` is not in the range from 2 to 36.
264 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
269 from_str_radix(src, radix)
274 concat!("Returns the number of ones in the binary representation of `self`.
281 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
283 assert_eq!(n.count_ones(), 1);",
287 #[stable(feature = "rust1", since = "1.0.0")]
288 #[rustc_const_unstable(feature = "const_int_ops")]
290 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
294 concat!("Returns the number of zeros in the binary representation of `self`.
301 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
303 #[stable(feature = "rust1", since = "1.0.0")]
304 #[rustc_const_unstable(feature = "const_int_ops")]
306 pub const fn count_zeros(self) -> u32 {
312 concat!("Returns the number of leading zeros in the binary representation of `self`.
319 ", $Feature, "let n = -1", stringify!($SelfT), ";
321 assert_eq!(n.leading_zeros(), 0);",
324 #[stable(feature = "rust1", since = "1.0.0")]
325 #[rustc_const_unstable(feature = "const_int_ops")]
327 pub const fn leading_zeros(self) -> u32 {
328 (self as $UnsignedT).leading_zeros()
333 concat!("Returns the number of trailing zeros in the binary representation of `self`.
340 ", $Feature, "let n = -4", stringify!($SelfT), ";
342 assert_eq!(n.trailing_zeros(), 2);",
345 #[stable(feature = "rust1", since = "1.0.0")]
346 #[rustc_const_unstable(feature = "const_int_ops")]
348 pub const fn trailing_zeros(self) -> u32 {
349 (self as $UnsignedT).trailing_zeros()
354 concat!("Shifts the bits to the left by a specified amount, `n`,
355 wrapping the truncated bits to the end of the resulting integer.
357 Please note this isn't the same operation as `<<`!
364 let n = ", $rot_op, stringify!($SelfT), ";
365 let m = ", $rot_result, ";
367 assert_eq!(n.rotate_left(", $rot, "), m);
369 #[stable(feature = "rust1", since = "1.0.0")]
370 #[rustc_const_unstable(feature = "const_int_rotate")]
372 pub const fn rotate_left(self, n: u32) -> Self {
373 (self as $UnsignedT).rotate_left(n) as Self
378 concat!("Shifts the bits to the right by a specified amount, `n`,
379 wrapping the truncated bits to the beginning of the resulting
382 Please note this isn't the same operation as `>>`!
389 let n = ", $rot_result, stringify!($SelfT), ";
390 let m = ", $rot_op, ";
392 assert_eq!(n.rotate_right(", $rot, "), m);
394 #[stable(feature = "rust1", since = "1.0.0")]
395 #[rustc_const_unstable(feature = "const_int_rotate")]
397 pub const fn rotate_right(self, n: u32) -> Self {
398 (self as $UnsignedT).rotate_right(n) as Self
403 concat!("Reverses the byte order of the integer.
410 let n = ", $swap_op, stringify!($SelfT), ";
412 let m = n.swap_bytes();
414 assert_eq!(m, ", $swapped, ");
416 #[stable(feature = "rust1", since = "1.0.0")]
417 #[rustc_const_unstable(feature = "const_int_ops")]
419 pub const fn swap_bytes(self) -> Self {
420 (self as $UnsignedT).swap_bytes() as Self
425 concat!("Reverses the bit pattern of the integer.
432 #![feature(reverse_bits)]
434 let n = ", $swap_op, stringify!($SelfT), ";
435 let m = n.reverse_bits();
437 assert_eq!(m, ", $reversed, ");
439 #[unstable(feature = "reverse_bits", issue = "48763")]
440 #[rustc_const_unstable(feature = "const_int_conversion")]
442 pub const fn reverse_bits(self) -> Self {
443 (self as $UnsignedT).reverse_bits() as Self
448 concat!("Converts an integer from big endian to the target's endianness.
450 On big endian this is a no-op. On little endian the bytes are swapped.
457 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
459 if cfg!(target_endian = \"big\") {
460 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
462 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
466 #[stable(feature = "rust1", since = "1.0.0")]
467 #[rustc_const_unstable(feature = "const_int_ops")]
469 pub const fn from_be(x: Self) -> Self {
470 #[cfg(target_endian = "big")]
474 #[cfg(not(target_endian = "big"))]
482 concat!("Converts an integer from little endian to the target's endianness.
484 On little endian this is a no-op. On big endian the bytes are swapped.
491 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
493 if cfg!(target_endian = \"little\") {
494 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
496 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
500 #[stable(feature = "rust1", since = "1.0.0")]
501 #[rustc_const_unstable(feature = "const_int_ops")]
503 pub const fn from_le(x: Self) -> Self {
504 #[cfg(target_endian = "little")]
508 #[cfg(not(target_endian = "little"))]
516 concat!("Converts `self` to big endian from the target's endianness.
518 On big endian this is a no-op. On little endian the bytes are swapped.
525 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
527 if cfg!(target_endian = \"big\") {
528 assert_eq!(n.to_be(), n)
530 assert_eq!(n.to_be(), n.swap_bytes())
534 #[stable(feature = "rust1", since = "1.0.0")]
535 #[rustc_const_unstable(feature = "const_int_ops")]
537 pub const fn to_be(self) -> Self { // or not to be?
538 #[cfg(target_endian = "big")]
542 #[cfg(not(target_endian = "big"))]
550 concat!("Converts `self` to little endian from the target's endianness.
552 On little endian this is a no-op. On big endian the bytes are swapped.
559 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
561 if cfg!(target_endian = \"little\") {
562 assert_eq!(n.to_le(), n)
564 assert_eq!(n.to_le(), n.swap_bytes())
568 #[stable(feature = "rust1", since = "1.0.0")]
569 #[rustc_const_unstable(feature = "const_int_ops")]
571 pub const fn to_le(self) -> Self {
572 #[cfg(target_endian = "little")]
576 #[cfg(not(target_endian = "little"))]
584 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
585 if overflow occurred.
592 ", $Feature, "assert_eq!((", stringify!($SelfT),
593 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
594 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
597 #[stable(feature = "rust1", since = "1.0.0")]
599 pub fn checked_add(self, rhs: Self) -> Option<Self> {
600 let (a, b) = self.overflowing_add(rhs);
601 if b {None} else {Some(a)}
606 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
614 ", $Feature, "assert_eq!((", stringify!($SelfT),
615 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
616 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
619 #[stable(feature = "rust1", since = "1.0.0")]
621 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
622 let (a, b) = self.overflowing_sub(rhs);
623 if b {None} else {Some(a)}
628 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
636 ", $Feature, "assert_eq!(", stringify!($SelfT),
637 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
638 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
641 #[stable(feature = "rust1", since = "1.0.0")]
643 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
644 let (a, b) = self.overflowing_mul(rhs);
645 if b {None} else {Some(a)}
650 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
651 or the division results in overflow.
658 ", $Feature, "assert_eq!((", stringify!($SelfT),
659 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
660 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
661 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
664 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn checked_div(self, rhs: Self) -> Option<Self> {
667 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
670 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
676 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`,
677 returning `None` if `rhs == 0` or the division results in overflow.
684 #![feature(euclidean_division)]
685 assert_eq!((", stringify!($SelfT),
686 "::min_value() + 1).checked_div_euc(-1), Some(", stringify!($Max), "));
687 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euc(-1), None);
688 assert_eq!((1", stringify!($SelfT), ").checked_div_euc(0), None);
690 #[unstable(feature = "euclidean_division", issue = "49048")]
692 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
693 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
696 Some(self.div_euc(rhs))
702 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
703 `rhs == 0` or the division results in overflow.
710 ", $Feature, "use std::", stringify!($SelfT), ";
712 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
713 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
714 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
717 #[stable(feature = "wrapping", since = "1.7.0")]
719 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
720 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
723 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
729 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None` if
730 `rhs == 0` or the division results in overflow.
737 #![feature(euclidean_division)]
738 use std::", stringify!($SelfT), ";
740 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
741 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
742 assert_eq!(", stringify!($SelfT), "::MIN.checked_mod_euc(-1), None);
744 #[unstable(feature = "euclidean_division", issue = "49048")]
746 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
747 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
750 Some(self.mod_euc(rhs))
756 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
763 ", $Feature, "use std::", stringify!($SelfT), ";
765 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
766 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
769 #[stable(feature = "wrapping", since = "1.7.0")]
771 pub fn checked_neg(self) -> Option<Self> {
772 let (a, b) = self.overflowing_neg();
773 if b {None} else {Some(a)}
778 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
779 than or equal to the number of bits in `self`.
786 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
787 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
790 #[stable(feature = "wrapping", since = "1.7.0")]
792 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
793 let (a, b) = self.overflowing_shl(rhs);
794 if b {None} else {Some(a)}
799 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
800 larger than or equal to the number of bits in `self`.
807 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
808 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
811 #[stable(feature = "wrapping", since = "1.7.0")]
813 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
814 let (a, b) = self.overflowing_shr(rhs);
815 if b {None} else {Some(a)}
820 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
828 ", $Feature, "use std::", stringify!($SelfT), ";
830 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
831 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
834 #[stable(feature = "no_panic_abs", since = "1.13.0")]
836 pub fn checked_abs(self) -> Option<Self> {
837 if self.is_negative() {
846 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
854 #![feature(no_panic_pow)]
855 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
856 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
860 #[unstable(feature = "no_panic_pow", issue = "48320")]
862 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
864 let mut acc: Self = 1;
868 acc = acc.checked_mul(base)?;
871 base = base.checked_mul(base)?;
874 // Deal with the final bit of the exponent separately, since
875 // squaring the base afterwards is not necessary and may cause a
876 // needless overflow.
878 acc = acc.checked_mul(base)?;
886 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
887 bounds instead of overflowing.
894 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
895 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
899 #[stable(feature = "rust1", since = "1.0.0")]
901 pub fn saturating_add(self, rhs: Self) -> Self {
902 match self.checked_add(rhs) {
904 None if rhs >= 0 => Self::max_value(),
905 None => Self::min_value(),
911 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
912 numeric bounds instead of overflowing.
919 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
920 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
924 #[stable(feature = "rust1", since = "1.0.0")]
926 pub fn saturating_sub(self, rhs: Self) -> Self {
927 match self.checked_sub(rhs) {
929 None if rhs >= 0 => Self::min_value(),
930 None => Self::max_value(),
936 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
937 numeric bounds instead of overflowing.
944 ", $Feature, "use std::", stringify!($SelfT), ";
946 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
947 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
948 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
951 #[stable(feature = "wrapping", since = "1.7.0")]
953 pub fn saturating_mul(self, rhs: Self) -> Self {
954 self.checked_mul(rhs).unwrap_or_else(|| {
955 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
965 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
966 saturating at the numeric bounds instead of overflowing.
973 #![feature(no_panic_pow)]
974 ", $Feature, "use std::", stringify!($SelfT), ";
976 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
977 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
978 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
981 #[unstable(feature = "no_panic_pow", issue = "48320")]
983 pub fn saturating_pow(self, exp: u32) -> Self {
984 match self.checked_pow(exp) {
986 None if self < 0 && exp % 2 == 1 => Self::min_value(),
987 None => Self::max_value(),
993 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
994 boundary of the type.
1001 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1002 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
1003 "::min_value() + 1);",
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 #[rustc_const_unstable(feature = "const_int_wrapping")]
1009 pub const fn wrapping_add(self, rhs: Self) -> Self {
1011 intrinsics::overflowing_add(self, rhs)
1017 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1018 boundary of the type.
1025 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1026 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1027 stringify!($SelfT), "::max_value());",
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 #[rustc_const_unstable(feature = "const_int_wrapping")]
1033 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1035 intrinsics::overflowing_sub(self, rhs)
1041 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1042 the boundary of the type.
1049 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1050 assert_eq!(11i8.wrapping_mul(12), -124);",
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 #[rustc_const_unstable(feature = "const_int_wrapping")]
1056 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1058 intrinsics::overflowing_mul(self, rhs)
1064 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1065 boundary of the type.
1067 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1068 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1069 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1073 This function will panic if `rhs` is 0.
1080 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1081 assert_eq!((-128i8).wrapping_div(-1), -128);",
1084 #[stable(feature = "num_wrapping", since = "1.2.0")]
1086 pub fn wrapping_div(self, rhs: Self) -> Self {
1087 self.overflowing_div(rhs).0
1092 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`,
1093 wrapping around at the boundary of the type.
1095 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1096 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1097 type. In this case, this method returns `MIN` itself.
1101 This function will panic if `rhs` is 0.
1108 #![feature(euclidean_division)]
1109 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
1110 assert_eq!((-128i8).wrapping_div_euc(-1), -128);
1112 #[unstable(feature = "euclidean_division", issue = "49048")]
1114 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
1115 self.overflowing_div_euc(rhs).0
1120 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1121 boundary of the type.
1123 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1124 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1125 this function returns `0`.
1129 This function will panic if `rhs` is 0.
1136 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1137 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1140 #[stable(feature = "num_wrapping", since = "1.2.0")]
1142 pub fn wrapping_rem(self, rhs: Self) -> Self {
1143 self.overflowing_rem(rhs).0
1148 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`, wrapping around at the
1149 boundary of the type.
1151 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1152 for the type). In this case, this method returns 0.
1156 This function will panic if `rhs` is 0.
1163 #![feature(euclidean_division)]
1164 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
1165 assert_eq!((-128i8).wrapping_mod_euc(-1), 0);
1167 #[unstable(feature = "euclidean_division", issue = "49048")]
1169 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
1170 self.overflowing_mod_euc(rhs).0
1175 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1178 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1179 is the negative minimal value for the type); this is a positive value that is too large to represent
1180 in the type. In such a case, this function returns `MIN` itself.
1187 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1188 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1192 #[stable(feature = "num_wrapping", since = "1.2.0")]
1194 pub fn wrapping_neg(self) -> Self {
1195 self.overflowing_neg().0
1200 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1201 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1203 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1204 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1205 The primitive integer types all implement a `rotate_left` function, which may be what you want
1213 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1214 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1217 #[stable(feature = "num_wrapping", since = "1.2.0")]
1218 #[rustc_const_unstable(feature = "const_int_wrapping")]
1220 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1222 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1228 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1229 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1231 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1232 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1233 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1241 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1242 assert_eq!((-128i16).wrapping_shr(64), -128);",
1245 #[stable(feature = "num_wrapping", since = "1.2.0")]
1246 #[rustc_const_unstable(feature = "const_int_wrapping")]
1248 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1250 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1256 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1257 the boundary of the type.
1259 The only case where such wrapping can occur is when one takes the absolute value of the negative
1260 minimal value for the type this is a positive value that is too large to represent in the type. In
1261 such a case, this function returns `MIN` itself.
1268 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1269 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1270 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1272 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1275 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1277 pub fn wrapping_abs(self) -> Self {
1278 if self.is_negative() {
1287 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1288 wrapping around at the boundary of the type.
1295 #![feature(no_panic_pow)]
1296 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1297 assert_eq!(3i8.wrapping_pow(5), -13);
1298 assert_eq!(3i8.wrapping_pow(6), -39);",
1301 #[unstable(feature = "no_panic_pow", issue = "48320")]
1303 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1304 let mut base = self;
1305 let mut acc: Self = 1;
1309 acc = acc.wrapping_mul(base);
1312 base = base.wrapping_mul(base);
1315 // Deal with the final bit of the exponent separately, since
1316 // squaring the base afterwards is not necessary and may cause a
1317 // needless overflow.
1319 acc = acc.wrapping_mul(base);
1327 concat!("Calculates `self` + `rhs`
1329 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1330 occur. If an overflow would have occurred then the wrapped value is returned.
1337 ", $Feature, "use std::", stringify!($SelfT), ";
1339 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1340 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1341 "::MIN, true));", $EndFeature, "
1343 #[stable(feature = "wrapping", since = "1.7.0")]
1344 #[rustc_const_unstable(feature = "const_int_overflowing")]
1346 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1347 let (a, b) = unsafe {
1348 intrinsics::add_with_overflow(self as $ActualT,
1356 concat!("Calculates `self` - `rhs`
1358 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1359 would occur. If an overflow would have occurred then the wrapped value is returned.
1366 ", $Feature, "use std::", stringify!($SelfT), ";
1368 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1369 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1370 "::MAX, true));", $EndFeature, "
1372 #[stable(feature = "wrapping", since = "1.7.0")]
1373 #[rustc_const_unstable(feature = "const_int_overflowing")]
1375 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1376 let (a, b) = unsafe {
1377 intrinsics::sub_with_overflow(self as $ActualT,
1385 concat!("Calculates the multiplication of `self` and `rhs`.
1387 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1388 would occur. If an overflow would have occurred then the wrapped value is returned.
1395 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1396 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1399 #[stable(feature = "wrapping", since = "1.7.0")]
1400 #[rustc_const_unstable(feature = "const_int_overflowing")]
1402 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1403 let (a, b) = unsafe {
1404 intrinsics::mul_with_overflow(self as $ActualT,
1412 concat!("Calculates the divisor when `self` is divided by `rhs`.
1414 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1415 occur. If an overflow would occur then self is returned.
1419 This function will panic if `rhs` is 0.
1426 ", $Feature, "use std::", stringify!($SelfT), ";
1428 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1429 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1434 #[stable(feature = "wrapping", since = "1.7.0")]
1435 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1436 if self == Self::min_value() && rhs == -1 {
1445 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
1447 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1448 occur. If an overflow would occur then `self` is returned.
1452 This function will panic if `rhs` is 0.
1459 #![feature(euclidean_division)]
1460 use std::", stringify!($SelfT), ";
1462 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
1463 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euc(-1), (", stringify!($SelfT),
1467 #[unstable(feature = "euclidean_division", issue = "49048")]
1468 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
1469 if self == Self::min_value() && rhs == -1 {
1472 (self.div_euc(rhs), false)
1478 concat!("Calculates the remainder when `self` is divided by `rhs`.
1480 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1481 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1485 This function will panic if `rhs` is 0.
1492 ", $Feature, "use std::", stringify!($SelfT), ";
1494 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1495 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1499 #[stable(feature = "wrapping", since = "1.7.0")]
1500 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1501 if self == Self::min_value() && rhs == -1 {
1511 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
1513 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1514 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1518 This function will panic if `rhs` is 0.
1525 #![feature(euclidean_division)]
1526 use std::", stringify!($SelfT), ";
1528 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
1529 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_mod_euc(-1), (0, true));
1531 #[unstable(feature = "euclidean_division", issue = "49048")]
1533 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
1534 if self == Self::min_value() && rhs == -1 {
1537 (self.mod_euc(rhs), false)
1544 concat!("Negates self, overflowing if this is equal to the minimum value.
1546 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1547 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1548 minimum value will be returned again and `true` will be returned for an overflow happening.
1555 ", $Feature, "use std::", stringify!($SelfT), ";
1557 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1558 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1559 "::MIN, true));", $EndFeature, "
1562 #[stable(feature = "wrapping", since = "1.7.0")]
1563 pub fn overflowing_neg(self) -> (Self, bool) {
1564 if self == Self::min_value() {
1565 (Self::min_value(), true)
1573 concat!("Shifts self left by `rhs` bits.
1575 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1576 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1577 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1584 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1585 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1588 #[stable(feature = "wrapping", since = "1.7.0")]
1589 #[rustc_const_unstable(feature = "const_int_overflowing")]
1591 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1592 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1597 concat!("Shifts self right by `rhs` bits.
1599 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1600 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1601 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1608 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1609 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1612 #[stable(feature = "wrapping", since = "1.7.0")]
1613 #[rustc_const_unstable(feature = "const_int_overflowing")]
1615 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1616 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1621 concat!("Computes the absolute value of `self`.
1623 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1624 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1625 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1626 for an overflow happening.
1633 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1634 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1635 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1636 "::min_value(), true));",
1639 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1641 pub fn overflowing_abs(self) -> (Self, bool) {
1642 if self.is_negative() {
1643 self.overflowing_neg()
1651 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1653 Returns a tuple of the exponentiation along with a bool indicating
1654 whether an overflow happened.
1661 #![feature(no_panic_pow)]
1662 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1663 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1666 #[unstable(feature = "no_panic_pow", issue = "48320")]
1668 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1669 let mut base = self;
1670 let mut acc: Self = 1;
1671 let mut overflown = false;
1672 // Scratch space for storing results of overflowing_mul.
1677 r = acc.overflowing_mul(base);
1682 r = base.overflowing_mul(base);
1687 // Deal with the final bit of the exponent separately, since
1688 // squaring the base afterwards is not necessary and may cause a
1689 // needless overflow.
1691 r = acc.overflowing_mul(base);
1701 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1708 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1710 assert_eq!(x.pow(5), 32);",
1713 #[stable(feature = "rust1", since = "1.0.0")]
1715 #[rustc_inherit_overflow_checks]
1716 pub fn pow(self, mut exp: u32) -> Self {
1717 let mut base = self;
1728 // Deal with the final bit of the exponent separately, since
1729 // squaring the base afterwards is not necessary and may cause a
1730 // needless overflow.
1740 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1742 This computes the integer `n` such that `self = n * rhs + self.mod_euc(rhs)`.
1743 In other words, the result is `self / rhs` rounded to the integer `n`
1744 such that `self >= n * rhs`.
1748 This function will panic if `rhs` is 0.
1755 #![feature(euclidean_division)]
1756 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1759 assert_eq!(a.div_euc(b), 1); // 7 >= 4 * 1
1760 assert_eq!(a.div_euc(-b), -1); // 7 >= -4 * -1
1761 assert_eq!((-a).div_euc(b), -2); // -7 >= 4 * -2
1762 assert_eq!((-a).div_euc(-b), 2); // -7 >= -4 * 2
1764 #[unstable(feature = "euclidean_division", issue = "49048")]
1766 #[rustc_inherit_overflow_checks]
1767 pub fn div_euc(self, rhs: Self) -> Self {
1770 return if rhs > 0 { q - 1 } else { q + 1 }
1778 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
1780 In particular, the result `n` satisfies `0 <= n < rhs.abs()`.
1784 This function will panic if `rhs` is 0.
1791 #![feature(euclidean_division)]
1792 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1795 assert_eq!(a.mod_euc(b), 3);
1796 assert_eq!((-a).mod_euc(b), 1);
1797 assert_eq!(a.mod_euc(-b), 3);
1798 assert_eq!((-a).mod_euc(-b), 1);
1800 #[unstable(feature = "euclidean_division", issue = "49048")]
1802 #[rustc_inherit_overflow_checks]
1803 pub fn mod_euc(self, rhs: Self) -> Self {
1818 concat!("Computes the absolute value of `self`.
1822 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1823 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1824 code in debug mode will trigger a panic on this case and optimized code will return `",
1825 stringify!($SelfT), "::min_value()` without a panic.
1832 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1833 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1836 #[stable(feature = "rust1", since = "1.0.0")]
1838 #[rustc_inherit_overflow_checks]
1839 pub fn abs(self) -> Self {
1840 if self.is_negative() {
1841 // Note that the #[inline] above means that the overflow
1842 // semantics of this negation depend on the crate we're being
1852 concat!("Returns a number representing sign of `self`.
1854 - `0` if the number is zero
1855 - `1` if the number is positive
1856 - `-1` if the number is negative
1863 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1864 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1865 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1868 #[stable(feature = "rust1", since = "1.0.0")]
1870 pub fn signum(self) -> Self {
1880 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1888 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1889 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1892 #[stable(feature = "rust1", since = "1.0.0")]
1893 #[rustc_const_unstable(feature = "const_int_sign")]
1895 pub const fn is_positive(self) -> bool { self > 0 }
1899 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1907 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1908 assert!(!10", stringify!($SelfT), ".is_negative());",
1911 #[stable(feature = "rust1", since = "1.0.0")]
1912 #[rustc_const_unstable(feature = "const_int_sign")]
1914 pub const fn is_negative(self) -> bool { self < 0 }
1918 concat!("Return the memory representation of this integer as a byte array in
1919 big-endian (network) byte order.
1924 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
1925 assert_eq!(bytes, ", $be_bytes, ");
1927 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1928 #[rustc_const_unstable(feature = "const_int_conversion")]
1930 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
1931 self.to_be().to_ne_bytes()
1936 concat!("Return the memory representation of this integer as a byte array in
1937 little-endian byte order.
1942 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
1943 assert_eq!(bytes, ", $le_bytes, ");
1945 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1946 #[rustc_const_unstable(feature = "const_int_conversion")]
1948 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
1949 self.to_le().to_ne_bytes()
1955 Return the memory representation of this integer as a byte array in
1958 As the target platform's native endianness is used, portable code
1959 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
1962 [`to_be_bytes`]: #method.to_be_bytes
1963 [`to_le_bytes`]: #method.to_le_bytes
1968 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
1969 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
1975 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1976 #[rustc_const_unstable(feature = "const_int_conversion")]
1978 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
1979 unsafe { mem::transmute(self) }
1984 concat!("Create an integer value from its representation as a byte array in
1990 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
1991 assert_eq!(value, ", $swap_op, ");
1993 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1994 #[rustc_const_unstable(feature = "const_int_conversion")]
1996 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1997 Self::from_be(Self::from_ne_bytes(bytes))
2003 Create an integer value from its representation as a byte array in
2009 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2010 assert_eq!(value, ", $swap_op, ");
2012 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2013 #[rustc_const_unstable(feature = "const_int_conversion")]
2015 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2016 Self::from_le(Self::from_ne_bytes(bytes))
2021 concat!("Create an integer value from its memory representation as a byte
2022 array in native endianness.
2024 As the target platform's native endianness is used, portable code
2025 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2026 appropriate instead.
2028 [`from_be_bytes`]: #method.from_be_bytes
2029 [`from_le_bytes`]: #method.from_le_bytes
2034 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2039 assert_eq!(value, ", $swap_op, ");
2041 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2042 #[rustc_const_unstable(feature = "const_int_conversion")]
2044 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2045 unsafe { mem::transmute(bytes) }
2053 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2054 "[0x12]", "[0x12]" }
2059 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2060 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]" }
2065 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2066 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2067 "[0x12, 0x34, 0x56, 0x78]" }
2072 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2073 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2074 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2075 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
2080 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2081 170141183460469231731687303715884105727, "", "", 16,
2082 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2083 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2084 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2085 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2086 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2087 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]" }
2090 #[cfg(target_pointer_width = "16")]
2093 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2094 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]" }
2097 #[cfg(target_pointer_width = "32")]
2100 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2101 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2102 "[0x12, 0x34, 0x56, 0x78]" }
2105 #[cfg(target_pointer_width = "64")]
2108 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2109 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2110 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2111 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
2114 // Emits the correct `cttz` call, depending on the size of the type.
2115 macro_rules! uint_cttz_call {
2116 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
2117 // emits two conditional moves on x86_64. By promoting the value to
2118 // u16 and setting bit 8, we get better code without any conditional
2120 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
2121 // pending, remove this workaround once LLVM generates better code
2123 ($value:expr, 8) => { intrinsics::cttz($value as u16 | 0x100) };
2124 ($value:expr, $_BITS:expr) => { intrinsics::cttz($value) }
2127 // `Int` + `UnsignedInt` implemented for unsigned integers
2128 macro_rules! uint_impl {
2129 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2130 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2131 $reversed:expr, $le_bytes:expr, $be_bytes:expr) => {
2133 concat!("Returns the smallest value that can be represented by this integer type.
2140 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2142 #[stable(feature = "rust1", since = "1.0.0")]
2145 pub const fn min_value() -> Self { 0 }
2149 concat!("Returns the largest value that can be represented by this integer type.
2156 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2157 stringify!($MaxV), ");", $EndFeature, "
2159 #[stable(feature = "rust1", since = "1.0.0")]
2162 pub const fn max_value() -> Self { !0 }
2166 concat!("Converts a string slice in a given base to an integer.
2168 The string is expected to be an optional `+` sign
2170 Leading and trailing whitespace represent an error.
2171 Digits are a subset of these characters, depending on `radix`:
2179 This function panics if `radix` is not in the range from 2 to 36.
2186 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2189 #[stable(feature = "rust1", since = "1.0.0")]
2190 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2191 from_str_radix(src, radix)
2196 concat!("Returns the number of ones in the binary representation of `self`.
2203 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2205 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2207 #[stable(feature = "rust1", since = "1.0.0")]
2208 #[rustc_const_unstable(feature = "const_int_ops")]
2210 pub const fn count_ones(self) -> u32 {
2211 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
2216 concat!("Returns the number of zeros in the binary representation of `self`.
2223 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2225 #[stable(feature = "rust1", since = "1.0.0")]
2226 #[rustc_const_unstable(feature = "const_int_ops")]
2228 pub const fn count_zeros(self) -> u32 {
2229 (!self).count_ones()
2234 concat!("Returns the number of leading zeros in the binary representation of `self`.
2241 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2243 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2245 #[stable(feature = "rust1", since = "1.0.0")]
2246 #[rustc_const_unstable(feature = "const_int_ops")]
2248 pub const fn leading_zeros(self) -> u32 {
2249 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
2254 concat!("Returns the number of trailing zeros in the binary representation
2262 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2264 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2266 #[stable(feature = "rust1", since = "1.0.0")]
2267 #[rustc_const_unstable(feature = "const_int_ops")]
2269 pub const fn trailing_zeros(self) -> u32 {
2270 unsafe { uint_cttz_call!(self, $BITS) as u32 }
2275 concat!("Shifts the bits to the left by a specified amount, `n`,
2276 wrapping the truncated bits to the end of the resulting integer.
2278 Please note this isn't the same operation as `<<`!
2285 let n = ", $rot_op, stringify!($SelfT), ";
2286 let m = ", $rot_result, ";
2288 assert_eq!(n.rotate_left(", $rot, "), m);
2290 #[stable(feature = "rust1", since = "1.0.0")]
2291 #[rustc_const_unstable(feature = "const_int_rotate")]
2293 pub const fn rotate_left(self, n: u32) -> Self {
2294 #[cfg(not(stage0))] {
2295 unsafe { intrinsics::rotate_left(self, n as $SelfT) }
2298 (self << (n % $BITS)) | (self >> (($BITS - (n % $BITS)) % $BITS))
2304 concat!("Shifts the bits to the right by a specified amount, `n`,
2305 wrapping the truncated bits to the beginning of the resulting
2308 Please note this isn't the same operation as `>>`!
2315 let n = ", $rot_result, stringify!($SelfT), ";
2316 let m = ", $rot_op, ";
2318 assert_eq!(n.rotate_right(", $rot, "), m);
2320 #[stable(feature = "rust1", since = "1.0.0")]
2321 #[rustc_const_unstable(feature = "const_int_rotate")]
2323 pub const fn rotate_right(self, n: u32) -> Self {
2324 #[cfg(not(stage0))] {
2325 unsafe { intrinsics::rotate_right(self, n as $SelfT) }
2328 (self >> (n % $BITS)) | (self << (($BITS - (n % $BITS)) % $BITS))
2335 Reverses the byte order of the integer.
2342 let n = ", $swap_op, stringify!($SelfT), ";
2343 let m = n.swap_bytes();
2345 assert_eq!(m, ", $swapped, ");
2347 #[stable(feature = "rust1", since = "1.0.0")]
2348 #[rustc_const_unstable(feature = "const_int_ops")]
2350 pub const fn swap_bytes(self) -> Self {
2351 unsafe { intrinsics::bswap(self as $ActualT) as Self }
2356 concat!("Reverses the bit pattern of the integer.
2363 #![feature(reverse_bits)]
2365 let n = ", $swap_op, stringify!($SelfT), ";
2366 let m = n.reverse_bits();
2368 assert_eq!(m, ", $reversed, ");
2370 #[unstable(feature = "reverse_bits", issue = "48763")]
2371 #[rustc_const_unstable(feature = "const_int_conversion")]
2373 pub const fn reverse_bits(self) -> Self {
2374 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
2379 concat!("Converts an integer from big endian to the target's endianness.
2381 On big endian this is a no-op. On little endian the bytes are
2389 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2391 if cfg!(target_endian = \"big\") {
2392 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2394 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2397 #[stable(feature = "rust1", since = "1.0.0")]
2398 #[rustc_const_unstable(feature = "const_int_ops")]
2400 pub const fn from_be(x: Self) -> Self {
2401 #[cfg(target_endian = "big")]
2405 #[cfg(not(target_endian = "big"))]
2413 concat!("Converts an integer from little endian to the target's endianness.
2415 On little endian this is a no-op. On big endian the bytes are
2423 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2425 if cfg!(target_endian = \"little\") {
2426 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2428 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2431 #[stable(feature = "rust1", since = "1.0.0")]
2432 #[rustc_const_unstable(feature = "const_int_ops")]
2434 pub const fn from_le(x: Self) -> Self {
2435 #[cfg(target_endian = "little")]
2439 #[cfg(not(target_endian = "little"))]
2447 concat!("Converts `self` to big endian from the target's endianness.
2449 On big endian this is a no-op. On little endian the bytes are
2457 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2459 if cfg!(target_endian = \"big\") {
2460 assert_eq!(n.to_be(), n)
2462 assert_eq!(n.to_be(), n.swap_bytes())
2465 #[stable(feature = "rust1", since = "1.0.0")]
2466 #[rustc_const_unstable(feature = "const_int_ops")]
2468 pub const fn to_be(self) -> Self { // or not to be?
2469 #[cfg(target_endian = "big")]
2473 #[cfg(not(target_endian = "big"))]
2481 concat!("Converts `self` to little endian from the target's endianness.
2483 On little endian this is a no-op. On big endian the bytes are
2491 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2493 if cfg!(target_endian = \"little\") {
2494 assert_eq!(n.to_le(), n)
2496 assert_eq!(n.to_le(), n.swap_bytes())
2499 #[stable(feature = "rust1", since = "1.0.0")]
2500 #[rustc_const_unstable(feature = "const_int_ops")]
2502 pub const fn to_le(self) -> Self {
2503 #[cfg(target_endian = "little")]
2507 #[cfg(not(target_endian = "little"))]
2515 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2516 if overflow occurred.
2523 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2524 "Some(", stringify!($SelfT), "::max_value() - 1));
2525 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2527 #[stable(feature = "rust1", since = "1.0.0")]
2529 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2530 let (a, b) = self.overflowing_add(rhs);
2531 if b {None} else {Some(a)}
2536 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2537 `None` if overflow occurred.
2544 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2545 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2547 #[stable(feature = "rust1", since = "1.0.0")]
2549 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2550 let (a, b) = self.overflowing_sub(rhs);
2551 if b {None} else {Some(a)}
2556 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2557 `None` if overflow occurred.
2564 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2565 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2567 #[stable(feature = "rust1", since = "1.0.0")]
2569 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2570 let (a, b) = self.overflowing_mul(rhs);
2571 if b {None} else {Some(a)}
2576 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2584 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2585 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2587 #[stable(feature = "rust1", since = "1.0.0")]
2589 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2592 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2598 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`, returning `None`
2606 #![feature(euclidean_division)]
2607 assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2608 assert_eq!(1", stringify!($SelfT), ".checked_div_euc(0), None);
2610 #[unstable(feature = "euclidean_division", issue = "49048")]
2612 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
2616 Some(self.div_euc(rhs))
2623 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2631 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2632 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2634 #[stable(feature = "wrapping", since = "1.7.0")]
2636 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2640 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2646 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None`
2654 #![feature(euclidean_division)]
2655 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
2656 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
2658 #[unstable(feature = "euclidean_division", issue = "49048")]
2660 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
2664 Some(self.mod_euc(rhs))
2670 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2673 Note that negating any positive integer will overflow.
2680 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2681 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2683 #[stable(feature = "wrapping", since = "1.7.0")]
2685 pub fn checked_neg(self) -> Option<Self> {
2686 let (a, b) = self.overflowing_neg();
2687 if b {None} else {Some(a)}
2692 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2693 if `rhs` is larger than or equal to the number of bits in `self`.
2700 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2701 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2703 #[stable(feature = "wrapping", since = "1.7.0")]
2705 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2706 let (a, b) = self.overflowing_shl(rhs);
2707 if b {None} else {Some(a)}
2712 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2713 if `rhs` is larger than or equal to the number of bits in `self`.
2720 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2721 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2723 #[stable(feature = "wrapping", since = "1.7.0")]
2725 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2726 let (a, b) = self.overflowing_shr(rhs);
2727 if b {None} else {Some(a)}
2732 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2740 #![feature(no_panic_pow)]
2741 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2742 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2744 #[unstable(feature = "no_panic_pow", issue = "48320")]
2746 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2747 let mut base = self;
2748 let mut acc: Self = 1;
2752 acc = acc.checked_mul(base)?;
2755 base = base.checked_mul(base)?;
2758 // Deal with the final bit of the exponent separately, since
2759 // squaring the base afterwards is not necessary and may cause a
2760 // needless overflow.
2762 acc = acc.checked_mul(base)?;
2770 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2771 the numeric bounds instead of overflowing.
2778 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2779 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2781 #[stable(feature = "rust1", since = "1.0.0")]
2783 pub fn saturating_add(self, rhs: Self) -> Self {
2784 match self.checked_add(rhs) {
2786 None => Self::max_value(),
2792 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2793 at the numeric bounds instead of overflowing.
2800 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2801 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2803 #[stable(feature = "rust1", since = "1.0.0")]
2805 pub fn saturating_sub(self, rhs: Self) -> Self {
2806 match self.checked_sub(rhs) {
2808 None => Self::min_value(),
2814 concat!("Saturating integer multiplication. Computes `self * rhs`,
2815 saturating at the numeric bounds instead of overflowing.
2822 ", $Feature, "use std::", stringify!($SelfT), ";
2824 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2825 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2826 "::MAX);", $EndFeature, "
2828 #[stable(feature = "wrapping", since = "1.7.0")]
2830 pub fn saturating_mul(self, rhs: Self) -> Self {
2831 self.checked_mul(rhs).unwrap_or(Self::max_value())
2836 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2837 saturating at the numeric bounds instead of overflowing.
2844 #![feature(no_panic_pow)]
2845 ", $Feature, "use std::", stringify!($SelfT), ";
2847 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2848 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2851 #[unstable(feature = "no_panic_pow", issue = "48320")]
2853 pub fn saturating_pow(self, exp: u32) -> Self {
2854 match self.checked_pow(exp) {
2856 None => Self::max_value(),
2862 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2863 wrapping around at the boundary of the type.
2870 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2871 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2874 #[stable(feature = "rust1", since = "1.0.0")]
2875 #[rustc_const_unstable(feature = "const_int_wrapping")]
2877 pub const fn wrapping_add(self, rhs: Self) -> Self {
2879 intrinsics::overflowing_add(self, rhs)
2885 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2886 wrapping around at the boundary of the type.
2893 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2894 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2897 #[stable(feature = "rust1", since = "1.0.0")]
2898 #[rustc_const_unstable(feature = "const_int_wrapping")]
2900 pub const fn wrapping_sub(self, rhs: Self) -> Self {
2902 intrinsics::overflowing_sub(self, rhs)
2907 /// Wrapping (modular) multiplication. Computes `self *
2908 /// rhs`, wrapping around at the boundary of the type.
2914 /// Please note that this example is shared between integer types.
2915 /// Which explains why `u8` is used here.
2918 /// assert_eq!(10u8.wrapping_mul(12), 120);
2919 /// assert_eq!(25u8.wrapping_mul(12), 44);
2921 #[stable(feature = "rust1", since = "1.0.0")]
2922 #[rustc_const_unstable(feature = "const_int_wrapping")]
2924 pub const fn wrapping_mul(self, rhs: Self) -> Self {
2926 intrinsics::overflowing_mul(self, rhs)
2931 concat!("Wrapping (modular) division. Computes `self / rhs`.
2932 Wrapped division on unsigned types is just normal division.
2933 There's no way wrapping could ever happen.
2934 This function exists, so that all operations
2935 are accounted for in the wrapping operations.
2942 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2944 #[stable(feature = "num_wrapping", since = "1.2.0")]
2946 pub fn wrapping_div(self, rhs: Self) -> Self {
2952 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`.
2953 Wrapped division on unsigned types is just normal division.
2954 There's no way wrapping could ever happen.
2955 This function exists, so that all operations
2956 are accounted for in the wrapping operations.
2963 #![feature(euclidean_division)]
2964 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
2966 #[unstable(feature = "euclidean_division", issue = "49048")]
2968 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
2974 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2975 Wrapped remainder calculation on unsigned types is
2976 just the regular remainder calculation.
2977 There's no way wrapping could ever happen.
2978 This function exists, so that all operations
2979 are accounted for in the wrapping operations.
2986 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2988 #[stable(feature = "num_wrapping", since = "1.2.0")]
2990 pub fn wrapping_rem(self, rhs: Self) -> Self {
2996 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`.
2997 Wrapped modulo calculation on unsigned types is
2998 just the regular remainder calculation.
2999 There's no way wrapping could ever happen.
3000 This function exists, so that all operations
3001 are accounted for in the wrapping operations.
3008 #![feature(euclidean_division)]
3009 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
3011 #[unstable(feature = "euclidean_division", issue = "49048")]
3013 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
3018 /// Wrapping (modular) negation. Computes `-self`,
3019 /// wrapping around at the boundary of the type.
3021 /// Since unsigned types do not have negative equivalents
3022 /// all applications of this function will wrap (except for `-0`).
3023 /// For values smaller than the corresponding signed type's maximum
3024 /// the result is the same as casting the corresponding signed value.
3025 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3026 /// `MAX` is the corresponding signed type's maximum.
3032 /// Please note that this example is shared between integer types.
3033 /// Which explains why `i8` is used here.
3036 /// assert_eq!(100i8.wrapping_neg(), -100);
3037 /// assert_eq!((-128i8).wrapping_neg(), -128);
3039 #[stable(feature = "num_wrapping", since = "1.2.0")]
3041 pub fn wrapping_neg(self) -> Self {
3042 self.overflowing_neg().0
3046 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3047 where `mask` removes any high-order bits of `rhs` that
3048 would cause the shift to exceed the bitwidth of the type.
3050 Note that this is *not* the same as a rotate-left; the
3051 RHS of a wrapping shift-left is restricted to the range
3052 of the type, rather than the bits shifted out of the LHS
3053 being returned to the other end. The primitive integer
3054 types all implement a `rotate_left` function, which may
3055 be what you want instead.
3062 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3063 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3065 #[stable(feature = "num_wrapping", since = "1.2.0")]
3066 #[rustc_const_unstable(feature = "const_int_wrapping")]
3068 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3070 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3076 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3077 where `mask` removes any high-order bits of `rhs` that
3078 would cause the shift to exceed the bitwidth of the type.
3080 Note that this is *not* the same as a rotate-right; the
3081 RHS of a wrapping shift-right is restricted to the range
3082 of the type, rather than the bits shifted out of the LHS
3083 being returned to the other end. The primitive integer
3084 types all implement a `rotate_right` function, which may
3085 be what you want instead.
3092 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3093 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3095 #[stable(feature = "num_wrapping", since = "1.2.0")]
3096 #[rustc_const_unstable(feature = "const_int_wrapping")]
3098 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3100 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3106 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3107 wrapping around at the boundary of the type.
3114 #![feature(no_panic_pow)]
3115 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3116 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3118 #[unstable(feature = "no_panic_pow", issue = "48320")]
3120 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3121 let mut base = self;
3122 let mut acc: Self = 1;
3126 acc = acc.wrapping_mul(base);
3129 base = base.wrapping_mul(base);
3132 // Deal with the final bit of the exponent separately, since
3133 // squaring the base afterwards is not necessary and may cause a
3134 // needless overflow.
3136 acc = acc.wrapping_mul(base);
3144 concat!("Calculates `self` + `rhs`
3146 Returns a tuple of the addition along with a boolean indicating
3147 whether an arithmetic overflow would occur. If an overflow would
3148 have occurred then the wrapped value is returned.
3155 ", $Feature, "use std::", stringify!($SelfT), ";
3157 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3158 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3160 #[stable(feature = "wrapping", since = "1.7.0")]
3161 #[rustc_const_unstable(feature = "const_int_overflowing")]
3163 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3164 let (a, b) = unsafe {
3165 intrinsics::add_with_overflow(self as $ActualT,
3173 concat!("Calculates `self` - `rhs`
3175 Returns a tuple of the subtraction along with a boolean indicating
3176 whether an arithmetic overflow would occur. If an overflow would
3177 have occurred then the wrapped value is returned.
3184 ", $Feature, "use std::", stringify!($SelfT), ";
3186 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3187 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3190 #[stable(feature = "wrapping", since = "1.7.0")]
3191 #[rustc_const_unstable(feature = "const_int_overflowing")]
3193 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3194 let (a, b) = unsafe {
3195 intrinsics::sub_with_overflow(self as $ActualT,
3202 /// Calculates the multiplication of `self` and `rhs`.
3204 /// Returns a tuple of the multiplication along with a boolean
3205 /// indicating whether an arithmetic overflow would occur. If an
3206 /// overflow would have occurred then the wrapped value is returned.
3212 /// Please note that this example is shared between integer types.
3213 /// Which explains why `u32` is used here.
3216 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3217 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3219 #[stable(feature = "wrapping", since = "1.7.0")]
3220 #[rustc_const_unstable(feature = "const_int_overflowing")]
3222 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3223 let (a, b) = unsafe {
3224 intrinsics::mul_with_overflow(self as $ActualT,
3231 concat!("Calculates the divisor when `self` is divided by `rhs`.
3233 Returns a tuple of the divisor along with a boolean indicating
3234 whether an arithmetic overflow would occur. Note that for unsigned
3235 integers overflow never occurs, so the second value is always
3240 This function will panic if `rhs` is 0.
3247 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3250 #[stable(feature = "wrapping", since = "1.7.0")]
3251 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3257 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
3259 Returns a tuple of the divisor along with a boolean indicating
3260 whether an arithmetic overflow would occur. Note that for unsigned
3261 integers overflow never occurs, so the second value is always
3266 This function will panic if `rhs` is 0.
3273 #![feature(euclidean_division)]
3274 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
3277 #[unstable(feature = "euclidean_division", issue = "49048")]
3278 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
3284 concat!("Calculates the remainder when `self` is divided by `rhs`.
3286 Returns a tuple of the remainder after dividing along with a boolean
3287 indicating whether an arithmetic overflow would occur. Note that for
3288 unsigned integers overflow never occurs, so the second value is
3293 This function will panic if `rhs` is 0.
3300 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3303 #[stable(feature = "wrapping", since = "1.7.0")]
3304 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3310 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
3312 Returns a tuple of the modulo after dividing along with a boolean
3313 indicating whether an arithmetic overflow would occur. Note that for
3314 unsigned integers overflow never occurs, so the second value is
3319 This function will panic if `rhs` is 0.
3326 #![feature(euclidean_division)]
3327 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
3330 #[unstable(feature = "euclidean_division", issue = "49048")]
3331 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
3337 concat!("Negates self in an overflowing fashion.
3339 Returns `!self + 1` using wrapping operations to return the value
3340 that represents the negation of this unsigned value. Note that for
3341 positive unsigned values overflow always occurs, but negating 0 does
3349 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3350 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3351 ", true));", $EndFeature, "
3354 #[stable(feature = "wrapping", since = "1.7.0")]
3355 pub fn overflowing_neg(self) -> (Self, bool) {
3356 ((!self).wrapping_add(1), self != 0)
3361 concat!("Shifts self left by `rhs` bits.
3363 Returns a tuple of the shifted version of self along with a boolean
3364 indicating whether the shift value was larger than or equal to the
3365 number of bits. If the shift value is too large, then value is
3366 masked (N-1) where N is the number of bits, and this value is then
3367 used to perform the shift.
3374 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3375 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3377 #[stable(feature = "wrapping", since = "1.7.0")]
3378 #[rustc_const_unstable(feature = "const_int_overflowing")]
3380 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3381 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3386 concat!("Shifts self right by `rhs` bits.
3388 Returns a tuple of the shifted version of self along with a boolean
3389 indicating whether the shift value was larger than or equal to the
3390 number of bits. If the shift value is too large, then value is
3391 masked (N-1) where N is the number of bits, and this value is then
3392 used to perform the shift.
3399 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3400 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3402 #[stable(feature = "wrapping", since = "1.7.0")]
3403 #[rustc_const_unstable(feature = "const_int_overflowing")]
3405 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3406 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3411 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3413 Returns a tuple of the exponentiation along with a bool indicating
3414 whether an overflow happened.
3421 #![feature(no_panic_pow)]
3422 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3423 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3425 #[unstable(feature = "no_panic_pow", issue = "48320")]
3427 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3428 let mut base = self;
3429 let mut acc: Self = 1;
3430 let mut overflown = false;
3431 // Scratch space for storing results of overflowing_mul.
3436 r = acc.overflowing_mul(base);
3441 r = base.overflowing_mul(base);
3446 // Deal with the final bit of the exponent separately, since
3447 // squaring the base afterwards is not necessary and may cause a
3448 // needless overflow.
3450 r = acc.overflowing_mul(base);
3460 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3467 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3469 #[stable(feature = "rust1", since = "1.0.0")]
3471 #[rustc_inherit_overflow_checks]
3472 pub fn pow(self, mut exp: u32) -> Self {
3473 let mut base = self;
3484 // Deal with the final bit of the exponent separately, since
3485 // squaring the base afterwards is not necessary and may cause a
3486 // needless overflow.
3496 concat!("Performs Euclidean division.
3498 For unsigned types, this is just the same as `self / rhs`.
3505 #![feature(euclidean_division)]
3506 assert_eq!(7", stringify!($SelfT), ".div_euc(4), 1); // or any other integer type
3508 #[unstable(feature = "euclidean_division", issue = "49048")]
3510 #[rustc_inherit_overflow_checks]
3511 pub fn div_euc(self, rhs: Self) -> Self {
3518 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
3520 For unsigned types, this is just the same as `self % rhs`.
3527 #![feature(euclidean_division)]
3528 assert_eq!(7", stringify!($SelfT), ".mod_euc(4), 3); // or any other integer type
3530 #[unstable(feature = "euclidean_division", issue = "49048")]
3532 #[rustc_inherit_overflow_checks]
3533 pub fn mod_euc(self, rhs: Self) -> Self {
3539 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3546 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3547 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3549 #[stable(feature = "rust1", since = "1.0.0")]
3551 pub fn is_power_of_two(self) -> bool {
3552 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3556 // Returns one less than next power of two.
3557 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3559 // 8u8.one_less_than_next_power_of_two() == 7
3560 // 6u8.one_less_than_next_power_of_two() == 7
3562 // This method cannot overflow, as in the `next_power_of_two`
3563 // overflow cases it instead ends up returning the maximum value
3564 // of the type, and can return 0 for 0.
3566 fn one_less_than_next_power_of_two(self) -> Self {
3567 if self <= 1 { return 0; }
3569 // Because `p > 0`, it cannot consist entirely of leading zeros.
3570 // That means the shift is always in-bounds, and some processors
3571 // (such as intel pre-haswell) have more efficient ctlz
3572 // intrinsics when the argument is non-zero.
3574 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3575 <$SelfT>::max_value() >> z
3579 concat!("Returns the smallest power of two greater than or equal to `self`.
3581 When return value overflows (i.e. `self > (1 << (N-1))` for type
3582 `uN`), it panics in debug mode and return value is wrapped to 0 in
3583 release mode (the only situation in which method can return 0).
3590 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3591 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3593 #[stable(feature = "rust1", since = "1.0.0")]
3595 pub fn next_power_of_two(self) -> Self {
3596 // Call the trait to get overflow checks
3597 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3602 concat!("Returns the smallest power of two greater than or equal to `n`. If
3603 the next power of two is greater than the type's maximum value,
3604 `None` is returned, otherwise the power of two is wrapped in `Some`.
3611 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3612 ".checked_next_power_of_two(), Some(2));
3613 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3614 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3617 #[stable(feature = "rust1", since = "1.0.0")]
3618 pub fn checked_next_power_of_two(self) -> Option<Self> {
3619 self.one_less_than_next_power_of_two().checked_add(1)
3624 concat!("Returns the smallest power of two greater than or equal to `n`. If
3625 the next power of two is greater than the type's maximum value,
3626 the return value is wrapped to `0`.
3633 #![feature(wrapping_next_power_of_two)]
3635 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3636 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3637 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3640 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3641 reason = "needs decision on wrapping behaviour")]
3642 pub fn wrapping_next_power_of_two(self) -> Self {
3643 self.one_less_than_next_power_of_two().wrapping_add(1)
3648 concat!("Return the memory representation of this integer as a byte array in
3649 big-endian (network) byte order.
3654 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
3655 assert_eq!(bytes, ", $be_bytes, ");
3657 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3658 #[rustc_const_unstable(feature = "const_int_conversion")]
3660 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
3661 self.to_be().to_ne_bytes()
3666 concat!("Return the memory representation of this integer as a byte array in
3667 little-endian byte order.
3672 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
3673 assert_eq!(bytes, ", $le_bytes, ");
3675 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3676 #[rustc_const_unstable(feature = "const_int_conversion")]
3678 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
3679 self.to_le().to_ne_bytes()
3685 Return the memory representation of this integer as a byte array in
3688 As the target platform's native endianness is used, portable code
3689 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3692 [`to_be_bytes`]: #method.to_be_bytes
3693 [`to_le_bytes`]: #method.to_le_bytes
3698 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
3699 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
3705 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3706 #[rustc_const_unstable(feature = "const_int_conversion")]
3708 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
3709 unsafe { mem::transmute(self) }
3714 concat!("Create an integer value from its representation as a byte array in
3720 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
3721 assert_eq!(value, ", $swap_op, ");
3723 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3724 #[rustc_const_unstable(feature = "const_int_conversion")]
3726 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3727 Self::from_be(Self::from_ne_bytes(bytes))
3733 Create an integer value from its representation as a byte array in
3739 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
3740 assert_eq!(value, ", $swap_op, ");
3742 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3743 #[rustc_const_unstable(feature = "const_int_conversion")]
3745 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3746 Self::from_le(Self::from_ne_bytes(bytes))
3751 concat!("Create an integer value from its memory representation as a byte
3752 array in native endianness.
3754 As the target platform's native endianness is used, portable code
3755 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3756 appropriate instead.
3758 [`from_be_bytes`]: #method.from_be_bytes
3759 [`from_le_bytes`]: #method.from_le_bytes
3764 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
3769 assert_eq!(value, ", $swap_op, ");
3771 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3772 #[rustc_const_unstable(feature = "const_int_conversion")]
3774 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3775 unsafe { mem::transmute(bytes) }
3783 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
3787 /// Checks if the value is within the ASCII range.
3792 /// let ascii = 97u8;
3793 /// let non_ascii = 150u8;
3795 /// assert!(ascii.is_ascii());
3796 /// assert!(!non_ascii.is_ascii());
3798 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3800 pub fn is_ascii(&self) -> bool {
3804 /// Makes a copy of the value in its ASCII upper case equivalent.
3806 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3807 /// but non-ASCII letters are unchanged.
3809 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
3814 /// let lowercase_a = 97u8;
3816 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
3819 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
3820 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3822 pub fn to_ascii_uppercase(&self) -> u8 {
3823 ASCII_UPPERCASE_MAP[*self as usize]
3826 /// Makes a copy of the value in its ASCII lower case equivalent.
3828 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3829 /// but non-ASCII letters are unchanged.
3831 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
3836 /// let uppercase_a = 65u8;
3838 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
3841 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
3842 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3844 pub fn to_ascii_lowercase(&self) -> u8 {
3845 ASCII_LOWERCASE_MAP[*self as usize]
3848 /// Checks that two values are an ASCII case-insensitive match.
3850 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3855 /// let lowercase_a = 97u8;
3856 /// let uppercase_a = 65u8;
3858 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3860 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3862 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3863 self.to_ascii_lowercase() == other.to_ascii_lowercase()
3866 /// Converts this value to its ASCII upper case equivalent in-place.
3868 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3869 /// but non-ASCII letters are unchanged.
3871 /// To return a new uppercased value without modifying the existing one, use
3872 /// [`to_ascii_uppercase`].
3877 /// let mut byte = b'a';
3879 /// byte.make_ascii_uppercase();
3881 /// assert_eq!(b'A', byte);
3884 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3885 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3887 pub fn make_ascii_uppercase(&mut self) {
3888 *self = self.to_ascii_uppercase();
3891 /// Converts this value to its ASCII lower case equivalent in-place.
3893 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3894 /// but non-ASCII letters are unchanged.
3896 /// To return a new lowercased value without modifying the existing one, use
3897 /// [`to_ascii_lowercase`].
3902 /// let mut byte = b'A';
3904 /// byte.make_ascii_lowercase();
3906 /// assert_eq!(b'a', byte);
3909 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3910 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3912 pub fn make_ascii_lowercase(&mut self) {
3913 *self = self.to_ascii_lowercase();
3916 /// Checks if the value is an ASCII alphabetic character:
3918 /// - U+0041 'A' ... U+005A 'Z', or
3919 /// - U+0061 'a' ... U+007A 'z'.
3924 /// let uppercase_a = b'A';
3925 /// let uppercase_g = b'G';
3928 /// let zero = b'0';
3929 /// let percent = b'%';
3930 /// let space = b' ';
3932 /// let esc = 0x1b_u8;
3934 /// assert!(uppercase_a.is_ascii_alphabetic());
3935 /// assert!(uppercase_g.is_ascii_alphabetic());
3936 /// assert!(a.is_ascii_alphabetic());
3937 /// assert!(g.is_ascii_alphabetic());
3938 /// assert!(!zero.is_ascii_alphabetic());
3939 /// assert!(!percent.is_ascii_alphabetic());
3940 /// assert!(!space.is_ascii_alphabetic());
3941 /// assert!(!lf.is_ascii_alphabetic());
3942 /// assert!(!esc.is_ascii_alphabetic());
3944 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3946 pub fn is_ascii_alphabetic(&self) -> bool {
3947 if *self >= 0x80 { return false; }
3948 match ASCII_CHARACTER_CLASS[*self as usize] {
3949 L | Lx | U | Ux => true,
3954 /// Checks if the value is an ASCII uppercase character:
3955 /// U+0041 'A' ... U+005A 'Z'.
3960 /// let uppercase_a = b'A';
3961 /// let uppercase_g = b'G';
3964 /// let zero = b'0';
3965 /// let percent = b'%';
3966 /// let space = b' ';
3968 /// let esc = 0x1b_u8;
3970 /// assert!(uppercase_a.is_ascii_uppercase());
3971 /// assert!(uppercase_g.is_ascii_uppercase());
3972 /// assert!(!a.is_ascii_uppercase());
3973 /// assert!(!g.is_ascii_uppercase());
3974 /// assert!(!zero.is_ascii_uppercase());
3975 /// assert!(!percent.is_ascii_uppercase());
3976 /// assert!(!space.is_ascii_uppercase());
3977 /// assert!(!lf.is_ascii_uppercase());
3978 /// assert!(!esc.is_ascii_uppercase());
3980 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3982 pub fn is_ascii_uppercase(&self) -> bool {
3983 if *self >= 0x80 { return false }
3984 match ASCII_CHARACTER_CLASS[*self as usize] {
3990 /// Checks if the value is an ASCII lowercase character:
3991 /// U+0061 'a' ... U+007A 'z'.
3996 /// let uppercase_a = b'A';
3997 /// let uppercase_g = b'G';
4000 /// let zero = b'0';
4001 /// let percent = b'%';
4002 /// let space = b' ';
4004 /// let esc = 0x1b_u8;
4006 /// assert!(!uppercase_a.is_ascii_lowercase());
4007 /// assert!(!uppercase_g.is_ascii_lowercase());
4008 /// assert!(a.is_ascii_lowercase());
4009 /// assert!(g.is_ascii_lowercase());
4010 /// assert!(!zero.is_ascii_lowercase());
4011 /// assert!(!percent.is_ascii_lowercase());
4012 /// assert!(!space.is_ascii_lowercase());
4013 /// assert!(!lf.is_ascii_lowercase());
4014 /// assert!(!esc.is_ascii_lowercase());
4016 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4018 pub fn is_ascii_lowercase(&self) -> bool {
4019 if *self >= 0x80 { return false }
4020 match ASCII_CHARACTER_CLASS[*self as usize] {
4026 /// Checks if the value is an ASCII alphanumeric character:
4028 /// - U+0041 'A' ... U+005A 'Z', or
4029 /// - U+0061 'a' ... U+007A 'z', or
4030 /// - U+0030 '0' ... U+0039 '9'.
4035 /// let uppercase_a = b'A';
4036 /// let uppercase_g = b'G';
4039 /// let zero = b'0';
4040 /// let percent = b'%';
4041 /// let space = b' ';
4043 /// let esc = 0x1b_u8;
4045 /// assert!(uppercase_a.is_ascii_alphanumeric());
4046 /// assert!(uppercase_g.is_ascii_alphanumeric());
4047 /// assert!(a.is_ascii_alphanumeric());
4048 /// assert!(g.is_ascii_alphanumeric());
4049 /// assert!(zero.is_ascii_alphanumeric());
4050 /// assert!(!percent.is_ascii_alphanumeric());
4051 /// assert!(!space.is_ascii_alphanumeric());
4052 /// assert!(!lf.is_ascii_alphanumeric());
4053 /// assert!(!esc.is_ascii_alphanumeric());
4055 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4057 pub fn is_ascii_alphanumeric(&self) -> bool {
4058 if *self >= 0x80 { return false }
4059 match ASCII_CHARACTER_CLASS[*self as usize] {
4060 D | L | Lx | U | Ux => true,
4065 /// Checks if the value is an ASCII decimal digit:
4066 /// U+0030 '0' ... U+0039 '9'.
4071 /// let uppercase_a = b'A';
4072 /// let uppercase_g = b'G';
4075 /// let zero = b'0';
4076 /// let percent = b'%';
4077 /// let space = b' ';
4079 /// let esc = 0x1b_u8;
4081 /// assert!(!uppercase_a.is_ascii_digit());
4082 /// assert!(!uppercase_g.is_ascii_digit());
4083 /// assert!(!a.is_ascii_digit());
4084 /// assert!(!g.is_ascii_digit());
4085 /// assert!(zero.is_ascii_digit());
4086 /// assert!(!percent.is_ascii_digit());
4087 /// assert!(!space.is_ascii_digit());
4088 /// assert!(!lf.is_ascii_digit());
4089 /// assert!(!esc.is_ascii_digit());
4091 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4093 pub fn is_ascii_digit(&self) -> bool {
4094 if *self >= 0x80 { return false }
4095 match ASCII_CHARACTER_CLASS[*self as usize] {
4101 /// Checks if the value is an ASCII hexadecimal digit:
4103 /// - U+0030 '0' ... U+0039 '9', or
4104 /// - U+0041 'A' ... U+0046 'F', or
4105 /// - U+0061 'a' ... U+0066 'f'.
4110 /// let uppercase_a = b'A';
4111 /// let uppercase_g = b'G';
4114 /// let zero = b'0';
4115 /// let percent = b'%';
4116 /// let space = b' ';
4118 /// let esc = 0x1b_u8;
4120 /// assert!(uppercase_a.is_ascii_hexdigit());
4121 /// assert!(!uppercase_g.is_ascii_hexdigit());
4122 /// assert!(a.is_ascii_hexdigit());
4123 /// assert!(!g.is_ascii_hexdigit());
4124 /// assert!(zero.is_ascii_hexdigit());
4125 /// assert!(!percent.is_ascii_hexdigit());
4126 /// assert!(!space.is_ascii_hexdigit());
4127 /// assert!(!lf.is_ascii_hexdigit());
4128 /// assert!(!esc.is_ascii_hexdigit());
4130 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4132 pub fn is_ascii_hexdigit(&self) -> bool {
4133 if *self >= 0x80 { return false }
4134 match ASCII_CHARACTER_CLASS[*self as usize] {
4135 D | Lx | Ux => true,
4140 /// Checks if the value is an ASCII punctuation character:
4142 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
4143 /// - U+003A ... U+0040 `: ; < = > ? @`, or
4144 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
4145 /// - U+007B ... U+007E `{ | } ~`
4150 /// let uppercase_a = b'A';
4151 /// let uppercase_g = b'G';
4154 /// let zero = b'0';
4155 /// let percent = b'%';
4156 /// let space = b' ';
4158 /// let esc = 0x1b_u8;
4160 /// assert!(!uppercase_a.is_ascii_punctuation());
4161 /// assert!(!uppercase_g.is_ascii_punctuation());
4162 /// assert!(!a.is_ascii_punctuation());
4163 /// assert!(!g.is_ascii_punctuation());
4164 /// assert!(!zero.is_ascii_punctuation());
4165 /// assert!(percent.is_ascii_punctuation());
4166 /// assert!(!space.is_ascii_punctuation());
4167 /// assert!(!lf.is_ascii_punctuation());
4168 /// assert!(!esc.is_ascii_punctuation());
4170 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4172 pub fn is_ascii_punctuation(&self) -> bool {
4173 if *self >= 0x80 { return false }
4174 match ASCII_CHARACTER_CLASS[*self as usize] {
4180 /// Checks if the value is an ASCII graphic character:
4181 /// U+0021 '!' ... U+007E '~'.
4186 /// let uppercase_a = b'A';
4187 /// let uppercase_g = b'G';
4190 /// let zero = b'0';
4191 /// let percent = b'%';
4192 /// let space = b' ';
4194 /// let esc = 0x1b_u8;
4196 /// assert!(uppercase_a.is_ascii_graphic());
4197 /// assert!(uppercase_g.is_ascii_graphic());
4198 /// assert!(a.is_ascii_graphic());
4199 /// assert!(g.is_ascii_graphic());
4200 /// assert!(zero.is_ascii_graphic());
4201 /// assert!(percent.is_ascii_graphic());
4202 /// assert!(!space.is_ascii_graphic());
4203 /// assert!(!lf.is_ascii_graphic());
4204 /// assert!(!esc.is_ascii_graphic());
4206 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4208 pub fn is_ascii_graphic(&self) -> bool {
4209 if *self >= 0x80 { return false; }
4210 match ASCII_CHARACTER_CLASS[*self as usize] {
4211 Ux | U | Lx | L | D | P => true,
4216 /// Checks if the value is an ASCII whitespace character:
4217 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4218 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4220 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4221 /// whitespace][infra-aw]. There are several other definitions in
4222 /// wide use. For instance, [the POSIX locale][pct] includes
4223 /// U+000B VERTICAL TAB as well as all the above characters,
4224 /// but—from the very same specification—[the default rule for
4225 /// "field splitting" in the Bourne shell][bfs] considers *only*
4226 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4228 /// If you are writing a program that will process an existing
4229 /// file format, check what that format's definition of whitespace is
4230 /// before using this function.
4232 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4233 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4234 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4239 /// let uppercase_a = b'A';
4240 /// let uppercase_g = b'G';
4243 /// let zero = b'0';
4244 /// let percent = b'%';
4245 /// let space = b' ';
4247 /// let esc = 0x1b_u8;
4249 /// assert!(!uppercase_a.is_ascii_whitespace());
4250 /// assert!(!uppercase_g.is_ascii_whitespace());
4251 /// assert!(!a.is_ascii_whitespace());
4252 /// assert!(!g.is_ascii_whitespace());
4253 /// assert!(!zero.is_ascii_whitespace());
4254 /// assert!(!percent.is_ascii_whitespace());
4255 /// assert!(space.is_ascii_whitespace());
4256 /// assert!(lf.is_ascii_whitespace());
4257 /// assert!(!esc.is_ascii_whitespace());
4259 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4261 pub fn is_ascii_whitespace(&self) -> bool {
4262 if *self >= 0x80 { return false; }
4263 match ASCII_CHARACTER_CLASS[*self as usize] {
4269 /// Checks if the value is an ASCII control character:
4270 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4271 /// Note that most ASCII whitespace characters are control
4272 /// characters, but SPACE is not.
4277 /// let uppercase_a = b'A';
4278 /// let uppercase_g = b'G';
4281 /// let zero = b'0';
4282 /// let percent = b'%';
4283 /// let space = b' ';
4285 /// let esc = 0x1b_u8;
4287 /// assert!(!uppercase_a.is_ascii_control());
4288 /// assert!(!uppercase_g.is_ascii_control());
4289 /// assert!(!a.is_ascii_control());
4290 /// assert!(!g.is_ascii_control());
4291 /// assert!(!zero.is_ascii_control());
4292 /// assert!(!percent.is_ascii_control());
4293 /// assert!(!space.is_ascii_control());
4294 /// assert!(lf.is_ascii_control());
4295 /// assert!(esc.is_ascii_control());
4297 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4299 pub fn is_ascii_control(&self) -> bool {
4300 if *self >= 0x80 { return false; }
4301 match ASCII_CHARACTER_CLASS[*self as usize] {
4310 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4311 "[0x34, 0x12]", "[0x12, 0x34]" }
4316 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4317 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]" }
4322 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4323 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4324 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4325 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
4330 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4331 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4332 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4333 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4334 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4335 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4336 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]" }
4339 #[cfg(target_pointer_width = "16")]
4342 uint_impl! { usize, u16, 16, 65536, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4343 "[0x34, 0x12]", "[0x12, 0x34]" }
4345 #[cfg(target_pointer_width = "32")]
4348 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4349 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]" }
4352 #[cfg(target_pointer_width = "64")]
4355 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4356 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4357 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4358 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
4361 /// A classification of floating point numbers.
4363 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4364 /// their documentation for more.
4366 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4367 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4372 /// use std::num::FpCategory;
4375 /// let num = 12.4_f32;
4376 /// let inf = f32::INFINITY;
4377 /// let zero = 0f32;
4378 /// let sub: f32 = 1.1754942e-38;
4379 /// let nan = f32::NAN;
4381 /// assert_eq!(num.classify(), FpCategory::Normal);
4382 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4383 /// assert_eq!(zero.classify(), FpCategory::Zero);
4384 /// assert_eq!(nan.classify(), FpCategory::Nan);
4385 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4387 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4388 #[stable(feature = "rust1", since = "1.0.0")]
4389 pub enum FpCategory {
4390 /// "Not a Number", often obtained by dividing by zero.
4391 #[stable(feature = "rust1", since = "1.0.0")]
4394 /// Positive or negative infinity.
4395 #[stable(feature = "rust1", since = "1.0.0")]
4398 /// Positive or negative zero.
4399 #[stable(feature = "rust1", since = "1.0.0")]
4402 /// De-normalized floating point representation (less precise than `Normal`).
4403 #[stable(feature = "rust1", since = "1.0.0")]
4406 /// A regular floating point number.
4407 #[stable(feature = "rust1", since = "1.0.0")]
4411 macro_rules! from_str_radix_int_impl {
4413 #[stable(feature = "rust1", since = "1.0.0")]
4414 impl FromStr for $t {
4415 type Err = ParseIntError;
4416 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4417 from_str_radix(src, 10)
4422 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4424 /// The error type returned when a checked integral type conversion fails.
4425 #[unstable(feature = "try_from", issue = "33417")]
4426 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4427 pub struct TryFromIntError(());
4429 impl TryFromIntError {
4430 #[unstable(feature = "int_error_internals",
4431 reason = "available through Error trait and this method should \
4432 not be exposed publicly",
4435 pub fn __description(&self) -> &str {
4436 "out of range integral type conversion attempted"
4440 #[unstable(feature = "try_from", issue = "33417")]
4441 impl fmt::Display for TryFromIntError {
4442 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4443 self.__description().fmt(fmt)
4447 #[unstable(feature = "try_from", issue = "33417")]
4448 impl From<!> for TryFromIntError {
4449 fn from(never: !) -> TryFromIntError {
4454 // no possible bounds violation
4455 macro_rules! try_from_unbounded {
4456 ($source:ty, $($target:ty),*) => {$(
4457 #[unstable(feature = "try_from", issue = "33417")]
4458 impl TryFrom<$source> for $target {
4459 type Error = TryFromIntError;
4462 fn try_from(value: $source) -> Result<Self, Self::Error> {
4463 Ok(value as $target)
4469 // only negative bounds
4470 macro_rules! try_from_lower_bounded {
4471 ($source:ty, $($target:ty),*) => {$(
4472 #[unstable(feature = "try_from", issue = "33417")]
4473 impl TryFrom<$source> for $target {
4474 type Error = TryFromIntError;
4477 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4481 Err(TryFromIntError(()))
4488 // unsigned to signed (only positive bound)
4489 macro_rules! try_from_upper_bounded {
4490 ($source:ty, $($target:ty),*) => {$(
4491 #[unstable(feature = "try_from", issue = "33417")]
4492 impl TryFrom<$source> for $target {
4493 type Error = TryFromIntError;
4496 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4497 if u > (<$target>::max_value() as $source) {
4498 Err(TryFromIntError(()))
4508 macro_rules! try_from_both_bounded {
4509 ($source:ty, $($target:ty),*) => {$(
4510 #[unstable(feature = "try_from", issue = "33417")]
4511 impl TryFrom<$source> for $target {
4512 type Error = TryFromIntError;
4515 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4516 let min = <$target>::min_value() as $source;
4517 let max = <$target>::max_value() as $source;
4518 if u < min || u > max {
4519 Err(TryFromIntError(()))
4529 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4530 $mac!($target, $source);
4534 /// intra-sign conversions
4535 try_from_upper_bounded!(u16, u8);
4536 try_from_upper_bounded!(u32, u16, u8);
4537 try_from_upper_bounded!(u64, u32, u16, u8);
4538 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4540 try_from_both_bounded!(i16, i8);
4541 try_from_both_bounded!(i32, i16, i8);
4542 try_from_both_bounded!(i64, i32, i16, i8);
4543 try_from_both_bounded!(i128, i64, i32, i16, i8);
4545 // unsigned-to-signed
4546 try_from_upper_bounded!(u8, i8);
4547 try_from_upper_bounded!(u16, i8, i16);
4548 try_from_upper_bounded!(u32, i8, i16, i32);
4549 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4550 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4552 // signed-to-unsigned
4553 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4554 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4555 try_from_lower_bounded!(i32, u32, u64, u128);
4556 try_from_lower_bounded!(i64, u64, u128);
4557 try_from_lower_bounded!(i128, u128);
4558 try_from_both_bounded!(i16, u8);
4559 try_from_both_bounded!(i32, u16, u8);
4560 try_from_both_bounded!(i64, u32, u16, u8);
4561 try_from_both_bounded!(i128, u64, u32, u16, u8);
4564 try_from_upper_bounded!(usize, isize);
4565 try_from_lower_bounded!(isize, usize);
4567 #[cfg(target_pointer_width = "16")]
4568 mod ptr_try_from_impls {
4569 use super::TryFromIntError;
4570 use convert::TryFrom;
4572 try_from_upper_bounded!(usize, u8);
4573 try_from_unbounded!(usize, u16, u32, u64, u128);
4574 try_from_upper_bounded!(usize, i8, i16);
4575 try_from_unbounded!(usize, i32, i64, i128);
4577 try_from_both_bounded!(isize, u8);
4578 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4579 try_from_both_bounded!(isize, i8);
4580 try_from_unbounded!(isize, i16, i32, i64, i128);
4582 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4583 rev!(try_from_lower_bounded, usize, i8, i16);
4584 rev!(try_from_both_bounded, usize, i32, i64, i128);
4586 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4587 rev!(try_from_both_bounded, isize, i32, i64, i128);
4590 #[cfg(target_pointer_width = "32")]
4591 mod ptr_try_from_impls {
4592 use super::TryFromIntError;
4593 use convert::TryFrom;
4595 try_from_upper_bounded!(usize, u8, u16);
4596 try_from_unbounded!(usize, u32, u64, u128);
4597 try_from_upper_bounded!(usize, i8, i16, i32);
4598 try_from_unbounded!(usize, i64, i128);
4600 try_from_both_bounded!(isize, u8, u16);
4601 try_from_lower_bounded!(isize, u32, u64, u128);
4602 try_from_both_bounded!(isize, i8, i16);
4603 try_from_unbounded!(isize, i32, i64, i128);
4605 rev!(try_from_unbounded, usize, u32);
4606 rev!(try_from_upper_bounded, usize, u64, u128);
4607 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4608 rev!(try_from_both_bounded, usize, i64, i128);
4610 rev!(try_from_unbounded, isize, u16);
4611 rev!(try_from_upper_bounded, isize, u32, u64, u128);
4612 rev!(try_from_unbounded, isize, i32);
4613 rev!(try_from_both_bounded, isize, i64, i128);
4616 #[cfg(target_pointer_width = "64")]
4617 mod ptr_try_from_impls {
4618 use super::TryFromIntError;
4619 use convert::TryFrom;
4621 try_from_upper_bounded!(usize, u8, u16, u32);
4622 try_from_unbounded!(usize, u64, u128);
4623 try_from_upper_bounded!(usize, i8, i16, i32, i64);
4624 try_from_unbounded!(usize, i128);
4626 try_from_both_bounded!(isize, u8, u16, u32);
4627 try_from_lower_bounded!(isize, u64, u128);
4628 try_from_both_bounded!(isize, i8, i16, i32);
4629 try_from_unbounded!(isize, i64, i128);
4631 rev!(try_from_unbounded, usize, u32, u64);
4632 rev!(try_from_upper_bounded, usize, u128);
4633 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4634 rev!(try_from_both_bounded, usize, i128);
4636 rev!(try_from_unbounded, isize, u16, u32);
4637 rev!(try_from_upper_bounded, isize, u64, u128);
4638 rev!(try_from_unbounded, isize, i32, i64);
4639 rev!(try_from_both_bounded, isize, i128);
4643 trait FromStrRadixHelper: PartialOrd + Copy {
4644 fn min_value() -> Self;
4645 fn max_value() -> Self;
4646 fn from_u32(u: u32) -> Self;
4647 fn checked_mul(&self, other: u32) -> Option<Self>;
4648 fn checked_sub(&self, other: u32) -> Option<Self>;
4649 fn checked_add(&self, other: u32) -> Option<Self>;
4653 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4655 fn min_value() -> Self { Self::min_value() }
4657 fn max_value() -> Self { Self::max_value() }
4659 fn from_u32(u: u32) -> Self { u as Self }
4661 fn checked_mul(&self, other: u32) -> Option<Self> {
4662 Self::checked_mul(*self, other as Self)
4665 fn checked_sub(&self, other: u32) -> Option<Self> {
4666 Self::checked_sub(*self, other as Self)
4669 fn checked_add(&self, other: u32) -> Option<Self> {
4670 Self::checked_add(*self, other as Self)
4674 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4676 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4677 use self::IntErrorKind::*;
4678 use self::ParseIntError as PIE;
4680 assert!(radix >= 2 && radix <= 36,
4681 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4685 return Err(PIE { kind: Empty });
4688 let is_signed_ty = T::from_u32(0) > T::min_value();
4690 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4691 // and cast them to chars. .to_digit() will safely return None for anything
4692 // other than a valid ascii digit for the given radix, including the first-byte
4693 // of multi-byte sequences
4694 let src = src.as_bytes();
4696 let (is_positive, digits) = match src[0] {
4697 b'+' => (true, &src[1..]),
4698 b'-' if is_signed_ty => (false, &src[1..]),
4702 if digits.is_empty() {
4703 return Err(PIE { kind: Empty });
4706 let mut result = T::from_u32(0);
4708 // The number is positive
4710 let x = match (c as char).to_digit(radix) {
4712 None => return Err(PIE { kind: InvalidDigit }),
4714 result = match result.checked_mul(radix) {
4715 Some(result) => result,
4716 None => return Err(PIE { kind: Overflow }),
4718 result = match result.checked_add(x) {
4719 Some(result) => result,
4720 None => return Err(PIE { kind: Overflow }),
4724 // The number is negative
4726 let x = match (c as char).to_digit(radix) {
4728 None => return Err(PIE { kind: InvalidDigit }),
4730 result = match result.checked_mul(radix) {
4731 Some(result) => result,
4732 None => return Err(PIE { kind: Underflow }),
4734 result = match result.checked_sub(x) {
4735 Some(result) => result,
4736 None => return Err(PIE { kind: Underflow }),
4743 /// An error which can be returned when parsing an integer.
4745 /// This error is used as the error type for the `from_str_radix()` functions
4746 /// on the primitive integer types, such as [`i8::from_str_radix`].
4748 /// # Potential causes
4750 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
4751 /// in the string e.g. when it is obtained from the standard input.
4752 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
4754 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
4755 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
4756 #[derive(Debug, Clone, PartialEq, Eq)]
4757 #[stable(feature = "rust1", since = "1.0.0")]
4758 pub struct ParseIntError {
4762 /// Enum to store the various types of errors that can cause parsing an integer to fail.
4763 #[unstable(feature = "int_error_matching",
4764 reason = "it can be useful to match errors when making error messages \
4765 for integer parsing",
4767 #[derive(Debug, Clone, PartialEq, Eq)]
4769 pub enum IntErrorKind {
4770 /// Value being parsed is empty.
4772 /// Among other causes, this variant will be constructed when parsing an empty string.
4774 /// Contains an invalid digit.
4776 /// Among other causes, this variant will be constructed when parsing a string that
4777 /// contains a letter.
4779 /// Integer is too large to store in target integer type.
4781 /// Integer is too small to store in target integer type.
4785 impl ParseIntError {
4786 /// Outputs the detailed cause of parsing an integer failing.
4787 #[unstable(feature = "int_error_matching",
4788 reason = "it can be useful to match errors when making error messages \
4789 for integer parsing",
4791 pub fn kind(&self) -> &IntErrorKind {
4794 #[unstable(feature = "int_error_internals",
4795 reason = "available through Error trait and this method should \
4796 not be exposed publicly",
4799 pub fn __description(&self) -> &str {
4801 IntErrorKind::Empty => "cannot parse integer from empty string",
4802 IntErrorKind::InvalidDigit => "invalid digit found in string",
4803 IntErrorKind::Overflow => "number too large to fit in target type",
4804 IntErrorKind::Underflow => "number too small to fit in target type",
4809 #[stable(feature = "rust1", since = "1.0.0")]
4810 impl fmt::Display for ParseIntError {
4811 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4812 self.__description().fmt(f)
4816 #[stable(feature = "rust1", since = "1.0.0")]
4817 pub use num::dec2flt::ParseFloatError;
4819 // Conversion traits for primitive integer and float types
4820 // Conversions T -> T are covered by a blanket impl and therefore excluded
4821 // Some conversions from and to usize/isize are not implemented due to portability concerns
4822 macro_rules! impl_from {
4823 ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
4826 impl From<$Small> for $Large {
4828 fn from(small: $Small) -> $Large {
4833 ($Small: ty, $Large: ty, #[$attr:meta]) => {
4837 concat!("Converts `",
4845 macro_rules! impl_from_bool {
4846 ($target: ty, #[$attr:meta]) => {
4847 impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
4848 stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
4854 assert_eq!(", stringify!($target), "::from(true), 1);
4855 assert_eq!(", stringify!($target), "::from(false), 0);
4861 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
4862 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
4863 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
4864 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
4865 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
4866 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
4867 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
4868 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
4869 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
4870 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
4871 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
4872 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
4874 // Unsigned -> Unsigned
4875 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4876 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4877 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4878 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
4879 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4880 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4881 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4882 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
4883 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4884 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
4885 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
4888 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4889 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4890 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4891 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4892 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4893 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4894 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4895 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4896 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4897 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4898 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4900 // Unsigned -> Signed
4901 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4902 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4903 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4904 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4905 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4906 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4907 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4908 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4909 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4910 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4912 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
4913 // which imply that pointer-sized integers must be at least 16 bits:
4914 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
4915 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4916 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4917 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4919 // RISC-V defines the possibility of a 128-bit address space (RV128).
4921 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
4922 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
4923 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
4926 // Note: integers can only be represented with full precision in a float if
4927 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4928 // Lossy float conversions are not implemented at this time.
4931 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4932 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4933 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4934 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4935 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4937 // Unsigned -> Float
4938 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4939 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4940 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4941 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4942 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4945 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4947 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4948 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4949 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4950 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4951 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4952 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4953 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4954 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4955 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4958 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4959 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4960 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4963 b'[', b'\\', b']', b'^', b'_',
4964 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4965 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4966 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4967 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4968 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4969 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4970 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4971 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4972 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4973 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4974 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4975 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4976 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4977 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4978 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4979 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4980 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4981 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4982 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4983 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4986 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4987 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4988 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4989 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4990 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4991 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4992 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4993 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4994 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4995 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4996 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4997 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4998 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
5001 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
5002 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
5003 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
5006 b'{', b'|', b'}', b'~', 0x7f,
5007 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
5008 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
5009 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
5010 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
5011 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
5012 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
5013 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
5014 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
5015 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
5016 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
5017 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
5018 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
5019 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
5020 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
5021 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
5022 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
5025 enum AsciiCharacterClass {
5027 Cw, // control whitespace
5031 Lx, // lowercase hex digit
5033 Ux, // uppercase hex digit
5036 use self::AsciiCharacterClass::*;
5038 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
5039 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
5040 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
5041 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
5042 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
5043 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
5044 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
5045 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
5046 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
5047 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_