1 //! Numeric traits and functions for the built-in numeric types.
3 #![stable(feature = "rust1", since = "1.0.0")]
12 macro_rules! impl_nonzero_fmt {
13 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
16 impl fmt::$Trait for $Ty {
18 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
26 macro_rules! doc_comment {
27 ($x:expr, $($tt:tt)*) => {
33 macro_rules! nonzero_integers {
34 ( $( #[$stability: meta] $Ty: ident($Int: ty); )+ ) => {
37 concat!("An integer that is known not to equal zero.
39 This enables some memory layout optimization.
40 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
43 use std::mem::size_of;
44 assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
48 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
50 #[rustc_layout_scalar_valid_range_start(1)]
55 /// Creates a non-zero without checking the value.
59 /// The value must not be zero.
62 pub const unsafe fn new_unchecked(n: $Int) -> Self {
66 /// Creates a non-zero if the given value is not zero.
69 pub fn new(n: $Int) -> Option<Self> {
71 Some(unsafe { $Ty(n) })
77 /// Returns the value as a primitive type.
80 pub const fn get(self) -> $Int {
86 #[stable(feature = "from_nonzero", since = "1.31.0")]
87 impl From<$Ty> for $Int {
88 fn from(nonzero: $Ty) -> Self {
94 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
101 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
102 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
103 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
104 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
105 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
106 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
107 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
108 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
109 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
110 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
111 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
112 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
115 /// Provides intentionally-wrapped arithmetic on `T`.
117 /// Operations like `+` on `u32` values is intended to never overflow,
118 /// and in some debug configurations overflow is detected and results
119 /// in a panic. While most arithmetic falls into this category, some
120 /// code explicitly expects and relies upon modular arithmetic (e.g.,
123 /// Wrapping arithmetic can be achieved either through methods like
124 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
125 /// all standard arithmetic operations on the underlying value are
126 /// intended to have wrapping semantics.
128 /// The underlying value can be retrieved through the `.0` index of the
129 /// `Wrapping` tuple.
134 /// use std::num::Wrapping;
136 /// let zero = Wrapping(0u32);
137 /// let one = Wrapping(1u32);
139 /// assert_eq!(std::u32::MAX, (zero - one).0);
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
144 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
149 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
154 #[stable(feature = "wrapping_display", since = "1.10.0")]
155 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
161 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
162 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
163 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
168 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
169 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
170 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
175 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
176 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
177 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
182 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
183 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
184 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
189 // All these modules are technically private and only exposed for coretests:
197 // `Int` + `SignedInt` implemented for signed integers
198 macro_rules! int_impl {
199 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
200 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
201 $reversed:expr, $le_bytes:expr, $be_bytes:expr) => {
203 concat!("Returns the smallest value that can be represented by this integer type.
210 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
213 #[stable(feature = "rust1", since = "1.0.0")]
216 pub const fn min_value() -> Self {
217 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
222 concat!("Returns the largest value that can be represented by this integer type.
229 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
232 #[stable(feature = "rust1", since = "1.0.0")]
235 pub const fn max_value() -> Self {
241 concat!("Converts a string slice in a given base to an integer.
243 The string is expected to be an optional `+` or `-` sign followed by digits.
244 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
245 depending on `radix`:
253 This function panics if `radix` is not in the range from 2 to 36.
260 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
265 from_str_radix(src, radix)
270 concat!("Returns the number of ones in the binary representation of `self`.
277 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
279 assert_eq!(n.count_ones(), 1);",
283 #[stable(feature = "rust1", since = "1.0.0")]
285 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
289 concat!("Returns the number of zeros in the binary representation of `self`.
296 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
298 #[stable(feature = "rust1", since = "1.0.0")]
300 pub const fn count_zeros(self) -> u32 {
306 concat!("Returns the number of leading zeros in the binary representation of `self`.
313 ", $Feature, "let n = -1", stringify!($SelfT), ";
315 assert_eq!(n.leading_zeros(), 0);",
318 #[stable(feature = "rust1", since = "1.0.0")]
320 pub const fn leading_zeros(self) -> u32 {
321 (self as $UnsignedT).leading_zeros()
326 concat!("Returns the number of trailing zeros in the binary representation of `self`.
333 ", $Feature, "let n = -4", stringify!($SelfT), ";
335 assert_eq!(n.trailing_zeros(), 2);",
338 #[stable(feature = "rust1", since = "1.0.0")]
340 pub const fn trailing_zeros(self) -> u32 {
341 (self as $UnsignedT).trailing_zeros()
346 concat!("Shifts the bits to the left by a specified amount, `n`,
347 wrapping the truncated bits to the end of the resulting integer.
349 Please note this isn't the same operation as `<<`!
356 let n = ", $rot_op, stringify!($SelfT), ";
357 let m = ", $rot_result, ";
359 assert_eq!(n.rotate_left(", $rot, "), m);
361 #[stable(feature = "rust1", since = "1.0.0")]
363 pub const fn rotate_left(self, n: u32) -> Self {
364 (self as $UnsignedT).rotate_left(n) as Self
369 concat!("Shifts the bits to the right by a specified amount, `n`,
370 wrapping the truncated bits to the beginning of the resulting
373 Please note this isn't the same operation as `>>`!
380 let n = ", $rot_result, stringify!($SelfT), ";
381 let m = ", $rot_op, ";
383 assert_eq!(n.rotate_right(", $rot, "), m);
385 #[stable(feature = "rust1", since = "1.0.0")]
387 pub const fn rotate_right(self, n: u32) -> Self {
388 (self as $UnsignedT).rotate_right(n) as Self
393 concat!("Reverses the byte order of the integer.
400 let n = ", $swap_op, stringify!($SelfT), ";
402 let m = n.swap_bytes();
404 assert_eq!(m, ", $swapped, ");
406 #[stable(feature = "rust1", since = "1.0.0")]
408 pub const fn swap_bytes(self) -> Self {
409 (self as $UnsignedT).swap_bytes() as Self
414 concat!("Reverses the bit pattern of the integer.
421 #![feature(reverse_bits)]
423 let n = ", $swap_op, stringify!($SelfT), ";
424 let m = n.reverse_bits();
426 assert_eq!(m, ", $reversed, ");
428 #[unstable(feature = "reverse_bits", issue = "48763")]
429 #[rustc_const_unstable(feature = "const_int_conversion")]
431 pub const fn reverse_bits(self) -> Self {
432 (self as $UnsignedT).reverse_bits() as Self
437 concat!("Converts an integer from big endian to the target's endianness.
439 On big endian this is a no-op. On little endian the bytes are swapped.
446 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
448 if cfg!(target_endian = \"big\") {
449 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
451 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
455 #[stable(feature = "rust1", since = "1.0.0")]
457 pub const fn from_be(x: Self) -> Self {
458 #[cfg(target_endian = "big")]
462 #[cfg(not(target_endian = "big"))]
470 concat!("Converts an integer from little endian to the target's endianness.
472 On little endian this is a no-op. On big endian the bytes are swapped.
479 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
481 if cfg!(target_endian = \"little\") {
482 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
484 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
488 #[stable(feature = "rust1", since = "1.0.0")]
490 pub const fn from_le(x: Self) -> Self {
491 #[cfg(target_endian = "little")]
495 #[cfg(not(target_endian = "little"))]
503 concat!("Converts `self` to big endian from the target's endianness.
505 On big endian this is a no-op. On little endian the bytes are swapped.
512 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
514 if cfg!(target_endian = \"big\") {
515 assert_eq!(n.to_be(), n)
517 assert_eq!(n.to_be(), n.swap_bytes())
521 #[stable(feature = "rust1", since = "1.0.0")]
523 pub const fn to_be(self) -> Self { // or not to be?
524 #[cfg(target_endian = "big")]
528 #[cfg(not(target_endian = "big"))]
536 concat!("Converts `self` to little endian from the target's endianness.
538 On little endian this is a no-op. On big endian the bytes are swapped.
545 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
547 if cfg!(target_endian = \"little\") {
548 assert_eq!(n.to_le(), n)
550 assert_eq!(n.to_le(), n.swap_bytes())
554 #[stable(feature = "rust1", since = "1.0.0")]
556 pub const fn to_le(self) -> Self {
557 #[cfg(target_endian = "little")]
561 #[cfg(not(target_endian = "little"))]
569 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
570 if overflow occurred.
577 ", $Feature, "assert_eq!((", stringify!($SelfT),
578 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
579 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
582 #[stable(feature = "rust1", since = "1.0.0")]
584 pub fn checked_add(self, rhs: Self) -> Option<Self> {
585 let (a, b) = self.overflowing_add(rhs);
586 if b {None} else {Some(a)}
591 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
599 ", $Feature, "assert_eq!((", stringify!($SelfT),
600 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
601 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
604 #[stable(feature = "rust1", since = "1.0.0")]
606 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
607 let (a, b) = self.overflowing_sub(rhs);
608 if b {None} else {Some(a)}
613 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
621 ", $Feature, "assert_eq!(", stringify!($SelfT),
622 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
623 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
626 #[stable(feature = "rust1", since = "1.0.0")]
628 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
629 let (a, b) = self.overflowing_mul(rhs);
630 if b {None} else {Some(a)}
635 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
636 or the division results in overflow.
643 ", $Feature, "assert_eq!((", stringify!($SelfT),
644 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
645 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
646 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
649 #[stable(feature = "rust1", since = "1.0.0")]
651 pub fn checked_div(self, rhs: Self) -> Option<Self> {
652 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
655 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
661 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
662 returning `None` if `rhs == 0` or the division results in overflow.
669 #![feature(euclidean_division)]
670 assert_eq!((", stringify!($SelfT),
671 "::min_value() + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
672 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euclid(-1), None);
673 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
675 #[unstable(feature = "euclidean_division", issue = "49048")]
677 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
678 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
681 Some(self.div_euclid(rhs))
687 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
688 `rhs == 0` or the division results in overflow.
695 ", $Feature, "use std::", stringify!($SelfT), ";
697 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
698 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
699 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
702 #[stable(feature = "wrapping", since = "1.7.0")]
704 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
705 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
708 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
714 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
715 if `rhs == 0` or the division results in overflow.
722 #![feature(euclidean_division)]
723 use std::", stringify!($SelfT), ";
725 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
726 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
727 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
729 #[unstable(feature = "euclidean_division", issue = "49048")]
731 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
732 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
735 Some(self.rem_euclid(rhs))
741 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
748 ", $Feature, "use std::", stringify!($SelfT), ";
750 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
751 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
754 #[stable(feature = "wrapping", since = "1.7.0")]
756 pub fn checked_neg(self) -> Option<Self> {
757 let (a, b) = self.overflowing_neg();
758 if b {None} else {Some(a)}
763 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
764 than or equal to the number of bits in `self`.
771 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
772 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
775 #[stable(feature = "wrapping", since = "1.7.0")]
777 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
778 let (a, b) = self.overflowing_shl(rhs);
779 if b {None} else {Some(a)}
784 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
785 larger than or equal to the number of bits in `self`.
792 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
793 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
796 #[stable(feature = "wrapping", since = "1.7.0")]
798 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
799 let (a, b) = self.overflowing_shr(rhs);
800 if b {None} else {Some(a)}
805 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
813 ", $Feature, "use std::", stringify!($SelfT), ";
815 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
816 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
819 #[stable(feature = "no_panic_abs", since = "1.13.0")]
821 pub fn checked_abs(self) -> Option<Self> {
822 if self.is_negative() {
831 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
839 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
840 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
844 #[stable(feature = "no_panic_pow", since = "1.34.0")]
846 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
848 let mut acc: Self = 1;
852 acc = acc.checked_mul(base)?;
855 base = base.checked_mul(base)?;
858 // Deal with the final bit of the exponent separately, since
859 // squaring the base afterwards is not necessary and may cause a
860 // needless overflow.
862 acc = acc.checked_mul(base)?;
870 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
871 bounds instead of overflowing.
878 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
879 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
883 #[stable(feature = "rust1", since = "1.0.0")]
886 pub fn saturating_add(self, rhs: Self) -> Self {
887 match self.checked_add(rhs) {
889 None if rhs >= 0 => Self::max_value(),
890 None => Self::min_value(),
897 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
898 bounds instead of overflowing.
905 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
906 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
911 #[stable(feature = "rust1", since = "1.0.0")]
912 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
915 pub const fn saturating_add(self, rhs: Self) -> Self {
916 intrinsics::saturating_add(self, rhs)
921 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
922 numeric bounds instead of overflowing.
929 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
930 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
934 #[stable(feature = "rust1", since = "1.0.0")]
937 pub fn saturating_sub(self, rhs: Self) -> Self {
938 match self.checked_sub(rhs) {
940 None if rhs >= 0 => Self::min_value(),
941 None => Self::max_value(),
947 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
948 numeric bounds instead of overflowing.
955 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
956 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
960 #[stable(feature = "rust1", since = "1.0.0")]
961 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
964 pub const fn saturating_sub(self, rhs: Self) -> Self {
965 intrinsics::saturating_sub(self, rhs)
970 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
971 numeric bounds instead of overflowing.
978 ", $Feature, "use std::", stringify!($SelfT), ";
980 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
981 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
982 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
985 #[stable(feature = "wrapping", since = "1.7.0")]
987 pub fn saturating_mul(self, rhs: Self) -> Self {
988 self.checked_mul(rhs).unwrap_or_else(|| {
989 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
999 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1000 saturating at the numeric bounds instead of overflowing.
1007 ", $Feature, "use std::", stringify!($SelfT), ";
1009 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1010 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1011 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1014 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1016 pub fn saturating_pow(self, exp: u32) -> Self {
1017 match self.checked_pow(exp) {
1019 None if self < 0 && exp % 2 == 1 => Self::min_value(),
1020 None => Self::max_value(),
1026 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1027 boundary of the type.
1034 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1035 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
1036 "::min_value() + 1);",
1039 #[stable(feature = "rust1", since = "1.0.0")]
1041 pub const fn wrapping_add(self, rhs: Self) -> Self {
1042 intrinsics::overflowing_add(self, rhs)
1047 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1048 boundary of the type.
1055 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1056 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1057 stringify!($SelfT), "::max_value());",
1060 #[stable(feature = "rust1", since = "1.0.0")]
1062 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1063 intrinsics::overflowing_sub(self, rhs)
1068 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1069 the boundary of the type.
1076 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1077 assert_eq!(11i8.wrapping_mul(12), -124);",
1080 #[stable(feature = "rust1", since = "1.0.0")]
1082 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1083 intrinsics::overflowing_mul(self, rhs)
1088 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1089 boundary of the type.
1091 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1092 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1093 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1097 This function will panic if `rhs` is 0.
1104 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1105 assert_eq!((-128i8).wrapping_div(-1), -128);",
1108 #[stable(feature = "num_wrapping", since = "1.2.0")]
1110 pub fn wrapping_div(self, rhs: Self) -> Self {
1111 self.overflowing_div(rhs).0
1116 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1117 wrapping around at the boundary of the type.
1119 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1120 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1121 type. In this case, this method returns `MIN` itself.
1125 This function will panic if `rhs` is 0.
1132 #![feature(euclidean_division)]
1133 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1134 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1136 #[unstable(feature = "euclidean_division", issue = "49048")]
1138 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
1139 self.overflowing_div_euclid(rhs).0
1144 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1145 boundary of the type.
1147 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1148 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1149 this function returns `0`.
1153 This function will panic if `rhs` is 0.
1160 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1161 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1164 #[stable(feature = "num_wrapping", since = "1.2.0")]
1166 pub fn wrapping_rem(self, rhs: Self) -> Self {
1167 self.overflowing_rem(rhs).0
1172 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1173 at the boundary of the type.
1175 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1176 for the type). In this case, this method returns 0.
1180 This function will panic if `rhs` is 0.
1187 #![feature(euclidean_division)]
1188 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1189 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1191 #[unstable(feature = "euclidean_division", issue = "49048")]
1193 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1194 self.overflowing_rem_euclid(rhs).0
1199 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1202 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1203 is the negative minimal value for the type); this is a positive value that is too large to represent
1204 in the type. In such a case, this function returns `MIN` itself.
1211 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1212 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1216 #[stable(feature = "num_wrapping", since = "1.2.0")]
1218 pub fn wrapping_neg(self) -> Self {
1219 self.overflowing_neg().0
1224 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1225 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1227 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1228 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1229 The primitive integer types all implement a `rotate_left` function, which may be what you want
1237 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1238 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1241 #[stable(feature = "num_wrapping", since = "1.2.0")]
1243 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1245 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1251 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1252 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1254 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1255 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1256 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1264 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1265 assert_eq!((-128i16).wrapping_shr(64), -128);",
1268 #[stable(feature = "num_wrapping", since = "1.2.0")]
1270 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1272 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1278 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1279 the boundary of the type.
1281 The only case where such wrapping can occur is when one takes the absolute value of the negative
1282 minimal value for the type this is a positive value that is too large to represent in the type. In
1283 such a case, this function returns `MIN` itself.
1290 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1291 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1292 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1294 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1297 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1299 pub fn wrapping_abs(self) -> Self {
1300 if self.is_negative() {
1309 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1310 wrapping around at the boundary of the type.
1317 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1318 assert_eq!(3i8.wrapping_pow(5), -13);
1319 assert_eq!(3i8.wrapping_pow(6), -39);",
1322 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1324 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1325 let mut base = self;
1326 let mut acc: Self = 1;
1330 acc = acc.wrapping_mul(base);
1333 base = base.wrapping_mul(base);
1336 // Deal with the final bit of the exponent separately, since
1337 // squaring the base afterwards is not necessary and may cause a
1338 // needless overflow.
1340 acc = acc.wrapping_mul(base);
1348 concat!("Calculates `self` + `rhs`
1350 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1351 occur. If an overflow would have occurred then the wrapped value is returned.
1358 ", $Feature, "use std::", stringify!($SelfT), ";
1360 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1361 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1362 "::MIN, true));", $EndFeature, "
1364 #[stable(feature = "wrapping", since = "1.7.0")]
1366 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1367 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1373 concat!("Calculates `self` - `rhs`
1375 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1376 would occur. If an overflow would have occurred then the wrapped value is returned.
1383 ", $Feature, "use std::", stringify!($SelfT), ";
1385 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1386 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1387 "::MAX, true));", $EndFeature, "
1389 #[stable(feature = "wrapping", since = "1.7.0")]
1391 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1392 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1398 concat!("Calculates the multiplication of `self` and `rhs`.
1400 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1401 would occur. If an overflow would have occurred then the wrapped value is returned.
1408 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1409 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1412 #[stable(feature = "wrapping", since = "1.7.0")]
1414 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1415 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1421 concat!("Calculates the divisor when `self` is divided by `rhs`.
1423 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1424 occur. If an overflow would occur then self is returned.
1428 This function will panic if `rhs` is 0.
1435 ", $Feature, "use std::", stringify!($SelfT), ";
1437 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1438 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1443 #[stable(feature = "wrapping", since = "1.7.0")]
1444 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1445 if self == Self::min_value() && rhs == -1 {
1454 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1456 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1457 occur. If an overflow would occur then `self` is returned.
1461 This function will panic if `rhs` is 0.
1468 #![feature(euclidean_division)]
1469 use std::", stringify!($SelfT), ";
1471 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1472 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1476 #[unstable(feature = "euclidean_division", issue = "49048")]
1477 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1478 if self == Self::min_value() && rhs == -1 {
1481 (self.div_euclid(rhs), false)
1487 concat!("Calculates the remainder when `self` is divided by `rhs`.
1489 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1490 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1494 This function will panic if `rhs` is 0.
1501 ", $Feature, "use std::", stringify!($SelfT), ";
1503 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1504 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1508 #[stable(feature = "wrapping", since = "1.7.0")]
1509 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1510 if self == Self::min_value() && rhs == -1 {
1520 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1522 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1523 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1527 This function will panic if `rhs` is 0.
1534 #![feature(euclidean_division)]
1535 use std::", stringify!($SelfT), ";
1537 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1538 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1540 #[unstable(feature = "euclidean_division", issue = "49048")]
1542 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1543 if self == Self::min_value() && rhs == -1 {
1546 (self.rem_euclid(rhs), false)
1553 concat!("Negates self, overflowing if this is equal to the minimum value.
1555 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1556 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1557 minimum value will be returned again and `true` will be returned for an overflow happening.
1564 ", $Feature, "use std::", stringify!($SelfT), ";
1566 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1567 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1568 "::MIN, true));", $EndFeature, "
1571 #[stable(feature = "wrapping", since = "1.7.0")]
1572 pub fn overflowing_neg(self) -> (Self, bool) {
1573 if self == Self::min_value() {
1574 (Self::min_value(), true)
1582 concat!("Shifts self left by `rhs` bits.
1584 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1585 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1586 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1593 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1594 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1597 #[stable(feature = "wrapping", since = "1.7.0")]
1599 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1600 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1605 concat!("Shifts self right by `rhs` bits.
1607 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1608 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1609 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1616 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1617 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1620 #[stable(feature = "wrapping", since = "1.7.0")]
1622 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1623 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1628 concat!("Computes the absolute value of `self`.
1630 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1631 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1632 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1633 for an overflow happening.
1640 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1641 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1642 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1643 "::min_value(), true));",
1646 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1648 pub fn overflowing_abs(self) -> (Self, bool) {
1649 if self.is_negative() {
1650 self.overflowing_neg()
1658 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1660 Returns a tuple of the exponentiation along with a bool indicating
1661 whether an overflow happened.
1668 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1669 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1672 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1674 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1675 let mut base = self;
1676 let mut acc: Self = 1;
1677 let mut overflown = false;
1678 // Scratch space for storing results of overflowing_mul.
1683 r = acc.overflowing_mul(base);
1688 r = base.overflowing_mul(base);
1693 // Deal with the final bit of the exponent separately, since
1694 // squaring the base afterwards is not necessary and may cause a
1695 // needless overflow.
1697 r = acc.overflowing_mul(base);
1707 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1714 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1716 assert_eq!(x.pow(5), 32);",
1719 #[stable(feature = "rust1", since = "1.0.0")]
1721 #[rustc_inherit_overflow_checks]
1722 pub fn pow(self, mut exp: u32) -> Self {
1723 let mut base = self;
1734 // Deal with the final bit of the exponent separately, since
1735 // squaring the base afterwards is not necessary and may cause a
1736 // needless overflow.
1746 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1748 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
1749 with `0 <= self.rem_euclid(rhs) < rhs`.
1751 In other words, the result is `self / rhs` rounded to the integer `n`
1752 such that `self >= n * rhs`.
1753 If `self > 0`, this is equal to round towards zero (the default in Rust);
1754 if `self < 0`, this is equal to round towards +/- infinity.
1758 This function will panic if `rhs` is 0.
1765 #![feature(euclidean_division)]
1766 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1769 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
1770 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
1771 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
1772 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
1774 #[unstable(feature = "euclidean_division", issue = "49048")]
1776 #[rustc_inherit_overflow_checks]
1777 pub fn div_euclid(self, rhs: Self) -> Self {
1780 return if rhs > 0 { q - 1 } else { q + 1 }
1788 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
1790 This is done as if by the Euclidean division algorithm -- given
1791 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
1792 `0 <= r < abs(rhs)`.
1796 This function will panic if `rhs` is 0.
1803 #![feature(euclidean_division)]
1804 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1807 assert_eq!(a.rem_euclid(b), 3);
1808 assert_eq!((-a).rem_euclid(b), 1);
1809 assert_eq!(a.rem_euclid(-b), 3);
1810 assert_eq!((-a).rem_euclid(-b), 1);
1812 #[unstable(feature = "euclidean_division", issue = "49048")]
1814 #[rustc_inherit_overflow_checks]
1815 pub fn rem_euclid(self, rhs: Self) -> Self {
1830 concat!("Computes the absolute value of `self`.
1834 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1835 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1836 code in debug mode will trigger a panic on this case and optimized code will return `",
1837 stringify!($SelfT), "::min_value()` without a panic.
1844 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1845 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1848 #[stable(feature = "rust1", since = "1.0.0")]
1850 #[rustc_inherit_overflow_checks]
1851 pub fn abs(self) -> Self {
1852 if self.is_negative() {
1853 // Note that the #[inline] above means that the overflow
1854 // semantics of this negation depend on the crate we're being
1864 concat!("Returns a number representing sign of `self`.
1866 - `0` if the number is zero
1867 - `1` if the number is positive
1868 - `-1` if the number is negative
1875 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1876 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1877 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1880 #[stable(feature = "rust1", since = "1.0.0")]
1882 pub fn signum(self) -> Self {
1892 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1900 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1901 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1904 #[stable(feature = "rust1", since = "1.0.0")]
1906 pub const fn is_positive(self) -> bool { self > 0 }
1910 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1918 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1919 assert!(!10", stringify!($SelfT), ".is_negative());",
1922 #[stable(feature = "rust1", since = "1.0.0")]
1924 pub const fn is_negative(self) -> bool { self < 0 }
1928 concat!("Return the memory representation of this integer as a byte array in
1929 big-endian (network) byte order.
1934 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
1935 assert_eq!(bytes, ", $be_bytes, ");
1937 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1938 #[rustc_const_unstable(feature = "const_int_conversion")]
1940 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
1941 self.to_be().to_ne_bytes()
1946 concat!("Return the memory representation of this integer as a byte array in
1947 little-endian byte order.
1952 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
1953 assert_eq!(bytes, ", $le_bytes, ");
1955 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1956 #[rustc_const_unstable(feature = "const_int_conversion")]
1958 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
1959 self.to_le().to_ne_bytes()
1965 Return the memory representation of this integer as a byte array in
1968 As the target platform's native endianness is used, portable code
1969 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
1972 [`to_be_bytes`]: #method.to_be_bytes
1973 [`to_le_bytes`]: #method.to_le_bytes
1978 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
1979 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
1985 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1986 #[rustc_const_unstable(feature = "const_int_conversion")]
1988 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
1989 unsafe { mem::transmute(self) }
1994 concat!("Create an integer value from its representation as a byte array in
2000 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2001 assert_eq!(value, ", $swap_op, ");
2004 When starting from a slice rather than an array, fallible conversion APIs can be used:
2007 #![feature(try_from)]
2008 use std::convert::TryInto;
2010 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2011 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2013 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2016 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2017 #[rustc_const_unstable(feature = "const_int_conversion")]
2019 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2020 Self::from_be(Self::from_ne_bytes(bytes))
2026 Create an integer value from its representation as a byte array in
2032 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2033 assert_eq!(value, ", $swap_op, ");
2036 When starting from a slice rather than an array, fallible conversion APIs can be used:
2039 #![feature(try_from)]
2040 use std::convert::TryInto;
2042 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2043 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2045 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2048 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2049 #[rustc_const_unstable(feature = "const_int_conversion")]
2051 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2052 Self::from_le(Self::from_ne_bytes(bytes))
2057 concat!("Create an integer value from its memory representation as a byte
2058 array in native endianness.
2060 As the target platform's native endianness is used, portable code
2061 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2062 appropriate instead.
2064 [`from_be_bytes`]: #method.from_be_bytes
2065 [`from_le_bytes`]: #method.from_le_bytes
2070 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2075 assert_eq!(value, ", $swap_op, ");
2078 When starting from a slice rather than an array, fallible conversion APIs can be used:
2081 #![feature(try_from)]
2082 use std::convert::TryInto;
2084 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2085 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2087 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2090 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2091 #[rustc_const_unstable(feature = "const_int_conversion")]
2093 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2094 unsafe { mem::transmute(bytes) }
2102 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2103 "[0x12]", "[0x12]" }
2108 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2109 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]" }
2114 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2115 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2116 "[0x12, 0x34, 0x56, 0x78]" }
2121 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2122 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2123 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2124 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
2129 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2130 170141183460469231731687303715884105727, "", "", 16,
2131 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2132 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2133 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2134 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2135 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2136 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]" }
2139 #[cfg(target_pointer_width = "16")]
2142 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2143 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]" }
2146 #[cfg(target_pointer_width = "32")]
2149 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2150 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2151 "[0x12, 0x34, 0x56, 0x78]" }
2154 #[cfg(target_pointer_width = "64")]
2157 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2158 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2159 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2160 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
2163 // `Int` + `UnsignedInt` implemented for unsigned integers
2164 macro_rules! uint_impl {
2165 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2166 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2167 $reversed:expr, $le_bytes:expr, $be_bytes:expr) => {
2169 concat!("Returns the smallest value that can be represented by this integer type.
2176 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2178 #[stable(feature = "rust1", since = "1.0.0")]
2181 pub const fn min_value() -> Self { 0 }
2185 concat!("Returns the largest value that can be represented by this integer type.
2192 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2193 stringify!($MaxV), ");", $EndFeature, "
2195 #[stable(feature = "rust1", since = "1.0.0")]
2198 pub const fn max_value() -> Self { !0 }
2202 concat!("Converts a string slice in a given base to an integer.
2204 The string is expected to be an optional `+` sign
2206 Leading and trailing whitespace represent an error.
2207 Digits are a subset of these characters, depending on `radix`:
2215 This function panics if `radix` is not in the range from 2 to 36.
2222 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2225 #[stable(feature = "rust1", since = "1.0.0")]
2226 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2227 from_str_radix(src, radix)
2232 concat!("Returns the number of ones in the binary representation of `self`.
2239 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2241 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2243 #[stable(feature = "rust1", since = "1.0.0")]
2245 pub const fn count_ones(self) -> u32 {
2246 intrinsics::ctpop(self as $ActualT) as u32
2251 concat!("Returns the number of zeros in the binary representation of `self`.
2258 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2260 #[stable(feature = "rust1", since = "1.0.0")]
2262 pub const fn count_zeros(self) -> u32 {
2263 (!self).count_ones()
2268 concat!("Returns the number of leading zeros in the binary representation of `self`.
2275 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2277 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2279 #[stable(feature = "rust1", since = "1.0.0")]
2281 pub const fn leading_zeros(self) -> u32 {
2282 intrinsics::ctlz(self as $ActualT) as u32
2287 concat!("Returns the number of trailing zeros in the binary representation
2295 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2297 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2299 #[stable(feature = "rust1", since = "1.0.0")]
2301 pub const fn trailing_zeros(self) -> u32 {
2302 intrinsics::cttz(self) as u32
2307 concat!("Shifts the bits to the left by a specified amount, `n`,
2308 wrapping the truncated bits to the end of the resulting integer.
2310 Please note this isn't the same operation as `<<`!
2317 let n = ", $rot_op, stringify!($SelfT), ";
2318 let m = ", $rot_result, ";
2320 assert_eq!(n.rotate_left(", $rot, "), m);
2322 #[stable(feature = "rust1", since = "1.0.0")]
2324 pub const fn rotate_left(self, n: u32) -> Self {
2325 intrinsics::rotate_left(self, n as $SelfT)
2330 concat!("Shifts the bits to the right by a specified amount, `n`,
2331 wrapping the truncated bits to the beginning of the resulting
2334 Please note this isn't the same operation as `>>`!
2341 let n = ", $rot_result, stringify!($SelfT), ";
2342 let m = ", $rot_op, ";
2344 assert_eq!(n.rotate_right(", $rot, "), m);
2346 #[stable(feature = "rust1", since = "1.0.0")]
2348 pub const fn rotate_right(self, n: u32) -> Self {
2349 intrinsics::rotate_right(self, n as $SelfT)
2355 Reverses the byte order of the integer.
2362 let n = ", $swap_op, stringify!($SelfT), ";
2363 let m = n.swap_bytes();
2365 assert_eq!(m, ", $swapped, ");
2367 #[stable(feature = "rust1", since = "1.0.0")]
2369 pub const fn swap_bytes(self) -> Self {
2370 intrinsics::bswap(self as $ActualT) as Self
2375 concat!("Reverses the bit pattern of the integer.
2382 #![feature(reverse_bits)]
2384 let n = ", $swap_op, stringify!($SelfT), ";
2385 let m = n.reverse_bits();
2387 assert_eq!(m, ", $reversed, ");
2389 #[unstable(feature = "reverse_bits", issue = "48763")]
2391 pub const fn reverse_bits(self) -> Self {
2392 intrinsics::bitreverse(self as $ActualT) as Self
2397 concat!("Converts an integer from big endian to the target's endianness.
2399 On big endian this is a no-op. On little endian the bytes are
2407 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2409 if cfg!(target_endian = \"big\") {
2410 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2412 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2415 #[stable(feature = "rust1", since = "1.0.0")]
2417 pub const fn from_be(x: Self) -> Self {
2418 #[cfg(target_endian = "big")]
2422 #[cfg(not(target_endian = "big"))]
2430 concat!("Converts an integer from little endian to the target's endianness.
2432 On little endian this is a no-op. On big endian the bytes are
2440 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2442 if cfg!(target_endian = \"little\") {
2443 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2445 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2448 #[stable(feature = "rust1", since = "1.0.0")]
2450 pub const fn from_le(x: Self) -> Self {
2451 #[cfg(target_endian = "little")]
2455 #[cfg(not(target_endian = "little"))]
2463 concat!("Converts `self` to big endian from the target's endianness.
2465 On big endian this is a no-op. On little endian the bytes are
2473 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2475 if cfg!(target_endian = \"big\") {
2476 assert_eq!(n.to_be(), n)
2478 assert_eq!(n.to_be(), n.swap_bytes())
2481 #[stable(feature = "rust1", since = "1.0.0")]
2483 pub const fn to_be(self) -> Self { // or not to be?
2484 #[cfg(target_endian = "big")]
2488 #[cfg(not(target_endian = "big"))]
2496 concat!("Converts `self` to little endian from the target's endianness.
2498 On little endian this is a no-op. On big endian the bytes are
2506 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2508 if cfg!(target_endian = \"little\") {
2509 assert_eq!(n.to_le(), n)
2511 assert_eq!(n.to_le(), n.swap_bytes())
2514 #[stable(feature = "rust1", since = "1.0.0")]
2516 pub const fn to_le(self) -> Self {
2517 #[cfg(target_endian = "little")]
2521 #[cfg(not(target_endian = "little"))]
2529 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2530 if overflow occurred.
2537 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2538 "Some(", stringify!($SelfT), "::max_value() - 1));
2539 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2541 #[stable(feature = "rust1", since = "1.0.0")]
2543 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2544 let (a, b) = self.overflowing_add(rhs);
2545 if b {None} else {Some(a)}
2550 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2551 `None` if overflow occurred.
2558 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2559 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2561 #[stable(feature = "rust1", since = "1.0.0")]
2563 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2564 let (a, b) = self.overflowing_sub(rhs);
2565 if b {None} else {Some(a)}
2570 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2571 `None` if overflow occurred.
2578 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2579 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2581 #[stable(feature = "rust1", since = "1.0.0")]
2583 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2584 let (a, b) = self.overflowing_mul(rhs);
2585 if b {None} else {Some(a)}
2590 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2598 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2599 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2601 #[stable(feature = "rust1", since = "1.0.0")]
2603 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2606 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2612 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2620 #![feature(euclidean_division)]
2621 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
2622 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
2624 #[unstable(feature = "euclidean_division", issue = "49048")]
2626 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
2630 Some(self.div_euclid(rhs))
2637 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2645 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2646 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2648 #[stable(feature = "wrapping", since = "1.7.0")]
2650 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2654 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2660 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
2668 #![feature(euclidean_division)]
2669 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
2670 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
2672 #[unstable(feature = "euclidean_division", issue = "49048")]
2674 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
2678 Some(self.rem_euclid(rhs))
2684 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2687 Note that negating any positive integer will overflow.
2694 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2695 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2697 #[stable(feature = "wrapping", since = "1.7.0")]
2699 pub fn checked_neg(self) -> Option<Self> {
2700 let (a, b) = self.overflowing_neg();
2701 if b {None} else {Some(a)}
2706 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2707 if `rhs` is larger than or equal to the number of bits in `self`.
2714 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2715 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2717 #[stable(feature = "wrapping", since = "1.7.0")]
2719 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2720 let (a, b) = self.overflowing_shl(rhs);
2721 if b {None} else {Some(a)}
2726 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2727 if `rhs` is larger than or equal to the number of bits in `self`.
2734 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2735 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2737 #[stable(feature = "wrapping", since = "1.7.0")]
2739 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2740 let (a, b) = self.overflowing_shr(rhs);
2741 if b {None} else {Some(a)}
2746 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2754 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2755 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2757 #[stable(feature = "no_panic_pow", since = "1.34.0")]
2759 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2760 let mut base = self;
2761 let mut acc: Self = 1;
2765 acc = acc.checked_mul(base)?;
2768 base = base.checked_mul(base)?;
2771 // Deal with the final bit of the exponent separately, since
2772 // squaring the base afterwards is not necessary and may cause a
2773 // needless overflow.
2775 acc = acc.checked_mul(base)?;
2783 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2784 the numeric bounds instead of overflowing.
2791 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2792 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2794 #[stable(feature = "rust1", since = "1.0.0")]
2797 pub fn saturating_add(self, rhs: Self) -> Self {
2798 match self.checked_add(rhs) {
2800 None => Self::max_value(),
2806 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2807 the numeric bounds instead of overflowing.
2814 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2815 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2818 #[stable(feature = "rust1", since = "1.0.0")]
2819 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
2822 pub const fn saturating_add(self, rhs: Self) -> Self {
2823 intrinsics::saturating_add(self, rhs)
2828 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2829 at the numeric bounds instead of overflowing.
2836 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2837 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2839 #[stable(feature = "rust1", since = "1.0.0")]
2842 pub fn saturating_sub(self, rhs: Self) -> Self {
2843 match self.checked_sub(rhs) {
2845 None => Self::min_value(),
2851 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2852 at the numeric bounds instead of overflowing.
2859 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2860 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2862 #[stable(feature = "rust1", since = "1.0.0")]
2863 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
2866 pub const fn saturating_sub(self, rhs: Self) -> Self {
2867 intrinsics::saturating_sub(self, rhs)
2872 concat!("Saturating integer multiplication. Computes `self * rhs`,
2873 saturating at the numeric bounds instead of overflowing.
2880 ", $Feature, "use std::", stringify!($SelfT), ";
2882 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2883 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2884 "::MAX);", $EndFeature, "
2886 #[stable(feature = "wrapping", since = "1.7.0")]
2888 pub fn saturating_mul(self, rhs: Self) -> Self {
2889 self.checked_mul(rhs).unwrap_or(Self::max_value())
2894 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2895 saturating at the numeric bounds instead of overflowing.
2902 ", $Feature, "use std::", stringify!($SelfT), ";
2904 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2905 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2908 #[stable(feature = "no_panic_pow", since = "1.34.0")]
2910 pub fn saturating_pow(self, exp: u32) -> Self {
2911 match self.checked_pow(exp) {
2913 None => Self::max_value(),
2919 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2920 wrapping around at the boundary of the type.
2927 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2928 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2931 #[stable(feature = "rust1", since = "1.0.0")]
2933 pub const fn wrapping_add(self, rhs: Self) -> Self {
2934 intrinsics::overflowing_add(self, rhs)
2939 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2940 wrapping around at the boundary of the type.
2947 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2948 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2951 #[stable(feature = "rust1", since = "1.0.0")]
2953 pub const fn wrapping_sub(self, rhs: Self) -> Self {
2954 intrinsics::overflowing_sub(self, rhs)
2958 /// Wrapping (modular) multiplication. Computes `self *
2959 /// rhs`, wrapping around at the boundary of the type.
2965 /// Please note that this example is shared between integer types.
2966 /// Which explains why `u8` is used here.
2969 /// assert_eq!(10u8.wrapping_mul(12), 120);
2970 /// assert_eq!(25u8.wrapping_mul(12), 44);
2972 #[stable(feature = "rust1", since = "1.0.0")]
2974 pub const fn wrapping_mul(self, rhs: Self) -> Self {
2975 intrinsics::overflowing_mul(self, rhs)
2979 concat!("Wrapping (modular) division. Computes `self / rhs`.
2980 Wrapped division on unsigned types is just normal division.
2981 There's no way wrapping could ever happen.
2982 This function exists, so that all operations
2983 are accounted for in the wrapping operations.
2990 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2992 #[stable(feature = "num_wrapping", since = "1.2.0")]
2994 pub fn wrapping_div(self, rhs: Self) -> Self {
3000 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3001 Wrapped division on unsigned types is just normal division.
3002 There's no way wrapping could ever happen.
3003 This function exists, so that all operations
3004 are accounted for in the wrapping operations.
3005 Since, for the positive integers, all common
3006 definitions of division are equal, this
3007 is exactly equal to `self.wrapping_div(rhs)`.
3014 #![feature(euclidean_division)]
3015 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3017 #[unstable(feature = "euclidean_division", issue = "49048")]
3019 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
3025 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3026 Wrapped remainder calculation on unsigned types is
3027 just the regular remainder calculation.
3028 There's no way wrapping could ever happen.
3029 This function exists, so that all operations
3030 are accounted for in the wrapping operations.
3037 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3039 #[stable(feature = "num_wrapping", since = "1.2.0")]
3041 pub fn wrapping_rem(self, rhs: Self) -> Self {
3047 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3048 Wrapped modulo calculation on unsigned types is
3049 just the regular remainder calculation.
3050 There's no way wrapping could ever happen.
3051 This function exists, so that all operations
3052 are accounted for in the wrapping operations.
3053 Since, for the positive integers, all common
3054 definitions of division are equal, this
3055 is exactly equal to `self.wrapping_rem(rhs)`.
3062 #![feature(euclidean_division)]
3063 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3065 #[unstable(feature = "euclidean_division", issue = "49048")]
3067 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3072 /// Wrapping (modular) negation. Computes `-self`,
3073 /// wrapping around at the boundary of the type.
3075 /// Since unsigned types do not have negative equivalents
3076 /// all applications of this function will wrap (except for `-0`).
3077 /// For values smaller than the corresponding signed type's maximum
3078 /// the result is the same as casting the corresponding signed value.
3079 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3080 /// `MAX` is the corresponding signed type's maximum.
3086 /// Please note that this example is shared between integer types.
3087 /// Which explains why `i8` is used here.
3090 /// assert_eq!(100i8.wrapping_neg(), -100);
3091 /// assert_eq!((-128i8).wrapping_neg(), -128);
3093 #[stable(feature = "num_wrapping", since = "1.2.0")]
3095 pub fn wrapping_neg(self) -> Self {
3096 self.overflowing_neg().0
3100 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3101 where `mask` removes any high-order bits of `rhs` that
3102 would cause the shift to exceed the bitwidth of the type.
3104 Note that this is *not* the same as a rotate-left; the
3105 RHS of a wrapping shift-left is restricted to the range
3106 of the type, rather than the bits shifted out of the LHS
3107 being returned to the other end. The primitive integer
3108 types all implement a `rotate_left` function, which may
3109 be what you want instead.
3116 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3117 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3119 #[stable(feature = "num_wrapping", since = "1.2.0")]
3121 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3123 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3129 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3130 where `mask` removes any high-order bits of `rhs` that
3131 would cause the shift to exceed the bitwidth of the type.
3133 Note that this is *not* the same as a rotate-right; the
3134 RHS of a wrapping shift-right is restricted to the range
3135 of the type, rather than the bits shifted out of the LHS
3136 being returned to the other end. The primitive integer
3137 types all implement a `rotate_right` function, which may
3138 be what you want instead.
3145 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3146 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3148 #[stable(feature = "num_wrapping", since = "1.2.0")]
3150 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3152 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3158 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3159 wrapping around at the boundary of the type.
3166 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3167 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3169 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3171 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3172 let mut base = self;
3173 let mut acc: Self = 1;
3177 acc = acc.wrapping_mul(base);
3180 base = base.wrapping_mul(base);
3183 // Deal with the final bit of the exponent separately, since
3184 // squaring the base afterwards is not necessary and may cause a
3185 // needless overflow.
3187 acc = acc.wrapping_mul(base);
3195 concat!("Calculates `self` + `rhs`
3197 Returns a tuple of the addition along with a boolean indicating
3198 whether an arithmetic overflow would occur. If an overflow would
3199 have occurred then the wrapped value is returned.
3206 ", $Feature, "use std::", stringify!($SelfT), ";
3208 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3209 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3211 #[stable(feature = "wrapping", since = "1.7.0")]
3213 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3214 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3220 concat!("Calculates `self` - `rhs`
3222 Returns a tuple of the subtraction along with a boolean indicating
3223 whether an arithmetic overflow would occur. If an overflow would
3224 have occurred then the wrapped value is returned.
3231 ", $Feature, "use std::", stringify!($SelfT), ";
3233 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3234 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3237 #[stable(feature = "wrapping", since = "1.7.0")]
3239 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3240 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3245 /// Calculates the multiplication of `self` and `rhs`.
3247 /// Returns a tuple of the multiplication along with a boolean
3248 /// indicating whether an arithmetic overflow would occur. If an
3249 /// overflow would have occurred then the wrapped value is returned.
3255 /// Please note that this example is shared between integer types.
3256 /// Which explains why `u32` is used here.
3259 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3260 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3262 #[stable(feature = "wrapping", since = "1.7.0")]
3264 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3265 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3270 concat!("Calculates the divisor when `self` is divided by `rhs`.
3272 Returns a tuple of the divisor along with a boolean indicating
3273 whether an arithmetic overflow would occur. Note that for unsigned
3274 integers overflow never occurs, so the second value is always
3279 This function will panic if `rhs` is 0.
3286 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3289 #[stable(feature = "wrapping", since = "1.7.0")]
3290 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3296 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3298 Returns a tuple of the divisor along with a boolean indicating
3299 whether an arithmetic overflow would occur. Note that for unsigned
3300 integers overflow never occurs, so the second value is always
3302 Since, for the positive integers, all common
3303 definitions of division are equal, this
3304 is exactly equal to `self.overflowing_div(rhs)`.
3308 This function will panic if `rhs` is 0.
3315 #![feature(euclidean_division)]
3316 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3319 #[unstable(feature = "euclidean_division", issue = "49048")]
3320 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3326 concat!("Calculates the remainder when `self` is divided by `rhs`.
3328 Returns a tuple of the remainder after dividing along with a boolean
3329 indicating whether an arithmetic overflow would occur. Note that for
3330 unsigned integers overflow never occurs, so the second value is
3335 This function will panic if `rhs` is 0.
3342 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3345 #[stable(feature = "wrapping", since = "1.7.0")]
3346 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3352 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3354 Returns a tuple of the modulo after dividing along with a boolean
3355 indicating whether an arithmetic overflow would occur. Note that for
3356 unsigned integers overflow never occurs, so the second value is
3358 Since, for the positive integers, all common
3359 definitions of division are equal, this operation
3360 is exactly equal to `self.overflowing_rem(rhs)`.
3364 This function will panic if `rhs` is 0.
3371 #![feature(euclidean_division)]
3372 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3375 #[unstable(feature = "euclidean_division", issue = "49048")]
3376 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3382 concat!("Negates self in an overflowing fashion.
3384 Returns `!self + 1` using wrapping operations to return the value
3385 that represents the negation of this unsigned value. Note that for
3386 positive unsigned values overflow always occurs, but negating 0 does
3394 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3395 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3396 ", true));", $EndFeature, "
3399 #[stable(feature = "wrapping", since = "1.7.0")]
3400 pub fn overflowing_neg(self) -> (Self, bool) {
3401 ((!self).wrapping_add(1), self != 0)
3406 concat!("Shifts self left by `rhs` bits.
3408 Returns a tuple of the shifted version of self along with a boolean
3409 indicating whether the shift value was larger than or equal to the
3410 number of bits. If the shift value is too large, then value is
3411 masked (N-1) where N is the number of bits, and this value is then
3412 used to perform the shift.
3419 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3420 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3422 #[stable(feature = "wrapping", since = "1.7.0")]
3424 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3425 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3430 concat!("Shifts self right by `rhs` bits.
3432 Returns a tuple of the shifted version of self along with a boolean
3433 indicating whether the shift value was larger than or equal to the
3434 number of bits. If the shift value is too large, then value is
3435 masked (N-1) where N is the number of bits, and this value is then
3436 used to perform the shift.
3443 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3444 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3446 #[stable(feature = "wrapping", since = "1.7.0")]
3448 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3449 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3454 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3456 Returns a tuple of the exponentiation along with a bool indicating
3457 whether an overflow happened.
3464 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3465 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3467 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3469 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3470 let mut base = self;
3471 let mut acc: Self = 1;
3472 let mut overflown = false;
3473 // Scratch space for storing results of overflowing_mul.
3478 r = acc.overflowing_mul(base);
3483 r = base.overflowing_mul(base);
3488 // Deal with the final bit of the exponent separately, since
3489 // squaring the base afterwards is not necessary and may cause a
3490 // needless overflow.
3492 r = acc.overflowing_mul(base);
3502 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3509 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3511 #[stable(feature = "rust1", since = "1.0.0")]
3513 #[rustc_inherit_overflow_checks]
3514 pub fn pow(self, mut exp: u32) -> Self {
3515 let mut base = self;
3526 // Deal with the final bit of the exponent separately, since
3527 // squaring the base afterwards is not necessary and may cause a
3528 // needless overflow.
3538 concat!("Performs Euclidean division.
3540 Since, for the positive integers, all common
3541 definitions of division are equal, this
3542 is exactly equal to `self / rhs`.
3549 #![feature(euclidean_division)]
3550 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
3552 #[unstable(feature = "euclidean_division", issue = "49048")]
3554 #[rustc_inherit_overflow_checks]
3555 pub fn div_euclid(self, rhs: Self) -> Self {
3562 concat!("Calculates the least remainder of `self (mod rhs)`.
3564 Since, for the positive integers, all common
3565 definitions of division are equal, this
3566 is exactly equal to `self % rhs`.
3573 #![feature(euclidean_division)]
3574 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
3576 #[unstable(feature = "euclidean_division", issue = "49048")]
3578 #[rustc_inherit_overflow_checks]
3579 pub fn rem_euclid(self, rhs: Self) -> Self {
3585 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3592 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3593 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3595 #[stable(feature = "rust1", since = "1.0.0")]
3597 pub fn is_power_of_two(self) -> bool {
3598 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3602 // Returns one less than next power of two.
3603 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3605 // 8u8.one_less_than_next_power_of_two() == 7
3606 // 6u8.one_less_than_next_power_of_two() == 7
3608 // This method cannot overflow, as in the `next_power_of_two`
3609 // overflow cases it instead ends up returning the maximum value
3610 // of the type, and can return 0 for 0.
3612 fn one_less_than_next_power_of_two(self) -> Self {
3613 if self <= 1 { return 0; }
3615 // Because `p > 0`, it cannot consist entirely of leading zeros.
3616 // That means the shift is always in-bounds, and some processors
3617 // (such as intel pre-haswell) have more efficient ctlz
3618 // intrinsics when the argument is non-zero.
3620 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3621 <$SelfT>::max_value() >> z
3625 concat!("Returns the smallest power of two greater than or equal to `self`.
3627 When return value overflows (i.e., `self > (1 << (N-1))` for type
3628 `uN`), it panics in debug mode and return value is wrapped to 0 in
3629 release mode (the only situation in which method can return 0).
3636 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3637 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3639 #[stable(feature = "rust1", since = "1.0.0")]
3641 pub fn next_power_of_two(self) -> Self {
3642 // Call the trait to get overflow checks
3643 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3648 concat!("Returns the smallest power of two greater than or equal to `n`. If
3649 the next power of two is greater than the type's maximum value,
3650 `None` is returned, otherwise the power of two is wrapped in `Some`.
3657 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3658 ".checked_next_power_of_two(), Some(2));
3659 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3660 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3664 #[stable(feature = "rust1", since = "1.0.0")]
3665 pub fn checked_next_power_of_two(self) -> Option<Self> {
3666 self.one_less_than_next_power_of_two().checked_add(1)
3671 concat!("Returns the smallest power of two greater than or equal to `n`. If
3672 the next power of two is greater than the type's maximum value,
3673 the return value is wrapped to `0`.
3680 #![feature(wrapping_next_power_of_two)]
3682 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3683 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3684 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3687 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3688 reason = "needs decision on wrapping behaviour")]
3689 pub fn wrapping_next_power_of_two(self) -> Self {
3690 self.one_less_than_next_power_of_two().wrapping_add(1)
3695 concat!("Return the memory representation of this integer as a byte array in
3696 big-endian (network) byte order.
3701 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
3702 assert_eq!(bytes, ", $be_bytes, ");
3704 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3705 #[rustc_const_unstable(feature = "const_int_conversion")]
3707 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
3708 self.to_be().to_ne_bytes()
3713 concat!("Return the memory representation of this integer as a byte array in
3714 little-endian byte order.
3719 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
3720 assert_eq!(bytes, ", $le_bytes, ");
3722 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3723 #[rustc_const_unstable(feature = "const_int_conversion")]
3725 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
3726 self.to_le().to_ne_bytes()
3732 Return the memory representation of this integer as a byte array in
3735 As the target platform's native endianness is used, portable code
3736 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3739 [`to_be_bytes`]: #method.to_be_bytes
3740 [`to_le_bytes`]: #method.to_le_bytes
3745 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
3746 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
3752 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3753 #[rustc_const_unstable(feature = "const_int_conversion")]
3755 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
3756 unsafe { mem::transmute(self) }
3761 concat!("Create an integer value from its representation as a byte array in
3767 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
3768 assert_eq!(value, ", $swap_op, ");
3771 When starting from a slice rather than an array, fallible conversion APIs can be used:
3774 #![feature(try_from)]
3775 use std::convert::TryInto;
3777 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3778 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3780 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
3783 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3784 #[rustc_const_unstable(feature = "const_int_conversion")]
3786 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3787 Self::from_be(Self::from_ne_bytes(bytes))
3793 Create an integer value from its representation as a byte array in
3799 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
3800 assert_eq!(value, ", $swap_op, ");
3803 When starting from a slice rather than an array, fallible conversion APIs can be used:
3806 #![feature(try_from)]
3807 use std::convert::TryInto;
3809 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3810 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3812 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
3815 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3816 #[rustc_const_unstable(feature = "const_int_conversion")]
3818 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3819 Self::from_le(Self::from_ne_bytes(bytes))
3824 concat!("Create an integer value from its memory representation as a byte
3825 array in native endianness.
3827 As the target platform's native endianness is used, portable code
3828 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3829 appropriate instead.
3831 [`from_be_bytes`]: #method.from_be_bytes
3832 [`from_le_bytes`]: #method.from_le_bytes
3837 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
3842 assert_eq!(value, ", $swap_op, ");
3845 When starting from a slice rather than an array, fallible conversion APIs can be used:
3848 #![feature(try_from)]
3849 use std::convert::TryInto;
3851 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3852 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3854 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
3857 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3858 #[rustc_const_unstable(feature = "const_int_conversion")]
3860 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3861 unsafe { mem::transmute(bytes) }
3869 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
3873 /// Checks if the value is within the ASCII range.
3878 /// let ascii = 97u8;
3879 /// let non_ascii = 150u8;
3881 /// assert!(ascii.is_ascii());
3882 /// assert!(!non_ascii.is_ascii());
3884 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3886 pub fn is_ascii(&self) -> bool {
3890 /// Makes a copy of the value in its ASCII upper case equivalent.
3892 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3893 /// but non-ASCII letters are unchanged.
3895 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
3900 /// let lowercase_a = 97u8;
3902 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
3905 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
3906 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3908 pub fn to_ascii_uppercase(&self) -> u8 {
3909 ASCII_UPPERCASE_MAP[*self as usize]
3912 /// Makes a copy of the value in its ASCII lower case equivalent.
3914 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3915 /// but non-ASCII letters are unchanged.
3917 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
3922 /// let uppercase_a = 65u8;
3924 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
3927 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
3928 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3930 pub fn to_ascii_lowercase(&self) -> u8 {
3931 ASCII_LOWERCASE_MAP[*self as usize]
3934 /// Checks that two values are an ASCII case-insensitive match.
3936 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3941 /// let lowercase_a = 97u8;
3942 /// let uppercase_a = 65u8;
3944 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3946 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3948 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3949 self.to_ascii_lowercase() == other.to_ascii_lowercase()
3952 /// Converts this value to its ASCII upper case equivalent in-place.
3954 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3955 /// but non-ASCII letters are unchanged.
3957 /// To return a new uppercased value without modifying the existing one, use
3958 /// [`to_ascii_uppercase`].
3963 /// let mut byte = b'a';
3965 /// byte.make_ascii_uppercase();
3967 /// assert_eq!(b'A', byte);
3970 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3971 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3973 pub fn make_ascii_uppercase(&mut self) {
3974 *self = self.to_ascii_uppercase();
3977 /// Converts this value to its ASCII lower case equivalent in-place.
3979 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3980 /// but non-ASCII letters are unchanged.
3982 /// To return a new lowercased value without modifying the existing one, use
3983 /// [`to_ascii_lowercase`].
3988 /// let mut byte = b'A';
3990 /// byte.make_ascii_lowercase();
3992 /// assert_eq!(b'a', byte);
3995 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3996 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3998 pub fn make_ascii_lowercase(&mut self) {
3999 *self = self.to_ascii_lowercase();
4002 /// Checks if the value is an ASCII alphabetic character:
4004 /// - U+0041 'A' ... U+005A 'Z', or
4005 /// - U+0061 'a' ... U+007A 'z'.
4010 /// let uppercase_a = b'A';
4011 /// let uppercase_g = b'G';
4014 /// let zero = b'0';
4015 /// let percent = b'%';
4016 /// let space = b' ';
4018 /// let esc = 0x1b_u8;
4020 /// assert!(uppercase_a.is_ascii_alphabetic());
4021 /// assert!(uppercase_g.is_ascii_alphabetic());
4022 /// assert!(a.is_ascii_alphabetic());
4023 /// assert!(g.is_ascii_alphabetic());
4024 /// assert!(!zero.is_ascii_alphabetic());
4025 /// assert!(!percent.is_ascii_alphabetic());
4026 /// assert!(!space.is_ascii_alphabetic());
4027 /// assert!(!lf.is_ascii_alphabetic());
4028 /// assert!(!esc.is_ascii_alphabetic());
4030 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4032 pub fn is_ascii_alphabetic(&self) -> bool {
4033 if *self >= 0x80 { return false; }
4034 match ASCII_CHARACTER_CLASS[*self as usize] {
4035 L | Lx | U | Ux => true,
4040 /// Checks if the value is an ASCII uppercase character:
4041 /// U+0041 'A' ... U+005A 'Z'.
4046 /// let uppercase_a = b'A';
4047 /// let uppercase_g = b'G';
4050 /// let zero = b'0';
4051 /// let percent = b'%';
4052 /// let space = b' ';
4054 /// let esc = 0x1b_u8;
4056 /// assert!(uppercase_a.is_ascii_uppercase());
4057 /// assert!(uppercase_g.is_ascii_uppercase());
4058 /// assert!(!a.is_ascii_uppercase());
4059 /// assert!(!g.is_ascii_uppercase());
4060 /// assert!(!zero.is_ascii_uppercase());
4061 /// assert!(!percent.is_ascii_uppercase());
4062 /// assert!(!space.is_ascii_uppercase());
4063 /// assert!(!lf.is_ascii_uppercase());
4064 /// assert!(!esc.is_ascii_uppercase());
4066 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4068 pub fn is_ascii_uppercase(&self) -> bool {
4069 if *self >= 0x80 { return false }
4070 match ASCII_CHARACTER_CLASS[*self as usize] {
4076 /// Checks if the value is an ASCII lowercase character:
4077 /// U+0061 'a' ... U+007A 'z'.
4082 /// let uppercase_a = b'A';
4083 /// let uppercase_g = b'G';
4086 /// let zero = b'0';
4087 /// let percent = b'%';
4088 /// let space = b' ';
4090 /// let esc = 0x1b_u8;
4092 /// assert!(!uppercase_a.is_ascii_lowercase());
4093 /// assert!(!uppercase_g.is_ascii_lowercase());
4094 /// assert!(a.is_ascii_lowercase());
4095 /// assert!(g.is_ascii_lowercase());
4096 /// assert!(!zero.is_ascii_lowercase());
4097 /// assert!(!percent.is_ascii_lowercase());
4098 /// assert!(!space.is_ascii_lowercase());
4099 /// assert!(!lf.is_ascii_lowercase());
4100 /// assert!(!esc.is_ascii_lowercase());
4102 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4104 pub fn is_ascii_lowercase(&self) -> bool {
4105 if *self >= 0x80 { return false }
4106 match ASCII_CHARACTER_CLASS[*self as usize] {
4112 /// Checks if the value is an ASCII alphanumeric character:
4114 /// - U+0041 'A' ... U+005A 'Z', or
4115 /// - U+0061 'a' ... U+007A 'z', or
4116 /// - U+0030 '0' ... U+0039 '9'.
4121 /// let uppercase_a = b'A';
4122 /// let uppercase_g = b'G';
4125 /// let zero = b'0';
4126 /// let percent = b'%';
4127 /// let space = b' ';
4129 /// let esc = 0x1b_u8;
4131 /// assert!(uppercase_a.is_ascii_alphanumeric());
4132 /// assert!(uppercase_g.is_ascii_alphanumeric());
4133 /// assert!(a.is_ascii_alphanumeric());
4134 /// assert!(g.is_ascii_alphanumeric());
4135 /// assert!(zero.is_ascii_alphanumeric());
4136 /// assert!(!percent.is_ascii_alphanumeric());
4137 /// assert!(!space.is_ascii_alphanumeric());
4138 /// assert!(!lf.is_ascii_alphanumeric());
4139 /// assert!(!esc.is_ascii_alphanumeric());
4141 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4143 pub fn is_ascii_alphanumeric(&self) -> bool {
4144 if *self >= 0x80 { return false }
4145 match ASCII_CHARACTER_CLASS[*self as usize] {
4146 D | L | Lx | U | Ux => true,
4151 /// Checks if the value is an ASCII decimal digit:
4152 /// U+0030 '0' ... U+0039 '9'.
4157 /// let uppercase_a = b'A';
4158 /// let uppercase_g = b'G';
4161 /// let zero = b'0';
4162 /// let percent = b'%';
4163 /// let space = b' ';
4165 /// let esc = 0x1b_u8;
4167 /// assert!(!uppercase_a.is_ascii_digit());
4168 /// assert!(!uppercase_g.is_ascii_digit());
4169 /// assert!(!a.is_ascii_digit());
4170 /// assert!(!g.is_ascii_digit());
4171 /// assert!(zero.is_ascii_digit());
4172 /// assert!(!percent.is_ascii_digit());
4173 /// assert!(!space.is_ascii_digit());
4174 /// assert!(!lf.is_ascii_digit());
4175 /// assert!(!esc.is_ascii_digit());
4177 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4179 pub fn is_ascii_digit(&self) -> bool {
4180 if *self >= 0x80 { return false }
4181 match ASCII_CHARACTER_CLASS[*self as usize] {
4187 /// Checks if the value is an ASCII hexadecimal digit:
4189 /// - U+0030 '0' ... U+0039 '9', or
4190 /// - U+0041 'A' ... U+0046 'F', or
4191 /// - U+0061 'a' ... U+0066 'f'.
4196 /// let uppercase_a = b'A';
4197 /// let uppercase_g = b'G';
4200 /// let zero = b'0';
4201 /// let percent = b'%';
4202 /// let space = b' ';
4204 /// let esc = 0x1b_u8;
4206 /// assert!(uppercase_a.is_ascii_hexdigit());
4207 /// assert!(!uppercase_g.is_ascii_hexdigit());
4208 /// assert!(a.is_ascii_hexdigit());
4209 /// assert!(!g.is_ascii_hexdigit());
4210 /// assert!(zero.is_ascii_hexdigit());
4211 /// assert!(!percent.is_ascii_hexdigit());
4212 /// assert!(!space.is_ascii_hexdigit());
4213 /// assert!(!lf.is_ascii_hexdigit());
4214 /// assert!(!esc.is_ascii_hexdigit());
4216 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4218 pub fn is_ascii_hexdigit(&self) -> bool {
4219 if *self >= 0x80 { return false }
4220 match ASCII_CHARACTER_CLASS[*self as usize] {
4221 D | Lx | Ux => true,
4226 /// Checks if the value is an ASCII punctuation character:
4228 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
4229 /// - U+003A ... U+0040 `: ; < = > ? @`, or
4230 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
4231 /// - U+007B ... U+007E `{ | } ~`
4236 /// let uppercase_a = b'A';
4237 /// let uppercase_g = b'G';
4240 /// let zero = b'0';
4241 /// let percent = b'%';
4242 /// let space = b' ';
4244 /// let esc = 0x1b_u8;
4246 /// assert!(!uppercase_a.is_ascii_punctuation());
4247 /// assert!(!uppercase_g.is_ascii_punctuation());
4248 /// assert!(!a.is_ascii_punctuation());
4249 /// assert!(!g.is_ascii_punctuation());
4250 /// assert!(!zero.is_ascii_punctuation());
4251 /// assert!(percent.is_ascii_punctuation());
4252 /// assert!(!space.is_ascii_punctuation());
4253 /// assert!(!lf.is_ascii_punctuation());
4254 /// assert!(!esc.is_ascii_punctuation());
4256 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4258 pub fn is_ascii_punctuation(&self) -> bool {
4259 if *self >= 0x80 { return false }
4260 match ASCII_CHARACTER_CLASS[*self as usize] {
4266 /// Checks if the value is an ASCII graphic character:
4267 /// U+0021 '!' ... U+007E '~'.
4272 /// let uppercase_a = b'A';
4273 /// let uppercase_g = b'G';
4276 /// let zero = b'0';
4277 /// let percent = b'%';
4278 /// let space = b' ';
4280 /// let esc = 0x1b_u8;
4282 /// assert!(uppercase_a.is_ascii_graphic());
4283 /// assert!(uppercase_g.is_ascii_graphic());
4284 /// assert!(a.is_ascii_graphic());
4285 /// assert!(g.is_ascii_graphic());
4286 /// assert!(zero.is_ascii_graphic());
4287 /// assert!(percent.is_ascii_graphic());
4288 /// assert!(!space.is_ascii_graphic());
4289 /// assert!(!lf.is_ascii_graphic());
4290 /// assert!(!esc.is_ascii_graphic());
4292 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4294 pub fn is_ascii_graphic(&self) -> bool {
4295 if *self >= 0x80 { return false; }
4296 match ASCII_CHARACTER_CLASS[*self as usize] {
4297 Ux | U | Lx | L | D | P => true,
4302 /// Checks if the value is an ASCII whitespace character:
4303 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4304 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4306 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4307 /// whitespace][infra-aw]. There are several other definitions in
4308 /// wide use. For instance, [the POSIX locale][pct] includes
4309 /// U+000B VERTICAL TAB as well as all the above characters,
4310 /// but—from the very same specification—[the default rule for
4311 /// "field splitting" in the Bourne shell][bfs] considers *only*
4312 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4314 /// If you are writing a program that will process an existing
4315 /// file format, check what that format's definition of whitespace is
4316 /// before using this function.
4318 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4319 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4320 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4325 /// let uppercase_a = b'A';
4326 /// let uppercase_g = b'G';
4329 /// let zero = b'0';
4330 /// let percent = b'%';
4331 /// let space = b' ';
4333 /// let esc = 0x1b_u8;
4335 /// assert!(!uppercase_a.is_ascii_whitespace());
4336 /// assert!(!uppercase_g.is_ascii_whitespace());
4337 /// assert!(!a.is_ascii_whitespace());
4338 /// assert!(!g.is_ascii_whitespace());
4339 /// assert!(!zero.is_ascii_whitespace());
4340 /// assert!(!percent.is_ascii_whitespace());
4341 /// assert!(space.is_ascii_whitespace());
4342 /// assert!(lf.is_ascii_whitespace());
4343 /// assert!(!esc.is_ascii_whitespace());
4345 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4347 pub fn is_ascii_whitespace(&self) -> bool {
4348 if *self >= 0x80 { return false; }
4349 match ASCII_CHARACTER_CLASS[*self as usize] {
4355 /// Checks if the value is an ASCII control character:
4356 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4357 /// Note that most ASCII whitespace characters are control
4358 /// characters, but SPACE is not.
4363 /// let uppercase_a = b'A';
4364 /// let uppercase_g = b'G';
4367 /// let zero = b'0';
4368 /// let percent = b'%';
4369 /// let space = b' ';
4371 /// let esc = 0x1b_u8;
4373 /// assert!(!uppercase_a.is_ascii_control());
4374 /// assert!(!uppercase_g.is_ascii_control());
4375 /// assert!(!a.is_ascii_control());
4376 /// assert!(!g.is_ascii_control());
4377 /// assert!(!zero.is_ascii_control());
4378 /// assert!(!percent.is_ascii_control());
4379 /// assert!(!space.is_ascii_control());
4380 /// assert!(lf.is_ascii_control());
4381 /// assert!(esc.is_ascii_control());
4383 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4385 pub fn is_ascii_control(&self) -> bool {
4386 if *self >= 0x80 { return false; }
4387 match ASCII_CHARACTER_CLASS[*self as usize] {
4396 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4397 "[0x34, 0x12]", "[0x12, 0x34]" }
4402 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4403 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]" }
4408 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4409 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4410 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4411 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
4416 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4417 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4418 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4419 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4420 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4421 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4422 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]" }
4425 #[cfg(target_pointer_width = "16")]
4428 uint_impl! { usize, u16, 16, 65536, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4429 "[0x34, 0x12]", "[0x12, 0x34]" }
4431 #[cfg(target_pointer_width = "32")]
4434 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4435 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]" }
4438 #[cfg(target_pointer_width = "64")]
4441 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4442 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4443 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4444 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
4447 /// A classification of floating point numbers.
4449 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4450 /// their documentation for more.
4452 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4453 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4458 /// use std::num::FpCategory;
4461 /// let num = 12.4_f32;
4462 /// let inf = f32::INFINITY;
4463 /// let zero = 0f32;
4464 /// let sub: f32 = 1.1754942e-38;
4465 /// let nan = f32::NAN;
4467 /// assert_eq!(num.classify(), FpCategory::Normal);
4468 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4469 /// assert_eq!(zero.classify(), FpCategory::Zero);
4470 /// assert_eq!(nan.classify(), FpCategory::Nan);
4471 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4473 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4474 #[stable(feature = "rust1", since = "1.0.0")]
4475 pub enum FpCategory {
4476 /// "Not a Number", often obtained by dividing by zero.
4477 #[stable(feature = "rust1", since = "1.0.0")]
4480 /// Positive or negative infinity.
4481 #[stable(feature = "rust1", since = "1.0.0")]
4484 /// Positive or negative zero.
4485 #[stable(feature = "rust1", since = "1.0.0")]
4488 /// De-normalized floating point representation (less precise than `Normal`).
4489 #[stable(feature = "rust1", since = "1.0.0")]
4492 /// A regular floating point number.
4493 #[stable(feature = "rust1", since = "1.0.0")]
4497 macro_rules! from_str_radix_int_impl {
4499 #[stable(feature = "rust1", since = "1.0.0")]
4500 impl FromStr for $t {
4501 type Err = ParseIntError;
4502 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4503 from_str_radix(src, 10)
4508 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4510 /// The error type returned when a checked integral type conversion fails.
4511 #[unstable(feature = "try_from", issue = "33417")]
4512 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4513 pub struct TryFromIntError(());
4515 impl TryFromIntError {
4516 #[unstable(feature = "int_error_internals",
4517 reason = "available through Error trait and this method should \
4518 not be exposed publicly",
4521 pub fn __description(&self) -> &str {
4522 "out of range integral type conversion attempted"
4526 #[unstable(feature = "try_from", issue = "33417")]
4527 impl fmt::Display for TryFromIntError {
4528 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4529 self.__description().fmt(fmt)
4533 #[unstable(feature = "try_from", issue = "33417")]
4534 impl From<!> for TryFromIntError {
4535 fn from(never: !) -> TryFromIntError {
4540 // no possible bounds violation
4541 macro_rules! try_from_unbounded {
4542 ($source:ty, $($target:ty),*) => {$(
4543 #[unstable(feature = "try_from", issue = "33417")]
4544 impl TryFrom<$source> for $target {
4545 type Error = TryFromIntError;
4548 fn try_from(value: $source) -> Result<Self, Self::Error> {
4549 Ok(value as $target)
4555 // only negative bounds
4556 macro_rules! try_from_lower_bounded {
4557 ($source:ty, $($target:ty),*) => {$(
4558 #[unstable(feature = "try_from", issue = "33417")]
4559 impl TryFrom<$source> for $target {
4560 type Error = TryFromIntError;
4563 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4567 Err(TryFromIntError(()))
4574 // unsigned to signed (only positive bound)
4575 macro_rules! try_from_upper_bounded {
4576 ($source:ty, $($target:ty),*) => {$(
4577 #[unstable(feature = "try_from", issue = "33417")]
4578 impl TryFrom<$source> for $target {
4579 type Error = TryFromIntError;
4582 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4583 if u > (<$target>::max_value() as $source) {
4584 Err(TryFromIntError(()))
4594 macro_rules! try_from_both_bounded {
4595 ($source:ty, $($target:ty),*) => {$(
4596 #[unstable(feature = "try_from", issue = "33417")]
4597 impl TryFrom<$source> for $target {
4598 type Error = TryFromIntError;
4601 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4602 let min = <$target>::min_value() as $source;
4603 let max = <$target>::max_value() as $source;
4604 if u < min || u > max {
4605 Err(TryFromIntError(()))
4615 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4616 $mac!($target, $source);
4620 /// intra-sign conversions
4621 try_from_upper_bounded!(u16, u8);
4622 try_from_upper_bounded!(u32, u16, u8);
4623 try_from_upper_bounded!(u64, u32, u16, u8);
4624 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4626 try_from_both_bounded!(i16, i8);
4627 try_from_both_bounded!(i32, i16, i8);
4628 try_from_both_bounded!(i64, i32, i16, i8);
4629 try_from_both_bounded!(i128, i64, i32, i16, i8);
4631 // unsigned-to-signed
4632 try_from_upper_bounded!(u8, i8);
4633 try_from_upper_bounded!(u16, i8, i16);
4634 try_from_upper_bounded!(u32, i8, i16, i32);
4635 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4636 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4638 // signed-to-unsigned
4639 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4640 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4641 try_from_lower_bounded!(i32, u32, u64, u128);
4642 try_from_lower_bounded!(i64, u64, u128);
4643 try_from_lower_bounded!(i128, u128);
4644 try_from_both_bounded!(i16, u8);
4645 try_from_both_bounded!(i32, u16, u8);
4646 try_from_both_bounded!(i64, u32, u16, u8);
4647 try_from_both_bounded!(i128, u64, u32, u16, u8);
4650 try_from_upper_bounded!(usize, isize);
4651 try_from_lower_bounded!(isize, usize);
4653 #[cfg(target_pointer_width = "16")]
4654 mod ptr_try_from_impls {
4655 use super::TryFromIntError;
4656 use convert::TryFrom;
4658 try_from_upper_bounded!(usize, u8);
4659 try_from_unbounded!(usize, u16, u32, u64, u128);
4660 try_from_upper_bounded!(usize, i8, i16);
4661 try_from_unbounded!(usize, i32, i64, i128);
4663 try_from_both_bounded!(isize, u8);
4664 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4665 try_from_both_bounded!(isize, i8);
4666 try_from_unbounded!(isize, i16, i32, i64, i128);
4668 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4669 rev!(try_from_lower_bounded, usize, i8, i16);
4670 rev!(try_from_both_bounded, usize, i32, i64, i128);
4672 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4673 rev!(try_from_both_bounded, isize, i32, i64, i128);
4676 #[cfg(target_pointer_width = "32")]
4677 mod ptr_try_from_impls {
4678 use super::TryFromIntError;
4679 use convert::TryFrom;
4681 try_from_upper_bounded!(usize, u8, u16);
4682 try_from_unbounded!(usize, u32, u64, u128);
4683 try_from_upper_bounded!(usize, i8, i16, i32);
4684 try_from_unbounded!(usize, i64, i128);
4686 try_from_both_bounded!(isize, u8, u16);
4687 try_from_lower_bounded!(isize, u32, u64, u128);
4688 try_from_both_bounded!(isize, i8, i16);
4689 try_from_unbounded!(isize, i32, i64, i128);
4691 rev!(try_from_unbounded, usize, u32);
4692 rev!(try_from_upper_bounded, usize, u64, u128);
4693 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4694 rev!(try_from_both_bounded, usize, i64, i128);
4696 rev!(try_from_unbounded, isize, u16);
4697 rev!(try_from_upper_bounded, isize, u32, u64, u128);
4698 rev!(try_from_unbounded, isize, i32);
4699 rev!(try_from_both_bounded, isize, i64, i128);
4702 #[cfg(target_pointer_width = "64")]
4703 mod ptr_try_from_impls {
4704 use super::TryFromIntError;
4705 use convert::TryFrom;
4707 try_from_upper_bounded!(usize, u8, u16, u32);
4708 try_from_unbounded!(usize, u64, u128);
4709 try_from_upper_bounded!(usize, i8, i16, i32, i64);
4710 try_from_unbounded!(usize, i128);
4712 try_from_both_bounded!(isize, u8, u16, u32);
4713 try_from_lower_bounded!(isize, u64, u128);
4714 try_from_both_bounded!(isize, i8, i16, i32);
4715 try_from_unbounded!(isize, i64, i128);
4717 rev!(try_from_unbounded, usize, u32, u64);
4718 rev!(try_from_upper_bounded, usize, u128);
4719 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4720 rev!(try_from_both_bounded, usize, i128);
4722 rev!(try_from_unbounded, isize, u16, u32);
4723 rev!(try_from_upper_bounded, isize, u64, u128);
4724 rev!(try_from_unbounded, isize, i32, i64);
4725 rev!(try_from_both_bounded, isize, i128);
4729 trait FromStrRadixHelper: PartialOrd + Copy {
4730 fn min_value() -> Self;
4731 fn max_value() -> Self;
4732 fn from_u32(u: u32) -> Self;
4733 fn checked_mul(&self, other: u32) -> Option<Self>;
4734 fn checked_sub(&self, other: u32) -> Option<Self>;
4735 fn checked_add(&self, other: u32) -> Option<Self>;
4739 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4741 fn min_value() -> Self { Self::min_value() }
4743 fn max_value() -> Self { Self::max_value() }
4745 fn from_u32(u: u32) -> Self { u as Self }
4747 fn checked_mul(&self, other: u32) -> Option<Self> {
4748 Self::checked_mul(*self, other as Self)
4751 fn checked_sub(&self, other: u32) -> Option<Self> {
4752 Self::checked_sub(*self, other as Self)
4755 fn checked_add(&self, other: u32) -> Option<Self> {
4756 Self::checked_add(*self, other as Self)
4760 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4762 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4763 use self::IntErrorKind::*;
4764 use self::ParseIntError as PIE;
4766 assert!(radix >= 2 && radix <= 36,
4767 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4771 return Err(PIE { kind: Empty });
4774 let is_signed_ty = T::from_u32(0) > T::min_value();
4776 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4777 // and cast them to chars. .to_digit() will safely return None for anything
4778 // other than a valid ascii digit for the given radix, including the first-byte
4779 // of multi-byte sequences
4780 let src = src.as_bytes();
4782 let (is_positive, digits) = match src[0] {
4783 b'+' => (true, &src[1..]),
4784 b'-' if is_signed_ty => (false, &src[1..]),
4788 if digits.is_empty() {
4789 return Err(PIE { kind: Empty });
4792 let mut result = T::from_u32(0);
4794 // The number is positive
4796 let x = match (c as char).to_digit(radix) {
4798 None => return Err(PIE { kind: InvalidDigit }),
4800 result = match result.checked_mul(radix) {
4801 Some(result) => result,
4802 None => return Err(PIE { kind: Overflow }),
4804 result = match result.checked_add(x) {
4805 Some(result) => result,
4806 None => return Err(PIE { kind: Overflow }),
4810 // The number is negative
4812 let x = match (c as char).to_digit(radix) {
4814 None => return Err(PIE { kind: InvalidDigit }),
4816 result = match result.checked_mul(radix) {
4817 Some(result) => result,
4818 None => return Err(PIE { kind: Underflow }),
4820 result = match result.checked_sub(x) {
4821 Some(result) => result,
4822 None => return Err(PIE { kind: Underflow }),
4829 /// An error which can be returned when parsing an integer.
4831 /// This error is used as the error type for the `from_str_radix()` functions
4832 /// on the primitive integer types, such as [`i8::from_str_radix`].
4834 /// # Potential causes
4836 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
4837 /// in the string e.g., when it is obtained from the standard input.
4838 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
4840 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
4841 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
4842 #[derive(Debug, Clone, PartialEq, Eq)]
4843 #[stable(feature = "rust1", since = "1.0.0")]
4844 pub struct ParseIntError {
4848 /// Enum to store the various types of errors that can cause parsing an integer to fail.
4849 #[unstable(feature = "int_error_matching",
4850 reason = "it can be useful to match errors when making error messages \
4851 for integer parsing",
4853 #[derive(Debug, Clone, PartialEq, Eq)]
4855 pub enum IntErrorKind {
4856 /// Value being parsed is empty.
4858 /// Among other causes, this variant will be constructed when parsing an empty string.
4860 /// Contains an invalid digit.
4862 /// Among other causes, this variant will be constructed when parsing a string that
4863 /// contains a letter.
4865 /// Integer is too large to store in target integer type.
4867 /// Integer is too small to store in target integer type.
4871 impl ParseIntError {
4872 /// Outputs the detailed cause of parsing an integer failing.
4873 #[unstable(feature = "int_error_matching",
4874 reason = "it can be useful to match errors when making error messages \
4875 for integer parsing",
4877 pub fn kind(&self) -> &IntErrorKind {
4880 #[unstable(feature = "int_error_internals",
4881 reason = "available through Error trait and this method should \
4882 not be exposed publicly",
4885 pub fn __description(&self) -> &str {
4887 IntErrorKind::Empty => "cannot parse integer from empty string",
4888 IntErrorKind::InvalidDigit => "invalid digit found in string",
4889 IntErrorKind::Overflow => "number too large to fit in target type",
4890 IntErrorKind::Underflow => "number too small to fit in target type",
4895 #[stable(feature = "rust1", since = "1.0.0")]
4896 impl fmt::Display for ParseIntError {
4897 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4898 self.__description().fmt(f)
4902 #[stable(feature = "rust1", since = "1.0.0")]
4903 pub use num::dec2flt::ParseFloatError;
4905 // Conversion traits for primitive integer and float types
4906 // Conversions T -> T are covered by a blanket impl and therefore excluded
4907 // Some conversions from and to usize/isize are not implemented due to portability concerns
4908 macro_rules! impl_from {
4909 ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
4912 impl From<$Small> for $Large {
4914 fn from(small: $Small) -> $Large {
4919 ($Small: ty, $Large: ty, #[$attr:meta]) => {
4923 concat!("Converts `",
4931 macro_rules! impl_from_bool {
4932 ($target: ty, #[$attr:meta]) => {
4933 impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
4934 stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
4940 assert_eq!(", stringify!($target), "::from(true), 1);
4941 assert_eq!(", stringify!($target), "::from(false), 0);
4947 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
4948 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
4949 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
4950 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
4951 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
4952 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
4953 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
4954 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
4955 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
4956 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
4957 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
4958 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
4960 // Unsigned -> Unsigned
4961 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4962 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4963 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4964 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
4965 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4966 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4967 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4968 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
4969 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4970 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
4971 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
4974 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4975 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4976 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4977 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4978 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4979 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4980 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4981 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4982 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4983 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4984 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4986 // Unsigned -> Signed
4987 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4988 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4989 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4990 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4991 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4992 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4993 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4994 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4995 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4996 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4998 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
4999 // which imply that pointer-sized integers must be at least 16 bits:
5000 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
5001 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5002 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5003 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5005 // RISC-V defines the possibility of a 128-bit address space (RV128).
5007 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
5008 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
5009 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
5012 // Note: integers can only be represented with full precision in a float if
5013 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
5014 // Lossy float conversions are not implemented at this time.
5017 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5018 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5019 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5020 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5021 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5023 // Unsigned -> Float
5024 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5025 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5026 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5027 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5028 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5031 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5033 static ASCII_LOWERCASE_MAP: [u8; 256] = [
5034 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
5035 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
5036 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
5037 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
5038 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
5039 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
5040 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
5041 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
5044 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
5045 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
5046 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
5049 b'[', b'\\', b']', b'^', b'_',
5050 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
5051 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
5052 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
5053 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
5054 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
5055 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
5056 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
5057 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
5058 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
5059 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
5060 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
5061 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
5062 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
5063 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
5064 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
5065 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
5066 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
5067 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
5068 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
5069 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
5072 static ASCII_UPPERCASE_MAP: [u8; 256] = [
5073 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
5074 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
5075 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
5076 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
5077 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
5078 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
5079 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
5080 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
5081 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
5082 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
5083 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
5084 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
5087 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
5088 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
5089 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
5092 b'{', b'|', b'}', b'~', 0x7f,
5093 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
5094 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
5095 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
5096 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
5097 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
5098 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
5099 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
5100 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
5101 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
5102 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
5103 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
5104 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
5105 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
5106 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
5107 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
5108 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
5111 enum AsciiCharacterClass {
5113 Cw, // control whitespace
5117 Lx, // lowercase hex digit
5119 Ux, // uppercase hex digit
5122 use self::AsciiCharacterClass::*;
5124 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
5125 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
5126 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
5127 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
5128 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
5129 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
5130 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
5131 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
5132 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
5133 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_