1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Numeric traits and functions for the built-in numeric types.
13 #![stable(feature = "rust1", since = "1.0.0")]
23 macro_rules! impl_nonzero_fmt {
24 ( ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
26 #[stable(feature = "nonzero", since = "1.28.0")]
27 impl fmt::$Trait for $Ty {
29 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37 macro_rules! doc_comment {
38 ($x:expr, $($tt:tt)*) => {
44 macro_rules! nonzero_integers {
45 ( $( $Ty: ident($Int: ty); )+ ) => {
48 concat!("An integer that is known not to equal zero.
50 This enables some memory layout optimization.
51 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
54 use std::mem::size_of;
55 assert_eq!(size_of::<Option<std::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
58 #[stable(feature = "nonzero", since = "1.28.0")]
59 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
61 pub struct $Ty(NonZero<$Int>);
65 /// Create a non-zero without checking the value.
69 /// The value must not be zero.
70 #[stable(feature = "nonzero", since = "1.28.0")]
72 pub const unsafe fn new_unchecked(n: $Int) -> Self {
76 /// Create a non-zero if the given value is not zero.
77 #[stable(feature = "nonzero", since = "1.28.0")]
79 pub fn new(n: $Int) -> Option<Self> {
87 /// Returns the value as a primitive type.
88 #[stable(feature = "nonzero", since = "1.28.0")]
90 pub fn get(self) -> $Int {
96 #[stable(feature = "from_nonzero", since = "1.31.0")]
97 impl From<$Ty> for $Int {
98 fn from(nonzero: $Ty) -> Self {
104 (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
119 /// Provides intentionally-wrapped arithmetic on `T`.
121 /// Operations like `+` on `u32` values is intended to never overflow,
122 /// and in some debug configurations overflow is detected and results
123 /// in a panic. While most arithmetic falls into this category, some
124 /// code explicitly expects and relies upon modular arithmetic (e.g.,
127 /// Wrapping arithmetic can be achieved either through methods like
128 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
129 /// all standard arithmetic operations on the underlying value are
130 /// intended to have wrapping semantics.
132 /// The underlying value can be retrieved through the `.0` index of the
133 /// `Wrapping` tuple.
138 /// use std::num::Wrapping;
140 /// let zero = Wrapping(0u32);
141 /// let one = Wrapping(1u32);
143 /// assert_eq!(std::u32::MAX, (zero - one).0);
145 #[stable(feature = "rust1", since = "1.0.0")]
146 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
148 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
151 #[stable(feature = "rust1", since = "1.0.0")]
152 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158 #[stable(feature = "wrapping_display", since = "1.10.0")]
159 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
160 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
165 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
166 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
172 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
173 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
174 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
179 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
180 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
181 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
186 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
187 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
188 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
193 // All these modules are technically private and only exposed for coretests:
201 // `Int` + `SignedInt` implemented for signed integers
202 macro_rules! int_impl {
203 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
204 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
205 $reversed:expr, $le_bytes:expr, $be_bytes:expr) => {
207 concat!("Returns the smallest value that can be represented by this integer type.
214 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
217 #[stable(feature = "rust1", since = "1.0.0")]
220 pub const fn min_value() -> Self {
221 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
226 concat!("Returns the largest value that can be represented by this integer type.
233 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
236 #[stable(feature = "rust1", since = "1.0.0")]
239 pub const fn max_value() -> Self {
245 concat!("Converts a string slice in a given base to an integer.
247 The string is expected to be an optional `+` or `-` sign followed by digits.
248 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
249 depending on `radix`:
257 This function panics if `radix` is not in the range from 2 to 36.
264 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
269 from_str_radix(src, radix)
274 concat!("Returns the number of ones in the binary representation of `self`.
281 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
283 assert_eq!(n.count_ones(), 1);",
287 #[stable(feature = "rust1", since = "1.0.0")]
288 #[rustc_const_unstable(feature = "const_int_ops")]
290 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
294 concat!("Returns the number of zeros in the binary representation of `self`.
301 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
303 #[stable(feature = "rust1", since = "1.0.0")]
304 #[rustc_const_unstable(feature = "const_int_ops")]
306 pub const fn count_zeros(self) -> u32 {
312 concat!("Returns the number of leading zeros in the binary representation of `self`.
319 ", $Feature, "let n = -1", stringify!($SelfT), ";
321 assert_eq!(n.leading_zeros(), 0);",
324 #[stable(feature = "rust1", since = "1.0.0")]
325 #[rustc_const_unstable(feature = "const_int_ops")]
327 pub const fn leading_zeros(self) -> u32 {
328 (self as $UnsignedT).leading_zeros()
333 concat!("Returns the number of trailing zeros in the binary representation of `self`.
340 ", $Feature, "let n = -4", stringify!($SelfT), ";
342 assert_eq!(n.trailing_zeros(), 2);",
345 #[stable(feature = "rust1", since = "1.0.0")]
346 #[rustc_const_unstable(feature = "const_int_ops")]
348 pub const fn trailing_zeros(self) -> u32 {
349 (self as $UnsignedT).trailing_zeros()
354 concat!("Shifts the bits to the left by a specified amount, `n`,
355 wrapping the truncated bits to the end of the resulting integer.
357 Please note this isn't the same operation as `<<`!
364 let n = ", $rot_op, stringify!($SelfT), ";
365 let m = ", $rot_result, ";
367 assert_eq!(n.rotate_left(", $rot, "), m);
369 #[stable(feature = "rust1", since = "1.0.0")]
370 #[rustc_const_unstable(feature = "const_int_rotate")]
372 pub const fn rotate_left(self, n: u32) -> Self {
373 (self as $UnsignedT).rotate_left(n) as Self
378 concat!("Shifts the bits to the right by a specified amount, `n`,
379 wrapping the truncated bits to the beginning of the resulting
382 Please note this isn't the same operation as `>>`!
389 let n = ", $rot_result, stringify!($SelfT), ";
390 let m = ", $rot_op, ";
392 assert_eq!(n.rotate_right(", $rot, "), m);
394 #[stable(feature = "rust1", since = "1.0.0")]
395 #[rustc_const_unstable(feature = "const_int_rotate")]
397 pub const fn rotate_right(self, n: u32) -> Self {
398 (self as $UnsignedT).rotate_right(n) as Self
403 concat!("Reverses the byte order of the integer.
410 let n = ", $swap_op, stringify!($SelfT), ";
412 let m = n.swap_bytes();
414 assert_eq!(m, ", $swapped, ");
416 #[stable(feature = "rust1", since = "1.0.0")]
417 #[rustc_const_unstable(feature = "const_int_ops")]
419 pub const fn swap_bytes(self) -> Self {
420 (self as $UnsignedT).swap_bytes() as Self
425 concat!("Reverses the bit pattern of the integer.
432 #![feature(reverse_bits)]
434 let n = ", $swap_op, stringify!($SelfT), ";
435 let m = n.reverse_bits();
437 assert_eq!(m, ", $reversed, ");
439 #[unstable(feature = "reverse_bits", issue = "48763")]
440 #[rustc_const_unstable(feature = "const_int_conversion")]
442 pub const fn reverse_bits(self) -> Self {
443 (self as $UnsignedT).reverse_bits() as Self
448 concat!("Converts an integer from big endian to the target's endianness.
450 On big endian this is a no-op. On little endian the bytes are swapped.
457 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
459 if cfg!(target_endian = \"big\") {
460 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
462 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
466 #[stable(feature = "rust1", since = "1.0.0")]
467 #[rustc_const_unstable(feature = "const_int_ops")]
469 pub const fn from_be(x: Self) -> Self {
470 #[cfg(target_endian = "big")]
474 #[cfg(not(target_endian = "big"))]
482 concat!("Converts an integer from little endian to the target's endianness.
484 On little endian this is a no-op. On big endian the bytes are swapped.
491 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
493 if cfg!(target_endian = \"little\") {
494 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
496 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
500 #[stable(feature = "rust1", since = "1.0.0")]
501 #[rustc_const_unstable(feature = "const_int_ops")]
503 pub const fn from_le(x: Self) -> Self {
504 #[cfg(target_endian = "little")]
508 #[cfg(not(target_endian = "little"))]
516 concat!("Converts `self` to big endian from the target's endianness.
518 On big endian this is a no-op. On little endian the bytes are swapped.
525 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
527 if cfg!(target_endian = \"big\") {
528 assert_eq!(n.to_be(), n)
530 assert_eq!(n.to_be(), n.swap_bytes())
534 #[stable(feature = "rust1", since = "1.0.0")]
535 #[rustc_const_unstable(feature = "const_int_ops")]
537 pub const fn to_be(self) -> Self { // or not to be?
538 #[cfg(target_endian = "big")]
542 #[cfg(not(target_endian = "big"))]
550 concat!("Converts `self` to little endian from the target's endianness.
552 On little endian this is a no-op. On big endian the bytes are swapped.
559 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
561 if cfg!(target_endian = \"little\") {
562 assert_eq!(n.to_le(), n)
564 assert_eq!(n.to_le(), n.swap_bytes())
568 #[stable(feature = "rust1", since = "1.0.0")]
569 #[rustc_const_unstable(feature = "const_int_ops")]
571 pub const fn to_le(self) -> Self {
572 #[cfg(target_endian = "little")]
576 #[cfg(not(target_endian = "little"))]
584 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
585 if overflow occurred.
592 ", $Feature, "assert_eq!((", stringify!($SelfT),
593 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
594 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
597 #[stable(feature = "rust1", since = "1.0.0")]
599 pub fn checked_add(self, rhs: Self) -> Option<Self> {
600 let (a, b) = self.overflowing_add(rhs);
601 if b {None} else {Some(a)}
606 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
614 ", $Feature, "assert_eq!((", stringify!($SelfT),
615 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
616 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
619 #[stable(feature = "rust1", since = "1.0.0")]
621 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
622 let (a, b) = self.overflowing_sub(rhs);
623 if b {None} else {Some(a)}
628 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
636 ", $Feature, "assert_eq!(", stringify!($SelfT),
637 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
638 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
641 #[stable(feature = "rust1", since = "1.0.0")]
643 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
644 let (a, b) = self.overflowing_mul(rhs);
645 if b {None} else {Some(a)}
650 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
651 or the division results in overflow.
658 ", $Feature, "assert_eq!((", stringify!($SelfT),
659 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
660 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
661 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
664 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn checked_div(self, rhs: Self) -> Option<Self> {
667 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
670 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
676 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`,
677 returning `None` if `rhs == 0` or the division results in overflow.
684 #![feature(euclidean_division)]
685 assert_eq!((", stringify!($SelfT),
686 "::min_value() + 1).checked_div_euc(-1), Some(", stringify!($Max), "));
687 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euc(-1), None);
688 assert_eq!((1", stringify!($SelfT), ").checked_div_euc(0), None);
690 #[unstable(feature = "euclidean_division", issue = "49048")]
692 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
693 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
696 Some(self.div_euc(rhs))
702 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
703 `rhs == 0` or the division results in overflow.
710 ", $Feature, "use std::", stringify!($SelfT), ";
712 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
713 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
714 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
717 #[stable(feature = "wrapping", since = "1.7.0")]
719 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
720 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
723 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
729 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None` if
730 `rhs == 0` or the division results in overflow.
737 #![feature(euclidean_division)]
738 use std::", stringify!($SelfT), ";
740 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
741 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
742 assert_eq!(", stringify!($SelfT), "::MIN.checked_mod_euc(-1), None);
744 #[unstable(feature = "euclidean_division", issue = "49048")]
746 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
747 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
750 Some(self.mod_euc(rhs))
756 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
763 ", $Feature, "use std::", stringify!($SelfT), ";
765 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
766 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
769 #[stable(feature = "wrapping", since = "1.7.0")]
771 pub fn checked_neg(self) -> Option<Self> {
772 let (a, b) = self.overflowing_neg();
773 if b {None} else {Some(a)}
778 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
779 than or equal to the number of bits in `self`.
786 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
787 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
790 #[stable(feature = "wrapping", since = "1.7.0")]
792 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
793 let (a, b) = self.overflowing_shl(rhs);
794 if b {None} else {Some(a)}
799 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
800 larger than or equal to the number of bits in `self`.
807 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
808 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
811 #[stable(feature = "wrapping", since = "1.7.0")]
813 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
814 let (a, b) = self.overflowing_shr(rhs);
815 if b {None} else {Some(a)}
820 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
828 ", $Feature, "use std::", stringify!($SelfT), ";
830 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
831 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
834 #[stable(feature = "no_panic_abs", since = "1.13.0")]
836 pub fn checked_abs(self) -> Option<Self> {
837 if self.is_negative() {
846 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
854 #![feature(no_panic_pow)]
855 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
856 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
860 #[unstable(feature = "no_panic_pow", issue = "48320")]
862 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
864 let mut acc: Self = 1;
868 acc = acc.checked_mul(base)?;
871 base = base.checked_mul(base)?;
874 // Deal with the final bit of the exponent separately, since
875 // squaring the base afterwards is not necessary and may cause a
876 // needless overflow.
878 acc = acc.checked_mul(base)?;
886 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
887 bounds instead of overflowing.
894 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
895 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
899 #[stable(feature = "rust1", since = "1.0.0")]
901 pub fn saturating_add(self, rhs: Self) -> Self {
902 match self.checked_add(rhs) {
904 None if rhs >= 0 => Self::max_value(),
905 None => Self::min_value(),
911 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
912 numeric bounds instead of overflowing.
919 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
920 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
924 #[stable(feature = "rust1", since = "1.0.0")]
926 pub fn saturating_sub(self, rhs: Self) -> Self {
927 match self.checked_sub(rhs) {
929 None if rhs >= 0 => Self::min_value(),
930 None => Self::max_value(),
936 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
937 numeric bounds instead of overflowing.
944 ", $Feature, "use std::", stringify!($SelfT), ";
946 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
947 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
948 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
951 #[stable(feature = "wrapping", since = "1.7.0")]
953 pub fn saturating_mul(self, rhs: Self) -> Self {
954 self.checked_mul(rhs).unwrap_or_else(|| {
955 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
965 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
966 saturating at the numeric bounds instead of overflowing.
973 #![feature(no_panic_pow)]
974 ", $Feature, "use std::", stringify!($SelfT), ";
976 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
977 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
978 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
981 #[unstable(feature = "no_panic_pow", issue = "48320")]
983 pub fn saturating_pow(self, exp: u32) -> Self {
984 match self.checked_pow(exp) {
986 None if self < 0 && exp % 2 == 1 => Self::min_value(),
987 None => Self::max_value(),
993 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
994 boundary of the type.
1001 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1002 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
1003 "::min_value() + 1);",
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 #[rustc_const_unstable(feature = "const_int_wrapping")]
1009 pub const fn wrapping_add(self, rhs: Self) -> Self {
1011 intrinsics::overflowing_add(self, rhs)
1017 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1018 boundary of the type.
1025 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1026 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1027 stringify!($SelfT), "::max_value());",
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 #[rustc_const_unstable(feature = "const_int_wrapping")]
1033 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1035 intrinsics::overflowing_sub(self, rhs)
1041 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1042 the boundary of the type.
1049 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1050 assert_eq!(11i8.wrapping_mul(12), -124);",
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 #[rustc_const_unstable(feature = "const_int_wrapping")]
1056 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1058 intrinsics::overflowing_mul(self, rhs)
1064 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1065 boundary of the type.
1067 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1068 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1069 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1073 This function will panic if `rhs` is 0.
1080 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1081 assert_eq!((-128i8).wrapping_div(-1), -128);",
1084 #[stable(feature = "num_wrapping", since = "1.2.0")]
1086 pub fn wrapping_div(self, rhs: Self) -> Self {
1087 self.overflowing_div(rhs).0
1092 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`,
1093 wrapping around at the boundary of the type.
1095 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1096 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1097 type. In this case, this method returns `MIN` itself.
1101 This function will panic if `rhs` is 0.
1108 #![feature(euclidean_division)]
1109 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
1110 assert_eq!((-128i8).wrapping_div_euc(-1), -128);
1112 #[unstable(feature = "euclidean_division", issue = "49048")]
1114 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
1115 self.overflowing_div_euc(rhs).0
1120 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1121 boundary of the type.
1123 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1124 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1125 this function returns `0`.
1129 This function will panic if `rhs` is 0.
1136 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1137 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1140 #[stable(feature = "num_wrapping", since = "1.2.0")]
1142 pub fn wrapping_rem(self, rhs: Self) -> Self {
1143 self.overflowing_rem(rhs).0
1148 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`, wrapping around at the
1149 boundary of the type.
1151 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1152 for the type). In this case, this method returns 0.
1156 This function will panic if `rhs` is 0.
1163 #![feature(euclidean_division)]
1164 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
1165 assert_eq!((-128i8).wrapping_mod_euc(-1), 0);
1167 #[unstable(feature = "euclidean_division", issue = "49048")]
1169 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
1170 self.overflowing_mod_euc(rhs).0
1175 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1178 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1179 is the negative minimal value for the type); this is a positive value that is too large to represent
1180 in the type. In such a case, this function returns `MIN` itself.
1187 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1188 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1192 #[stable(feature = "num_wrapping", since = "1.2.0")]
1194 pub fn wrapping_neg(self) -> Self {
1195 self.overflowing_neg().0
1200 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1201 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1203 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1204 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1205 The primitive integer types all implement a `rotate_left` function, which may be what you want
1213 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1214 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1217 #[stable(feature = "num_wrapping", since = "1.2.0")]
1218 #[rustc_const_unstable(feature = "const_int_wrapping")]
1220 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1222 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1228 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1229 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1231 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1232 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1233 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1241 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1242 assert_eq!((-128i16).wrapping_shr(64), -128);",
1245 #[stable(feature = "num_wrapping", since = "1.2.0")]
1246 #[rustc_const_unstable(feature = "const_int_wrapping")]
1248 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1250 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1256 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1257 the boundary of the type.
1259 The only case where such wrapping can occur is when one takes the absolute value of the negative
1260 minimal value for the type this is a positive value that is too large to represent in the type. In
1261 such a case, this function returns `MIN` itself.
1268 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1269 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1270 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1272 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1275 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1277 pub fn wrapping_abs(self) -> Self {
1278 if self.is_negative() {
1287 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1288 wrapping around at the boundary of the type.
1295 #![feature(no_panic_pow)]
1296 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1297 assert_eq!(3i8.wrapping_pow(5), -13);
1298 assert_eq!(3i8.wrapping_pow(6), -39);",
1301 #[unstable(feature = "no_panic_pow", issue = "48320")]
1303 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1304 let mut base = self;
1305 let mut acc: Self = 1;
1309 acc = acc.wrapping_mul(base);
1312 base = base.wrapping_mul(base);
1315 // Deal with the final bit of the exponent separately, since
1316 // squaring the base afterwards is not necessary and may cause a
1317 // needless overflow.
1319 acc = acc.wrapping_mul(base);
1327 concat!("Calculates `self` + `rhs`
1329 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1330 occur. If an overflow would have occurred then the wrapped value is returned.
1337 ", $Feature, "use std::", stringify!($SelfT), ";
1339 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1340 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1341 "::MIN, true));", $EndFeature, "
1343 #[stable(feature = "wrapping", since = "1.7.0")]
1344 #[rustc_const_unstable(feature = "const_int_overflowing")]
1346 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1347 let (a, b) = unsafe {
1348 intrinsics::add_with_overflow(self as $ActualT,
1356 concat!("Calculates `self` - `rhs`
1358 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1359 would occur. If an overflow would have occurred then the wrapped value is returned.
1366 ", $Feature, "use std::", stringify!($SelfT), ";
1368 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1369 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1370 "::MAX, true));", $EndFeature, "
1372 #[stable(feature = "wrapping", since = "1.7.0")]
1373 #[rustc_const_unstable(feature = "const_int_overflowing")]
1375 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1376 let (a, b) = unsafe {
1377 intrinsics::sub_with_overflow(self as $ActualT,
1385 concat!("Calculates the multiplication of `self` and `rhs`.
1387 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1388 would occur. If an overflow would have occurred then the wrapped value is returned.
1395 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1396 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1399 #[stable(feature = "wrapping", since = "1.7.0")]
1400 #[rustc_const_unstable(feature = "const_int_overflowing")]
1402 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1403 let (a, b) = unsafe {
1404 intrinsics::mul_with_overflow(self as $ActualT,
1412 concat!("Calculates the divisor when `self` is divided by `rhs`.
1414 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1415 occur. If an overflow would occur then self is returned.
1419 This function will panic if `rhs` is 0.
1426 ", $Feature, "use std::", stringify!($SelfT), ";
1428 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1429 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1434 #[stable(feature = "wrapping", since = "1.7.0")]
1435 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1436 if self == Self::min_value() && rhs == -1 {
1445 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
1447 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1448 occur. If an overflow would occur then `self` is returned.
1452 This function will panic if `rhs` is 0.
1459 #![feature(euclidean_division)]
1460 use std::", stringify!($SelfT), ";
1462 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
1463 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euc(-1), (", stringify!($SelfT),
1467 #[unstable(feature = "euclidean_division", issue = "49048")]
1468 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
1469 if self == Self::min_value() && rhs == -1 {
1472 (self.div_euc(rhs), false)
1478 concat!("Calculates the remainder when `self` is divided by `rhs`.
1480 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1481 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1485 This function will panic if `rhs` is 0.
1492 ", $Feature, "use std::", stringify!($SelfT), ";
1494 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1495 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1499 #[stable(feature = "wrapping", since = "1.7.0")]
1500 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1501 if self == Self::min_value() && rhs == -1 {
1511 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
1513 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1514 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1518 This function will panic if `rhs` is 0.
1525 #![feature(euclidean_division)]
1526 use std::", stringify!($SelfT), ";
1528 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
1529 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_mod_euc(-1), (0, true));
1531 #[unstable(feature = "euclidean_division", issue = "49048")]
1533 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
1534 if self == Self::min_value() && rhs == -1 {
1537 (self.mod_euc(rhs), false)
1544 concat!("Negates self, overflowing if this is equal to the minimum value.
1546 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1547 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1548 minimum value will be returned again and `true` will be returned for an overflow happening.
1555 ", $Feature, "use std::", stringify!($SelfT), ";
1557 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1558 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1559 "::MIN, true));", $EndFeature, "
1562 #[stable(feature = "wrapping", since = "1.7.0")]
1563 pub fn overflowing_neg(self) -> (Self, bool) {
1564 if self == Self::min_value() {
1565 (Self::min_value(), true)
1573 concat!("Shifts self left by `rhs` bits.
1575 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1576 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1577 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1584 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1585 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1588 #[stable(feature = "wrapping", since = "1.7.0")]
1589 #[rustc_const_unstable(feature = "const_int_overflowing")]
1591 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1592 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1597 concat!("Shifts self right by `rhs` bits.
1599 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1600 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1601 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1608 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1609 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1612 #[stable(feature = "wrapping", since = "1.7.0")]
1613 #[rustc_const_unstable(feature = "const_int_overflowing")]
1615 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1616 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1621 concat!("Computes the absolute value of `self`.
1623 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1624 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1625 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1626 for an overflow happening.
1633 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1634 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1635 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1636 "::min_value(), true));",
1639 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1641 pub fn overflowing_abs(self) -> (Self, bool) {
1642 if self.is_negative() {
1643 self.overflowing_neg()
1651 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1653 Returns a tuple of the exponentiation along with a bool indicating
1654 whether an overflow happened.
1661 #![feature(no_panic_pow)]
1662 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1663 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1666 #[unstable(feature = "no_panic_pow", issue = "48320")]
1668 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1669 let mut base = self;
1670 let mut acc: Self = 1;
1671 let mut overflown = false;
1672 // Scratch space for storing results of overflowing_mul.
1677 r = acc.overflowing_mul(base);
1682 r = base.overflowing_mul(base);
1687 // Deal with the final bit of the exponent separately, since
1688 // squaring the base afterwards is not necessary and may cause a
1689 // needless overflow.
1691 r = acc.overflowing_mul(base);
1701 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1708 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1710 assert_eq!(x.pow(5), 32);",
1713 #[stable(feature = "rust1", since = "1.0.0")]
1715 #[rustc_inherit_overflow_checks]
1716 pub fn pow(self, mut exp: u32) -> Self {
1717 let mut base = self;
1728 // Deal with the final bit of the exponent separately, since
1729 // squaring the base afterwards is not necessary and may cause a
1730 // needless overflow.
1740 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1742 This computes the integer `n` such that `self = n * rhs + self.mod_euc(rhs)`.
1743 In other words, the result is `self / rhs` rounded to the integer `n`
1744 such that `self >= n * rhs`.
1748 This function will panic if `rhs` is 0.
1755 #![feature(euclidean_division)]
1756 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1759 assert_eq!(a.div_euc(b), 1); // 7 >= 4 * 1
1760 assert_eq!(a.div_euc(-b), -1); // 7 >= -4 * -1
1761 assert_eq!((-a).div_euc(b), -2); // -7 >= 4 * -2
1762 assert_eq!((-a).div_euc(-b), 2); // -7 >= -4 * 2
1764 #[unstable(feature = "euclidean_division", issue = "49048")]
1766 #[rustc_inherit_overflow_checks]
1767 pub fn div_euc(self, rhs: Self) -> Self {
1770 return if rhs > 0 { q - 1 } else { q + 1 }
1778 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
1780 In particular, the result `n` satisfies `0 <= n < rhs.abs()`.
1784 This function will panic if `rhs` is 0.
1791 #![feature(euclidean_division)]
1792 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1795 assert_eq!(a.mod_euc(b), 3);
1796 assert_eq!((-a).mod_euc(b), 1);
1797 assert_eq!(a.mod_euc(-b), 3);
1798 assert_eq!((-a).mod_euc(-b), 1);
1800 #[unstable(feature = "euclidean_division", issue = "49048")]
1802 #[rustc_inherit_overflow_checks]
1803 pub fn mod_euc(self, rhs: Self) -> Self {
1818 concat!("Computes the absolute value of `self`.
1822 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1823 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1824 code in debug mode will trigger a panic on this case and optimized code will return `",
1825 stringify!($SelfT), "::min_value()` without a panic.
1832 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1833 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1836 #[stable(feature = "rust1", since = "1.0.0")]
1838 #[rustc_inherit_overflow_checks]
1839 pub fn abs(self) -> Self {
1840 if self.is_negative() {
1841 // Note that the #[inline] above means that the overflow
1842 // semantics of this negation depend on the crate we're being
1852 concat!("Returns a number representing sign of `self`.
1854 - `0` if the number is zero
1855 - `1` if the number is positive
1856 - `-1` if the number is negative
1863 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1864 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1865 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1868 #[stable(feature = "rust1", since = "1.0.0")]
1870 pub fn signum(self) -> Self {
1880 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1888 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1889 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1892 #[stable(feature = "rust1", since = "1.0.0")]
1893 #[rustc_const_unstable(feature = "const_int_sign")]
1895 pub const fn is_positive(self) -> bool { self > 0 }
1899 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1907 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1908 assert!(!10", stringify!($SelfT), ".is_negative());",
1911 #[stable(feature = "rust1", since = "1.0.0")]
1912 #[rustc_const_unstable(feature = "const_int_sign")]
1914 pub const fn is_negative(self) -> bool { self < 0 }
1918 concat!("Return the memory representation of this integer as a byte array in
1919 big-endian (network) byte order.
1924 #![feature(int_to_from_bytes)]
1926 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
1927 assert_eq!(bytes, ", $be_bytes, ");
1929 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1930 #[rustc_const_unstable(feature = "const_int_conversion")]
1932 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
1933 self.to_be().to_ne_bytes()
1938 concat!("Return the memory representation of this integer as a byte array in
1939 little-endian byte order.
1944 #![feature(int_to_from_bytes)]
1946 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
1947 assert_eq!(bytes, ", $le_bytes, ");
1949 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1950 #[rustc_const_unstable(feature = "const_int_conversion")]
1952 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
1953 self.to_le().to_ne_bytes()
1959 Return the memory representation of this integer as a byte array in
1962 As the target platform's native endianness is used, portable code
1963 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
1966 [`to_be_bytes`]: #method.to_be_bytes
1967 [`to_le_bytes`]: #method.to_le_bytes
1972 #![feature(int_to_from_bytes)]
1974 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
1975 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
1981 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1982 #[rustc_const_unstable(feature = "const_int_conversion")]
1984 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
1985 unsafe { mem::transmute(self) }
1990 concat!("Create an integer value from its representation as a byte array in
1996 #![feature(int_to_from_bytes)]
1998 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
1999 assert_eq!(value, ", $swap_op, ");
2001 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2002 #[rustc_const_unstable(feature = "const_int_conversion")]
2004 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2005 Self::from_be(Self::from_ne_bytes(bytes))
2011 Create an integer value from its representation as a byte array in
2017 #![feature(int_to_from_bytes)]
2019 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2020 assert_eq!(value, ", $swap_op, ");
2022 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2023 #[rustc_const_unstable(feature = "const_int_conversion")]
2025 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2026 Self::from_le(Self::from_ne_bytes(bytes))
2031 concat!("Create an integer value from its memory representation as a byte
2032 array in native endianness.
2034 As the target platform's native endianness is used, portable code
2035 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2036 appropriate instead.
2038 [`from_be_bytes`]: #method.from_be_bytes
2039 [`from_le_bytes`]: #method.from_le_bytes
2044 #![feature(int_to_from_bytes)]
2046 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2051 assert_eq!(value, ", $swap_op, ");
2053 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2054 #[rustc_const_unstable(feature = "const_int_conversion")]
2056 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2057 unsafe { mem::transmute(bytes) }
2065 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2066 "[0x12]", "[0x12]" }
2071 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2072 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]" }
2077 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2078 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2079 "[0x12, 0x34, 0x56, 0x78]" }
2084 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2085 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2086 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2087 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
2092 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2093 170141183460469231731687303715884105727, "", "", 16,
2094 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2095 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2096 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2097 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2098 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2099 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]" }
2102 #[cfg(target_pointer_width = "16")]
2105 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2106 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]" }
2109 #[cfg(target_pointer_width = "32")]
2112 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2113 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2114 "[0x12, 0x34, 0x56, 0x78]" }
2117 #[cfg(target_pointer_width = "64")]
2120 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2121 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2122 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2123 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
2126 // Emits the correct `cttz` call, depending on the size of the type.
2127 macro_rules! uint_cttz_call {
2128 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
2129 // emits two conditional moves on x86_64. By promoting the value to
2130 // u16 and setting bit 8, we get better code without any conditional
2132 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
2133 // pending, remove this workaround once LLVM generates better code
2135 ($value:expr, 8) => { intrinsics::cttz($value as u16 | 0x100) };
2136 ($value:expr, $_BITS:expr) => { intrinsics::cttz($value) }
2139 // `Int` + `UnsignedInt` implemented for unsigned integers
2140 macro_rules! uint_impl {
2141 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2142 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2143 $reversed:expr, $le_bytes:expr, $be_bytes:expr) => {
2145 concat!("Returns the smallest value that can be represented by this integer type.
2152 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2154 #[stable(feature = "rust1", since = "1.0.0")]
2157 pub const fn min_value() -> Self { 0 }
2161 concat!("Returns the largest value that can be represented by this integer type.
2168 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2169 stringify!($MaxV), ");", $EndFeature, "
2171 #[stable(feature = "rust1", since = "1.0.0")]
2174 pub const fn max_value() -> Self { !0 }
2178 concat!("Converts a string slice in a given base to an integer.
2180 The string is expected to be an optional `+` sign
2182 Leading and trailing whitespace represent an error.
2183 Digits are a subset of these characters, depending on `radix`:
2191 This function panics if `radix` is not in the range from 2 to 36.
2198 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2201 #[stable(feature = "rust1", since = "1.0.0")]
2202 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2203 from_str_radix(src, radix)
2208 concat!("Returns the number of ones in the binary representation of `self`.
2215 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2217 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2219 #[stable(feature = "rust1", since = "1.0.0")]
2220 #[rustc_const_unstable(feature = "const_int_ops")]
2222 pub const fn count_ones(self) -> u32 {
2223 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
2228 concat!("Returns the number of zeros in the binary representation of `self`.
2235 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2237 #[stable(feature = "rust1", since = "1.0.0")]
2238 #[rustc_const_unstable(feature = "const_int_ops")]
2240 pub const fn count_zeros(self) -> u32 {
2241 (!self).count_ones()
2246 concat!("Returns the number of leading zeros in the binary representation of `self`.
2253 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2255 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2257 #[stable(feature = "rust1", since = "1.0.0")]
2258 #[rustc_const_unstable(feature = "const_int_ops")]
2260 pub const fn leading_zeros(self) -> u32 {
2261 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
2266 concat!("Returns the number of trailing zeros in the binary representation
2274 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2276 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2278 #[stable(feature = "rust1", since = "1.0.0")]
2279 #[rustc_const_unstable(feature = "const_int_ops")]
2281 pub const fn trailing_zeros(self) -> u32 {
2282 unsafe { uint_cttz_call!(self, $BITS) as u32 }
2287 concat!("Shifts the bits to the left by a specified amount, `n`,
2288 wrapping the truncated bits to the end of the resulting integer.
2290 Please note this isn't the same operation as `<<`!
2297 let n = ", $rot_op, stringify!($SelfT), ";
2298 let m = ", $rot_result, ";
2300 assert_eq!(n.rotate_left(", $rot, "), m);
2302 #[stable(feature = "rust1", since = "1.0.0")]
2303 #[rustc_const_unstable(feature = "const_int_rotate")]
2305 pub const fn rotate_left(self, n: u32) -> Self {
2306 #[cfg(not(stage0))] {
2307 unsafe { intrinsics::rotate_left(self, n as $SelfT) }
2310 (self << (n % $BITS)) | (self >> (($BITS - (n % $BITS)) % $BITS))
2316 concat!("Shifts the bits to the right by a specified amount, `n`,
2317 wrapping the truncated bits to the beginning of the resulting
2320 Please note this isn't the same operation as `>>`!
2327 let n = ", $rot_result, stringify!($SelfT), ";
2328 let m = ", $rot_op, ";
2330 assert_eq!(n.rotate_right(", $rot, "), m);
2332 #[stable(feature = "rust1", since = "1.0.0")]
2333 #[rustc_const_unstable(feature = "const_int_rotate")]
2335 pub const fn rotate_right(self, n: u32) -> Self {
2336 #[cfg(not(stage0))] {
2337 unsafe { intrinsics::rotate_right(self, n as $SelfT) }
2340 (self >> (n % $BITS)) | (self << (($BITS - (n % $BITS)) % $BITS))
2347 Reverses the byte order of the integer.
2354 let n = ", $swap_op, stringify!($SelfT), ";
2355 let m = n.swap_bytes();
2357 assert_eq!(m, ", $swapped, ");
2359 #[stable(feature = "rust1", since = "1.0.0")]
2360 #[rustc_const_unstable(feature = "const_int_ops")]
2362 pub const fn swap_bytes(self) -> Self {
2363 unsafe { intrinsics::bswap(self as $ActualT) as Self }
2368 concat!("Reverses the bit pattern of the integer.
2375 #![feature(reverse_bits)]
2377 let n = ", $swap_op, stringify!($SelfT), ";
2378 let m = n.reverse_bits();
2380 assert_eq!(m, ", $reversed, ");
2382 #[unstable(feature = "reverse_bits", issue = "48763")]
2383 #[rustc_const_unstable(feature = "const_int_conversion")]
2385 pub const fn reverse_bits(self) -> Self {
2386 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
2391 concat!("Converts an integer from big endian to the target's endianness.
2393 On big endian this is a no-op. On little endian the bytes are
2401 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2403 if cfg!(target_endian = \"big\") {
2404 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2406 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2409 #[stable(feature = "rust1", since = "1.0.0")]
2410 #[rustc_const_unstable(feature = "const_int_ops")]
2412 pub const fn from_be(x: Self) -> Self {
2413 #[cfg(target_endian = "big")]
2417 #[cfg(not(target_endian = "big"))]
2425 concat!("Converts an integer from little endian to the target's endianness.
2427 On little endian this is a no-op. On big endian the bytes are
2435 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2437 if cfg!(target_endian = \"little\") {
2438 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2440 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2443 #[stable(feature = "rust1", since = "1.0.0")]
2444 #[rustc_const_unstable(feature = "const_int_ops")]
2446 pub const fn from_le(x: Self) -> Self {
2447 #[cfg(target_endian = "little")]
2451 #[cfg(not(target_endian = "little"))]
2459 concat!("Converts `self` to big endian from the target's endianness.
2461 On big endian this is a no-op. On little endian the bytes are
2469 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2471 if cfg!(target_endian = \"big\") {
2472 assert_eq!(n.to_be(), n)
2474 assert_eq!(n.to_be(), n.swap_bytes())
2477 #[stable(feature = "rust1", since = "1.0.0")]
2478 #[rustc_const_unstable(feature = "const_int_ops")]
2480 pub const fn to_be(self) -> Self { // or not to be?
2481 #[cfg(target_endian = "big")]
2485 #[cfg(not(target_endian = "big"))]
2493 concat!("Converts `self` to little endian from the target's endianness.
2495 On little endian this is a no-op. On big endian the bytes are
2503 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2505 if cfg!(target_endian = \"little\") {
2506 assert_eq!(n.to_le(), n)
2508 assert_eq!(n.to_le(), n.swap_bytes())
2511 #[stable(feature = "rust1", since = "1.0.0")]
2512 #[rustc_const_unstable(feature = "const_int_ops")]
2514 pub const fn to_le(self) -> Self {
2515 #[cfg(target_endian = "little")]
2519 #[cfg(not(target_endian = "little"))]
2527 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2528 if overflow occurred.
2535 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2536 "Some(", stringify!($SelfT), "::max_value() - 1));
2537 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2539 #[stable(feature = "rust1", since = "1.0.0")]
2541 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2542 let (a, b) = self.overflowing_add(rhs);
2543 if b {None} else {Some(a)}
2548 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2549 `None` if overflow occurred.
2556 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2557 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2559 #[stable(feature = "rust1", since = "1.0.0")]
2561 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2562 let (a, b) = self.overflowing_sub(rhs);
2563 if b {None} else {Some(a)}
2568 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2569 `None` if overflow occurred.
2576 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2577 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2579 #[stable(feature = "rust1", since = "1.0.0")]
2581 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2582 let (a, b) = self.overflowing_mul(rhs);
2583 if b {None} else {Some(a)}
2588 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2596 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2597 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2599 #[stable(feature = "rust1", since = "1.0.0")]
2601 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2604 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2610 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`, returning `None`
2618 #![feature(euclidean_division)]
2619 assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2620 assert_eq!(1", stringify!($SelfT), ".checked_div_euc(0), None);
2622 #[unstable(feature = "euclidean_division", issue = "49048")]
2624 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
2628 Some(self.div_euc(rhs))
2635 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2643 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2644 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2646 #[stable(feature = "wrapping", since = "1.7.0")]
2648 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2652 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2658 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None`
2666 #![feature(euclidean_division)]
2667 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
2668 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
2670 #[unstable(feature = "euclidean_division", issue = "49048")]
2672 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
2676 Some(self.mod_euc(rhs))
2682 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2685 Note that negating any positive integer will overflow.
2692 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2693 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2695 #[stable(feature = "wrapping", since = "1.7.0")]
2697 pub fn checked_neg(self) -> Option<Self> {
2698 let (a, b) = self.overflowing_neg();
2699 if b {None} else {Some(a)}
2704 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2705 if `rhs` is larger than or equal to the number of bits in `self`.
2712 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2713 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2715 #[stable(feature = "wrapping", since = "1.7.0")]
2717 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2718 let (a, b) = self.overflowing_shl(rhs);
2719 if b {None} else {Some(a)}
2724 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2725 if `rhs` is larger than or equal to the number of bits in `self`.
2732 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2733 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2735 #[stable(feature = "wrapping", since = "1.7.0")]
2737 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2738 let (a, b) = self.overflowing_shr(rhs);
2739 if b {None} else {Some(a)}
2744 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2752 #![feature(no_panic_pow)]
2753 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2754 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2756 #[unstable(feature = "no_panic_pow", issue = "48320")]
2758 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2759 let mut base = self;
2760 let mut acc: Self = 1;
2764 acc = acc.checked_mul(base)?;
2767 base = base.checked_mul(base)?;
2770 // Deal with the final bit of the exponent separately, since
2771 // squaring the base afterwards is not necessary and may cause a
2772 // needless overflow.
2774 acc = acc.checked_mul(base)?;
2782 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2783 the numeric bounds instead of overflowing.
2790 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2791 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2793 #[stable(feature = "rust1", since = "1.0.0")]
2795 pub fn saturating_add(self, rhs: Self) -> Self {
2796 match self.checked_add(rhs) {
2798 None => Self::max_value(),
2804 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2805 at the numeric bounds instead of overflowing.
2812 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2813 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2815 #[stable(feature = "rust1", since = "1.0.0")]
2817 pub fn saturating_sub(self, rhs: Self) -> Self {
2818 match self.checked_sub(rhs) {
2820 None => Self::min_value(),
2826 concat!("Saturating integer multiplication. Computes `self * rhs`,
2827 saturating at the numeric bounds instead of overflowing.
2834 ", $Feature, "use std::", stringify!($SelfT), ";
2836 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2837 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2838 "::MAX);", $EndFeature, "
2840 #[stable(feature = "wrapping", since = "1.7.0")]
2842 pub fn saturating_mul(self, rhs: Self) -> Self {
2843 self.checked_mul(rhs).unwrap_or(Self::max_value())
2848 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2849 saturating at the numeric bounds instead of overflowing.
2856 #![feature(no_panic_pow)]
2857 ", $Feature, "use std::", stringify!($SelfT), ";
2859 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2860 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2863 #[unstable(feature = "no_panic_pow", issue = "48320")]
2865 pub fn saturating_pow(self, exp: u32) -> Self {
2866 match self.checked_pow(exp) {
2868 None => Self::max_value(),
2874 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2875 wrapping around at the boundary of the type.
2882 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2883 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2886 #[stable(feature = "rust1", since = "1.0.0")]
2887 #[rustc_const_unstable(feature = "const_int_wrapping")]
2889 pub const fn wrapping_add(self, rhs: Self) -> Self {
2891 intrinsics::overflowing_add(self, rhs)
2897 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2898 wrapping around at the boundary of the type.
2905 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2906 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2909 #[stable(feature = "rust1", since = "1.0.0")]
2910 #[rustc_const_unstable(feature = "const_int_wrapping")]
2912 pub const fn wrapping_sub(self, rhs: Self) -> Self {
2914 intrinsics::overflowing_sub(self, rhs)
2919 /// Wrapping (modular) multiplication. Computes `self *
2920 /// rhs`, wrapping around at the boundary of the type.
2926 /// Please note that this example is shared between integer types.
2927 /// Which explains why `u8` is used here.
2930 /// assert_eq!(10u8.wrapping_mul(12), 120);
2931 /// assert_eq!(25u8.wrapping_mul(12), 44);
2933 #[stable(feature = "rust1", since = "1.0.0")]
2934 #[rustc_const_unstable(feature = "const_int_wrapping")]
2936 pub const fn wrapping_mul(self, rhs: Self) -> Self {
2938 intrinsics::overflowing_mul(self, rhs)
2943 concat!("Wrapping (modular) division. Computes `self / rhs`.
2944 Wrapped division on unsigned types is just normal division.
2945 There's no way wrapping could ever happen.
2946 This function exists, so that all operations
2947 are accounted for in the wrapping operations.
2954 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2956 #[stable(feature = "num_wrapping", since = "1.2.0")]
2958 pub fn wrapping_div(self, rhs: Self) -> Self {
2964 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`.
2965 Wrapped division on unsigned types is just normal division.
2966 There's no way wrapping could ever happen.
2967 This function exists, so that all operations
2968 are accounted for in the wrapping operations.
2975 #![feature(euclidean_division)]
2976 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
2978 #[unstable(feature = "euclidean_division", issue = "49048")]
2980 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
2986 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2987 Wrapped remainder calculation on unsigned types is
2988 just the regular remainder calculation.
2989 There's no way wrapping could ever happen.
2990 This function exists, so that all operations
2991 are accounted for in the wrapping operations.
2998 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3000 #[stable(feature = "num_wrapping", since = "1.2.0")]
3002 pub fn wrapping_rem(self, rhs: Self) -> Self {
3008 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`.
3009 Wrapped modulo calculation on unsigned types is
3010 just the regular remainder calculation.
3011 There's no way wrapping could ever happen.
3012 This function exists, so that all operations
3013 are accounted for in the wrapping operations.
3020 #![feature(euclidean_division)]
3021 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
3023 #[unstable(feature = "euclidean_division", issue = "49048")]
3025 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
3030 /// Wrapping (modular) negation. Computes `-self`,
3031 /// wrapping around at the boundary of the type.
3033 /// Since unsigned types do not have negative equivalents
3034 /// all applications of this function will wrap (except for `-0`).
3035 /// For values smaller than the corresponding signed type's maximum
3036 /// the result is the same as casting the corresponding signed value.
3037 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3038 /// `MAX` is the corresponding signed type's maximum.
3044 /// Please note that this example is shared between integer types.
3045 /// Which explains why `i8` is used here.
3048 /// assert_eq!(100i8.wrapping_neg(), -100);
3049 /// assert_eq!((-128i8).wrapping_neg(), -128);
3051 #[stable(feature = "num_wrapping", since = "1.2.0")]
3053 pub fn wrapping_neg(self) -> Self {
3054 self.overflowing_neg().0
3058 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3059 where `mask` removes any high-order bits of `rhs` that
3060 would cause the shift to exceed the bitwidth of the type.
3062 Note that this is *not* the same as a rotate-left; the
3063 RHS of a wrapping shift-left is restricted to the range
3064 of the type, rather than the bits shifted out of the LHS
3065 being returned to the other end. The primitive integer
3066 types all implement a `rotate_left` function, which may
3067 be what you want instead.
3074 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3075 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3077 #[stable(feature = "num_wrapping", since = "1.2.0")]
3078 #[rustc_const_unstable(feature = "const_int_wrapping")]
3080 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3082 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3088 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3089 where `mask` removes any high-order bits of `rhs` that
3090 would cause the shift to exceed the bitwidth of the type.
3092 Note that this is *not* the same as a rotate-right; the
3093 RHS of a wrapping shift-right is restricted to the range
3094 of the type, rather than the bits shifted out of the LHS
3095 being returned to the other end. The primitive integer
3096 types all implement a `rotate_right` function, which may
3097 be what you want instead.
3104 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3105 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3107 #[stable(feature = "num_wrapping", since = "1.2.0")]
3108 #[rustc_const_unstable(feature = "const_int_wrapping")]
3110 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3112 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3118 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3119 wrapping around at the boundary of the type.
3126 #![feature(no_panic_pow)]
3127 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3128 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3130 #[unstable(feature = "no_panic_pow", issue = "48320")]
3132 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3133 let mut base = self;
3134 let mut acc: Self = 1;
3138 acc = acc.wrapping_mul(base);
3141 base = base.wrapping_mul(base);
3144 // Deal with the final bit of the exponent separately, since
3145 // squaring the base afterwards is not necessary and may cause a
3146 // needless overflow.
3148 acc = acc.wrapping_mul(base);
3156 concat!("Calculates `self` + `rhs`
3158 Returns a tuple of the addition along with a boolean indicating
3159 whether an arithmetic overflow would occur. If an overflow would
3160 have occurred then the wrapped value is returned.
3167 ", $Feature, "use std::", stringify!($SelfT), ";
3169 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3170 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3172 #[stable(feature = "wrapping", since = "1.7.0")]
3173 #[rustc_const_unstable(feature = "const_int_overflowing")]
3175 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3176 let (a, b) = unsafe {
3177 intrinsics::add_with_overflow(self as $ActualT,
3185 concat!("Calculates `self` - `rhs`
3187 Returns a tuple of the subtraction along with a boolean indicating
3188 whether an arithmetic overflow would occur. If an overflow would
3189 have occurred then the wrapped value is returned.
3196 ", $Feature, "use std::", stringify!($SelfT), ";
3198 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3199 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3202 #[stable(feature = "wrapping", since = "1.7.0")]
3203 #[rustc_const_unstable(feature = "const_int_overflowing")]
3205 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3206 let (a, b) = unsafe {
3207 intrinsics::sub_with_overflow(self as $ActualT,
3214 /// Calculates the multiplication of `self` and `rhs`.
3216 /// Returns a tuple of the multiplication along with a boolean
3217 /// indicating whether an arithmetic overflow would occur. If an
3218 /// overflow would have occurred then the wrapped value is returned.
3224 /// Please note that this example is shared between integer types.
3225 /// Which explains why `u32` is used here.
3228 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3229 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3231 #[stable(feature = "wrapping", since = "1.7.0")]
3232 #[rustc_const_unstable(feature = "const_int_overflowing")]
3234 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3235 let (a, b) = unsafe {
3236 intrinsics::mul_with_overflow(self as $ActualT,
3243 concat!("Calculates the divisor when `self` is divided by `rhs`.
3245 Returns a tuple of the divisor along with a boolean indicating
3246 whether an arithmetic overflow would occur. Note that for unsigned
3247 integers overflow never occurs, so the second value is always
3252 This function will panic if `rhs` is 0.
3259 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3262 #[stable(feature = "wrapping", since = "1.7.0")]
3263 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3269 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
3271 Returns a tuple of the divisor along with a boolean indicating
3272 whether an arithmetic overflow would occur. Note that for unsigned
3273 integers overflow never occurs, so the second value is always
3278 This function will panic if `rhs` is 0.
3285 #![feature(euclidean_division)]
3286 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
3289 #[unstable(feature = "euclidean_division", issue = "49048")]
3290 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
3296 concat!("Calculates the remainder when `self` is divided by `rhs`.
3298 Returns a tuple of the remainder after dividing along with a boolean
3299 indicating whether an arithmetic overflow would occur. Note that for
3300 unsigned integers overflow never occurs, so the second value is
3305 This function will panic if `rhs` is 0.
3312 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3315 #[stable(feature = "wrapping", since = "1.7.0")]
3316 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3322 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
3324 Returns a tuple of the modulo after dividing along with a boolean
3325 indicating whether an arithmetic overflow would occur. Note that for
3326 unsigned integers overflow never occurs, so the second value is
3331 This function will panic if `rhs` is 0.
3338 #![feature(euclidean_division)]
3339 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
3342 #[unstable(feature = "euclidean_division", issue = "49048")]
3343 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
3349 concat!("Negates self in an overflowing fashion.
3351 Returns `!self + 1` using wrapping operations to return the value
3352 that represents the negation of this unsigned value. Note that for
3353 positive unsigned values overflow always occurs, but negating 0 does
3361 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3362 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3363 ", true));", $EndFeature, "
3366 #[stable(feature = "wrapping", since = "1.7.0")]
3367 pub fn overflowing_neg(self) -> (Self, bool) {
3368 ((!self).wrapping_add(1), self != 0)
3373 concat!("Shifts self left by `rhs` bits.
3375 Returns a tuple of the shifted version of self along with a boolean
3376 indicating whether the shift value was larger than or equal to the
3377 number of bits. If the shift value is too large, then value is
3378 masked (N-1) where N is the number of bits, and this value is then
3379 used to perform the shift.
3386 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3387 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3389 #[stable(feature = "wrapping", since = "1.7.0")]
3390 #[rustc_const_unstable(feature = "const_int_overflowing")]
3392 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3393 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3398 concat!("Shifts self right by `rhs` bits.
3400 Returns a tuple of the shifted version of self along with a boolean
3401 indicating whether the shift value was larger than or equal to the
3402 number of bits. If the shift value is too large, then value is
3403 masked (N-1) where N is the number of bits, and this value is then
3404 used to perform the shift.
3411 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3412 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3414 #[stable(feature = "wrapping", since = "1.7.0")]
3415 #[rustc_const_unstable(feature = "const_int_overflowing")]
3417 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3418 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3423 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3425 Returns a tuple of the exponentiation along with a bool indicating
3426 whether an overflow happened.
3433 #![feature(no_panic_pow)]
3434 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3435 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3437 #[unstable(feature = "no_panic_pow", issue = "48320")]
3439 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3440 let mut base = self;
3441 let mut acc: Self = 1;
3442 let mut overflown = false;
3443 // Scratch space for storing results of overflowing_mul.
3448 r = acc.overflowing_mul(base);
3453 r = base.overflowing_mul(base);
3458 // Deal with the final bit of the exponent separately, since
3459 // squaring the base afterwards is not necessary and may cause a
3460 // needless overflow.
3462 r = acc.overflowing_mul(base);
3472 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3479 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3481 #[stable(feature = "rust1", since = "1.0.0")]
3483 #[rustc_inherit_overflow_checks]
3484 pub fn pow(self, mut exp: u32) -> Self {
3485 let mut base = self;
3496 // Deal with the final bit of the exponent separately, since
3497 // squaring the base afterwards is not necessary and may cause a
3498 // needless overflow.
3508 concat!("Performs Euclidean division.
3510 For unsigned types, this is just the same as `self / rhs`.
3517 #![feature(euclidean_division)]
3518 assert_eq!(7", stringify!($SelfT), ".div_euc(4), 1); // or any other integer type
3520 #[unstable(feature = "euclidean_division", issue = "49048")]
3522 #[rustc_inherit_overflow_checks]
3523 pub fn div_euc(self, rhs: Self) -> Self {
3530 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
3532 For unsigned types, this is just the same as `self % rhs`.
3539 #![feature(euclidean_division)]
3540 assert_eq!(7", stringify!($SelfT), ".mod_euc(4), 3); // or any other integer type
3542 #[unstable(feature = "euclidean_division", issue = "49048")]
3544 #[rustc_inherit_overflow_checks]
3545 pub fn mod_euc(self, rhs: Self) -> Self {
3551 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3558 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3559 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3561 #[stable(feature = "rust1", since = "1.0.0")]
3563 pub fn is_power_of_two(self) -> bool {
3564 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3568 // Returns one less than next power of two.
3569 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3571 // 8u8.one_less_than_next_power_of_two() == 7
3572 // 6u8.one_less_than_next_power_of_two() == 7
3574 // This method cannot overflow, as in the `next_power_of_two`
3575 // overflow cases it instead ends up returning the maximum value
3576 // of the type, and can return 0 for 0.
3578 fn one_less_than_next_power_of_two(self) -> Self {
3579 if self <= 1 { return 0; }
3581 // Because `p > 0`, it cannot consist entirely of leading zeros.
3582 // That means the shift is always in-bounds, and some processors
3583 // (such as intel pre-haswell) have more efficient ctlz
3584 // intrinsics when the argument is non-zero.
3586 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3587 <$SelfT>::max_value() >> z
3591 concat!("Returns the smallest power of two greater than or equal to `self`.
3593 When return value overflows (i.e. `self > (1 << (N-1))` for type
3594 `uN`), it panics in debug mode and return value is wrapped to 0 in
3595 release mode (the only situation in which method can return 0).
3602 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3603 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3605 #[stable(feature = "rust1", since = "1.0.0")]
3607 pub fn next_power_of_two(self) -> Self {
3608 // Call the trait to get overflow checks
3609 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3614 concat!("Returns the smallest power of two greater than or equal to `n`. If
3615 the next power of two is greater than the type's maximum value,
3616 `None` is returned, otherwise the power of two is wrapped in `Some`.
3623 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3624 ".checked_next_power_of_two(), Some(2));
3625 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3626 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3629 #[stable(feature = "rust1", since = "1.0.0")]
3630 pub fn checked_next_power_of_two(self) -> Option<Self> {
3631 self.one_less_than_next_power_of_two().checked_add(1)
3636 concat!("Returns the smallest power of two greater than or equal to `n`. If
3637 the next power of two is greater than the type's maximum value,
3638 the return value is wrapped to `0`.
3645 #![feature(wrapping_next_power_of_two)]
3647 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3648 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3649 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3652 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3653 reason = "needs decision on wrapping behaviour")]
3654 pub fn wrapping_next_power_of_two(self) -> Self {
3655 self.one_less_than_next_power_of_two().wrapping_add(1)
3660 concat!("Return the memory representation of this integer as a byte array in
3661 big-endian (network) byte order.
3666 #![feature(int_to_from_bytes)]
3668 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
3669 assert_eq!(bytes, ", $be_bytes, ");
3671 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3672 #[rustc_const_unstable(feature = "const_int_conversion")]
3674 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
3675 self.to_be().to_ne_bytes()
3680 concat!("Return the memory representation of this integer as a byte array in
3681 little-endian byte order.
3686 #![feature(int_to_from_bytes)]
3688 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
3689 assert_eq!(bytes, ", $le_bytes, ");
3691 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3692 #[rustc_const_unstable(feature = "const_int_conversion")]
3694 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
3695 self.to_le().to_ne_bytes()
3701 Return the memory representation of this integer as a byte array in
3704 As the target platform's native endianness is used, portable code
3705 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3708 [`to_be_bytes`]: #method.to_be_bytes
3709 [`to_le_bytes`]: #method.to_le_bytes
3714 #![feature(int_to_from_bytes)]
3716 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
3717 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
3723 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3724 #[rustc_const_unstable(feature = "const_int_conversion")]
3726 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
3727 unsafe { mem::transmute(self) }
3732 concat!("Create an integer value from its representation as a byte array in
3738 #![feature(int_to_from_bytes)]
3740 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
3741 assert_eq!(value, ", $swap_op, ");
3743 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3744 #[rustc_const_unstable(feature = "const_int_conversion")]
3746 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3747 Self::from_be(Self::from_ne_bytes(bytes))
3753 Create an integer value from its representation as a byte array in
3759 #![feature(int_to_from_bytes)]
3761 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
3762 assert_eq!(value, ", $swap_op, ");
3764 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3765 #[rustc_const_unstable(feature = "const_int_conversion")]
3767 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3768 Self::from_le(Self::from_ne_bytes(bytes))
3773 concat!("Create an integer value from its memory representation as a byte
3774 array in native endianness.
3776 As the target platform's native endianness is used, portable code
3777 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3778 appropriate instead.
3780 [`from_be_bytes`]: #method.from_be_bytes
3781 [`from_le_bytes`]: #method.from_le_bytes
3786 #![feature(int_to_from_bytes)]
3788 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
3793 assert_eq!(value, ", $swap_op, ");
3795 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3796 #[rustc_const_unstable(feature = "const_int_conversion")]
3798 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3799 unsafe { mem::transmute(bytes) }
3807 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
3811 /// Checks if the value is within the ASCII range.
3816 /// let ascii = 97u8;
3817 /// let non_ascii = 150u8;
3819 /// assert!(ascii.is_ascii());
3820 /// assert!(!non_ascii.is_ascii());
3822 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3824 pub fn is_ascii(&self) -> bool {
3828 /// Makes a copy of the value in its ASCII upper case equivalent.
3830 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3831 /// but non-ASCII letters are unchanged.
3833 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
3838 /// let lowercase_a = 97u8;
3840 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
3843 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
3844 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3846 pub fn to_ascii_uppercase(&self) -> u8 {
3847 ASCII_UPPERCASE_MAP[*self as usize]
3850 /// Makes a copy of the value in its ASCII lower case equivalent.
3852 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3853 /// but non-ASCII letters are unchanged.
3855 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
3860 /// let uppercase_a = 65u8;
3862 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
3865 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
3866 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3868 pub fn to_ascii_lowercase(&self) -> u8 {
3869 ASCII_LOWERCASE_MAP[*self as usize]
3872 /// Checks that two values are an ASCII case-insensitive match.
3874 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3879 /// let lowercase_a = 97u8;
3880 /// let uppercase_a = 65u8;
3882 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3884 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3886 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3887 self.to_ascii_lowercase() == other.to_ascii_lowercase()
3890 /// Converts this value to its ASCII upper case equivalent in-place.
3892 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3893 /// but non-ASCII letters are unchanged.
3895 /// To return a new uppercased value without modifying the existing one, use
3896 /// [`to_ascii_uppercase`].
3901 /// let mut byte = b'a';
3903 /// byte.make_ascii_uppercase();
3905 /// assert_eq!(b'A', byte);
3908 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3909 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3911 pub fn make_ascii_uppercase(&mut self) {
3912 *self = self.to_ascii_uppercase();
3915 /// Converts this value to its ASCII lower case equivalent in-place.
3917 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3918 /// but non-ASCII letters are unchanged.
3920 /// To return a new lowercased value without modifying the existing one, use
3921 /// [`to_ascii_lowercase`].
3926 /// let mut byte = b'A';
3928 /// byte.make_ascii_lowercase();
3930 /// assert_eq!(b'a', byte);
3933 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3934 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3936 pub fn make_ascii_lowercase(&mut self) {
3937 *self = self.to_ascii_lowercase();
3940 /// Checks if the value is an ASCII alphabetic character:
3942 /// - U+0041 'A' ... U+005A 'Z', or
3943 /// - U+0061 'a' ... U+007A 'z'.
3948 /// let uppercase_a = b'A';
3949 /// let uppercase_g = b'G';
3952 /// let zero = b'0';
3953 /// let percent = b'%';
3954 /// let space = b' ';
3956 /// let esc = 0x1b_u8;
3958 /// assert!(uppercase_a.is_ascii_alphabetic());
3959 /// assert!(uppercase_g.is_ascii_alphabetic());
3960 /// assert!(a.is_ascii_alphabetic());
3961 /// assert!(g.is_ascii_alphabetic());
3962 /// assert!(!zero.is_ascii_alphabetic());
3963 /// assert!(!percent.is_ascii_alphabetic());
3964 /// assert!(!space.is_ascii_alphabetic());
3965 /// assert!(!lf.is_ascii_alphabetic());
3966 /// assert!(!esc.is_ascii_alphabetic());
3968 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3970 pub fn is_ascii_alphabetic(&self) -> bool {
3971 if *self >= 0x80 { return false; }
3972 match ASCII_CHARACTER_CLASS[*self as usize] {
3973 L | Lx | U | Ux => true,
3978 /// Checks if the value is an ASCII uppercase character:
3979 /// U+0041 'A' ... U+005A 'Z'.
3984 /// let uppercase_a = b'A';
3985 /// let uppercase_g = b'G';
3988 /// let zero = b'0';
3989 /// let percent = b'%';
3990 /// let space = b' ';
3992 /// let esc = 0x1b_u8;
3994 /// assert!(uppercase_a.is_ascii_uppercase());
3995 /// assert!(uppercase_g.is_ascii_uppercase());
3996 /// assert!(!a.is_ascii_uppercase());
3997 /// assert!(!g.is_ascii_uppercase());
3998 /// assert!(!zero.is_ascii_uppercase());
3999 /// assert!(!percent.is_ascii_uppercase());
4000 /// assert!(!space.is_ascii_uppercase());
4001 /// assert!(!lf.is_ascii_uppercase());
4002 /// assert!(!esc.is_ascii_uppercase());
4004 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4006 pub fn is_ascii_uppercase(&self) -> bool {
4007 if *self >= 0x80 { return false }
4008 match ASCII_CHARACTER_CLASS[*self as usize] {
4014 /// Checks if the value is an ASCII lowercase character:
4015 /// U+0061 'a' ... U+007A 'z'.
4020 /// let uppercase_a = b'A';
4021 /// let uppercase_g = b'G';
4024 /// let zero = b'0';
4025 /// let percent = b'%';
4026 /// let space = b' ';
4028 /// let esc = 0x1b_u8;
4030 /// assert!(!uppercase_a.is_ascii_lowercase());
4031 /// assert!(!uppercase_g.is_ascii_lowercase());
4032 /// assert!(a.is_ascii_lowercase());
4033 /// assert!(g.is_ascii_lowercase());
4034 /// assert!(!zero.is_ascii_lowercase());
4035 /// assert!(!percent.is_ascii_lowercase());
4036 /// assert!(!space.is_ascii_lowercase());
4037 /// assert!(!lf.is_ascii_lowercase());
4038 /// assert!(!esc.is_ascii_lowercase());
4040 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4042 pub fn is_ascii_lowercase(&self) -> bool {
4043 if *self >= 0x80 { return false }
4044 match ASCII_CHARACTER_CLASS[*self as usize] {
4050 /// Checks if the value is an ASCII alphanumeric character:
4052 /// - U+0041 'A' ... U+005A 'Z', or
4053 /// - U+0061 'a' ... U+007A 'z', or
4054 /// - U+0030 '0' ... U+0039 '9'.
4059 /// let uppercase_a = b'A';
4060 /// let uppercase_g = b'G';
4063 /// let zero = b'0';
4064 /// let percent = b'%';
4065 /// let space = b' ';
4067 /// let esc = 0x1b_u8;
4069 /// assert!(uppercase_a.is_ascii_alphanumeric());
4070 /// assert!(uppercase_g.is_ascii_alphanumeric());
4071 /// assert!(a.is_ascii_alphanumeric());
4072 /// assert!(g.is_ascii_alphanumeric());
4073 /// assert!(zero.is_ascii_alphanumeric());
4074 /// assert!(!percent.is_ascii_alphanumeric());
4075 /// assert!(!space.is_ascii_alphanumeric());
4076 /// assert!(!lf.is_ascii_alphanumeric());
4077 /// assert!(!esc.is_ascii_alphanumeric());
4079 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4081 pub fn is_ascii_alphanumeric(&self) -> bool {
4082 if *self >= 0x80 { return false }
4083 match ASCII_CHARACTER_CLASS[*self as usize] {
4084 D | L | Lx | U | Ux => true,
4089 /// Checks if the value is an ASCII decimal digit:
4090 /// U+0030 '0' ... U+0039 '9'.
4095 /// let uppercase_a = b'A';
4096 /// let uppercase_g = b'G';
4099 /// let zero = b'0';
4100 /// let percent = b'%';
4101 /// let space = b' ';
4103 /// let esc = 0x1b_u8;
4105 /// assert!(!uppercase_a.is_ascii_digit());
4106 /// assert!(!uppercase_g.is_ascii_digit());
4107 /// assert!(!a.is_ascii_digit());
4108 /// assert!(!g.is_ascii_digit());
4109 /// assert!(zero.is_ascii_digit());
4110 /// assert!(!percent.is_ascii_digit());
4111 /// assert!(!space.is_ascii_digit());
4112 /// assert!(!lf.is_ascii_digit());
4113 /// assert!(!esc.is_ascii_digit());
4115 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4117 pub fn is_ascii_digit(&self) -> bool {
4118 if *self >= 0x80 { return false }
4119 match ASCII_CHARACTER_CLASS[*self as usize] {
4125 /// Checks if the value is an ASCII hexadecimal digit:
4127 /// - U+0030 '0' ... U+0039 '9', or
4128 /// - U+0041 'A' ... U+0046 'F', or
4129 /// - U+0061 'a' ... U+0066 'f'.
4134 /// let uppercase_a = b'A';
4135 /// let uppercase_g = b'G';
4138 /// let zero = b'0';
4139 /// let percent = b'%';
4140 /// let space = b' ';
4142 /// let esc = 0x1b_u8;
4144 /// assert!(uppercase_a.is_ascii_hexdigit());
4145 /// assert!(!uppercase_g.is_ascii_hexdigit());
4146 /// assert!(a.is_ascii_hexdigit());
4147 /// assert!(!g.is_ascii_hexdigit());
4148 /// assert!(zero.is_ascii_hexdigit());
4149 /// assert!(!percent.is_ascii_hexdigit());
4150 /// assert!(!space.is_ascii_hexdigit());
4151 /// assert!(!lf.is_ascii_hexdigit());
4152 /// assert!(!esc.is_ascii_hexdigit());
4154 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4156 pub fn is_ascii_hexdigit(&self) -> bool {
4157 if *self >= 0x80 { return false }
4158 match ASCII_CHARACTER_CLASS[*self as usize] {
4159 D | Lx | Ux => true,
4164 /// Checks if the value is an ASCII punctuation character:
4166 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
4167 /// - U+003A ... U+0040 `: ; < = > ? @`, or
4168 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
4169 /// - U+007B ... U+007E `{ | } ~`
4174 /// let uppercase_a = b'A';
4175 /// let uppercase_g = b'G';
4178 /// let zero = b'0';
4179 /// let percent = b'%';
4180 /// let space = b' ';
4182 /// let esc = 0x1b_u8;
4184 /// assert!(!uppercase_a.is_ascii_punctuation());
4185 /// assert!(!uppercase_g.is_ascii_punctuation());
4186 /// assert!(!a.is_ascii_punctuation());
4187 /// assert!(!g.is_ascii_punctuation());
4188 /// assert!(!zero.is_ascii_punctuation());
4189 /// assert!(percent.is_ascii_punctuation());
4190 /// assert!(!space.is_ascii_punctuation());
4191 /// assert!(!lf.is_ascii_punctuation());
4192 /// assert!(!esc.is_ascii_punctuation());
4194 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4196 pub fn is_ascii_punctuation(&self) -> bool {
4197 if *self >= 0x80 { return false }
4198 match ASCII_CHARACTER_CLASS[*self as usize] {
4204 /// Checks if the value is an ASCII graphic character:
4205 /// U+0021 '!' ... U+007E '~'.
4210 /// let uppercase_a = b'A';
4211 /// let uppercase_g = b'G';
4214 /// let zero = b'0';
4215 /// let percent = b'%';
4216 /// let space = b' ';
4218 /// let esc = 0x1b_u8;
4220 /// assert!(uppercase_a.is_ascii_graphic());
4221 /// assert!(uppercase_g.is_ascii_graphic());
4222 /// assert!(a.is_ascii_graphic());
4223 /// assert!(g.is_ascii_graphic());
4224 /// assert!(zero.is_ascii_graphic());
4225 /// assert!(percent.is_ascii_graphic());
4226 /// assert!(!space.is_ascii_graphic());
4227 /// assert!(!lf.is_ascii_graphic());
4228 /// assert!(!esc.is_ascii_graphic());
4230 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4232 pub fn is_ascii_graphic(&self) -> bool {
4233 if *self >= 0x80 { return false; }
4234 match ASCII_CHARACTER_CLASS[*self as usize] {
4235 Ux | U | Lx | L | D | P => true,
4240 /// Checks if the value is an ASCII whitespace character:
4241 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4242 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4244 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4245 /// whitespace][infra-aw]. There are several other definitions in
4246 /// wide use. For instance, [the POSIX locale][pct] includes
4247 /// U+000B VERTICAL TAB as well as all the above characters,
4248 /// but—from the very same specification—[the default rule for
4249 /// "field splitting" in the Bourne shell][bfs] considers *only*
4250 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4252 /// If you are writing a program that will process an existing
4253 /// file format, check what that format's definition of whitespace is
4254 /// before using this function.
4256 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4257 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4258 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4263 /// let uppercase_a = b'A';
4264 /// let uppercase_g = b'G';
4267 /// let zero = b'0';
4268 /// let percent = b'%';
4269 /// let space = b' ';
4271 /// let esc = 0x1b_u8;
4273 /// assert!(!uppercase_a.is_ascii_whitespace());
4274 /// assert!(!uppercase_g.is_ascii_whitespace());
4275 /// assert!(!a.is_ascii_whitespace());
4276 /// assert!(!g.is_ascii_whitespace());
4277 /// assert!(!zero.is_ascii_whitespace());
4278 /// assert!(!percent.is_ascii_whitespace());
4279 /// assert!(space.is_ascii_whitespace());
4280 /// assert!(lf.is_ascii_whitespace());
4281 /// assert!(!esc.is_ascii_whitespace());
4283 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4285 pub fn is_ascii_whitespace(&self) -> bool {
4286 if *self >= 0x80 { return false; }
4287 match ASCII_CHARACTER_CLASS[*self as usize] {
4293 /// Checks if the value is an ASCII control character:
4294 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4295 /// Note that most ASCII whitespace characters are control
4296 /// characters, but SPACE is not.
4301 /// let uppercase_a = b'A';
4302 /// let uppercase_g = b'G';
4305 /// let zero = b'0';
4306 /// let percent = b'%';
4307 /// let space = b' ';
4309 /// let esc = 0x1b_u8;
4311 /// assert!(!uppercase_a.is_ascii_control());
4312 /// assert!(!uppercase_g.is_ascii_control());
4313 /// assert!(!a.is_ascii_control());
4314 /// assert!(!g.is_ascii_control());
4315 /// assert!(!zero.is_ascii_control());
4316 /// assert!(!percent.is_ascii_control());
4317 /// assert!(!space.is_ascii_control());
4318 /// assert!(lf.is_ascii_control());
4319 /// assert!(esc.is_ascii_control());
4321 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4323 pub fn is_ascii_control(&self) -> bool {
4324 if *self >= 0x80 { return false; }
4325 match ASCII_CHARACTER_CLASS[*self as usize] {
4334 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4335 "[0x34, 0x12]", "[0x12, 0x34]" }
4340 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4341 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]" }
4346 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4347 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4348 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4349 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
4354 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4355 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4356 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4357 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4358 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4359 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4360 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]" }
4363 #[cfg(target_pointer_width = "16")]
4366 uint_impl! { usize, u16, 16, 65536, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4367 "[0x34, 0x12]", "[0x12, 0x34]" }
4369 #[cfg(target_pointer_width = "32")]
4372 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4373 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]" }
4376 #[cfg(target_pointer_width = "64")]
4379 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4380 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4381 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4382 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
4385 /// A classification of floating point numbers.
4387 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4388 /// their documentation for more.
4390 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4391 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4396 /// use std::num::FpCategory;
4399 /// let num = 12.4_f32;
4400 /// let inf = f32::INFINITY;
4401 /// let zero = 0f32;
4402 /// let sub: f32 = 1.1754942e-38;
4403 /// let nan = f32::NAN;
4405 /// assert_eq!(num.classify(), FpCategory::Normal);
4406 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4407 /// assert_eq!(zero.classify(), FpCategory::Zero);
4408 /// assert_eq!(nan.classify(), FpCategory::Nan);
4409 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4411 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4412 #[stable(feature = "rust1", since = "1.0.0")]
4413 pub enum FpCategory {
4414 /// "Not a Number", often obtained by dividing by zero.
4415 #[stable(feature = "rust1", since = "1.0.0")]
4418 /// Positive or negative infinity.
4419 #[stable(feature = "rust1", since = "1.0.0")]
4422 /// Positive or negative zero.
4423 #[stable(feature = "rust1", since = "1.0.0")]
4426 /// De-normalized floating point representation (less precise than `Normal`).
4427 #[stable(feature = "rust1", since = "1.0.0")]
4430 /// A regular floating point number.
4431 #[stable(feature = "rust1", since = "1.0.0")]
4435 macro_rules! from_str_radix_int_impl {
4437 #[stable(feature = "rust1", since = "1.0.0")]
4438 impl FromStr for $t {
4439 type Err = ParseIntError;
4440 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4441 from_str_radix(src, 10)
4446 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4448 /// The error type returned when a checked integral type conversion fails.
4449 #[unstable(feature = "try_from", issue = "33417")]
4450 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4451 pub struct TryFromIntError(());
4453 impl TryFromIntError {
4454 #[unstable(feature = "int_error_internals",
4455 reason = "available through Error trait and this method should \
4456 not be exposed publicly",
4459 pub fn __description(&self) -> &str {
4460 "out of range integral type conversion attempted"
4464 #[unstable(feature = "try_from", issue = "33417")]
4465 impl fmt::Display for TryFromIntError {
4466 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4467 self.__description().fmt(fmt)
4471 #[unstable(feature = "try_from", issue = "33417")]
4472 impl From<!> for TryFromIntError {
4473 fn from(never: !) -> TryFromIntError {
4478 // no possible bounds violation
4479 macro_rules! try_from_unbounded {
4480 ($source:ty, $($target:ty),*) => {$(
4481 #[unstable(feature = "try_from", issue = "33417")]
4482 impl TryFrom<$source> for $target {
4483 type Error = TryFromIntError;
4486 fn try_from(value: $source) -> Result<Self, Self::Error> {
4487 Ok(value as $target)
4493 // only negative bounds
4494 macro_rules! try_from_lower_bounded {
4495 ($source:ty, $($target:ty),*) => {$(
4496 #[unstable(feature = "try_from", issue = "33417")]
4497 impl TryFrom<$source> for $target {
4498 type Error = TryFromIntError;
4501 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4505 Err(TryFromIntError(()))
4512 // unsigned to signed (only positive bound)
4513 macro_rules! try_from_upper_bounded {
4514 ($source:ty, $($target:ty),*) => {$(
4515 #[unstable(feature = "try_from", issue = "33417")]
4516 impl TryFrom<$source> for $target {
4517 type Error = TryFromIntError;
4520 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4521 if u > (<$target>::max_value() as $source) {
4522 Err(TryFromIntError(()))
4532 macro_rules! try_from_both_bounded {
4533 ($source:ty, $($target:ty),*) => {$(
4534 #[unstable(feature = "try_from", issue = "33417")]
4535 impl TryFrom<$source> for $target {
4536 type Error = TryFromIntError;
4539 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4540 let min = <$target>::min_value() as $source;
4541 let max = <$target>::max_value() as $source;
4542 if u < min || u > max {
4543 Err(TryFromIntError(()))
4553 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4554 $mac!($target, $source);
4558 /// intra-sign conversions
4559 try_from_upper_bounded!(u16, u8);
4560 try_from_upper_bounded!(u32, u16, u8);
4561 try_from_upper_bounded!(u64, u32, u16, u8);
4562 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4564 try_from_both_bounded!(i16, i8);
4565 try_from_both_bounded!(i32, i16, i8);
4566 try_from_both_bounded!(i64, i32, i16, i8);
4567 try_from_both_bounded!(i128, i64, i32, i16, i8);
4569 // unsigned-to-signed
4570 try_from_upper_bounded!(u8, i8);
4571 try_from_upper_bounded!(u16, i8, i16);
4572 try_from_upper_bounded!(u32, i8, i16, i32);
4573 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4574 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4576 // signed-to-unsigned
4577 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4578 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4579 try_from_lower_bounded!(i32, u32, u64, u128);
4580 try_from_lower_bounded!(i64, u64, u128);
4581 try_from_lower_bounded!(i128, u128);
4582 try_from_both_bounded!(i16, u8);
4583 try_from_both_bounded!(i32, u16, u8);
4584 try_from_both_bounded!(i64, u32, u16, u8);
4585 try_from_both_bounded!(i128, u64, u32, u16, u8);
4588 try_from_upper_bounded!(usize, isize);
4589 try_from_lower_bounded!(isize, usize);
4591 #[cfg(target_pointer_width = "16")]
4592 mod ptr_try_from_impls {
4593 use super::TryFromIntError;
4594 use convert::TryFrom;
4596 try_from_upper_bounded!(usize, u8);
4597 try_from_unbounded!(usize, u16, u32, u64, u128);
4598 try_from_upper_bounded!(usize, i8, i16);
4599 try_from_unbounded!(usize, i32, i64, i128);
4601 try_from_both_bounded!(isize, u8);
4602 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4603 try_from_both_bounded!(isize, i8);
4604 try_from_unbounded!(isize, i16, i32, i64, i128);
4606 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4607 rev!(try_from_lower_bounded, usize, i8, i16);
4608 rev!(try_from_both_bounded, usize, i32, i64, i128);
4610 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4611 rev!(try_from_both_bounded, isize, i32, i64, i128);
4614 #[cfg(target_pointer_width = "32")]
4615 mod ptr_try_from_impls {
4616 use super::TryFromIntError;
4617 use convert::TryFrom;
4619 try_from_upper_bounded!(usize, u8, u16);
4620 try_from_unbounded!(usize, u32, u64, u128);
4621 try_from_upper_bounded!(usize, i8, i16, i32);
4622 try_from_unbounded!(usize, i64, i128);
4624 try_from_both_bounded!(isize, u8, u16);
4625 try_from_lower_bounded!(isize, u32, u64, u128);
4626 try_from_both_bounded!(isize, i8, i16);
4627 try_from_unbounded!(isize, i32, i64, i128);
4629 rev!(try_from_unbounded, usize, u32);
4630 rev!(try_from_upper_bounded, usize, u64, u128);
4631 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4632 rev!(try_from_both_bounded, usize, i64, i128);
4634 rev!(try_from_unbounded, isize, u16);
4635 rev!(try_from_upper_bounded, isize, u32, u64, u128);
4636 rev!(try_from_unbounded, isize, i32);
4637 rev!(try_from_both_bounded, isize, i64, i128);
4640 #[cfg(target_pointer_width = "64")]
4641 mod ptr_try_from_impls {
4642 use super::TryFromIntError;
4643 use convert::TryFrom;
4645 try_from_upper_bounded!(usize, u8, u16, u32);
4646 try_from_unbounded!(usize, u64, u128);
4647 try_from_upper_bounded!(usize, i8, i16, i32, i64);
4648 try_from_unbounded!(usize, i128);
4650 try_from_both_bounded!(isize, u8, u16, u32);
4651 try_from_lower_bounded!(isize, u64, u128);
4652 try_from_both_bounded!(isize, i8, i16, i32);
4653 try_from_unbounded!(isize, i64, i128);
4655 rev!(try_from_unbounded, usize, u32, u64);
4656 rev!(try_from_upper_bounded, usize, u128);
4657 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4658 rev!(try_from_both_bounded, usize, i128);
4660 rev!(try_from_unbounded, isize, u16, u32);
4661 rev!(try_from_upper_bounded, isize, u64, u128);
4662 rev!(try_from_unbounded, isize, i32, i64);
4663 rev!(try_from_both_bounded, isize, i128);
4667 trait FromStrRadixHelper: PartialOrd + Copy {
4668 fn min_value() -> Self;
4669 fn max_value() -> Self;
4670 fn from_u32(u: u32) -> Self;
4671 fn checked_mul(&self, other: u32) -> Option<Self>;
4672 fn checked_sub(&self, other: u32) -> Option<Self>;
4673 fn checked_add(&self, other: u32) -> Option<Self>;
4677 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4679 fn min_value() -> Self { Self::min_value() }
4681 fn max_value() -> Self { Self::max_value() }
4683 fn from_u32(u: u32) -> Self { u as Self }
4685 fn checked_mul(&self, other: u32) -> Option<Self> {
4686 Self::checked_mul(*self, other as Self)
4689 fn checked_sub(&self, other: u32) -> Option<Self> {
4690 Self::checked_sub(*self, other as Self)
4693 fn checked_add(&self, other: u32) -> Option<Self> {
4694 Self::checked_add(*self, other as Self)
4698 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4700 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4701 use self::IntErrorKind::*;
4702 use self::ParseIntError as PIE;
4704 assert!(radix >= 2 && radix <= 36,
4705 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4709 return Err(PIE { kind: Empty });
4712 let is_signed_ty = T::from_u32(0) > T::min_value();
4714 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4715 // and cast them to chars. .to_digit() will safely return None for anything
4716 // other than a valid ascii digit for the given radix, including the first-byte
4717 // of multi-byte sequences
4718 let src = src.as_bytes();
4720 let (is_positive, digits) = match src[0] {
4721 b'+' => (true, &src[1..]),
4722 b'-' if is_signed_ty => (false, &src[1..]),
4726 if digits.is_empty() {
4727 return Err(PIE { kind: Empty });
4730 let mut result = T::from_u32(0);
4732 // The number is positive
4734 let x = match (c as char).to_digit(radix) {
4736 None => return Err(PIE { kind: InvalidDigit }),
4738 result = match result.checked_mul(radix) {
4739 Some(result) => result,
4740 None => return Err(PIE { kind: Overflow }),
4742 result = match result.checked_add(x) {
4743 Some(result) => result,
4744 None => return Err(PIE { kind: Overflow }),
4748 // The number is negative
4750 let x = match (c as char).to_digit(radix) {
4752 None => return Err(PIE { kind: InvalidDigit }),
4754 result = match result.checked_mul(radix) {
4755 Some(result) => result,
4756 None => return Err(PIE { kind: Underflow }),
4758 result = match result.checked_sub(x) {
4759 Some(result) => result,
4760 None => return Err(PIE { kind: Underflow }),
4767 /// An error which can be returned when parsing an integer.
4769 /// This error is used as the error type for the `from_str_radix()` functions
4770 /// on the primitive integer types, such as [`i8::from_str_radix`].
4772 /// # Potential causes
4774 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
4775 /// in the string e.g. when it is obtained from the standard input.
4776 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
4778 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
4779 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
4780 #[derive(Debug, Clone, PartialEq, Eq)]
4781 #[stable(feature = "rust1", since = "1.0.0")]
4782 pub struct ParseIntError {
4786 #[derive(Debug, Clone, PartialEq, Eq)]
4794 impl ParseIntError {
4795 #[unstable(feature = "int_error_internals",
4796 reason = "available through Error trait and this method should \
4797 not be exposed publicly",
4800 pub fn __description(&self) -> &str {
4802 IntErrorKind::Empty => "cannot parse integer from empty string",
4803 IntErrorKind::InvalidDigit => "invalid digit found in string",
4804 IntErrorKind::Overflow => "number too large to fit in target type",
4805 IntErrorKind::Underflow => "number too small to fit in target type",
4810 #[stable(feature = "rust1", since = "1.0.0")]
4811 impl fmt::Display for ParseIntError {
4812 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4813 self.__description().fmt(f)
4817 #[stable(feature = "rust1", since = "1.0.0")]
4818 pub use num::dec2flt::ParseFloatError;
4820 // Conversion traits for primitive integer and float types
4821 // Conversions T -> T are covered by a blanket impl and therefore excluded
4822 // Some conversions from and to usize/isize are not implemented due to portability concerns
4823 macro_rules! impl_from {
4824 ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
4827 impl From<$Small> for $Large {
4829 fn from(small: $Small) -> $Large {
4834 ($Small: ty, $Large: ty, #[$attr:meta]) => {
4838 concat!("Converts `",
4846 macro_rules! impl_from_bool {
4847 ($target: ty, #[$attr:meta]) => {
4848 impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
4849 stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
4855 assert_eq!(", stringify!($target), "::from(true), 1);
4856 assert_eq!(", stringify!($target), "::from(false), 0);
4862 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
4863 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
4864 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
4865 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
4866 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
4867 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
4868 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
4869 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
4870 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
4871 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
4872 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
4873 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
4875 // Unsigned -> Unsigned
4876 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4877 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4878 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4879 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
4880 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4881 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4882 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4883 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
4884 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4885 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
4886 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
4889 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4890 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4891 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4892 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4893 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4894 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4895 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4896 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4897 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4898 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4899 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4901 // Unsigned -> Signed
4902 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4903 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4904 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4905 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4906 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4907 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4908 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4909 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4910 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4911 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4913 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
4914 // which imply that pointer-sized integers must be at least 16 bits:
4915 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
4916 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4917 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4918 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4920 // RISC-V defines the possibility of a 128-bit address space (RV128).
4922 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
4923 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
4924 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
4927 // Note: integers can only be represented with full precision in a float if
4928 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4929 // Lossy float conversions are not implemented at this time.
4932 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4933 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4934 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4935 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4936 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4938 // Unsigned -> Float
4939 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4940 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4941 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4942 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4943 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4946 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4948 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4949 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4950 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4951 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4952 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4953 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4954 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4955 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4956 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4959 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4960 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4961 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4964 b'[', b'\\', b']', b'^', b'_',
4965 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4966 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4967 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4968 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4969 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4970 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4971 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4972 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4973 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4974 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4975 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4976 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4977 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4978 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4979 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4980 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4981 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4982 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4983 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4984 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4987 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4988 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4989 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4990 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4991 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4992 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4993 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4994 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4995 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4996 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4997 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4998 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4999 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
5002 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
5003 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
5004 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
5007 b'{', b'|', b'}', b'~', 0x7f,
5008 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
5009 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
5010 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
5011 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
5012 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
5013 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
5014 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
5015 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
5016 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
5017 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
5018 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
5019 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
5020 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
5021 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
5022 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
5023 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
5026 enum AsciiCharacterClass {
5028 Cw, // control whitespace
5032 Lx, // lowercase hex digit
5034 Ux, // uppercase hex digit
5037 use self::AsciiCharacterClass::*;
5039 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
5040 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
5041 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
5042 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
5043 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
5044 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
5045 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
5046 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
5047 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
5048 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_