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! nonzero_integers {
38 ( $( $Ty: ident($Int: ty); )+ ) => {
40 /// An integer that is known not to equal zero.
42 /// This may enable some memory layout optimization such as:
45 /// # #![feature(nonzero)]
46 /// use std::mem::size_of;
47 /// assert_eq!(size_of::<Option<std::num::NonZeroU32>>(), size_of::<u32>());
49 #[stable(feature = "nonzero", since = "1.28.0")]
50 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
51 pub struct $Ty(NonZero<$Int>);
54 /// Create a non-zero without checking the value.
58 /// The value must not be zero.
59 #[stable(feature = "nonzero", since = "1.28.0")]
61 pub const unsafe fn new_unchecked(n: $Int) -> Self {
65 /// Create a non-zero if the given value is not zero.
66 #[stable(feature = "nonzero", since = "1.28.0")]
68 pub fn new(n: $Int) -> Option<Self> {
76 /// Returns the value as a primitive type.
77 #[stable(feature = "nonzero", since = "1.28.0")]
79 pub fn get(self) -> $Int {
86 (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
101 /// Provides intentionally-wrapped arithmetic on `T`.
103 /// Operations like `+` on `u32` values is intended to never overflow,
104 /// and in some debug configurations overflow is detected and results
105 /// in a panic. While most arithmetic falls into this category, some
106 /// code explicitly expects and relies upon modular arithmetic (e.g.,
109 /// Wrapping arithmetic can be achieved either through methods like
110 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
111 /// all standard arithmetic operations on the underlying value are
112 /// intended to have wrapping semantics.
117 /// use std::num::Wrapping;
119 /// let zero = Wrapping(0u32);
120 /// let one = Wrapping(1u32);
122 /// assert_eq!(std::u32::MAX, (zero - one).0);
124 #[stable(feature = "rust1", since = "1.0.0")]
125 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
126 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
129 #[stable(feature = "rust1", since = "1.0.0")]
130 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
131 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
136 #[stable(feature = "wrapping_display", since = "1.10.0")]
137 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
138 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
143 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
144 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
145 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
151 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
152 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
158 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
159 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
164 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
165 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
166 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171 // All these modules are technically private and only exposed for coretests:
177 macro_rules! doc_comment {
178 ($x:expr, $($tt:tt)*) => {
186 // `Int` + `SignedInt` implemented for signed integers
187 macro_rules! int_impl {
188 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
189 $EndFeature:expr) => {
191 concat!("Returns the smallest value that can be represented by this integer type.
198 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
201 #[stable(feature = "rust1", since = "1.0.0")]
203 pub const fn min_value() -> Self {
204 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
209 concat!("Returns the largest value that can be represented by this integer type.
216 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
219 #[stable(feature = "rust1", since = "1.0.0")]
221 pub const fn max_value() -> Self {
227 concat!("Converts a string slice in a given base to an integer.
229 The string is expected to be an optional `+` or `-` sign followed by digits.
230 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
231 depending on `radix`:
239 This function panics if `radix` is not in the range from 2 to 36.
246 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
251 from_str_radix(src, radix)
256 concat!("Returns the number of ones in the binary representation of `self`.
263 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
265 assert_eq!(n.count_ones(), 1);",
269 #[stable(feature = "rust1", since = "1.0.0")]
271 #[rustc_const_unstable(feature = "const_int_ops")]
273 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
277 concat!("Dummy docs. See !stage0 documentation"),
278 #[stable(feature = "rust1", since = "1.0.0")]
281 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
285 concat!("Returns the number of zeros in the binary representation of `self`.
292 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
294 #[stable(feature = "rust1", since = "1.0.0")]
296 #[rustc_const_unstable(feature = "const_int_ops")]
298 pub const fn count_zeros(self) -> u32 {
304 concat!("Dummy docs. See !stage0 documentatio"),
305 #[stable(feature = "rust1", since = "1.0.0")]
308 pub fn count_zeros(self) -> u32 {
314 concat!("Returns the number of leading zeros in the binary representation of `self`.
321 ", $Feature, "let n = -1", stringify!($SelfT), ";
323 assert_eq!(n.leading_zeros(), 0);",
326 #[stable(feature = "rust1", since = "1.0.0")]
328 #[rustc_const_unstable(feature = "const_int_ops")]
330 pub const fn leading_zeros(self) -> u32 {
331 (self as $UnsignedT).leading_zeros()
336 concat!("Dummy docs. See !stage0 documentation"),
337 #[stable(feature = "rust1", since = "1.0.0")]
340 pub fn leading_zeros(self) -> u32 {
341 (self as $UnsignedT).leading_zeros()
346 concat!("Returns the number of trailing zeros in the binary representation of `self`.
353 ", $Feature, "let n = -4", stringify!($SelfT), ";
355 assert_eq!(n.trailing_zeros(), 2);",
358 #[stable(feature = "rust1", since = "1.0.0")]
360 #[rustc_const_unstable(feature = "const_int_ops")]
362 pub const fn trailing_zeros(self) -> u32 {
363 (self as $UnsignedT).trailing_zeros()
368 concat!("Dummy docs. See !stage0 documentation"),
369 #[stable(feature = "rust1", since = "1.0.0")]
372 pub fn trailing_zeros(self) -> u32 {
373 (self as $UnsignedT).trailing_zeros()
377 /// Shifts the bits to the left by a specified amount, `n`,
378 /// wrapping the truncated bits to the end of the resulting integer.
380 /// Please note this isn't the same operation as `<<`!
384 /// Please note that this example is shared between integer types.
385 /// Which explains why `i64` is used here.
390 /// let n = 0x0123456789ABCDEFi64;
391 /// let m = -0x76543210FEDCBA99i64;
393 /// assert_eq!(n.rotate_left(32), m);
395 #[stable(feature = "rust1", since = "1.0.0")]
397 pub fn rotate_left(self, n: u32) -> Self {
398 (self as $UnsignedT).rotate_left(n) as Self
401 /// Shifts the bits to the right by a specified amount, `n`,
402 /// wrapping the truncated bits to the beginning of the resulting
405 /// Please note this isn't the same operation as `>>`!
409 /// Please note that this example is shared between integer types.
410 /// Which explains why `i64` is used here.
415 /// let n = 0x0123456789ABCDEFi64;
416 /// let m = -0xFEDCBA987654322i64;
418 /// assert_eq!(n.rotate_right(4), m);
420 #[stable(feature = "rust1", since = "1.0.0")]
422 pub fn rotate_right(self, n: u32) -> Self {
423 (self as $UnsignedT).rotate_right(n) as Self
426 /// Reverses the byte order of the integer.
430 /// Please note that this example is shared between integer types.
431 /// Which explains why `i16` is used here.
436 /// let n: i16 = 0b0000000_01010101;
437 /// assert_eq!(n, 85);
439 /// let m = n.swap_bytes();
441 /// assert_eq!(m, 0b01010101_00000000);
442 /// assert_eq!(m, 21760);
444 #[stable(feature = "rust1", since = "1.0.0")]
446 #[rustc_const_unstable(feature = "const_int_ops")]
448 pub const fn swap_bytes(self) -> Self {
449 (self as $UnsignedT).swap_bytes() as Self
452 /// Dummy docs. See !stage0 documentation.
453 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn swap_bytes(self) -> Self {
457 (self as $UnsignedT).swap_bytes() as Self
460 /// Reverses the bit pattern of the integer.
464 /// Please note that this example is shared between integer types.
465 /// Which explains why `i16` is used here.
470 /// #![feature(reverse_bits)]
472 /// let n: i16 = 0b0000000_01010101;
473 /// assert_eq!(n, 85);
475 /// let m = n.reverse_bits();
477 /// assert_eq!(m as u16, 0b10101010_00000000);
478 /// assert_eq!(m, -22016);
480 #[unstable(feature = "reverse_bits", issue = "48763")]
482 pub fn reverse_bits(self) -> Self {
483 (self as $UnsignedT).reverse_bits() as Self
487 concat!("Converts an integer from big endian to the target's endianness.
489 On big endian this is a no-op. On little endian the bytes are swapped.
496 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
498 if cfg!(target_endian = \"big\") {
499 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
501 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
505 #[stable(feature = "rust1", since = "1.0.0")]
507 #[rustc_const_unstable(feature = "const_int_ops")]
509 pub const fn from_be(x: Self) -> Self {
510 #[cfg(target_endian = "big")]
514 #[cfg(not(target_endian = "big"))]
522 concat!("Dummy docs. See !stage0 documentation"),
523 #[stable(feature = "rust1", since = "1.0.0")]
526 pub fn from_be(x: Self) -> Self {
527 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
532 concat!("Converts an integer from little endian to the target's endianness.
534 On little endian this is a no-op. On big endian the bytes are swapped.
541 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
543 if cfg!(target_endian = \"little\") {
544 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
546 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
550 #[stable(feature = "rust1", since = "1.0.0")]
552 #[rustc_const_unstable(feature = "const_int_ops")]
554 pub const fn from_le(x: Self) -> Self {
555 #[cfg(target_endian = "little")]
559 #[cfg(not(target_endian = "little"))]
567 concat!("Dummy docs. See !stage0 documentation"),
568 #[stable(feature = "rust1", since = "1.0.0")]
571 pub fn from_le(x: Self) -> Self {
572 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
577 concat!("Converts `self` to big endian from the target's endianness.
579 On big endian this is a no-op. On little endian the bytes are swapped.
586 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
588 if cfg!(target_endian = \"big\") {
589 assert_eq!(n.to_be(), n)
591 assert_eq!(n.to_be(), n.swap_bytes())
595 #[stable(feature = "rust1", since = "1.0.0")]
597 #[rustc_const_unstable(feature = "const_int_ops")]
599 pub const fn to_be(self) -> Self { // or not to be?
600 #[cfg(target_endian = "big")]
604 #[cfg(not(target_endian = "big"))]
612 concat!("Dummy docs. See !stage0 documentation"),
613 #[stable(feature = "rust1", since = "1.0.0")]
616 pub fn to_be(self) -> Self { // or not to be?
617 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
622 concat!("Converts `self` to little endian from the target's endianness.
624 On little endian this is a no-op. On big endian the bytes are swapped.
631 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
633 if cfg!(target_endian = \"little\") {
634 assert_eq!(n.to_le(), n)
636 assert_eq!(n.to_le(), n.swap_bytes())
640 #[stable(feature = "rust1", since = "1.0.0")]
642 #[rustc_const_unstable(feature = "const_int_ops")]
644 pub const fn to_le(self) -> Self {
645 #[cfg(target_endian = "little")]
649 #[cfg(not(target_endian = "little"))]
657 concat!("Dummy docs. See !stage0 documentation"),
658 #[stable(feature = "rust1", since = "1.0.0")]
661 pub fn to_le(self) -> Self {
662 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
667 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
668 if overflow occurred.
675 ", $Feature, "assert_eq!((", stringify!($SelfT),
676 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
677 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
680 #[stable(feature = "rust1", since = "1.0.0")]
682 pub fn checked_add(self, rhs: Self) -> Option<Self> {
683 let (a, b) = self.overflowing_add(rhs);
684 if b {None} else {Some(a)}
689 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
697 ", $Feature, "assert_eq!((", stringify!($SelfT),
698 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
699 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
702 #[stable(feature = "rust1", since = "1.0.0")]
704 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
705 let (a, b) = self.overflowing_sub(rhs);
706 if b {None} else {Some(a)}
711 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
719 ", $Feature, "assert_eq!(", stringify!($SelfT),
720 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
721 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
724 #[stable(feature = "rust1", since = "1.0.0")]
726 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
727 let (a, b) = self.overflowing_mul(rhs);
728 if b {None} else {Some(a)}
733 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
734 or the division results in overflow.
741 ", $Feature, "assert_eq!((", stringify!($SelfT),
742 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
743 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
744 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
747 #[stable(feature = "rust1", since = "1.0.0")]
749 pub fn checked_div(self, rhs: Self) -> Option<Self> {
750 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
753 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
759 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`,
760 returning `None` if `rhs == 0` or the division results in overflow.
767 #![feature(euclidean_division)]
768 assert_eq!((", stringify!($SelfT),
769 "::min_value() + 1).checked_div_euc(-1), Some(", stringify!($Max), "));
770 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euc(-1), None);
771 assert_eq!((1", stringify!($SelfT), ").checked_div_euc(0), None);
773 #[unstable(feature = "euclidean_division", issue = "49048")]
775 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
776 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
779 Some(self.div_euc(rhs))
785 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
786 `rhs == 0` or the division results in overflow.
793 ", $Feature, "use std::", stringify!($SelfT), ";
795 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
796 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
797 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
800 #[stable(feature = "wrapping", since = "1.7.0")]
802 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
803 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
806 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
812 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None` if
813 `rhs == 0` or the division results in overflow.
820 #![feature(euclidean_division)]
821 use std::", stringify!($SelfT), ";
823 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
824 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
825 assert_eq!(", stringify!($SelfT), "::MIN.checked_mod_euc(-1), None);
827 #[unstable(feature = "euclidean_division", issue = "49048")]
829 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
830 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
833 Some(self.mod_euc(rhs))
839 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
846 ", $Feature, "use std::", stringify!($SelfT), ";
848 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
849 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
852 #[stable(feature = "wrapping", since = "1.7.0")]
854 pub fn checked_neg(self) -> Option<Self> {
855 let (a, b) = self.overflowing_neg();
856 if b {None} else {Some(a)}
861 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
862 than or equal to the number of bits in `self`.
869 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
870 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
873 #[stable(feature = "wrapping", since = "1.7.0")]
875 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
876 let (a, b) = self.overflowing_shl(rhs);
877 if b {None} else {Some(a)}
882 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
883 larger than or equal to the number of bits in `self`.
890 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
891 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
894 #[stable(feature = "wrapping", since = "1.7.0")]
896 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
897 let (a, b) = self.overflowing_shr(rhs);
898 if b {None} else {Some(a)}
903 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
911 ", $Feature, "use std::", stringify!($SelfT), ";
913 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
914 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
917 #[stable(feature = "no_panic_abs", since = "1.13.0")]
919 pub fn checked_abs(self) -> Option<Self> {
920 if self.is_negative() {
929 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
937 #![feature(no_panic_pow)]
938 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
939 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
943 #[unstable(feature = "no_panic_pow", issue = "48320")]
945 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
947 let mut acc: Self = 1;
951 acc = acc.checked_mul(base)?;
954 base = base.checked_mul(base)?;
957 // Deal with the final bit of the exponent separately, since
958 // squaring the base afterwards is not necessary and may cause a
959 // needless overflow.
961 acc = acc.checked_mul(base)?;
969 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
970 bounds instead of overflowing.
977 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
978 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
982 #[stable(feature = "rust1", since = "1.0.0")]
984 pub fn saturating_add(self, rhs: Self) -> Self {
985 match self.checked_add(rhs) {
987 None if rhs >= 0 => Self::max_value(),
988 None => Self::min_value(),
994 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
995 numeric bounds instead of overflowing.
1002 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
1003 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
1007 #[stable(feature = "rust1", since = "1.0.0")]
1009 pub fn saturating_sub(self, rhs: Self) -> Self {
1010 match self.checked_sub(rhs) {
1012 None if rhs >= 0 => Self::min_value(),
1013 None => Self::max_value(),
1019 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1020 numeric bounds instead of overflowing.
1027 ", $Feature, "use std::", stringify!($SelfT), ";
1029 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1030 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1031 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1034 #[stable(feature = "wrapping", since = "1.7.0")]
1036 pub fn saturating_mul(self, rhs: Self) -> Self {
1037 self.checked_mul(rhs).unwrap_or_else(|| {
1038 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
1048 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1049 saturating at the numeric bounds instead of overflowing.
1056 #![feature(no_panic_pow)]
1057 ", $Feature, "use std::", stringify!($SelfT), ";
1059 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1060 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1061 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1064 #[unstable(feature = "no_panic_pow", issue = "48320")]
1066 pub fn saturating_pow(self, exp: u32) -> Self {
1067 match self.checked_pow(exp) {
1069 None if self < 0 && exp % 2 == 1 => Self::min_value(),
1070 None => Self::max_value(),
1076 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1077 boundary of the type.
1084 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1085 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
1086 "::min_value() + 1);",
1089 #[stable(feature = "rust1", since = "1.0.0")]
1091 pub fn wrapping_add(self, rhs: Self) -> Self {
1093 intrinsics::overflowing_add(self, rhs)
1099 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1100 boundary of the type.
1107 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1108 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1109 stringify!($SelfT), "::max_value());",
1112 #[stable(feature = "rust1", since = "1.0.0")]
1114 pub fn wrapping_sub(self, rhs: Self) -> Self {
1116 intrinsics::overflowing_sub(self, rhs)
1122 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1123 the boundary of the type.
1130 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1131 assert_eq!(11i8.wrapping_mul(12), -124);",
1134 #[stable(feature = "rust1", since = "1.0.0")]
1136 pub fn wrapping_mul(self, rhs: Self) -> Self {
1138 intrinsics::overflowing_mul(self, rhs)
1144 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1145 boundary of the type.
1147 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1148 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1149 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1153 This function will panic if `rhs` is 0.
1160 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1161 assert_eq!((-128i8).wrapping_div(-1), -128);",
1164 #[stable(feature = "num_wrapping", since = "1.2.0")]
1166 pub fn wrapping_div(self, rhs: Self) -> Self {
1167 self.overflowing_div(rhs).0
1172 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`,
1173 wrapping around at the boundary of the type.
1175 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1176 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1177 type. In this case, this method returns `MIN` itself.
1181 This function will panic if `rhs` is 0.
1188 #![feature(euclidean_division)]
1189 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
1190 assert_eq!((-128i8).wrapping_div_euc(-1), -128);
1192 #[unstable(feature = "euclidean_division", issue = "49048")]
1194 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
1195 self.overflowing_div_euc(rhs).0
1200 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1201 boundary of the type.
1203 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1204 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1205 this function returns `0`.
1209 This function will panic if `rhs` is 0.
1216 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1217 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1220 #[stable(feature = "num_wrapping", since = "1.2.0")]
1222 pub fn wrapping_rem(self, rhs: Self) -> Self {
1223 self.overflowing_rem(rhs).0
1228 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`, wrapping around at the
1229 boundary of the type.
1231 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1232 for the type). In this case, this method returns 0.
1236 This function will panic if `rhs` is 0.
1243 #![feature(euclidean_division)]
1244 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
1245 assert_eq!((-128i8).wrapping_mod_euc(-1), 0);
1247 #[unstable(feature = "euclidean_division", issue = "49048")]
1249 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
1250 self.overflowing_mod_euc(rhs).0
1255 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1258 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1259 is the negative minimal value for the type); this is a positive value that is too large to represent
1260 in the type. In such a case, this function returns `MIN` itself.
1267 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1268 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1272 #[stable(feature = "num_wrapping", since = "1.2.0")]
1274 pub fn wrapping_neg(self) -> Self {
1275 self.overflowing_neg().0
1280 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1281 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1283 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1284 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1285 The primitive integer types all implement a `rotate_left` function, which may be what you want
1293 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1294 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1297 #[stable(feature = "num_wrapping", since = "1.2.0")]
1299 pub fn wrapping_shl(self, rhs: u32) -> Self {
1301 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1307 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1308 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1310 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1311 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1312 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1320 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1321 assert_eq!((-128i16).wrapping_shr(64), -128);",
1324 #[stable(feature = "num_wrapping", since = "1.2.0")]
1326 pub fn wrapping_shr(self, rhs: u32) -> Self {
1328 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1334 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1335 the boundary of the type.
1337 The only case where such wrapping can occur is when one takes the absolute value of the negative
1338 minimal value for the type this is a positive value that is too large to represent in the type. In
1339 such a case, this function returns `MIN` itself.
1346 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1347 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1348 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1350 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1353 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1355 pub fn wrapping_abs(self) -> Self {
1356 if self.is_negative() {
1365 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1366 wrapping around at the boundary of the type.
1373 #![feature(no_panic_pow)]
1374 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1375 assert_eq!(3i8.wrapping_pow(5), -13);
1376 assert_eq!(3i8.wrapping_pow(6), -39);",
1379 #[unstable(feature = "no_panic_pow", issue = "48320")]
1381 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1382 let mut base = self;
1383 let mut acc: Self = 1;
1387 acc = acc.wrapping_mul(base);
1390 base = base.wrapping_mul(base);
1393 // Deal with the final bit of the exponent separately, since
1394 // squaring the base afterwards is not necessary and may cause a
1395 // needless overflow.
1397 acc = acc.wrapping_mul(base);
1405 concat!("Calculates `self` + `rhs`
1407 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1408 occur. If an overflow would have occurred then the wrapped value is returned.
1415 ", $Feature, "use std::", stringify!($SelfT), ";
1417 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1418 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1419 "::MIN, true));", $EndFeature, "
1422 #[stable(feature = "wrapping", since = "1.7.0")]
1423 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1424 let (a, b) = unsafe {
1425 intrinsics::add_with_overflow(self as $ActualT,
1433 concat!("Calculates `self` - `rhs`
1435 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1436 would occur. If an overflow would have occurred then the wrapped value is returned.
1443 ", $Feature, "use std::", stringify!($SelfT), ";
1445 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1446 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1447 "::MAX, true));", $EndFeature, "
1450 #[stable(feature = "wrapping", since = "1.7.0")]
1451 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1452 let (a, b) = unsafe {
1453 intrinsics::sub_with_overflow(self as $ActualT,
1461 concat!("Calculates the multiplication of `self` and `rhs`.
1463 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1464 would occur. If an overflow would have occurred then the wrapped value is returned.
1471 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1472 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1476 #[stable(feature = "wrapping", since = "1.7.0")]
1477 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1478 let (a, b) = unsafe {
1479 intrinsics::mul_with_overflow(self as $ActualT,
1487 concat!("Calculates the divisor when `self` is divided by `rhs`.
1489 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1490 occur. If an overflow would occur then self is returned.
1494 This function will panic if `rhs` is 0.
1501 ", $Feature, "use std::", stringify!($SelfT), ";
1503 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1504 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1509 #[stable(feature = "wrapping", since = "1.7.0")]
1510 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1511 if self == Self::min_value() && rhs == -1 {
1520 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
1522 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1523 occur. If an overflow would occur then `self` is returned.
1527 This function will panic if `rhs` is 0.
1534 #![feature(euclidean_division)]
1535 use std::", stringify!($SelfT), ";
1537 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
1538 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euc(-1), (", stringify!($SelfT),
1542 #[unstable(feature = "euclidean_division", issue = "49048")]
1543 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
1544 if self == Self::min_value() && rhs == -1 {
1547 (self.div_euc(rhs), false)
1553 concat!("Calculates the remainder when `self` is divided by `rhs`.
1555 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1556 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1560 This function will panic if `rhs` is 0.
1567 ", $Feature, "use std::", stringify!($SelfT), ";
1569 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1570 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1574 #[stable(feature = "wrapping", since = "1.7.0")]
1575 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1576 if self == Self::min_value() && rhs == -1 {
1586 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
1588 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1589 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1593 This function will panic if `rhs` is 0.
1600 #![feature(euclidean_division)]
1601 use std::", stringify!($SelfT), ";
1603 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
1604 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_mod_euc(-1), (0, true));
1606 #[unstable(feature = "euclidean_division", issue = "49048")]
1608 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
1609 if self == Self::min_value() && rhs == -1 {
1612 (self.mod_euc(rhs), false)
1619 concat!("Negates self, overflowing if this is equal to the minimum value.
1621 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1622 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1623 minimum value will be returned again and `true` will be returned for an overflow happening.
1630 ", $Feature, "use std::", stringify!($SelfT), ";
1632 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1633 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1634 "::MIN, true));", $EndFeature, "
1637 #[stable(feature = "wrapping", since = "1.7.0")]
1638 pub fn overflowing_neg(self) -> (Self, bool) {
1639 if self == Self::min_value() {
1640 (Self::min_value(), true)
1648 concat!("Shifts self left by `rhs` bits.
1650 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1651 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1652 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1659 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1660 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1664 #[stable(feature = "wrapping", since = "1.7.0")]
1665 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1666 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1671 concat!("Shifts self right by `rhs` bits.
1673 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1674 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1675 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1682 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1683 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1687 #[stable(feature = "wrapping", since = "1.7.0")]
1688 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1689 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1694 concat!("Computes the absolute value of `self`.
1696 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1697 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1698 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1699 for an overflow happening.
1706 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1707 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1708 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1709 "::min_value(), true));",
1712 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1714 pub fn overflowing_abs(self) -> (Self, bool) {
1715 if self.is_negative() {
1716 self.overflowing_neg()
1724 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1726 Returns a tuple of the exponentiation along with a bool indicating
1727 whether an overflow happened.
1734 #![feature(no_panic_pow)]
1735 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1736 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1739 #[unstable(feature = "no_panic_pow", issue = "48320")]
1741 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1742 let mut base = self;
1743 let mut acc: Self = 1;
1744 let mut overflown = false;
1745 // Scratch space for storing results of overflowing_mul.
1750 r = acc.overflowing_mul(base);
1755 r = base.overflowing_mul(base);
1760 // Deal with the final bit of the exponent separately, since
1761 // squaring the base afterwards is not necessary and may cause a
1762 // needless overflow.
1764 r = acc.overflowing_mul(base);
1774 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1781 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1783 assert_eq!(x.pow(5), 32);",
1786 #[stable(feature = "rust1", since = "1.0.0")]
1788 #[rustc_inherit_overflow_checks]
1789 pub fn pow(self, mut exp: u32) -> Self {
1790 let mut base = self;
1801 // Deal with the final bit of the exponent separately, since
1802 // squaring the base afterwards is not necessary and may cause a
1803 // needless overflow.
1813 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1815 This computes the integer `n` such that `self = n * rhs + self.mod_euc(rhs)`.
1816 In other words, the result is `self / rhs` rounded to the integer `n`
1817 such that `self >= n * rhs`.
1821 This function will panic if `rhs` is 0.
1828 #![feature(euclidean_division)]
1829 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1832 assert_eq!(a.div_euc(b), 1); // 7 >= 4 * 1
1833 assert_eq!(a.div_euc(-b), -1); // 7 >= -4 * -1
1834 assert_eq!((-a).div_euc(b), -2); // -7 >= 4 * -2
1835 assert_eq!((-a).div_euc(-b), 2); // -7 >= -4 * 2
1837 #[unstable(feature = "euclidean_division", issue = "49048")]
1839 #[rustc_inherit_overflow_checks]
1840 pub fn div_euc(self, rhs: Self) -> Self {
1843 return if rhs > 0 { q - 1 } else { q + 1 }
1851 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
1853 In particular, the result `n` satisfies `0 <= n < rhs.abs()`.
1857 This function will panic if `rhs` is 0.
1864 #![feature(euclidean_division)]
1865 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1868 assert_eq!(a.mod_euc(b), 3);
1869 assert_eq!((-a).mod_euc(b), 1);
1870 assert_eq!(a.mod_euc(-b), 3);
1871 assert_eq!((-a).mod_euc(-b), 1);
1873 #[unstable(feature = "euclidean_division", issue = "49048")]
1875 #[rustc_inherit_overflow_checks]
1876 pub fn mod_euc(self, rhs: Self) -> Self {
1891 concat!("Computes the absolute value of `self`.
1895 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1896 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1897 code in debug mode will trigger a panic on this case and optimized code will return `",
1898 stringify!($SelfT), "::min_value()` without a panic.
1905 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1906 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1909 #[stable(feature = "rust1", since = "1.0.0")]
1911 #[rustc_inherit_overflow_checks]
1912 pub fn abs(self) -> Self {
1913 if self.is_negative() {
1914 // Note that the #[inline] above means that the overflow
1915 // semantics of this negation depend on the crate we're being
1925 concat!("Returns a number representing sign of `self`.
1927 - `0` if the number is zero
1928 - `1` if the number is positive
1929 - `-1` if the number is negative
1936 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1937 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1938 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1941 #[stable(feature = "rust1", since = "1.0.0")]
1943 pub fn signum(self) -> Self {
1953 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1961 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1962 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1965 #[stable(feature = "rust1", since = "1.0.0")]
1967 pub fn is_positive(self) -> bool { self > 0 }
1971 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1979 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1980 assert!(!10", stringify!($SelfT), ".is_negative());",
1983 #[stable(feature = "rust1", since = "1.0.0")]
1985 pub fn is_negative(self) -> bool { self < 0 }
1988 /// Return the memory representation of this integer as a byte array.
1990 /// The target platform’s native endianness is used.
1991 /// Portable code likely wants to use this after [`to_be`] or [`to_le`].
1993 /// [`to_be`]: #method.to_be
1994 /// [`to_le`]: #method.to_le
1999 /// #![feature(int_to_from_bytes)]
2001 /// let bytes = i32::min_value().to_be().to_bytes();
2002 /// assert_eq!(bytes, [0x80, 0, 0, 0]);
2004 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
2006 pub fn to_bytes(self) -> [u8; mem::size_of::<Self>()] {
2007 unsafe { mem::transmute(self) }
2010 /// Create an integer value from its memory representation as a byte array.
2012 /// The target platform’s native endianness is used.
2013 /// Portable code likely wants to use [`from_be`] or [`from_le`] after this.
2015 /// [`from_be`]: #method.from_be
2016 /// [`from_le`]: #method.from_le
2021 /// #![feature(int_to_from_bytes)]
2023 /// let int = i32::from_be(i32::from_bytes([0x80, 0, 0, 0]));
2024 /// assert_eq!(int, i32::min_value());
2026 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
2028 pub fn from_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2029 unsafe { mem::transmute(bytes) }
2036 int_impl! { i8, i8, u8, 8, -128, 127, "", "" }
2041 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "" }
2046 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "" }
2051 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
2056 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2057 170141183460469231731687303715884105727, "", "" }
2060 #[cfg(target_pointer_width = "16")]
2063 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "" }
2066 #[cfg(target_pointer_width = "32")]
2069 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "" }
2072 #[cfg(target_pointer_width = "64")]
2075 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
2078 // Emits the correct `cttz` call, depending on the size of the type.
2079 macro_rules! uint_cttz_call {
2080 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
2081 // emits two conditional moves on x86_64. By promoting the value to
2082 // u16 and setting bit 8, we get better code without any conditional
2084 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
2085 // pending, remove this workaround once LLVM generates better code
2087 ($value:expr, 8) => { intrinsics::cttz($value as u16 | 0x100) };
2088 ($value:expr, $_BITS:expr) => { intrinsics::cttz($value) }
2091 // `Int` + `UnsignedInt` implemented for unsigned integers
2092 macro_rules! uint_impl {
2093 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr) => {
2095 concat!("Returns the smallest value that can be represented by this integer type.
2102 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2104 #[stable(feature = "rust1", since = "1.0.0")]
2106 pub const fn min_value() -> Self { 0 }
2110 concat!("Returns the largest value that can be represented by this integer type.
2117 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2118 stringify!($MaxV), ");", $EndFeature, "
2120 #[stable(feature = "rust1", since = "1.0.0")]
2122 pub const fn max_value() -> Self { !0 }
2126 concat!("Converts a string slice in a given base to an integer.
2128 The string is expected to be an optional `+` sign
2130 Leading and trailing whitespace represent an error.
2131 Digits are a subset of these characters, depending on `radix`:
2139 This function panics if `radix` is not in the range from 2 to 36.
2146 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2149 #[stable(feature = "rust1", since = "1.0.0")]
2150 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2151 from_str_radix(src, radix)
2156 concat!("Returns the number of ones in the binary representation of `self`.
2163 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2165 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2167 #[stable(feature = "rust1", since = "1.0.0")]
2169 #[rustc_const_unstable(feature = "const_int_ops")]
2171 pub const fn count_ones(self) -> u32 {
2172 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
2177 concat!("Dummy docs. See !stage0 documentation"),
2178 #[stable(feature = "rust1", since = "1.0.0")]
2181 pub fn count_ones(self) -> u32 {
2182 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
2187 concat!("Returns the number of zeros in the binary representation of `self`.
2194 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2196 #[stable(feature = "rust1", since = "1.0.0")]
2198 #[rustc_const_unstable(feature = "const_int_ops")]
2200 pub const fn count_zeros(self) -> u32 {
2201 (!self).count_ones()
2206 concat!("Dummy docs. See !stage0 documentation"),
2207 #[stable(feature = "rust1", since = "1.0.0")]
2210 pub fn count_zeros(self) -> u32 {
2211 (!self).count_ones()
2216 concat!("Returns the number of leading zeros in the binary representation of `self`.
2223 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2225 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2227 #[stable(feature = "rust1", since = "1.0.0")]
2229 #[rustc_const_unstable(feature = "const_int_ops")]
2231 pub const fn leading_zeros(self) -> u32 {
2232 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
2237 concat!("Dummy docs. See !stage0 documentation"),
2238 #[stable(feature = "rust1", since = "1.0.0")]
2241 pub fn leading_zeros(self) -> u32 {
2242 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
2247 concat!("Returns the number of trailing zeros in the binary representation
2255 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2257 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2259 #[stable(feature = "rust1", since = "1.0.0")]
2261 #[rustc_const_unstable(feature = "const_int_ops")]
2263 pub const fn trailing_zeros(self) -> u32 {
2264 unsafe { uint_cttz_call!(self, $BITS) as u32 }
2269 concat!("Dummy docs. See !stage0 documentation"),
2270 #[stable(feature = "rust1", since = "1.0.0")]
2273 pub fn trailing_zeros(self) -> u32 {
2274 unsafe { uint_cttz_call!(self, $BITS) as u32 }
2278 /// Shifts the bits to the left by a specified amount, `n`,
2279 /// wrapping the truncated bits to the end of the resulting integer.
2281 /// Please note this isn't the same operation as `<<`!
2287 /// Please note that this example is shared between integer types.
2288 /// Which explains why `u64` is used here.
2291 /// let n = 0x0123456789ABCDEFu64;
2292 /// let m = 0x3456789ABCDEF012u64;
2294 /// assert_eq!(n.rotate_left(12), m);
2296 #[stable(feature = "rust1", since = "1.0.0")]
2298 pub fn rotate_left(self, n: u32) -> Self {
2299 // Protect against undefined behaviour for over-long bit shifts
2301 (self << n) | (self >> (($BITS - n) % $BITS))
2304 /// Shifts the bits to the right by a specified amount, `n`,
2305 /// wrapping the truncated bits to the beginning of the resulting
2308 /// Please note this isn't the same operation as `>>`!
2314 /// Please note that this example is shared between integer types.
2315 /// Which explains why `u64` is used here.
2318 /// let n = 0x0123456789ABCDEFu64;
2319 /// let m = 0xDEF0123456789ABCu64;
2321 /// assert_eq!(n.rotate_right(12), m);
2323 #[stable(feature = "rust1", since = "1.0.0")]
2325 pub fn rotate_right(self, n: u32) -> Self {
2326 // Protect against undefined behaviour for over-long bit shifts
2328 (self >> n) | (self << (($BITS - n) % $BITS))
2331 /// Reverses the byte order of the integer.
2337 /// Please note that this example is shared between integer types.
2338 /// Which explains why `u16` is used here.
2341 /// let n: u16 = 0b0000000_01010101;
2342 /// assert_eq!(n, 85);
2344 /// let m = n.swap_bytes();
2346 /// assert_eq!(m, 0b01010101_00000000);
2347 /// assert_eq!(m, 21760);
2349 #[stable(feature = "rust1", since = "1.0.0")]
2351 #[rustc_const_unstable(feature = "const_int_ops")]
2353 pub const fn swap_bytes(self) -> Self {
2354 unsafe { intrinsics::bswap(self as $ActualT) as Self }
2357 /// Dummy docs. See !stage0 documentation.
2358 #[stable(feature = "rust1", since = "1.0.0")]
2361 pub fn swap_bytes(self) -> Self {
2362 unsafe { intrinsics::bswap(self as $ActualT) as Self }
2365 /// Reverses the bit pattern of the integer.
2371 /// Please note that this example is shared between integer types.
2372 /// Which explains why `u16` is used here.
2375 /// #![feature(reverse_bits)]
2377 /// let n: u16 = 0b0000000_01010101;
2378 /// assert_eq!(n, 85);
2380 /// let m = n.reverse_bits();
2382 /// assert_eq!(m, 0b10101010_00000000);
2383 /// assert_eq!(m, 43520);
2385 #[unstable(feature = "reverse_bits", issue = "48763")]
2387 pub fn reverse_bits(self) -> Self {
2388 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
2392 concat!("Converts an integer from big endian to the target's endianness.
2394 On big endian this is a no-op. On little endian the bytes are
2402 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2404 if cfg!(target_endian = \"big\") {
2405 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2407 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2410 #[stable(feature = "rust1", since = "1.0.0")]
2412 #[rustc_const_unstable(feature = "const_int_ops")]
2414 pub const fn from_be(x: Self) -> Self {
2415 #[cfg(target_endian = "big")]
2419 #[cfg(not(target_endian = "big"))]
2427 concat!("Dummy docs. See !stage0 documentation"),
2428 #[stable(feature = "rust1", since = "1.0.0")]
2431 pub fn from_be(x: Self) -> Self {
2432 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
2437 concat!("Converts an integer from little endian to the target's endianness.
2439 On little endian this is a no-op. On big endian the bytes are
2447 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2449 if cfg!(target_endian = \"little\") {
2450 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2452 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2455 #[stable(feature = "rust1", since = "1.0.0")]
2457 #[rustc_const_unstable(feature = "const_int_ops")]
2459 pub const fn from_le(x: Self) -> Self {
2460 #[cfg(target_endian = "little")]
2464 #[cfg(not(target_endian = "little"))]
2472 concat!("Dummy docs. See !stage0 documentation"),
2473 #[stable(feature = "rust1", since = "1.0.0")]
2476 pub fn from_le(x: Self) -> Self {
2477 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
2482 concat!("Converts `self` to big endian from the target's endianness.
2484 On big endian this is a no-op. On little endian the bytes are
2492 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2494 if cfg!(target_endian = \"big\") {
2495 assert_eq!(n.to_be(), n)
2497 assert_eq!(n.to_be(), n.swap_bytes())
2500 #[stable(feature = "rust1", since = "1.0.0")]
2502 #[rustc_const_unstable(feature = "const_int_ops")]
2504 pub const fn to_be(self) -> Self { // or not to be?
2505 #[cfg(target_endian = "big")]
2509 #[cfg(not(target_endian = "big"))]
2517 concat!("Dummy docs. See !stage0 documentation"),
2518 #[stable(feature = "rust1", since = "1.0.0")]
2521 pub fn to_be(self) -> Self { // or not to be?
2522 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
2527 concat!("Converts `self` to little endian from the target's endianness.
2529 On little endian this is a no-op. On big endian the bytes are
2537 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2539 if cfg!(target_endian = \"little\") {
2540 assert_eq!(n.to_le(), n)
2542 assert_eq!(n.to_le(), n.swap_bytes())
2545 #[stable(feature = "rust1", since = "1.0.0")]
2547 #[rustc_const_unstable(feature = "const_int_ops")]
2549 pub const fn to_le(self) -> Self {
2550 #[cfg(target_endian = "little")]
2554 #[cfg(not(target_endian = "little"))]
2562 concat!("Dummy docs. See !stage0 documentation"),
2563 #[stable(feature = "rust1", since = "1.0.0")]
2566 pub fn to_le(self) -> Self {
2567 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
2572 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2573 if overflow occurred.
2580 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2581 "Some(", stringify!($SelfT), "::max_value() - 1));
2582 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2584 #[stable(feature = "rust1", since = "1.0.0")]
2586 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2587 let (a, b) = self.overflowing_add(rhs);
2588 if b {None} else {Some(a)}
2593 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2594 `None` if overflow occurred.
2601 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2602 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2604 #[stable(feature = "rust1", since = "1.0.0")]
2606 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2607 let (a, b) = self.overflowing_sub(rhs);
2608 if b {None} else {Some(a)}
2613 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2614 `None` if overflow occurred.
2621 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2622 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2624 #[stable(feature = "rust1", since = "1.0.0")]
2626 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2627 let (a, b) = self.overflowing_mul(rhs);
2628 if b {None} else {Some(a)}
2633 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2641 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2642 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2644 #[stable(feature = "rust1", since = "1.0.0")]
2646 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2649 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2655 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`, returning `None`
2663 #![feature(euclidean_division)]
2664 assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2665 assert_eq!(1", stringify!($SelfT), ".checked_div_euc(0), None);
2667 #[unstable(feature = "euclidean_division", issue = "49048")]
2669 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
2673 Some(self.div_euc(rhs))
2680 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2688 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2689 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2691 #[stable(feature = "wrapping", since = "1.7.0")]
2693 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2697 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2703 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None`
2711 #![feature(euclidean_division)]
2712 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
2713 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
2715 #[unstable(feature = "euclidean_division", issue = "49048")]
2717 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
2721 Some(self.mod_euc(rhs))
2727 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2730 Note that negating any positive integer will overflow.
2737 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2738 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2740 #[stable(feature = "wrapping", since = "1.7.0")]
2742 pub fn checked_neg(self) -> Option<Self> {
2743 let (a, b) = self.overflowing_neg();
2744 if b {None} else {Some(a)}
2749 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2750 if `rhs` is larger than or equal to the number of bits in `self`.
2757 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2758 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2760 #[stable(feature = "wrapping", since = "1.7.0")]
2762 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2763 let (a, b) = self.overflowing_shl(rhs);
2764 if b {None} else {Some(a)}
2769 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2770 if `rhs` is larger than or equal to the number of bits in `self`.
2777 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2778 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2780 #[stable(feature = "wrapping", since = "1.7.0")]
2782 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2783 let (a, b) = self.overflowing_shr(rhs);
2784 if b {None} else {Some(a)}
2789 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2797 #![feature(no_panic_pow)]
2798 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2799 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2801 #[unstable(feature = "no_panic_pow", issue = "48320")]
2803 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2804 let mut base = self;
2805 let mut acc: Self = 1;
2809 acc = acc.checked_mul(base)?;
2812 base = base.checked_mul(base)?;
2815 // Deal with the final bit of the exponent separately, since
2816 // squaring the base afterwards is not necessary and may cause a
2817 // needless overflow.
2819 acc = acc.checked_mul(base)?;
2827 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2828 the numeric bounds instead of overflowing.
2835 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2836 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2838 #[stable(feature = "rust1", since = "1.0.0")]
2840 pub fn saturating_add(self, rhs: Self) -> Self {
2841 match self.checked_add(rhs) {
2843 None => Self::max_value(),
2849 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2850 at the numeric bounds instead of overflowing.
2857 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2858 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2860 #[stable(feature = "rust1", since = "1.0.0")]
2862 pub fn saturating_sub(self, rhs: Self) -> Self {
2863 match self.checked_sub(rhs) {
2865 None => Self::min_value(),
2871 concat!("Saturating integer multiplication. Computes `self * rhs`,
2872 saturating at the numeric bounds instead of overflowing.
2879 ", $Feature, "use std::", stringify!($SelfT), ";
2881 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2882 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2883 "::MAX);", $EndFeature, "
2885 #[stable(feature = "wrapping", since = "1.7.0")]
2887 pub fn saturating_mul(self, rhs: Self) -> Self {
2888 self.checked_mul(rhs).unwrap_or(Self::max_value())
2893 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2894 saturating at the numeric bounds instead of overflowing.
2901 #![feature(no_panic_pow)]
2902 ", $Feature, "use std::", stringify!($SelfT), ";
2904 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2905 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2908 #[unstable(feature = "no_panic_pow", issue = "48320")]
2910 pub fn saturating_pow(self, exp: u32) -> Self {
2911 match self.checked_pow(exp) {
2913 None => Self::max_value(),
2919 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2920 wrapping around at the boundary of the type.
2927 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2928 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2931 #[stable(feature = "rust1", since = "1.0.0")]
2933 pub fn wrapping_add(self, rhs: Self) -> Self {
2935 intrinsics::overflowing_add(self, rhs)
2941 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2942 wrapping around at the boundary of the type.
2949 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2950 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2953 #[stable(feature = "rust1", since = "1.0.0")]
2955 pub fn wrapping_sub(self, rhs: Self) -> Self {
2957 intrinsics::overflowing_sub(self, rhs)
2962 /// Wrapping (modular) multiplication. Computes `self *
2963 /// rhs`, wrapping around at the boundary of the type.
2969 /// Please note that this example is shared between integer types.
2970 /// Which explains why `u8` is used here.
2973 /// assert_eq!(10u8.wrapping_mul(12), 120);
2974 /// assert_eq!(25u8.wrapping_mul(12), 44);
2976 #[stable(feature = "rust1", since = "1.0.0")]
2978 pub fn wrapping_mul(self, rhs: Self) -> Self {
2980 intrinsics::overflowing_mul(self, rhs)
2985 concat!("Wrapping (modular) division. Computes `self / rhs`.
2986 Wrapped division on unsigned types is just normal division.
2987 There's no way wrapping could ever happen.
2988 This function exists, so that all operations
2989 are accounted for in the wrapping operations.
2996 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2998 #[stable(feature = "num_wrapping", since = "1.2.0")]
3000 pub fn wrapping_div(self, rhs: Self) -> Self {
3006 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`.
3007 Wrapped division on unsigned types is just normal division.
3008 There's no way wrapping could ever happen.
3009 This function exists, so that all operations
3010 are accounted for in the wrapping operations.
3017 #![feature(euclidean_division)]
3018 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
3020 #[unstable(feature = "euclidean_division", issue = "49048")]
3022 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
3028 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3029 Wrapped remainder calculation on unsigned types is
3030 just the regular remainder calculation.
3031 There's no way wrapping could ever happen.
3032 This function exists, so that all operations
3033 are accounted for in the wrapping operations.
3040 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3042 #[stable(feature = "num_wrapping", since = "1.2.0")]
3044 pub fn wrapping_rem(self, rhs: Self) -> Self {
3050 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`.
3051 Wrapped modulo calculation on unsigned types is
3052 just the regular remainder calculation.
3053 There's no way wrapping could ever happen.
3054 This function exists, so that all operations
3055 are accounted for in the wrapping operations.
3062 #![feature(euclidean_division)]
3063 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
3065 #[unstable(feature = "euclidean_division", issue = "49048")]
3067 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
3072 /// Wrapping (modular) negation. Computes `-self`,
3073 /// wrapping around at the boundary of the type.
3075 /// Since unsigned types do not have negative equivalents
3076 /// all applications of this function will wrap (except for `-0`).
3077 /// For values smaller than the corresponding signed type's maximum
3078 /// the result is the same as casting the corresponding signed value.
3079 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3080 /// `MAX` is the corresponding signed type's maximum.
3086 /// Please note that this example is shared between integer types.
3087 /// Which explains why `i8` is used here.
3090 /// assert_eq!(100i8.wrapping_neg(), -100);
3091 /// assert_eq!((-128i8).wrapping_neg(), -128);
3093 #[stable(feature = "num_wrapping", since = "1.2.0")]
3095 pub fn wrapping_neg(self) -> Self {
3096 self.overflowing_neg().0
3100 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3101 where `mask` removes any high-order bits of `rhs` that
3102 would cause the shift to exceed the bitwidth of the type.
3104 Note that this is *not* the same as a rotate-left; the
3105 RHS of a wrapping shift-left is restricted to the range
3106 of the type, rather than the bits shifted out of the LHS
3107 being returned to the other end. The primitive integer
3108 types all implement a `rotate_left` function, which may
3109 be what you want instead.
3116 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3117 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3119 #[stable(feature = "num_wrapping", since = "1.2.0")]
3121 pub fn wrapping_shl(self, rhs: u32) -> Self {
3123 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3129 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3130 where `mask` removes any high-order bits of `rhs` that
3131 would cause the shift to exceed the bitwidth of the type.
3133 Note that this is *not* the same as a rotate-right; the
3134 RHS of a wrapping shift-right is restricted to the range
3135 of the type, rather than the bits shifted out of the LHS
3136 being returned to the other end. The primitive integer
3137 types all implement a `rotate_right` function, which may
3138 be what you want instead.
3145 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3146 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3148 #[stable(feature = "num_wrapping", since = "1.2.0")]
3150 pub fn wrapping_shr(self, rhs: u32) -> Self {
3152 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3158 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3159 wrapping around at the boundary of the type.
3166 #![feature(no_panic_pow)]
3167 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3168 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3170 #[unstable(feature = "no_panic_pow", issue = "48320")]
3172 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3173 let mut base = self;
3174 let mut acc: Self = 1;
3178 acc = acc.wrapping_mul(base);
3181 base = base.wrapping_mul(base);
3184 // Deal with the final bit of the exponent separately, since
3185 // squaring the base afterwards is not necessary and may cause a
3186 // needless overflow.
3188 acc = acc.wrapping_mul(base);
3196 concat!("Calculates `self` + `rhs`
3198 Returns a tuple of the addition along with a boolean indicating
3199 whether an arithmetic overflow would occur. If an overflow would
3200 have occurred then the wrapped value is returned.
3207 ", $Feature, "use std::", stringify!($SelfT), ";
3209 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3210 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3213 #[stable(feature = "wrapping", since = "1.7.0")]
3214 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3215 let (a, b) = unsafe {
3216 intrinsics::add_with_overflow(self as $ActualT,
3224 concat!("Calculates `self` - `rhs`
3226 Returns a tuple of the subtraction along with a boolean indicating
3227 whether an arithmetic overflow would occur. If an overflow would
3228 have occurred then the wrapped value is returned.
3235 ", $Feature, "use std::", stringify!($SelfT), ";
3237 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3238 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3242 #[stable(feature = "wrapping", since = "1.7.0")]
3243 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3244 let (a, b) = unsafe {
3245 intrinsics::sub_with_overflow(self as $ActualT,
3252 /// Calculates the multiplication of `self` and `rhs`.
3254 /// Returns a tuple of the multiplication along with a boolean
3255 /// indicating whether an arithmetic overflow would occur. If an
3256 /// overflow would have occurred then the wrapped value is returned.
3262 /// Please note that this example is shared between integer types.
3263 /// Which explains why `u32` is used here.
3266 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3267 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3270 #[stable(feature = "wrapping", since = "1.7.0")]
3271 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3272 let (a, b) = unsafe {
3273 intrinsics::mul_with_overflow(self as $ActualT,
3280 concat!("Calculates the divisor when `self` is divided by `rhs`.
3282 Returns a tuple of the divisor along with a boolean indicating
3283 whether an arithmetic overflow would occur. Note that for unsigned
3284 integers overflow never occurs, so the second value is always
3289 This function will panic if `rhs` is 0.
3296 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3299 #[stable(feature = "wrapping", since = "1.7.0")]
3300 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3306 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
3308 Returns a tuple of the divisor along with a boolean indicating
3309 whether an arithmetic overflow would occur. Note that for unsigned
3310 integers overflow never occurs, so the second value is always
3315 This function will panic if `rhs` is 0.
3322 #![feature(euclidean_division)]
3323 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
3326 #[unstable(feature = "euclidean_division", issue = "49048")]
3327 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
3333 concat!("Calculates the remainder when `self` is divided by `rhs`.
3335 Returns a tuple of the remainder after dividing along with a boolean
3336 indicating whether an arithmetic overflow would occur. Note that for
3337 unsigned integers overflow never occurs, so the second value is
3342 This function will panic if `rhs` is 0.
3349 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3352 #[stable(feature = "wrapping", since = "1.7.0")]
3353 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3359 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
3361 Returns a tuple of the modulo after dividing along with a boolean
3362 indicating whether an arithmetic overflow would occur. Note that for
3363 unsigned integers overflow never occurs, so the second value is
3368 This function will panic if `rhs` is 0.
3375 #![feature(euclidean_division)]
3376 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
3379 #[unstable(feature = "euclidean_division", issue = "49048")]
3380 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
3386 concat!("Negates self in an overflowing fashion.
3388 Returns `!self + 1` using wrapping operations to return the value
3389 that represents the negation of this unsigned value. Note that for
3390 positive unsigned values overflow always occurs, but negating 0 does
3398 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3399 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3400 ", true));", $EndFeature, "
3403 #[stable(feature = "wrapping", since = "1.7.0")]
3404 pub fn overflowing_neg(self) -> (Self, bool) {
3405 ((!self).wrapping_add(1), self != 0)
3410 concat!("Shifts self left by `rhs` bits.
3412 Returns a tuple of the shifted version of self along with a boolean
3413 indicating whether the shift value was larger than or equal to the
3414 number of bits. If the shift value is too large, then value is
3415 masked (N-1) where N is the number of bits, and this value is then
3416 used to perform the shift.
3423 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3424 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3427 #[stable(feature = "wrapping", since = "1.7.0")]
3428 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3429 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3434 concat!("Shifts self right by `rhs` bits.
3436 Returns a tuple of the shifted version of self along with a boolean
3437 indicating whether the shift value was larger than or equal to the
3438 number of bits. If the shift value is too large, then value is
3439 masked (N-1) where N is the number of bits, and this value is then
3440 used to perform the shift.
3447 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3448 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3451 #[stable(feature = "wrapping", since = "1.7.0")]
3452 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3453 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3458 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3460 Returns a tuple of the exponentiation along with a bool indicating
3461 whether an overflow happened.
3468 #![feature(no_panic_pow)]
3469 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3470 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3472 #[unstable(feature = "no_panic_pow", issue = "48320")]
3474 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3475 let mut base = self;
3476 let mut acc: Self = 1;
3477 let mut overflown = false;
3478 // Scratch space for storing results of overflowing_mul.
3483 r = acc.overflowing_mul(base);
3488 r = base.overflowing_mul(base);
3493 // Deal with the final bit of the exponent separately, since
3494 // squaring the base afterwards is not necessary and may cause a
3495 // needless overflow.
3497 r = acc.overflowing_mul(base);
3507 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3514 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3516 #[stable(feature = "rust1", since = "1.0.0")]
3518 #[rustc_inherit_overflow_checks]
3519 pub fn pow(self, mut exp: u32) -> Self {
3520 let mut base = self;
3531 // Deal with the final bit of the exponent separately, since
3532 // squaring the base afterwards is not necessary and may cause a
3533 // needless overflow.
3543 concat!("Performs Euclidean division.
3545 For unsigned types, this is just the same as `self / rhs`.
3552 #![feature(euclidean_division)]
3553 assert_eq!(7", stringify!($SelfT), ".div_euc(4), 1); // or any other integer type
3555 #[unstable(feature = "euclidean_division", issue = "49048")]
3557 #[rustc_inherit_overflow_checks]
3558 pub fn div_euc(self, rhs: Self) -> Self {
3565 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
3567 For unsigned types, this is just the same as `self % rhs`.
3574 #![feature(euclidean_division)]
3575 assert_eq!(7", stringify!($SelfT), ".mod_euc(4), 3); // or any other integer type
3577 #[unstable(feature = "euclidean_division", issue = "49048")]
3579 #[rustc_inherit_overflow_checks]
3580 pub fn mod_euc(self, rhs: Self) -> Self {
3586 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3593 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3594 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3596 #[stable(feature = "rust1", since = "1.0.0")]
3598 pub fn is_power_of_two(self) -> bool {
3599 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3603 // Returns one less than next power of two.
3604 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3606 // 8u8.one_less_than_next_power_of_two() == 7
3607 // 6u8.one_less_than_next_power_of_two() == 7
3609 // This method cannot overflow, as in the `next_power_of_two`
3610 // overflow cases it instead ends up returning the maximum value
3611 // of the type, and can return 0 for 0.
3613 fn one_less_than_next_power_of_two(self) -> Self {
3614 if self <= 1 { return 0; }
3616 // Because `p > 0`, it cannot consist entirely of leading zeros.
3617 // That means the shift is always in-bounds, and some processors
3618 // (such as intel pre-haswell) have more efficient ctlz
3619 // intrinsics when the argument is non-zero.
3621 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3622 <$SelfT>::max_value() >> z
3626 concat!("Returns the smallest power of two greater than or equal to `self`.
3628 When return value overflows (i.e. `self > (1 << (N-1))` for type
3629 `uN`), it panics in debug mode and return value is wrapped to 0 in
3630 release mode (the only situation in which method can return 0).
3637 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3638 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3640 #[stable(feature = "rust1", since = "1.0.0")]
3642 pub fn next_power_of_two(self) -> Self {
3643 // Call the trait to get overflow checks
3644 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3649 concat!("Returns the smallest power of two greater than or equal to `n`. If
3650 the next power of two is greater than the type's maximum value,
3651 `None` is returned, otherwise the power of two is wrapped in `Some`.
3658 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3659 ".checked_next_power_of_two(), Some(2));
3660 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3661 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3664 #[stable(feature = "rust1", since = "1.0.0")]
3665 pub fn checked_next_power_of_two(self) -> Option<Self> {
3666 self.one_less_than_next_power_of_two().checked_add(1)
3671 concat!("Returns the smallest power of two greater than or equal to `n`. If
3672 the next power of two is greater than the type's maximum value,
3673 the return value is wrapped to `0`.
3680 #![feature(wrapping_next_power_of_two)]
3682 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3683 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3684 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3687 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3688 reason = "needs decision on wrapping behaviour")]
3689 pub fn wrapping_next_power_of_two(self) -> Self {
3690 self.one_less_than_next_power_of_two().wrapping_add(1)
3694 /// Return the memory representation of this integer as a byte array.
3696 /// The target platform’s native endianness is used.
3697 /// Portable code likely wants to use this after [`to_be`] or [`to_le`].
3699 /// [`to_be`]: #method.to_be
3700 /// [`to_le`]: #method.to_le
3705 /// #![feature(int_to_from_bytes)]
3707 /// let bytes = 0x1234_5678_u32.to_be().to_bytes();
3708 /// assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);
3710 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
3712 pub fn to_bytes(self) -> [u8; mem::size_of::<Self>()] {
3713 unsafe { mem::transmute(self) }
3716 /// Create an integer value from its memory representation as a byte array.
3718 /// The target platform’s native endianness is used.
3719 /// Portable code likely wants to use [`to_be`] or [`to_le`] after this.
3721 /// [`to_be`]: #method.to_be
3722 /// [`to_le`]: #method.to_le
3727 /// #![feature(int_to_from_bytes)]
3729 /// let int = u32::from_be(u32::from_bytes([0x12, 0x34, 0x56, 0x78]));
3730 /// assert_eq!(int, 0x1234_5678_u32);
3732 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
3734 pub fn from_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3735 unsafe { mem::transmute(bytes) }
3742 uint_impl! { u8, u8, 8, 255, "", "" }
3745 /// Checks if the value is within the ASCII range.
3750 /// let ascii = 97u8;
3751 /// let non_ascii = 150u8;
3753 /// assert!(ascii.is_ascii());
3754 /// assert!(!non_ascii.is_ascii());
3756 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3758 pub fn is_ascii(&self) -> bool {
3762 /// Makes a copy of the value in its ASCII upper case equivalent.
3764 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3765 /// but non-ASCII letters are unchanged.
3767 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
3772 /// let lowercase_a = 97u8;
3774 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
3777 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
3778 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3780 pub fn to_ascii_uppercase(&self) -> u8 {
3781 ASCII_UPPERCASE_MAP[*self as usize]
3784 /// Makes a copy of the value in its ASCII lower case equivalent.
3786 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3787 /// but non-ASCII letters are unchanged.
3789 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
3794 /// let uppercase_a = 65u8;
3796 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
3799 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
3800 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3802 pub fn to_ascii_lowercase(&self) -> u8 {
3803 ASCII_LOWERCASE_MAP[*self as usize]
3806 /// Checks that two values are an ASCII case-insensitive match.
3808 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3813 /// let lowercase_a = 97u8;
3814 /// let uppercase_a = 65u8;
3816 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3818 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3820 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3821 self.to_ascii_lowercase() == other.to_ascii_lowercase()
3824 /// Converts this value to its ASCII upper case equivalent in-place.
3826 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3827 /// but non-ASCII letters are unchanged.
3829 /// To return a new uppercased value without modifying the existing one, use
3830 /// [`to_ascii_uppercase`].
3835 /// let mut byte = b'a';
3837 /// byte.make_ascii_uppercase();
3839 /// assert_eq!(b'A', byte);
3842 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3843 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3845 pub fn make_ascii_uppercase(&mut self) {
3846 *self = self.to_ascii_uppercase();
3849 /// Converts this value to its ASCII lower case equivalent in-place.
3851 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3852 /// but non-ASCII letters are unchanged.
3854 /// To return a new lowercased value without modifying the existing one, use
3855 /// [`to_ascii_lowercase`].
3860 /// let mut byte = b'A';
3862 /// byte.make_ascii_lowercase();
3864 /// assert_eq!(b'a', byte);
3867 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3868 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3870 pub fn make_ascii_lowercase(&mut self) {
3871 *self = self.to_ascii_lowercase();
3874 /// Checks if the value is an ASCII alphabetic character:
3876 /// - U+0041 'A' ... U+005A 'Z', or
3877 /// - U+0061 'a' ... U+007A 'z'.
3882 /// #![feature(ascii_ctype)]
3884 /// let uppercase_a = b'A';
3885 /// let uppercase_g = b'G';
3888 /// let zero = b'0';
3889 /// let percent = b'%';
3890 /// let space = b' ';
3892 /// let esc = 0x1b_u8;
3894 /// assert!(uppercase_a.is_ascii_alphabetic());
3895 /// assert!(uppercase_g.is_ascii_alphabetic());
3896 /// assert!(a.is_ascii_alphabetic());
3897 /// assert!(g.is_ascii_alphabetic());
3898 /// assert!(!zero.is_ascii_alphabetic());
3899 /// assert!(!percent.is_ascii_alphabetic());
3900 /// assert!(!space.is_ascii_alphabetic());
3901 /// assert!(!lf.is_ascii_alphabetic());
3902 /// assert!(!esc.is_ascii_alphabetic());
3904 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3906 pub fn is_ascii_alphabetic(&self) -> bool {
3907 if *self >= 0x80 { return false; }
3908 match ASCII_CHARACTER_CLASS[*self as usize] {
3909 L | Lx | U | Ux => true,
3914 /// Checks if the value is an ASCII uppercase character:
3915 /// U+0041 'A' ... U+005A 'Z'.
3920 /// #![feature(ascii_ctype)]
3922 /// let uppercase_a = b'A';
3923 /// let uppercase_g = b'G';
3926 /// let zero = b'0';
3927 /// let percent = b'%';
3928 /// let space = b' ';
3930 /// let esc = 0x1b_u8;
3932 /// assert!(uppercase_a.is_ascii_uppercase());
3933 /// assert!(uppercase_g.is_ascii_uppercase());
3934 /// assert!(!a.is_ascii_uppercase());
3935 /// assert!(!g.is_ascii_uppercase());
3936 /// assert!(!zero.is_ascii_uppercase());
3937 /// assert!(!percent.is_ascii_uppercase());
3938 /// assert!(!space.is_ascii_uppercase());
3939 /// assert!(!lf.is_ascii_uppercase());
3940 /// assert!(!esc.is_ascii_uppercase());
3942 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3944 pub fn is_ascii_uppercase(&self) -> bool {
3945 if *self >= 0x80 { return false }
3946 match ASCII_CHARACTER_CLASS[*self as usize] {
3952 /// Checks if the value is an ASCII lowercase character:
3953 /// U+0061 'a' ... U+007A 'z'.
3958 /// #![feature(ascii_ctype)]
3960 /// let uppercase_a = b'A';
3961 /// let uppercase_g = b'G';
3964 /// let zero = b'0';
3965 /// let percent = b'%';
3966 /// let space = b' ';
3968 /// let esc = 0x1b_u8;
3970 /// assert!(!uppercase_a.is_ascii_lowercase());
3971 /// assert!(!uppercase_g.is_ascii_lowercase());
3972 /// assert!(a.is_ascii_lowercase());
3973 /// assert!(g.is_ascii_lowercase());
3974 /// assert!(!zero.is_ascii_lowercase());
3975 /// assert!(!percent.is_ascii_lowercase());
3976 /// assert!(!space.is_ascii_lowercase());
3977 /// assert!(!lf.is_ascii_lowercase());
3978 /// assert!(!esc.is_ascii_lowercase());
3980 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3982 pub fn is_ascii_lowercase(&self) -> bool {
3983 if *self >= 0x80 { return false }
3984 match ASCII_CHARACTER_CLASS[*self as usize] {
3990 /// Checks if the value is an ASCII alphanumeric character:
3992 /// - U+0041 'A' ... U+005A 'Z', or
3993 /// - U+0061 'a' ... U+007A 'z', or
3994 /// - U+0030 '0' ... U+0039 '9'.
3999 /// #![feature(ascii_ctype)]
4001 /// let uppercase_a = b'A';
4002 /// let uppercase_g = b'G';
4005 /// let zero = b'0';
4006 /// let percent = b'%';
4007 /// let space = b' ';
4009 /// let esc = 0x1b_u8;
4011 /// assert!(uppercase_a.is_ascii_alphanumeric());
4012 /// assert!(uppercase_g.is_ascii_alphanumeric());
4013 /// assert!(a.is_ascii_alphanumeric());
4014 /// assert!(g.is_ascii_alphanumeric());
4015 /// assert!(zero.is_ascii_alphanumeric());
4016 /// assert!(!percent.is_ascii_alphanumeric());
4017 /// assert!(!space.is_ascii_alphanumeric());
4018 /// assert!(!lf.is_ascii_alphanumeric());
4019 /// assert!(!esc.is_ascii_alphanumeric());
4021 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4023 pub fn is_ascii_alphanumeric(&self) -> bool {
4024 if *self >= 0x80 { return false }
4025 match ASCII_CHARACTER_CLASS[*self as usize] {
4026 D | L | Lx | U | Ux => true,
4031 /// Checks if the value is an ASCII decimal digit:
4032 /// U+0030 '0' ... U+0039 '9'.
4037 /// #![feature(ascii_ctype)]
4039 /// let uppercase_a = b'A';
4040 /// let uppercase_g = b'G';
4043 /// let zero = b'0';
4044 /// let percent = b'%';
4045 /// let space = b' ';
4047 /// let esc = 0x1b_u8;
4049 /// assert!(!uppercase_a.is_ascii_digit());
4050 /// assert!(!uppercase_g.is_ascii_digit());
4051 /// assert!(!a.is_ascii_digit());
4052 /// assert!(!g.is_ascii_digit());
4053 /// assert!(zero.is_ascii_digit());
4054 /// assert!(!percent.is_ascii_digit());
4055 /// assert!(!space.is_ascii_digit());
4056 /// assert!(!lf.is_ascii_digit());
4057 /// assert!(!esc.is_ascii_digit());
4059 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4061 pub fn is_ascii_digit(&self) -> bool {
4062 if *self >= 0x80 { return false }
4063 match ASCII_CHARACTER_CLASS[*self as usize] {
4069 /// Checks if the value is an ASCII hexadecimal digit:
4071 /// - U+0030 '0' ... U+0039 '9', or
4072 /// - U+0041 'A' ... U+0046 'F', or
4073 /// - U+0061 'a' ... U+0066 'f'.
4078 /// #![feature(ascii_ctype)]
4080 /// let uppercase_a = b'A';
4081 /// let uppercase_g = b'G';
4084 /// let zero = b'0';
4085 /// let percent = b'%';
4086 /// let space = b' ';
4088 /// let esc = 0x1b_u8;
4090 /// assert!(uppercase_a.is_ascii_hexdigit());
4091 /// assert!(!uppercase_g.is_ascii_hexdigit());
4092 /// assert!(a.is_ascii_hexdigit());
4093 /// assert!(!g.is_ascii_hexdigit());
4094 /// assert!(zero.is_ascii_hexdigit());
4095 /// assert!(!percent.is_ascii_hexdigit());
4096 /// assert!(!space.is_ascii_hexdigit());
4097 /// assert!(!lf.is_ascii_hexdigit());
4098 /// assert!(!esc.is_ascii_hexdigit());
4100 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4102 pub fn is_ascii_hexdigit(&self) -> bool {
4103 if *self >= 0x80 { return false }
4104 match ASCII_CHARACTER_CLASS[*self as usize] {
4105 D | Lx | Ux => true,
4110 /// Checks if the value is an ASCII punctuation character:
4112 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
4113 /// - U+003A ... U+0040 `: ; < = > ? @`, or
4114 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
4115 /// - U+007B ... U+007E `{ | } ~`
4120 /// #![feature(ascii_ctype)]
4122 /// let uppercase_a = b'A';
4123 /// let uppercase_g = b'G';
4126 /// let zero = b'0';
4127 /// let percent = b'%';
4128 /// let space = b' ';
4130 /// let esc = 0x1b_u8;
4132 /// assert!(!uppercase_a.is_ascii_punctuation());
4133 /// assert!(!uppercase_g.is_ascii_punctuation());
4134 /// assert!(!a.is_ascii_punctuation());
4135 /// assert!(!g.is_ascii_punctuation());
4136 /// assert!(!zero.is_ascii_punctuation());
4137 /// assert!(percent.is_ascii_punctuation());
4138 /// assert!(!space.is_ascii_punctuation());
4139 /// assert!(!lf.is_ascii_punctuation());
4140 /// assert!(!esc.is_ascii_punctuation());
4142 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4144 pub fn is_ascii_punctuation(&self) -> bool {
4145 if *self >= 0x80 { return false }
4146 match ASCII_CHARACTER_CLASS[*self as usize] {
4152 /// Checks if the value is an ASCII graphic character:
4153 /// U+0021 '!' ... U+007E '~'.
4158 /// #![feature(ascii_ctype)]
4160 /// let uppercase_a = b'A';
4161 /// let uppercase_g = b'G';
4164 /// let zero = b'0';
4165 /// let percent = b'%';
4166 /// let space = b' ';
4168 /// let esc = 0x1b_u8;
4170 /// assert!(uppercase_a.is_ascii_graphic());
4171 /// assert!(uppercase_g.is_ascii_graphic());
4172 /// assert!(a.is_ascii_graphic());
4173 /// assert!(g.is_ascii_graphic());
4174 /// assert!(zero.is_ascii_graphic());
4175 /// assert!(percent.is_ascii_graphic());
4176 /// assert!(!space.is_ascii_graphic());
4177 /// assert!(!lf.is_ascii_graphic());
4178 /// assert!(!esc.is_ascii_graphic());
4180 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4182 pub fn is_ascii_graphic(&self) -> bool {
4183 if *self >= 0x80 { return false; }
4184 match ASCII_CHARACTER_CLASS[*self as usize] {
4185 Ux | U | Lx | L | D | P => true,
4190 /// Checks if the value is an ASCII whitespace character:
4191 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4192 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4194 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4195 /// whitespace][infra-aw]. There are several other definitions in
4196 /// wide use. For instance, [the POSIX locale][pct] includes
4197 /// U+000B VERTICAL TAB as well as all the above characters,
4198 /// but—from the very same specification—[the default rule for
4199 /// "field splitting" in the Bourne shell][bfs] considers *only*
4200 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4202 /// If you are writing a program that will process an existing
4203 /// file format, check what that format's definition of whitespace is
4204 /// before using this function.
4206 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4207 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4208 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4213 /// #![feature(ascii_ctype)]
4215 /// let uppercase_a = b'A';
4216 /// let uppercase_g = b'G';
4219 /// let zero = b'0';
4220 /// let percent = b'%';
4221 /// let space = b' ';
4223 /// let esc = 0x1b_u8;
4225 /// assert!(!uppercase_a.is_ascii_whitespace());
4226 /// assert!(!uppercase_g.is_ascii_whitespace());
4227 /// assert!(!a.is_ascii_whitespace());
4228 /// assert!(!g.is_ascii_whitespace());
4229 /// assert!(!zero.is_ascii_whitespace());
4230 /// assert!(!percent.is_ascii_whitespace());
4231 /// assert!(space.is_ascii_whitespace());
4232 /// assert!(lf.is_ascii_whitespace());
4233 /// assert!(!esc.is_ascii_whitespace());
4235 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4237 pub fn is_ascii_whitespace(&self) -> bool {
4238 if *self >= 0x80 { return false; }
4239 match ASCII_CHARACTER_CLASS[*self as usize] {
4245 /// Checks if the value is an ASCII control character:
4246 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4247 /// Note that most ASCII whitespace characters are control
4248 /// characters, but SPACE is not.
4253 /// #![feature(ascii_ctype)]
4255 /// let uppercase_a = b'A';
4256 /// let uppercase_g = b'G';
4259 /// let zero = b'0';
4260 /// let percent = b'%';
4261 /// let space = b' ';
4263 /// let esc = 0x1b_u8;
4265 /// assert!(!uppercase_a.is_ascii_control());
4266 /// assert!(!uppercase_g.is_ascii_control());
4267 /// assert!(!a.is_ascii_control());
4268 /// assert!(!g.is_ascii_control());
4269 /// assert!(!zero.is_ascii_control());
4270 /// assert!(!percent.is_ascii_control());
4271 /// assert!(!space.is_ascii_control());
4272 /// assert!(lf.is_ascii_control());
4273 /// assert!(esc.is_ascii_control());
4275 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4277 pub fn is_ascii_control(&self) -> bool {
4278 if *self >= 0x80 { return false; }
4279 match ASCII_CHARACTER_CLASS[*self as usize] {
4288 uint_impl! { u16, u16, 16, 65535, "", "" }
4293 uint_impl! { u32, u32, 32, 4294967295, "", "" }
4298 uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
4303 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "" }
4306 #[cfg(target_pointer_width = "16")]
4309 uint_impl! { usize, u16, 16, 65536, "", "" }
4311 #[cfg(target_pointer_width = "32")]
4314 uint_impl! { usize, u32, 32, 4294967295, "", "" }
4317 #[cfg(target_pointer_width = "64")]
4320 uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
4323 /// A classification of floating point numbers.
4325 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4326 /// their documentation for more.
4328 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4329 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4334 /// use std::num::FpCategory;
4337 /// let num = 12.4_f32;
4338 /// let inf = f32::INFINITY;
4339 /// let zero = 0f32;
4340 /// let sub: f32 = 1.1754942e-38;
4341 /// let nan = f32::NAN;
4343 /// assert_eq!(num.classify(), FpCategory::Normal);
4344 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4345 /// assert_eq!(zero.classify(), FpCategory::Zero);
4346 /// assert_eq!(nan.classify(), FpCategory::Nan);
4347 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4349 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4350 #[stable(feature = "rust1", since = "1.0.0")]
4351 pub enum FpCategory {
4352 /// "Not a Number", often obtained by dividing by zero.
4353 #[stable(feature = "rust1", since = "1.0.0")]
4356 /// Positive or negative infinity.
4357 #[stable(feature = "rust1", since = "1.0.0")]
4360 /// Positive or negative zero.
4361 #[stable(feature = "rust1", since = "1.0.0")]
4364 /// De-normalized floating point representation (less precise than `Normal`).
4365 #[stable(feature = "rust1", since = "1.0.0")]
4368 /// A regular floating point number.
4369 #[stable(feature = "rust1", since = "1.0.0")]
4373 macro_rules! from_str_radix_int_impl {
4375 #[stable(feature = "rust1", since = "1.0.0")]
4376 impl FromStr for $t {
4377 type Err = ParseIntError;
4378 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4379 from_str_radix(src, 10)
4384 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4386 /// The error type returned when a checked integral type conversion fails.
4387 #[unstable(feature = "try_from", issue = "33417")]
4388 #[derive(Debug, Copy, Clone)]
4389 pub struct TryFromIntError(());
4391 impl TryFromIntError {
4392 #[unstable(feature = "int_error_internals",
4393 reason = "available through Error trait and this method should \
4394 not be exposed publicly",
4397 pub fn __description(&self) -> &str {
4398 "out of range integral type conversion attempted"
4402 #[unstable(feature = "try_from", issue = "33417")]
4403 impl fmt::Display for TryFromIntError {
4404 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4405 self.__description().fmt(fmt)
4409 #[unstable(feature = "try_from", issue = "33417")]
4410 impl From<!> for TryFromIntError {
4411 fn from(never: !) -> TryFromIntError {
4416 // only negative bounds
4417 macro_rules! try_from_lower_bounded {
4418 ($source:ty, $($target:ty),*) => {$(
4419 #[unstable(feature = "try_from", issue = "33417")]
4420 impl TryFrom<$source> for $target {
4421 type Error = TryFromIntError;
4424 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4428 Err(TryFromIntError(()))
4435 // unsigned to signed (only positive bound)
4436 macro_rules! try_from_upper_bounded {
4437 ($source:ty, $($target:ty),*) => {$(
4438 #[unstable(feature = "try_from", issue = "33417")]
4439 impl TryFrom<$source> for $target {
4440 type Error = TryFromIntError;
4443 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4444 if u > (<$target>::max_value() as $source) {
4445 Err(TryFromIntError(()))
4455 macro_rules! try_from_both_bounded {
4456 ($source:ty, $($target:ty),*) => {$(
4457 #[unstable(feature = "try_from", issue = "33417")]
4458 impl TryFrom<$source> for $target {
4459 type Error = TryFromIntError;
4462 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4463 let min = <$target>::min_value() as $source;
4464 let max = <$target>::max_value() as $source;
4465 if u < min || u > max {
4466 Err(TryFromIntError(()))
4476 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4477 $mac!($target, $source);
4481 /// intra-sign conversions
4482 try_from_upper_bounded!(u16, u8);
4483 try_from_upper_bounded!(u32, u16, u8);
4484 try_from_upper_bounded!(u64, u32, u16, u8);
4485 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4487 try_from_both_bounded!(i16, i8);
4488 try_from_both_bounded!(i32, i16, i8);
4489 try_from_both_bounded!(i64, i32, i16, i8);
4490 try_from_both_bounded!(i128, i64, i32, i16, i8);
4492 // unsigned-to-signed
4493 try_from_upper_bounded!(u8, i8);
4494 try_from_upper_bounded!(u16, i8, i16);
4495 try_from_upper_bounded!(u32, i8, i16, i32);
4496 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4497 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4499 // signed-to-unsigned
4500 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4501 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4502 try_from_lower_bounded!(i32, u32, u64, u128);
4503 try_from_lower_bounded!(i64, u64, u128);
4504 try_from_lower_bounded!(i128, u128);
4505 try_from_both_bounded!(i16, u8);
4506 try_from_both_bounded!(i32, u16, u8);
4507 try_from_both_bounded!(i64, u32, u16, u8);
4508 try_from_both_bounded!(i128, u64, u32, u16, u8);
4511 try_from_upper_bounded!(usize, isize);
4512 try_from_lower_bounded!(isize, usize);
4514 try_from_upper_bounded!(usize, u8);
4515 try_from_upper_bounded!(usize, i8, i16);
4516 try_from_both_bounded!(isize, u8);
4517 try_from_both_bounded!(isize, i8);
4519 #[cfg(target_pointer_width = "16")]
4520 mod ptr_try_from_impls {
4521 use super::TryFromIntError;
4522 use convert::TryFrom;
4524 // Fallible across platfoms, only implementation differs
4525 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4526 rev!(try_from_lower_bounded, usize, i8, i16);
4527 rev!(try_from_both_bounded, usize, i32, i64, i128);
4530 #[cfg(target_pointer_width = "32")]
4531 mod ptr_try_from_impls {
4532 use super::TryFromIntError;
4533 use convert::TryFrom;
4535 // Fallible across platfoms, only implementation differs
4536 try_from_both_bounded!(isize, u16);
4537 try_from_lower_bounded!(isize, u32, u64, u128);
4538 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4539 rev!(try_from_both_bounded, usize, i64, i128);
4542 #[cfg(target_pointer_width = "64")]
4543 mod ptr_try_from_impls {
4544 use super::TryFromIntError;
4545 use convert::TryFrom;
4547 // Fallible across platfoms, only implementation differs
4548 try_from_both_bounded!(isize, u16, u32);
4549 try_from_lower_bounded!(isize, u64, u128);
4550 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4551 rev!(try_from_both_bounded, usize, i128);
4555 trait FromStrRadixHelper: PartialOrd + Copy {
4556 fn min_value() -> Self;
4557 fn max_value() -> Self;
4558 fn from_u32(u: u32) -> Self;
4559 fn checked_mul(&self, other: u32) -> Option<Self>;
4560 fn checked_sub(&self, other: u32) -> Option<Self>;
4561 fn checked_add(&self, other: u32) -> Option<Self>;
4565 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4567 fn min_value() -> Self { Self::min_value() }
4569 fn max_value() -> Self { Self::max_value() }
4571 fn from_u32(u: u32) -> Self { u as Self }
4573 fn checked_mul(&self, other: u32) -> Option<Self> {
4574 Self::checked_mul(*self, other as Self)
4577 fn checked_sub(&self, other: u32) -> Option<Self> {
4578 Self::checked_sub(*self, other as Self)
4581 fn checked_add(&self, other: u32) -> Option<Self> {
4582 Self::checked_add(*self, other as Self)
4586 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4588 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4589 use self::IntErrorKind::*;
4590 use self::ParseIntError as PIE;
4592 assert!(radix >= 2 && radix <= 36,
4593 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4597 return Err(PIE { kind: Empty });
4600 let is_signed_ty = T::from_u32(0) > T::min_value();
4602 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4603 // and cast them to chars. .to_digit() will safely return None for anything
4604 // other than a valid ascii digit for the given radix, including the first-byte
4605 // of multi-byte sequences
4606 let src = src.as_bytes();
4608 let (is_positive, digits) = match src[0] {
4609 b'+' => (true, &src[1..]),
4610 b'-' if is_signed_ty => (false, &src[1..]),
4614 if digits.is_empty() {
4615 return Err(PIE { kind: Empty });
4618 let mut result = T::from_u32(0);
4620 // The number is positive
4622 let x = match (c as char).to_digit(radix) {
4624 None => return Err(PIE { kind: InvalidDigit }),
4626 result = match result.checked_mul(radix) {
4627 Some(result) => result,
4628 None => return Err(PIE { kind: Overflow }),
4630 result = match result.checked_add(x) {
4631 Some(result) => result,
4632 None => return Err(PIE { kind: Overflow }),
4636 // The number is negative
4638 let x = match (c as char).to_digit(radix) {
4640 None => return Err(PIE { kind: InvalidDigit }),
4642 result = match result.checked_mul(radix) {
4643 Some(result) => result,
4644 None => return Err(PIE { kind: Underflow }),
4646 result = match result.checked_sub(x) {
4647 Some(result) => result,
4648 None => return Err(PIE { kind: Underflow }),
4655 /// An error which can be returned when parsing an integer.
4657 /// This error is used as the error type for the `from_str_radix()` functions
4658 /// on the primitive integer types, such as [`i8::from_str_radix`].
4660 /// # Potential causes
4662 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
4663 /// in the string e.g. when it is obtained from the standard input.
4664 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
4666 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
4667 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
4668 #[derive(Debug, Clone, PartialEq, Eq)]
4669 #[stable(feature = "rust1", since = "1.0.0")]
4670 pub struct ParseIntError {
4674 #[derive(Debug, Clone, PartialEq, Eq)]
4682 impl ParseIntError {
4683 #[unstable(feature = "int_error_internals",
4684 reason = "available through Error trait and this method should \
4685 not be exposed publicly",
4688 pub fn __description(&self) -> &str {
4690 IntErrorKind::Empty => "cannot parse integer from empty string",
4691 IntErrorKind::InvalidDigit => "invalid digit found in string",
4692 IntErrorKind::Overflow => "number too large to fit in target type",
4693 IntErrorKind::Underflow => "number too small to fit in target type",
4698 #[stable(feature = "rust1", since = "1.0.0")]
4699 impl fmt::Display for ParseIntError {
4700 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4701 self.__description().fmt(f)
4705 #[stable(feature = "rust1", since = "1.0.0")]
4706 pub use num::dec2flt::ParseFloatError;
4708 // Conversion traits for primitive integer and float types
4709 // Conversions T -> T are covered by a blanket impl and therefore excluded
4710 // Some conversions from and to usize/isize are not implemented due to portability concerns
4711 macro_rules! impl_from {
4712 ($Small: ty, $Large: ty, #[$attr:meta]) => {
4714 impl From<$Small> for $Large {
4716 fn from(small: $Small) -> $Large {
4724 impl_from! { bool, u8, #[stable(feature = "from_bool", since = "1.28.0")] }
4725 impl_from! { bool, u16, #[stable(feature = "from_bool", since = "1.28.0")] }
4726 impl_from! { bool, u32, #[stable(feature = "from_bool", since = "1.28.0")] }
4727 impl_from! { bool, u64, #[stable(feature = "from_bool", since = "1.28.0")] }
4728 impl_from! { bool, u128, #[stable(feature = "from_bool", since = "1.28.0")] }
4729 impl_from! { bool, usize, #[stable(feature = "from_bool", since = "1.28.0")] }
4730 impl_from! { bool, i8, #[stable(feature = "from_bool", since = "1.28.0")] }
4731 impl_from! { bool, i16, #[stable(feature = "from_bool", since = "1.28.0")] }
4732 impl_from! { bool, i32, #[stable(feature = "from_bool", since = "1.28.0")] }
4733 impl_from! { bool, i64, #[stable(feature = "from_bool", since = "1.28.0")] }
4734 impl_from! { bool, i128, #[stable(feature = "from_bool", since = "1.28.0")] }
4735 impl_from! { bool, isize, #[stable(feature = "from_bool", since = "1.28.0")] }
4737 // Unsigned -> Unsigned
4738 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4739 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4740 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4741 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
4742 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4743 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4744 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4745 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
4746 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4747 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
4748 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
4751 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4752 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4753 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4754 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4755 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4756 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4757 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4758 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4759 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4760 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4761 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4763 // Unsigned -> Signed
4764 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4765 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4766 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4767 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4768 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4769 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4770 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4771 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4772 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4773 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4775 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
4776 // which imply that pointer-sized integers must be at least 16 bits:
4777 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
4778 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4779 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4780 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4782 // RISC-V defines the possibility of a 128-bit address space (RV128).
4784 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
4785 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
4786 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
4789 // Note: integers can only be represented with full precision in a float if
4790 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4791 // Lossy float conversions are not implemented at this time.
4794 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4795 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4796 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4797 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4798 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4800 // Unsigned -> Float
4801 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4802 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4803 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4804 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4805 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4808 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4810 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4811 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4812 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4813 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4814 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4815 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4816 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4817 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4818 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4821 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4822 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4823 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4826 b'[', b'\\', b']', b'^', b'_',
4827 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4828 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4829 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4830 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4831 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4832 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4833 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4834 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4835 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4836 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4837 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4838 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4839 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4840 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4841 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4842 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4843 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4844 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4845 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4846 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4849 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4850 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4851 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4852 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4853 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4854 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4855 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4856 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4857 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4858 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4859 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4860 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4861 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4864 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4865 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4866 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4869 b'{', b'|', b'}', b'~', 0x7f,
4870 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4871 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4872 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4873 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4874 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4875 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4876 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4877 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4878 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4879 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4880 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4881 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4882 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4883 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4884 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4885 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4888 enum AsciiCharacterClass {
4890 Cw, // control whitespace
4894 Lx, // lowercase hex digit
4896 Ux, // uppercase hex digit
4899 use self::AsciiCharacterClass::*;
4901 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4902 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4903 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4904 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4905 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4906 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4907 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4908 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4909 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4910 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_