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 enables some memory layout optimization.
43 /// For example, `Option<NonZeroU32>` is the same size as `u32`:
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)]
52 pub struct $Ty(NonZero<$Int>);
55 /// Create a non-zero without checking the value.
59 /// The value must not be zero.
60 #[stable(feature = "nonzero", since = "1.28.0")]
62 pub const unsafe fn new_unchecked(n: $Int) -> Self {
66 /// Create a non-zero if the given value is not zero.
67 #[stable(feature = "nonzero", since = "1.28.0")]
69 pub fn new(n: $Int) -> Option<Self> {
77 /// Returns the value as a primitive type.
78 #[stable(feature = "nonzero", since = "1.28.0")]
80 pub fn get(self) -> $Int {
87 (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
102 /// Provides intentionally-wrapped arithmetic on `T`.
104 /// Operations like `+` on `u32` values is intended to never overflow,
105 /// and in some debug configurations overflow is detected and results
106 /// in a panic. While most arithmetic falls into this category, some
107 /// code explicitly expects and relies upon modular arithmetic (e.g.,
110 /// Wrapping arithmetic can be achieved either through methods like
111 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
112 /// all standard arithmetic operations on the underlying value are
113 /// intended to have wrapping semantics.
118 /// use std::num::Wrapping;
120 /// let zero = Wrapping(0u32);
121 /// let one = Wrapping(1u32);
123 /// assert_eq!(std::u32::MAX, (zero - one).0);
125 #[stable(feature = "rust1", since = "1.0.0")]
126 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
128 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
131 #[stable(feature = "rust1", since = "1.0.0")]
132 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
133 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
138 #[stable(feature = "wrapping_display", since = "1.10.0")]
139 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
140 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
145 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
146 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
147 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
152 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
153 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
154 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
159 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
160 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
161 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
166 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
167 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
168 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
173 // All these modules are technically private and only exposed for coretests:
179 macro_rules! doc_comment {
180 ($x:expr, $($tt:tt)*) => {
188 // `Int` + `SignedInt` implemented for signed integers
189 macro_rules! int_impl {
190 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
191 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
194 concat!("Returns the smallest value that can be represented by this integer type.
201 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
204 #[stable(feature = "rust1", since = "1.0.0")]
206 pub const fn min_value() -> Self {
207 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
212 concat!("Returns the largest value that can be represented by this integer type.
219 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
222 #[stable(feature = "rust1", since = "1.0.0")]
224 pub const fn max_value() -> Self {
230 concat!("Converts a string slice in a given base to an integer.
232 The string is expected to be an optional `+` or `-` sign followed by digits.
233 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
234 depending on `radix`:
242 This function panics if `radix` is not in the range from 2 to 36.
249 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
252 #[stable(feature = "rust1", since = "1.0.0")]
253 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
254 from_str_radix(src, radix)
259 concat!("Returns the number of ones in the binary representation of `self`.
266 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
268 assert_eq!(n.count_ones(), 1);",
272 #[stable(feature = "rust1", since = "1.0.0")]
273 #[rustc_const_unstable(feature = "const_int_ops")]
275 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
279 concat!("Returns the number of zeros in the binary representation of `self`.
286 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
288 #[stable(feature = "rust1", since = "1.0.0")]
289 #[rustc_const_unstable(feature = "const_int_ops")]
291 pub const fn count_zeros(self) -> u32 {
297 concat!("Returns the number of leading zeros in the binary representation of `self`.
304 ", $Feature, "let n = -1", stringify!($SelfT), ";
306 assert_eq!(n.leading_zeros(), 0);",
309 #[stable(feature = "rust1", since = "1.0.0")]
310 #[rustc_const_unstable(feature = "const_int_ops")]
312 pub const fn leading_zeros(self) -> u32 {
313 (self as $UnsignedT).leading_zeros()
318 concat!("Returns the number of trailing zeros in the binary representation of `self`.
325 ", $Feature, "let n = -4", stringify!($SelfT), ";
327 assert_eq!(n.trailing_zeros(), 2);",
330 #[stable(feature = "rust1", since = "1.0.0")]
331 #[rustc_const_unstable(feature = "const_int_ops")]
333 pub const fn trailing_zeros(self) -> u32 {
334 (self as $UnsignedT).trailing_zeros()
339 concat!("Shifts the bits to the left by a specified amount, `n`,
340 wrapping the truncated bits to the end of the resulting integer.
342 Please note this isn't the same operation as `<<`!
349 let n = ", $rot_op, stringify!($SelfT), ";
350 let m = ", $rot_result, ";
352 assert_eq!(n.rotate_left(", $rot, "), m);
354 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn rotate_left(self, n: u32) -> Self {
357 (self as $UnsignedT).rotate_left(n) as Self
362 concat!("Shifts the bits to the right by a specified amount, `n`,
363 wrapping the truncated bits to the beginning of the resulting
366 Please note this isn't the same operation as `>>`!
373 let n = ", $rot_result, stringify!($SelfT), ";
374 let m = ", $rot_op, ";
376 assert_eq!(n.rotate_right(", $rot, "), m);
378 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn rotate_right(self, n: u32) -> Self {
381 (self as $UnsignedT).rotate_right(n) as Self
385 concat!("Reverses the byte order of the integer.
392 let n = ", $swap_op, stringify!($SelfT), ";
394 let m = n.swap_bytes();
396 assert_eq!(m, ", $swapped, ");
398 #[stable(feature = "rust1", since = "1.0.0")]
399 #[rustc_const_unstable(feature = "const_int_ops")]
401 pub const fn swap_bytes(self) -> Self {
402 (self as $UnsignedT).swap_bytes() as Self
407 concat!("Reverses the bit pattern of the integer.
414 #![feature(reverse_bits)]
416 let n = ", $swap_op, stringify!($SelfT), ";
417 let m = n.reverse_bits();
419 assert_eq!(m, ", $reversed, ");
421 #[unstable(feature = "reverse_bits", issue = "48763")]
423 pub fn reverse_bits(self) -> Self {
424 (self as $UnsignedT).reverse_bits() as Self
429 concat!("Converts an integer from big endian to the target's endianness.
431 On big endian this is a no-op. On little endian the bytes are swapped.
438 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
440 if cfg!(target_endian = \"big\") {
441 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
443 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
447 #[stable(feature = "rust1", since = "1.0.0")]
448 #[rustc_const_unstable(feature = "const_int_ops")]
450 pub const fn from_be(x: Self) -> Self {
451 #[cfg(target_endian = "big")]
455 #[cfg(not(target_endian = "big"))]
463 concat!("Converts an integer from little endian to the target's endianness.
465 On little endian this is a no-op. On big endian the bytes are swapped.
472 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
474 if cfg!(target_endian = \"little\") {
475 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
477 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
481 #[stable(feature = "rust1", since = "1.0.0")]
482 #[rustc_const_unstable(feature = "const_int_ops")]
484 pub const fn from_le(x: Self) -> Self {
485 #[cfg(target_endian = "little")]
489 #[cfg(not(target_endian = "little"))]
497 concat!("Converts `self` to big endian from the target's endianness.
499 On big endian this is a no-op. On little endian the bytes are swapped.
506 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
508 if cfg!(target_endian = \"big\") {
509 assert_eq!(n.to_be(), n)
511 assert_eq!(n.to_be(), n.swap_bytes())
515 #[stable(feature = "rust1", since = "1.0.0")]
516 #[rustc_const_unstable(feature = "const_int_ops")]
518 pub const fn to_be(self) -> Self { // or not to be?
519 #[cfg(target_endian = "big")]
523 #[cfg(not(target_endian = "big"))]
531 concat!("Converts `self` to little endian from the target's endianness.
533 On little endian this is a no-op. On big endian the bytes are swapped.
540 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
542 if cfg!(target_endian = \"little\") {
543 assert_eq!(n.to_le(), n)
545 assert_eq!(n.to_le(), n.swap_bytes())
549 #[stable(feature = "rust1", since = "1.0.0")]
550 #[rustc_const_unstable(feature = "const_int_ops")]
552 pub const fn to_le(self) -> Self {
553 #[cfg(target_endian = "little")]
557 #[cfg(not(target_endian = "little"))]
565 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
566 if overflow occurred.
573 ", $Feature, "assert_eq!((", stringify!($SelfT),
574 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
575 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
578 #[stable(feature = "rust1", since = "1.0.0")]
580 pub fn checked_add(self, rhs: Self) -> Option<Self> {
581 let (a, b) = self.overflowing_add(rhs);
582 if b {None} else {Some(a)}
587 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
595 ", $Feature, "assert_eq!((", stringify!($SelfT),
596 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
597 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
600 #[stable(feature = "rust1", since = "1.0.0")]
602 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
603 let (a, b) = self.overflowing_sub(rhs);
604 if b {None} else {Some(a)}
609 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
617 ", $Feature, "assert_eq!(", stringify!($SelfT),
618 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
619 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
622 #[stable(feature = "rust1", since = "1.0.0")]
624 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
625 let (a, b) = self.overflowing_mul(rhs);
626 if b {None} else {Some(a)}
631 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
632 or the division results in overflow.
639 ", $Feature, "assert_eq!((", stringify!($SelfT),
640 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
641 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
642 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
645 #[stable(feature = "rust1", since = "1.0.0")]
647 pub fn checked_div(self, rhs: Self) -> Option<Self> {
648 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
651 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
657 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`,
658 returning `None` if `rhs == 0` or the division results in overflow.
665 #![feature(euclidean_division)]
666 assert_eq!((", stringify!($SelfT),
667 "::min_value() + 1).checked_div_euc(-1), Some(", stringify!($Max), "));
668 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euc(-1), None);
669 assert_eq!((1", stringify!($SelfT), ").checked_div_euc(0), None);
671 #[unstable(feature = "euclidean_division", issue = "49048")]
673 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
674 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
677 Some(self.div_euc(rhs))
683 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
684 `rhs == 0` or the division results in overflow.
691 ", $Feature, "use std::", stringify!($SelfT), ";
693 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
694 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
695 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
698 #[stable(feature = "wrapping", since = "1.7.0")]
700 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
701 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
704 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
710 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None` if
711 `rhs == 0` or the division results in overflow.
718 #![feature(euclidean_division)]
719 use std::", stringify!($SelfT), ";
721 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
722 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
723 assert_eq!(", stringify!($SelfT), "::MIN.checked_mod_euc(-1), None);
725 #[unstable(feature = "euclidean_division", issue = "49048")]
727 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
728 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
731 Some(self.mod_euc(rhs))
737 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
744 ", $Feature, "use std::", stringify!($SelfT), ";
746 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
747 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
750 #[stable(feature = "wrapping", since = "1.7.0")]
752 pub fn checked_neg(self) -> Option<Self> {
753 let (a, b) = self.overflowing_neg();
754 if b {None} else {Some(a)}
759 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
760 than or equal to the number of bits in `self`.
767 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
768 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
771 #[stable(feature = "wrapping", since = "1.7.0")]
773 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
774 let (a, b) = self.overflowing_shl(rhs);
775 if b {None} else {Some(a)}
780 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
781 larger than or equal to the number of bits in `self`.
788 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
789 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
792 #[stable(feature = "wrapping", since = "1.7.0")]
794 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
795 let (a, b) = self.overflowing_shr(rhs);
796 if b {None} else {Some(a)}
801 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
809 ", $Feature, "use std::", stringify!($SelfT), ";
811 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
812 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
815 #[stable(feature = "no_panic_abs", since = "1.13.0")]
817 pub fn checked_abs(self) -> Option<Self> {
818 if self.is_negative() {
827 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
835 #![feature(no_panic_pow)]
836 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
837 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
841 #[unstable(feature = "no_panic_pow", issue = "48320")]
843 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
845 let mut acc: Self = 1;
849 acc = acc.checked_mul(base)?;
852 base = base.checked_mul(base)?;
855 // Deal with the final bit of the exponent separately, since
856 // squaring the base afterwards is not necessary and may cause a
857 // needless overflow.
859 acc = acc.checked_mul(base)?;
867 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
868 bounds instead of overflowing.
875 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
876 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
880 #[stable(feature = "rust1", since = "1.0.0")]
882 pub fn saturating_add(self, rhs: Self) -> Self {
883 match self.checked_add(rhs) {
885 None if rhs >= 0 => Self::max_value(),
886 None => Self::min_value(),
892 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
893 numeric bounds instead of overflowing.
900 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
901 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
905 #[stable(feature = "rust1", since = "1.0.0")]
907 pub fn saturating_sub(self, rhs: Self) -> Self {
908 match self.checked_sub(rhs) {
910 None if rhs >= 0 => Self::min_value(),
911 None => Self::max_value(),
917 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
918 numeric bounds instead of overflowing.
925 ", $Feature, "use std::", stringify!($SelfT), ";
927 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
928 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
929 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
932 #[stable(feature = "wrapping", since = "1.7.0")]
934 pub fn saturating_mul(self, rhs: Self) -> Self {
935 self.checked_mul(rhs).unwrap_or_else(|| {
936 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
946 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
947 saturating at the numeric bounds instead of overflowing.
954 #![feature(no_panic_pow)]
955 ", $Feature, "use std::", stringify!($SelfT), ";
957 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
958 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
959 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
962 #[unstable(feature = "no_panic_pow", issue = "48320")]
964 pub fn saturating_pow(self, exp: u32) -> Self {
965 match self.checked_pow(exp) {
967 None if self < 0 && exp % 2 == 1 => Self::min_value(),
968 None => Self::max_value(),
974 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
975 boundary of the type.
982 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
983 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
984 "::min_value() + 1);",
987 #[stable(feature = "rust1", since = "1.0.0")]
989 pub fn wrapping_add(self, rhs: Self) -> Self {
991 intrinsics::overflowing_add(self, rhs)
997 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
998 boundary of the type.
1005 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1006 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1007 stringify!($SelfT), "::max_value());",
1010 #[stable(feature = "rust1", since = "1.0.0")]
1012 pub fn wrapping_sub(self, rhs: Self) -> Self {
1014 intrinsics::overflowing_sub(self, rhs)
1020 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1021 the boundary of the type.
1028 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1029 assert_eq!(11i8.wrapping_mul(12), -124);",
1032 #[stable(feature = "rust1", since = "1.0.0")]
1034 pub fn wrapping_mul(self, rhs: Self) -> Self {
1036 intrinsics::overflowing_mul(self, rhs)
1042 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1043 boundary of the type.
1045 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1046 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1047 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1051 This function will panic if `rhs` is 0.
1058 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1059 assert_eq!((-128i8).wrapping_div(-1), -128);",
1062 #[stable(feature = "num_wrapping", since = "1.2.0")]
1064 pub fn wrapping_div(self, rhs: Self) -> Self {
1065 self.overflowing_div(rhs).0
1070 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`,
1071 wrapping around at the boundary of the type.
1073 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1074 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1075 type. In this case, this method returns `MIN` itself.
1079 This function will panic if `rhs` is 0.
1086 #![feature(euclidean_division)]
1087 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
1088 assert_eq!((-128i8).wrapping_div_euc(-1), -128);
1090 #[unstable(feature = "euclidean_division", issue = "49048")]
1092 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
1093 self.overflowing_div_euc(rhs).0
1098 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1099 boundary of the type.
1101 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1102 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1103 this function returns `0`.
1107 This function will panic if `rhs` is 0.
1114 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1115 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1118 #[stable(feature = "num_wrapping", since = "1.2.0")]
1120 pub fn wrapping_rem(self, rhs: Self) -> Self {
1121 self.overflowing_rem(rhs).0
1126 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`, wrapping around at the
1127 boundary of the type.
1129 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1130 for the type). In this case, this method returns 0.
1134 This function will panic if `rhs` is 0.
1141 #![feature(euclidean_division)]
1142 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
1143 assert_eq!((-128i8).wrapping_mod_euc(-1), 0);
1145 #[unstable(feature = "euclidean_division", issue = "49048")]
1147 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
1148 self.overflowing_mod_euc(rhs).0
1153 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1156 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1157 is the negative minimal value for the type); this is a positive value that is too large to represent
1158 in the type. In such a case, this function returns `MIN` itself.
1165 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1166 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1170 #[stable(feature = "num_wrapping", since = "1.2.0")]
1172 pub fn wrapping_neg(self) -> Self {
1173 self.overflowing_neg().0
1178 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1179 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1181 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1182 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1183 The primitive integer types all implement a `rotate_left` function, which may be what you want
1191 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1192 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1195 #[stable(feature = "num_wrapping", since = "1.2.0")]
1197 pub fn wrapping_shl(self, rhs: u32) -> Self {
1199 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1205 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1206 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1208 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1209 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1210 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1218 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1219 assert_eq!((-128i16).wrapping_shr(64), -128);",
1222 #[stable(feature = "num_wrapping", since = "1.2.0")]
1224 pub fn wrapping_shr(self, rhs: u32) -> Self {
1226 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1232 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1233 the boundary of the type.
1235 The only case where such wrapping can occur is when one takes the absolute value of the negative
1236 minimal value for the type this is a positive value that is too large to represent in the type. In
1237 such a case, this function returns `MIN` itself.
1244 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1245 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1246 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1248 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1251 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1253 pub fn wrapping_abs(self) -> Self {
1254 if self.is_negative() {
1263 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1264 wrapping around at the boundary of the type.
1271 #![feature(no_panic_pow)]
1272 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1273 assert_eq!(3i8.wrapping_pow(5), -13);
1274 assert_eq!(3i8.wrapping_pow(6), -39);",
1277 #[unstable(feature = "no_panic_pow", issue = "48320")]
1279 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1280 let mut base = self;
1281 let mut acc: Self = 1;
1285 acc = acc.wrapping_mul(base);
1288 base = base.wrapping_mul(base);
1291 // Deal with the final bit of the exponent separately, since
1292 // squaring the base afterwards is not necessary and may cause a
1293 // needless overflow.
1295 acc = acc.wrapping_mul(base);
1303 concat!("Calculates `self` + `rhs`
1305 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1306 occur. If an overflow would have occurred then the wrapped value is returned.
1313 ", $Feature, "use std::", stringify!($SelfT), ";
1315 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1316 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1317 "::MIN, true));", $EndFeature, "
1320 #[stable(feature = "wrapping", since = "1.7.0")]
1321 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1322 let (a, b) = unsafe {
1323 intrinsics::add_with_overflow(self as $ActualT,
1331 concat!("Calculates `self` - `rhs`
1333 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1334 would occur. If an overflow would have occurred then the wrapped value is returned.
1341 ", $Feature, "use std::", stringify!($SelfT), ";
1343 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1344 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1345 "::MAX, true));", $EndFeature, "
1348 #[stable(feature = "wrapping", since = "1.7.0")]
1349 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1350 let (a, b) = unsafe {
1351 intrinsics::sub_with_overflow(self as $ActualT,
1359 concat!("Calculates the multiplication of `self` and `rhs`.
1361 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1362 would occur. If an overflow would have occurred then the wrapped value is returned.
1369 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1370 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1374 #[stable(feature = "wrapping", since = "1.7.0")]
1375 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1376 let (a, b) = unsafe {
1377 intrinsics::mul_with_overflow(self as $ActualT,
1385 concat!("Calculates the divisor when `self` is divided by `rhs`.
1387 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1388 occur. If an overflow would occur then self is returned.
1392 This function will panic if `rhs` is 0.
1399 ", $Feature, "use std::", stringify!($SelfT), ";
1401 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1402 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1407 #[stable(feature = "wrapping", since = "1.7.0")]
1408 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1409 if self == Self::min_value() && rhs == -1 {
1418 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
1420 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1421 occur. If an overflow would occur then `self` is returned.
1425 This function will panic if `rhs` is 0.
1432 #![feature(euclidean_division)]
1433 use std::", stringify!($SelfT), ";
1435 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
1436 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euc(-1), (", stringify!($SelfT),
1440 #[unstable(feature = "euclidean_division", issue = "49048")]
1441 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
1442 if self == Self::min_value() && rhs == -1 {
1445 (self.div_euc(rhs), false)
1451 concat!("Calculates the remainder when `self` is divided by `rhs`.
1453 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1454 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1458 This function will panic if `rhs` is 0.
1465 ", $Feature, "use std::", stringify!($SelfT), ";
1467 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1468 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1472 #[stable(feature = "wrapping", since = "1.7.0")]
1473 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1474 if self == Self::min_value() && rhs == -1 {
1484 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
1486 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1487 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1491 This function will panic if `rhs` is 0.
1498 #![feature(euclidean_division)]
1499 use std::", stringify!($SelfT), ";
1501 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
1502 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_mod_euc(-1), (0, true));
1504 #[unstable(feature = "euclidean_division", issue = "49048")]
1506 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
1507 if self == Self::min_value() && rhs == -1 {
1510 (self.mod_euc(rhs), false)
1517 concat!("Negates self, overflowing if this is equal to the minimum value.
1519 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1520 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1521 minimum value will be returned again and `true` will be returned for an overflow happening.
1528 ", $Feature, "use std::", stringify!($SelfT), ";
1530 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1531 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1532 "::MIN, true));", $EndFeature, "
1535 #[stable(feature = "wrapping", since = "1.7.0")]
1536 pub fn overflowing_neg(self) -> (Self, bool) {
1537 if self == Self::min_value() {
1538 (Self::min_value(), true)
1546 concat!("Shifts self left by `rhs` bits.
1548 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1549 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1550 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1557 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1558 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1562 #[stable(feature = "wrapping", since = "1.7.0")]
1563 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1564 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1569 concat!("Shifts self right by `rhs` bits.
1571 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1572 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1573 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1580 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1581 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1585 #[stable(feature = "wrapping", since = "1.7.0")]
1586 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1587 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1592 concat!("Computes the absolute value of `self`.
1594 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1595 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1596 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1597 for an overflow happening.
1604 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1605 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1606 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1607 "::min_value(), true));",
1610 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1612 pub fn overflowing_abs(self) -> (Self, bool) {
1613 if self.is_negative() {
1614 self.overflowing_neg()
1622 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1624 Returns a tuple of the exponentiation along with a bool indicating
1625 whether an overflow happened.
1632 #![feature(no_panic_pow)]
1633 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1634 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1637 #[unstable(feature = "no_panic_pow", issue = "48320")]
1639 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1640 let mut base = self;
1641 let mut acc: Self = 1;
1642 let mut overflown = false;
1643 // Scratch space for storing results of overflowing_mul.
1648 r = acc.overflowing_mul(base);
1653 r = base.overflowing_mul(base);
1658 // Deal with the final bit of the exponent separately, since
1659 // squaring the base afterwards is not necessary and may cause a
1660 // needless overflow.
1662 r = acc.overflowing_mul(base);
1672 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1679 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1681 assert_eq!(x.pow(5), 32);",
1684 #[stable(feature = "rust1", since = "1.0.0")]
1686 #[rustc_inherit_overflow_checks]
1687 pub fn pow(self, mut exp: u32) -> Self {
1688 let mut base = self;
1699 // Deal with the final bit of the exponent separately, since
1700 // squaring the base afterwards is not necessary and may cause a
1701 // needless overflow.
1711 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1713 This computes the integer `n` such that `self = n * rhs + self.mod_euc(rhs)`.
1714 In other words, the result is `self / rhs` rounded to the integer `n`
1715 such that `self >= n * rhs`.
1719 This function will panic if `rhs` is 0.
1726 #![feature(euclidean_division)]
1727 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1730 assert_eq!(a.div_euc(b), 1); // 7 >= 4 * 1
1731 assert_eq!(a.div_euc(-b), -1); // 7 >= -4 * -1
1732 assert_eq!((-a).div_euc(b), -2); // -7 >= 4 * -2
1733 assert_eq!((-a).div_euc(-b), 2); // -7 >= -4 * 2
1735 #[unstable(feature = "euclidean_division", issue = "49048")]
1737 #[rustc_inherit_overflow_checks]
1738 pub fn div_euc(self, rhs: Self) -> Self {
1741 return if rhs > 0 { q - 1 } else { q + 1 }
1749 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
1751 In particular, the result `n` satisfies `0 <= n < rhs.abs()`.
1755 This function will panic if `rhs` is 0.
1762 #![feature(euclidean_division)]
1763 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1766 assert_eq!(a.mod_euc(b), 3);
1767 assert_eq!((-a).mod_euc(b), 1);
1768 assert_eq!(a.mod_euc(-b), 3);
1769 assert_eq!((-a).mod_euc(-b), 1);
1771 #[unstable(feature = "euclidean_division", issue = "49048")]
1773 #[rustc_inherit_overflow_checks]
1774 pub fn mod_euc(self, rhs: Self) -> Self {
1789 concat!("Computes the absolute value of `self`.
1793 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1794 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1795 code in debug mode will trigger a panic on this case and optimized code will return `",
1796 stringify!($SelfT), "::min_value()` without a panic.
1803 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1804 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1807 #[stable(feature = "rust1", since = "1.0.0")]
1809 #[rustc_inherit_overflow_checks]
1810 pub fn abs(self) -> Self {
1811 if self.is_negative() {
1812 // Note that the #[inline] above means that the overflow
1813 // semantics of this negation depend on the crate we're being
1823 concat!("Returns a number representing sign of `self`.
1825 - `0` if the number is zero
1826 - `1` if the number is positive
1827 - `-1` if the number is negative
1834 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1835 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1836 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1839 #[stable(feature = "rust1", since = "1.0.0")]
1841 pub fn signum(self) -> Self {
1851 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1859 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1860 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1863 #[stable(feature = "rust1", since = "1.0.0")]
1865 pub fn is_positive(self) -> bool { self > 0 }
1869 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1877 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1878 assert!(!10", stringify!($SelfT), ".is_negative());",
1881 #[stable(feature = "rust1", since = "1.0.0")]
1883 pub fn is_negative(self) -> bool { self < 0 }
1886 /// Return the memory representation of this integer as a byte array in
1887 /// big-endian (network) byte order.
1892 /// #![feature(int_to_from_bytes)]
1894 /// let bytes = 0x12_34_56_78_i32.to_be_bytes();
1895 /// assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);
1897 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1899 pub fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
1900 self.to_be().to_ne_bytes()
1903 /// Return the memory representation of this integer as a byte array in
1904 /// little-endian byte order.
1909 /// #![feature(int_to_from_bytes)]
1911 /// let bytes = 0x12_34_56_78_i32.to_le_bytes();
1912 /// assert_eq!(bytes, [0x78, 0x56, 0x34, 0x12]);
1914 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1916 pub fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
1917 self.to_le().to_ne_bytes()
1920 /// Return the memory representation of this integer as a byte array in
1921 /// native byte order.
1923 /// As the target platform's native endianness is used, portable code
1924 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
1927 /// [`to_be_bytes`]: #method.to_be_bytes
1928 /// [`to_le_bytes`]: #method.to_le_bytes
1933 /// #![feature(int_to_from_bytes)]
1935 /// let bytes = i32::min_value().to_be().to_ne_bytes();
1936 /// assert_eq!(bytes, [0x80, 0, 0, 0]);
1938 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1940 pub fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
1941 unsafe { mem::transmute(self) }
1944 /// Create an integer value from its representation as a byte array in
1950 /// #![feature(int_to_from_bytes)]
1952 /// let int = i32::from_be_bytes([0x12, 0x34, 0x56, 0x78]);
1953 /// assert_eq!(int, 0x12_34_56_78);
1955 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1957 pub fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1958 Self::from_be(Self::from_ne_bytes(bytes))
1961 /// Create an integer value from its representation as a byte array in
1967 /// #![feature(int_to_from_bytes)]
1969 /// let int = i32::from_le_bytes([0x12, 0x34, 0x56, 0x78]);
1970 /// assert_eq!(int, 0x78_56_34_12);
1972 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1974 pub fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1975 Self::from_le(Self::from_ne_bytes(bytes))
1978 /// Create an integer value from its memory representation as a byte
1979 /// array in native endianness.
1981 /// As the target platform's native endianness is used, portable code
1982 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1983 /// appropriate instead.
1985 /// [`from_be_bytes`]: #method.from_be_bytes
1986 /// [`from_le_bytes`]: #method.from_le_bytes
1991 /// #![feature(int_to_from_bytes)]
1993 /// let int = i32::from_be(i32::from_ne_bytes([0x80, 0, 0, 0]));
1994 /// assert_eq!(int, i32::min_value());
1996 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1998 pub fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1999 unsafe { mem::transmute(bytes) }
2006 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48" }
2011 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2017 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2018 "0x12345678", "0x78563412", "0x1e6a2c48" }
2023 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2024 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2025 "0x6a2c48091e6a2c48" }
2030 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2031 170141183460469231731687303715884105727, "", "", 16,
2032 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2033 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48"
2037 #[cfg(target_pointer_width = "16")]
2040 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2041 "0x3412", "0x2c48" }
2044 #[cfg(target_pointer_width = "32")]
2047 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2048 "0x12345678", "0x78563412", "0x1e6a2c48" }
2051 #[cfg(target_pointer_width = "64")]
2054 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2055 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2056 "0x6a2c48091e6a2c48" }
2059 // Emits the correct `cttz` call, depending on the size of the type.
2060 macro_rules! uint_cttz_call {
2061 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
2062 // emits two conditional moves on x86_64. By promoting the value to
2063 // u16 and setting bit 8, we get better code without any conditional
2065 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
2066 // pending, remove this workaround once LLVM generates better code
2068 ($value:expr, 8) => { intrinsics::cttz($value as u16 | 0x100) };
2069 ($value:expr, $_BITS:expr) => { intrinsics::cttz($value) }
2072 // `Int` + `UnsignedInt` implemented for unsigned integers
2073 macro_rules! uint_impl {
2074 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2075 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2076 $reversed:expr ) => {
2078 concat!("Returns the smallest value that can be represented by this integer type.
2085 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2087 #[stable(feature = "rust1", since = "1.0.0")]
2089 pub const fn min_value() -> Self { 0 }
2093 concat!("Returns the largest value that can be represented by this integer type.
2100 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2101 stringify!($MaxV), ");", $EndFeature, "
2103 #[stable(feature = "rust1", since = "1.0.0")]
2105 pub const fn max_value() -> Self { !0 }
2109 concat!("Converts a string slice in a given base to an integer.
2111 The string is expected to be an optional `+` sign
2113 Leading and trailing whitespace represent an error.
2114 Digits are a subset of these characters, depending on `radix`:
2122 This function panics if `radix` is not in the range from 2 to 36.
2129 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2132 #[stable(feature = "rust1", since = "1.0.0")]
2133 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2134 from_str_radix(src, radix)
2139 concat!("Returns the number of ones in the binary representation of `self`.
2146 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2148 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2150 #[stable(feature = "rust1", since = "1.0.0")]
2151 #[rustc_const_unstable(feature = "const_int_ops")]
2153 pub const fn count_ones(self) -> u32 {
2154 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
2159 concat!("Returns the number of zeros in the binary representation of `self`.
2166 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2168 #[stable(feature = "rust1", since = "1.0.0")]
2169 #[rustc_const_unstable(feature = "const_int_ops")]
2171 pub const fn count_zeros(self) -> u32 {
2172 (!self).count_ones()
2177 concat!("Returns the number of leading zeros in the binary representation of `self`.
2184 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2186 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2188 #[stable(feature = "rust1", since = "1.0.0")]
2189 #[rustc_const_unstable(feature = "const_int_ops")]
2191 pub const fn leading_zeros(self) -> u32 {
2192 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
2197 concat!("Returns the number of trailing zeros in the binary representation
2205 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2207 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2209 #[stable(feature = "rust1", since = "1.0.0")]
2210 #[rustc_const_unstable(feature = "const_int_ops")]
2212 pub const fn trailing_zeros(self) -> u32 {
2213 unsafe { uint_cttz_call!(self, $BITS) as u32 }
2218 concat!("Shifts the bits to the left by a specified amount, `n`,
2219 wrapping the truncated bits to the end of the resulting integer.
2221 Please note this isn't the same operation as `<<`!
2228 let n = ", $rot_op, stringify!($SelfT), ";
2229 let m = ", $rot_result, ";
2231 assert_eq!(n.rotate_left(", $rot, "), m);
2233 #[stable(feature = "rust1", since = "1.0.0")]
2235 pub fn rotate_left(self, n: u32) -> Self {
2236 // Protect against undefined behaviour for over-long bit shifts
2238 (self << n) | (self >> (($BITS - n) % $BITS))
2243 concat!("Shifts the bits to the right by a specified amount, `n`,
2244 wrapping the truncated bits to the beginning of the resulting
2247 Please note this isn't the same operation as `>>`!
2254 let n = ", $rot_result, stringify!($SelfT), ";
2255 let m = ", $rot_op, ";
2257 assert_eq!(n.rotate_right(", $rot, "), m);
2259 #[stable(feature = "rust1", since = "1.0.0")]
2261 pub fn rotate_right(self, n: u32) -> Self {
2262 // Protect against undefined behaviour for over-long bit shifts
2264 (self >> n) | (self << (($BITS - n) % $BITS))
2270 Reverses the byte order of the integer.
2277 let n = ", $swap_op, stringify!($SelfT), ";
2278 let m = n.swap_bytes();
2280 assert_eq!(m, ", $swapped, ");
2282 #[stable(feature = "rust1", since = "1.0.0")]
2283 #[rustc_const_unstable(feature = "const_int_ops")]
2285 pub const fn swap_bytes(self) -> Self {
2286 unsafe { intrinsics::bswap(self as $ActualT) as Self }
2291 concat!("Reverses the bit pattern of the integer.
2298 #![feature(reverse_bits)]
2300 let n = ", $swap_op, stringify!($SelfT), ";
2301 let m = n.reverse_bits();
2303 assert_eq!(m, ", $reversed, ");
2305 #[unstable(feature = "reverse_bits", issue = "48763")]
2307 pub fn reverse_bits(self) -> Self {
2308 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
2313 concat!("Converts an integer from big endian to the target's endianness.
2315 On big endian this is a no-op. On little endian the bytes are
2323 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2325 if cfg!(target_endian = \"big\") {
2326 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2328 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2331 #[stable(feature = "rust1", since = "1.0.0")]
2332 #[rustc_const_unstable(feature = "const_int_ops")]
2334 pub const fn from_be(x: Self) -> Self {
2335 #[cfg(target_endian = "big")]
2339 #[cfg(not(target_endian = "big"))]
2347 concat!("Converts an integer from little endian to the target's endianness.
2349 On little endian this is a no-op. On big endian the bytes are
2357 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2359 if cfg!(target_endian = \"little\") {
2360 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2362 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2365 #[stable(feature = "rust1", since = "1.0.0")]
2366 #[rustc_const_unstable(feature = "const_int_ops")]
2368 pub const fn from_le(x: Self) -> Self {
2369 #[cfg(target_endian = "little")]
2373 #[cfg(not(target_endian = "little"))]
2381 concat!("Converts `self` to big endian from the target's endianness.
2383 On big endian this is a no-op. On little endian the bytes are
2391 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2393 if cfg!(target_endian = \"big\") {
2394 assert_eq!(n.to_be(), n)
2396 assert_eq!(n.to_be(), n.swap_bytes())
2399 #[stable(feature = "rust1", since = "1.0.0")]
2400 #[rustc_const_unstable(feature = "const_int_ops")]
2402 pub const fn to_be(self) -> Self { // or not to be?
2403 #[cfg(target_endian = "big")]
2407 #[cfg(not(target_endian = "big"))]
2415 concat!("Converts `self` to little endian from the target's endianness.
2417 On little endian this is a no-op. On big endian the bytes are
2425 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2427 if cfg!(target_endian = \"little\") {
2428 assert_eq!(n.to_le(), n)
2430 assert_eq!(n.to_le(), n.swap_bytes())
2433 #[stable(feature = "rust1", since = "1.0.0")]
2434 #[rustc_const_unstable(feature = "const_int_ops")]
2436 pub const fn to_le(self) -> Self {
2437 #[cfg(target_endian = "little")]
2441 #[cfg(not(target_endian = "little"))]
2449 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2450 if overflow occurred.
2457 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2458 "Some(", stringify!($SelfT), "::max_value() - 1));
2459 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2461 #[stable(feature = "rust1", since = "1.0.0")]
2463 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2464 let (a, b) = self.overflowing_add(rhs);
2465 if b {None} else {Some(a)}
2470 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2471 `None` if overflow occurred.
2478 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2479 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2481 #[stable(feature = "rust1", since = "1.0.0")]
2483 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2484 let (a, b) = self.overflowing_sub(rhs);
2485 if b {None} else {Some(a)}
2490 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2491 `None` if overflow occurred.
2498 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2499 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2501 #[stable(feature = "rust1", since = "1.0.0")]
2503 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2504 let (a, b) = self.overflowing_mul(rhs);
2505 if b {None} else {Some(a)}
2510 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2518 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2519 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2521 #[stable(feature = "rust1", since = "1.0.0")]
2523 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2526 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2532 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`, returning `None`
2540 #![feature(euclidean_division)]
2541 assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2542 assert_eq!(1", stringify!($SelfT), ".checked_div_euc(0), None);
2544 #[unstable(feature = "euclidean_division", issue = "49048")]
2546 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
2550 Some(self.div_euc(rhs))
2557 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2565 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2566 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2568 #[stable(feature = "wrapping", since = "1.7.0")]
2570 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2574 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2580 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None`
2588 #![feature(euclidean_division)]
2589 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
2590 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
2592 #[unstable(feature = "euclidean_division", issue = "49048")]
2594 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
2598 Some(self.mod_euc(rhs))
2604 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2607 Note that negating any positive integer will overflow.
2614 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2615 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2617 #[stable(feature = "wrapping", since = "1.7.0")]
2619 pub fn checked_neg(self) -> Option<Self> {
2620 let (a, b) = self.overflowing_neg();
2621 if b {None} else {Some(a)}
2626 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2627 if `rhs` is larger than or equal to the number of bits in `self`.
2634 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2635 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2637 #[stable(feature = "wrapping", since = "1.7.0")]
2639 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2640 let (a, b) = self.overflowing_shl(rhs);
2641 if b {None} else {Some(a)}
2646 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2647 if `rhs` is larger than or equal to the number of bits in `self`.
2654 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2655 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2657 #[stable(feature = "wrapping", since = "1.7.0")]
2659 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2660 let (a, b) = self.overflowing_shr(rhs);
2661 if b {None} else {Some(a)}
2666 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2674 #![feature(no_panic_pow)]
2675 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2676 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2678 #[unstable(feature = "no_panic_pow", issue = "48320")]
2680 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2681 let mut base = self;
2682 let mut acc: Self = 1;
2686 acc = acc.checked_mul(base)?;
2689 base = base.checked_mul(base)?;
2692 // Deal with the final bit of the exponent separately, since
2693 // squaring the base afterwards is not necessary and may cause a
2694 // needless overflow.
2696 acc = acc.checked_mul(base)?;
2704 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2705 the numeric bounds instead of overflowing.
2712 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2713 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2715 #[stable(feature = "rust1", since = "1.0.0")]
2717 pub fn saturating_add(self, rhs: Self) -> Self {
2718 match self.checked_add(rhs) {
2720 None => Self::max_value(),
2726 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2727 at the numeric bounds instead of overflowing.
2734 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2735 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2737 #[stable(feature = "rust1", since = "1.0.0")]
2739 pub fn saturating_sub(self, rhs: Self) -> Self {
2740 match self.checked_sub(rhs) {
2742 None => Self::min_value(),
2748 concat!("Saturating integer multiplication. Computes `self * rhs`,
2749 saturating at the numeric bounds instead of overflowing.
2756 ", $Feature, "use std::", stringify!($SelfT), ";
2758 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2759 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2760 "::MAX);", $EndFeature, "
2762 #[stable(feature = "wrapping", since = "1.7.0")]
2764 pub fn saturating_mul(self, rhs: Self) -> Self {
2765 self.checked_mul(rhs).unwrap_or(Self::max_value())
2770 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2771 saturating at the numeric bounds instead of overflowing.
2778 #![feature(no_panic_pow)]
2779 ", $Feature, "use std::", stringify!($SelfT), ";
2781 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2782 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2785 #[unstable(feature = "no_panic_pow", issue = "48320")]
2787 pub fn saturating_pow(self, exp: u32) -> Self {
2788 match self.checked_pow(exp) {
2790 None => Self::max_value(),
2796 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2797 wrapping around at the boundary of the type.
2804 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2805 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2808 #[stable(feature = "rust1", since = "1.0.0")]
2810 pub fn wrapping_add(self, rhs: Self) -> Self {
2812 intrinsics::overflowing_add(self, rhs)
2818 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2819 wrapping around at the boundary of the type.
2826 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2827 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2830 #[stable(feature = "rust1", since = "1.0.0")]
2832 pub fn wrapping_sub(self, rhs: Self) -> Self {
2834 intrinsics::overflowing_sub(self, rhs)
2839 /// Wrapping (modular) multiplication. Computes `self *
2840 /// rhs`, wrapping around at the boundary of the type.
2846 /// Please note that this example is shared between integer types.
2847 /// Which explains why `u8` is used here.
2850 /// assert_eq!(10u8.wrapping_mul(12), 120);
2851 /// assert_eq!(25u8.wrapping_mul(12), 44);
2853 #[stable(feature = "rust1", since = "1.0.0")]
2855 pub fn wrapping_mul(self, rhs: Self) -> Self {
2857 intrinsics::overflowing_mul(self, rhs)
2862 concat!("Wrapping (modular) division. Computes `self / rhs`.
2863 Wrapped division on unsigned types is just normal division.
2864 There's no way wrapping could ever happen.
2865 This function exists, so that all operations
2866 are accounted for in the wrapping operations.
2873 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2875 #[stable(feature = "num_wrapping", since = "1.2.0")]
2877 pub fn wrapping_div(self, rhs: Self) -> Self {
2883 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`.
2884 Wrapped division on unsigned types is just normal division.
2885 There's no way wrapping could ever happen.
2886 This function exists, so that all operations
2887 are accounted for in the wrapping operations.
2894 #![feature(euclidean_division)]
2895 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
2897 #[unstable(feature = "euclidean_division", issue = "49048")]
2899 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
2905 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2906 Wrapped remainder calculation on unsigned types is
2907 just the regular remainder calculation.
2908 There's no way wrapping could ever happen.
2909 This function exists, so that all operations
2910 are accounted for in the wrapping operations.
2917 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2919 #[stable(feature = "num_wrapping", since = "1.2.0")]
2921 pub fn wrapping_rem(self, rhs: Self) -> Self {
2927 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`.
2928 Wrapped modulo calculation on unsigned types is
2929 just the regular remainder calculation.
2930 There's no way wrapping could ever happen.
2931 This function exists, so that all operations
2932 are accounted for in the wrapping operations.
2939 #![feature(euclidean_division)]
2940 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
2942 #[unstable(feature = "euclidean_division", issue = "49048")]
2944 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
2949 /// Wrapping (modular) negation. Computes `-self`,
2950 /// wrapping around at the boundary of the type.
2952 /// Since unsigned types do not have negative equivalents
2953 /// all applications of this function will wrap (except for `-0`).
2954 /// For values smaller than the corresponding signed type's maximum
2955 /// the result is the same as casting the corresponding signed value.
2956 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2957 /// `MAX` is the corresponding signed type's maximum.
2963 /// Please note that this example is shared between integer types.
2964 /// Which explains why `i8` is used here.
2967 /// assert_eq!(100i8.wrapping_neg(), -100);
2968 /// assert_eq!((-128i8).wrapping_neg(), -128);
2970 #[stable(feature = "num_wrapping", since = "1.2.0")]
2972 pub fn wrapping_neg(self) -> Self {
2973 self.overflowing_neg().0
2977 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2978 where `mask` removes any high-order bits of `rhs` that
2979 would cause the shift to exceed the bitwidth of the type.
2981 Note that this is *not* the same as a rotate-left; the
2982 RHS of a wrapping shift-left is restricted to the range
2983 of the type, rather than the bits shifted out of the LHS
2984 being returned to the other end. The primitive integer
2985 types all implement a `rotate_left` function, which may
2986 be what you want instead.
2993 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2994 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2996 #[stable(feature = "num_wrapping", since = "1.2.0")]
2998 pub fn wrapping_shl(self, rhs: u32) -> Self {
3000 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3006 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3007 where `mask` removes any high-order bits of `rhs` that
3008 would cause the shift to exceed the bitwidth of the type.
3010 Note that this is *not* the same as a rotate-right; the
3011 RHS of a wrapping shift-right is restricted to the range
3012 of the type, rather than the bits shifted out of the LHS
3013 being returned to the other end. The primitive integer
3014 types all implement a `rotate_right` function, which may
3015 be what you want instead.
3022 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3023 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3025 #[stable(feature = "num_wrapping", since = "1.2.0")]
3027 pub fn wrapping_shr(self, rhs: u32) -> Self {
3029 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3035 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3036 wrapping around at the boundary of the type.
3043 #![feature(no_panic_pow)]
3044 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3045 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3047 #[unstable(feature = "no_panic_pow", issue = "48320")]
3049 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3050 let mut base = self;
3051 let mut acc: Self = 1;
3055 acc = acc.wrapping_mul(base);
3058 base = base.wrapping_mul(base);
3061 // Deal with the final bit of the exponent separately, since
3062 // squaring the base afterwards is not necessary and may cause a
3063 // needless overflow.
3065 acc = acc.wrapping_mul(base);
3073 concat!("Calculates `self` + `rhs`
3075 Returns a tuple of the addition along with a boolean indicating
3076 whether an arithmetic overflow would occur. If an overflow would
3077 have occurred then the wrapped value is returned.
3084 ", $Feature, "use std::", stringify!($SelfT), ";
3086 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3087 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3090 #[stable(feature = "wrapping", since = "1.7.0")]
3091 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3092 let (a, b) = unsafe {
3093 intrinsics::add_with_overflow(self as $ActualT,
3101 concat!("Calculates `self` - `rhs`
3103 Returns a tuple of the subtraction along with a boolean indicating
3104 whether an arithmetic overflow would occur. If an overflow would
3105 have occurred then the wrapped value is returned.
3112 ", $Feature, "use std::", stringify!($SelfT), ";
3114 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3115 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3119 #[stable(feature = "wrapping", since = "1.7.0")]
3120 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3121 let (a, b) = unsafe {
3122 intrinsics::sub_with_overflow(self as $ActualT,
3129 /// Calculates the multiplication of `self` and `rhs`.
3131 /// Returns a tuple of the multiplication along with a boolean
3132 /// indicating whether an arithmetic overflow would occur. If an
3133 /// overflow would have occurred then the wrapped value is returned.
3139 /// Please note that this example is shared between integer types.
3140 /// Which explains why `u32` is used here.
3143 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3144 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3147 #[stable(feature = "wrapping", since = "1.7.0")]
3148 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3149 let (a, b) = unsafe {
3150 intrinsics::mul_with_overflow(self as $ActualT,
3157 concat!("Calculates the divisor when `self` is divided by `rhs`.
3159 Returns a tuple of the divisor along with a boolean indicating
3160 whether an arithmetic overflow would occur. Note that for unsigned
3161 integers overflow never occurs, so the second value is always
3166 This function will panic if `rhs` is 0.
3173 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3176 #[stable(feature = "wrapping", since = "1.7.0")]
3177 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3183 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
3185 Returns a tuple of the divisor along with a boolean indicating
3186 whether an arithmetic overflow would occur. Note that for unsigned
3187 integers overflow never occurs, so the second value is always
3192 This function will panic if `rhs` is 0.
3199 #![feature(euclidean_division)]
3200 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
3203 #[unstable(feature = "euclidean_division", issue = "49048")]
3204 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
3210 concat!("Calculates the remainder when `self` is divided by `rhs`.
3212 Returns a tuple of the remainder after dividing along with a boolean
3213 indicating whether an arithmetic overflow would occur. Note that for
3214 unsigned integers overflow never occurs, so the second value is
3219 This function will panic if `rhs` is 0.
3226 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3229 #[stable(feature = "wrapping", since = "1.7.0")]
3230 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3236 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
3238 Returns a tuple of the modulo after dividing along with a boolean
3239 indicating whether an arithmetic overflow would occur. Note that for
3240 unsigned integers overflow never occurs, so the second value is
3245 This function will panic if `rhs` is 0.
3252 #![feature(euclidean_division)]
3253 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
3256 #[unstable(feature = "euclidean_division", issue = "49048")]
3257 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
3263 concat!("Negates self in an overflowing fashion.
3265 Returns `!self + 1` using wrapping operations to return the value
3266 that represents the negation of this unsigned value. Note that for
3267 positive unsigned values overflow always occurs, but negating 0 does
3275 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3276 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3277 ", true));", $EndFeature, "
3280 #[stable(feature = "wrapping", since = "1.7.0")]
3281 pub fn overflowing_neg(self) -> (Self, bool) {
3282 ((!self).wrapping_add(1), self != 0)
3287 concat!("Shifts self left by `rhs` bits.
3289 Returns a tuple of the shifted version of self along with a boolean
3290 indicating whether the shift value was larger than or equal to the
3291 number of bits. If the shift value is too large, then value is
3292 masked (N-1) where N is the number of bits, and this value is then
3293 used to perform the shift.
3300 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3301 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3304 #[stable(feature = "wrapping", since = "1.7.0")]
3305 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3306 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3311 concat!("Shifts self right by `rhs` bits.
3313 Returns a tuple of the shifted version of self along with a boolean
3314 indicating whether the shift value was larger than or equal to the
3315 number of bits. If the shift value is too large, then value is
3316 masked (N-1) where N is the number of bits, and this value is then
3317 used to perform the shift.
3324 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3325 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3328 #[stable(feature = "wrapping", since = "1.7.0")]
3329 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3330 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3335 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3337 Returns a tuple of the exponentiation along with a bool indicating
3338 whether an overflow happened.
3345 #![feature(no_panic_pow)]
3346 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3347 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3349 #[unstable(feature = "no_panic_pow", issue = "48320")]
3351 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3352 let mut base = self;
3353 let mut acc: Self = 1;
3354 let mut overflown = false;
3355 // Scratch space for storing results of overflowing_mul.
3360 r = acc.overflowing_mul(base);
3365 r = base.overflowing_mul(base);
3370 // Deal with the final bit of the exponent separately, since
3371 // squaring the base afterwards is not necessary and may cause a
3372 // needless overflow.
3374 r = acc.overflowing_mul(base);
3384 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3391 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3393 #[stable(feature = "rust1", since = "1.0.0")]
3395 #[rustc_inherit_overflow_checks]
3396 pub fn pow(self, mut exp: u32) -> Self {
3397 let mut base = self;
3408 // Deal with the final bit of the exponent separately, since
3409 // squaring the base afterwards is not necessary and may cause a
3410 // needless overflow.
3420 concat!("Performs Euclidean division.
3422 For unsigned types, this is just the same as `self / rhs`.
3429 #![feature(euclidean_division)]
3430 assert_eq!(7", stringify!($SelfT), ".div_euc(4), 1); // or any other integer type
3432 #[unstable(feature = "euclidean_division", issue = "49048")]
3434 #[rustc_inherit_overflow_checks]
3435 pub fn div_euc(self, rhs: Self) -> Self {
3442 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
3444 For unsigned types, this is just the same as `self % rhs`.
3451 #![feature(euclidean_division)]
3452 assert_eq!(7", stringify!($SelfT), ".mod_euc(4), 3); // or any other integer type
3454 #[unstable(feature = "euclidean_division", issue = "49048")]
3456 #[rustc_inherit_overflow_checks]
3457 pub fn mod_euc(self, rhs: Self) -> Self {
3463 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3470 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3471 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3473 #[stable(feature = "rust1", since = "1.0.0")]
3475 pub fn is_power_of_two(self) -> bool {
3476 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3480 // Returns one less than next power of two.
3481 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3483 // 8u8.one_less_than_next_power_of_two() == 7
3484 // 6u8.one_less_than_next_power_of_two() == 7
3486 // This method cannot overflow, as in the `next_power_of_two`
3487 // overflow cases it instead ends up returning the maximum value
3488 // of the type, and can return 0 for 0.
3490 fn one_less_than_next_power_of_two(self) -> Self {
3491 if self <= 1 { return 0; }
3493 // Because `p > 0`, it cannot consist entirely of leading zeros.
3494 // That means the shift is always in-bounds, and some processors
3495 // (such as intel pre-haswell) have more efficient ctlz
3496 // intrinsics when the argument is non-zero.
3498 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3499 <$SelfT>::max_value() >> z
3503 concat!("Returns the smallest power of two greater than or equal to `self`.
3505 When return value overflows (i.e. `self > (1 << (N-1))` for type
3506 `uN`), it panics in debug mode and return value is wrapped to 0 in
3507 release mode (the only situation in which method can return 0).
3514 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3515 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3517 #[stable(feature = "rust1", since = "1.0.0")]
3519 pub fn next_power_of_two(self) -> Self {
3520 // Call the trait to get overflow checks
3521 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3526 concat!("Returns the smallest power of two greater than or equal to `n`. If
3527 the next power of two is greater than the type's maximum value,
3528 `None` is returned, otherwise the power of two is wrapped in `Some`.
3535 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3536 ".checked_next_power_of_two(), Some(2));
3537 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3538 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3541 #[stable(feature = "rust1", since = "1.0.0")]
3542 pub fn checked_next_power_of_two(self) -> Option<Self> {
3543 self.one_less_than_next_power_of_two().checked_add(1)
3548 concat!("Returns the smallest power of two greater than or equal to `n`. If
3549 the next power of two is greater than the type's maximum value,
3550 the return value is wrapped to `0`.
3557 #![feature(wrapping_next_power_of_two)]
3559 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3560 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3561 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3564 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3565 reason = "needs decision on wrapping behaviour")]
3566 pub fn wrapping_next_power_of_two(self) -> Self {
3567 self.one_less_than_next_power_of_two().wrapping_add(1)
3571 /// Return the memory representation of this integer as a byte array in
3572 /// big-endian (network) byte order.
3577 /// #![feature(int_to_from_bytes)]
3579 /// let bytes = 0x12_34_56_78_i32.to_be_bytes();
3580 /// assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);
3582 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3584 pub fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
3585 self.to_be().to_ne_bytes()
3588 /// Return the memory representation of this integer as a byte array in
3589 /// little-endian byte order.
3594 /// #![feature(int_to_from_bytes)]
3596 /// let bytes = 0x12_34_56_78_i32.to_le_bytes();
3597 /// assert_eq!(bytes, [0x78, 0x56, 0x34, 0x12]);
3599 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3601 pub fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
3602 self.to_le().to_ne_bytes()
3605 /// Return the memory representation of this integer as a byte array in
3606 /// native byte order.
3608 /// As the target platform's native endianness is used, portable code
3609 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3612 /// [`to_be_bytes`]: #method.to_be_bytes
3613 /// [`to_le_bytes`]: #method.to_le_bytes
3618 /// #![feature(int_to_from_bytes)]
3620 /// let bytes = i32::min_value().to_be().to_ne_bytes();
3621 /// assert_eq!(bytes, [0x80, 0, 0, 0]);
3623 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3625 pub fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
3626 unsafe { mem::transmute(self) }
3629 /// Create an integer value from its representation as a byte array in
3635 /// #![feature(int_to_from_bytes)]
3637 /// let int = i32::from_be_bytes([0x12, 0x34, 0x56, 0x78]);
3638 /// assert_eq!(int, 0x12_34_56_78);
3640 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3642 pub fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3643 Self::from_be(Self::from_ne_bytes(bytes))
3646 /// Create an integer value from its representation as a byte array in
3652 /// #![feature(int_to_from_bytes)]
3654 /// let int = i32::from_le_bytes([0x12, 0x34, 0x56, 0x78]);
3655 /// assert_eq!(int, 0x78_56_34_12);
3657 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3659 pub fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3660 Self::from_le(Self::from_ne_bytes(bytes))
3663 /// Create an integer value from its memory representation as a byte
3664 /// array in native endianness.
3666 /// As the target platform's native endianness is used, portable code
3667 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3668 /// appropriate instead.
3670 /// [`from_be_bytes`]: #method.from_be_bytes
3671 /// [`from_le_bytes`]: #method.from_le_bytes
3676 /// #![feature(int_to_from_bytes)]
3678 /// let int = i32::from_be(i32::from_ne_bytes([0x80, 0, 0, 0]));
3679 /// assert_eq!(int, i32::min_value());
3681 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3683 pub fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3684 unsafe { mem::transmute(bytes) }
3691 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48" }
3694 /// Checks if the value is within the ASCII range.
3699 /// let ascii = 97u8;
3700 /// let non_ascii = 150u8;
3702 /// assert!(ascii.is_ascii());
3703 /// assert!(!non_ascii.is_ascii());
3705 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3707 pub fn is_ascii(&self) -> bool {
3711 /// Makes a copy of the value in its ASCII upper case equivalent.
3713 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3714 /// but non-ASCII letters are unchanged.
3716 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
3721 /// let lowercase_a = 97u8;
3723 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
3726 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
3727 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3729 pub fn to_ascii_uppercase(&self) -> u8 {
3730 ASCII_UPPERCASE_MAP[*self as usize]
3733 /// Makes a copy of the value in its ASCII lower case equivalent.
3735 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3736 /// but non-ASCII letters are unchanged.
3738 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
3743 /// let uppercase_a = 65u8;
3745 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
3748 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
3749 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3751 pub fn to_ascii_lowercase(&self) -> u8 {
3752 ASCII_LOWERCASE_MAP[*self as usize]
3755 /// Checks that two values are an ASCII case-insensitive match.
3757 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3762 /// let lowercase_a = 97u8;
3763 /// let uppercase_a = 65u8;
3765 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3767 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3769 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3770 self.to_ascii_lowercase() == other.to_ascii_lowercase()
3773 /// Converts this value to its ASCII upper case equivalent in-place.
3775 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3776 /// but non-ASCII letters are unchanged.
3778 /// To return a new uppercased value without modifying the existing one, use
3779 /// [`to_ascii_uppercase`].
3784 /// let mut byte = b'a';
3786 /// byte.make_ascii_uppercase();
3788 /// assert_eq!(b'A', byte);
3791 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3792 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3794 pub fn make_ascii_uppercase(&mut self) {
3795 *self = self.to_ascii_uppercase();
3798 /// Converts this value to its ASCII lower case equivalent in-place.
3800 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3801 /// but non-ASCII letters are unchanged.
3803 /// To return a new lowercased value without modifying the existing one, use
3804 /// [`to_ascii_lowercase`].
3809 /// let mut byte = b'A';
3811 /// byte.make_ascii_lowercase();
3813 /// assert_eq!(b'a', byte);
3816 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3817 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3819 pub fn make_ascii_lowercase(&mut self) {
3820 *self = self.to_ascii_lowercase();
3823 /// Checks if the value is an ASCII alphabetic character:
3825 /// - U+0041 'A' ... U+005A 'Z', or
3826 /// - U+0061 'a' ... U+007A 'z'.
3831 /// let uppercase_a = b'A';
3832 /// let uppercase_g = b'G';
3835 /// let zero = b'0';
3836 /// let percent = b'%';
3837 /// let space = b' ';
3839 /// let esc = 0x1b_u8;
3841 /// assert!(uppercase_a.is_ascii_alphabetic());
3842 /// assert!(uppercase_g.is_ascii_alphabetic());
3843 /// assert!(a.is_ascii_alphabetic());
3844 /// assert!(g.is_ascii_alphabetic());
3845 /// assert!(!zero.is_ascii_alphabetic());
3846 /// assert!(!percent.is_ascii_alphabetic());
3847 /// assert!(!space.is_ascii_alphabetic());
3848 /// assert!(!lf.is_ascii_alphabetic());
3849 /// assert!(!esc.is_ascii_alphabetic());
3851 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3853 pub fn is_ascii_alphabetic(&self) -> bool {
3854 if *self >= 0x80 { return false; }
3855 match ASCII_CHARACTER_CLASS[*self as usize] {
3856 L | Lx | U | Ux => true,
3861 /// Checks if the value is an ASCII uppercase character:
3862 /// U+0041 'A' ... U+005A 'Z'.
3867 /// let uppercase_a = b'A';
3868 /// let uppercase_g = b'G';
3871 /// let zero = b'0';
3872 /// let percent = b'%';
3873 /// let space = b' ';
3875 /// let esc = 0x1b_u8;
3877 /// assert!(uppercase_a.is_ascii_uppercase());
3878 /// assert!(uppercase_g.is_ascii_uppercase());
3879 /// assert!(!a.is_ascii_uppercase());
3880 /// assert!(!g.is_ascii_uppercase());
3881 /// assert!(!zero.is_ascii_uppercase());
3882 /// assert!(!percent.is_ascii_uppercase());
3883 /// assert!(!space.is_ascii_uppercase());
3884 /// assert!(!lf.is_ascii_uppercase());
3885 /// assert!(!esc.is_ascii_uppercase());
3887 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3889 pub fn is_ascii_uppercase(&self) -> bool {
3890 if *self >= 0x80 { return false }
3891 match ASCII_CHARACTER_CLASS[*self as usize] {
3897 /// Checks if the value is an ASCII lowercase character:
3898 /// U+0061 'a' ... U+007A 'z'.
3903 /// let uppercase_a = b'A';
3904 /// let uppercase_g = b'G';
3907 /// let zero = b'0';
3908 /// let percent = b'%';
3909 /// let space = b' ';
3911 /// let esc = 0x1b_u8;
3913 /// assert!(!uppercase_a.is_ascii_lowercase());
3914 /// assert!(!uppercase_g.is_ascii_lowercase());
3915 /// assert!(a.is_ascii_lowercase());
3916 /// assert!(g.is_ascii_lowercase());
3917 /// assert!(!zero.is_ascii_lowercase());
3918 /// assert!(!percent.is_ascii_lowercase());
3919 /// assert!(!space.is_ascii_lowercase());
3920 /// assert!(!lf.is_ascii_lowercase());
3921 /// assert!(!esc.is_ascii_lowercase());
3923 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3925 pub fn is_ascii_lowercase(&self) -> bool {
3926 if *self >= 0x80 { return false }
3927 match ASCII_CHARACTER_CLASS[*self as usize] {
3933 /// Checks if the value is an ASCII alphanumeric character:
3935 /// - U+0041 'A' ... U+005A 'Z', or
3936 /// - U+0061 'a' ... U+007A 'z', or
3937 /// - U+0030 '0' ... U+0039 '9'.
3942 /// let uppercase_a = b'A';
3943 /// let uppercase_g = b'G';
3946 /// let zero = b'0';
3947 /// let percent = b'%';
3948 /// let space = b' ';
3950 /// let esc = 0x1b_u8;
3952 /// assert!(uppercase_a.is_ascii_alphanumeric());
3953 /// assert!(uppercase_g.is_ascii_alphanumeric());
3954 /// assert!(a.is_ascii_alphanumeric());
3955 /// assert!(g.is_ascii_alphanumeric());
3956 /// assert!(zero.is_ascii_alphanumeric());
3957 /// assert!(!percent.is_ascii_alphanumeric());
3958 /// assert!(!space.is_ascii_alphanumeric());
3959 /// assert!(!lf.is_ascii_alphanumeric());
3960 /// assert!(!esc.is_ascii_alphanumeric());
3962 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3964 pub fn is_ascii_alphanumeric(&self) -> bool {
3965 if *self >= 0x80 { return false }
3966 match ASCII_CHARACTER_CLASS[*self as usize] {
3967 D | L | Lx | U | Ux => true,
3972 /// Checks if the value is an ASCII decimal digit:
3973 /// U+0030 '0' ... U+0039 '9'.
3978 /// let uppercase_a = b'A';
3979 /// let uppercase_g = b'G';
3982 /// let zero = b'0';
3983 /// let percent = b'%';
3984 /// let space = b' ';
3986 /// let esc = 0x1b_u8;
3988 /// assert!(!uppercase_a.is_ascii_digit());
3989 /// assert!(!uppercase_g.is_ascii_digit());
3990 /// assert!(!a.is_ascii_digit());
3991 /// assert!(!g.is_ascii_digit());
3992 /// assert!(zero.is_ascii_digit());
3993 /// assert!(!percent.is_ascii_digit());
3994 /// assert!(!space.is_ascii_digit());
3995 /// assert!(!lf.is_ascii_digit());
3996 /// assert!(!esc.is_ascii_digit());
3998 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4000 pub fn is_ascii_digit(&self) -> bool {
4001 if *self >= 0x80 { return false }
4002 match ASCII_CHARACTER_CLASS[*self as usize] {
4008 /// Checks if the value is an ASCII hexadecimal digit:
4010 /// - U+0030 '0' ... U+0039 '9', or
4011 /// - U+0041 'A' ... U+0046 'F', or
4012 /// - U+0061 'a' ... U+0066 'f'.
4017 /// let uppercase_a = b'A';
4018 /// let uppercase_g = b'G';
4021 /// let zero = b'0';
4022 /// let percent = b'%';
4023 /// let space = b' ';
4025 /// let esc = 0x1b_u8;
4027 /// assert!(uppercase_a.is_ascii_hexdigit());
4028 /// assert!(!uppercase_g.is_ascii_hexdigit());
4029 /// assert!(a.is_ascii_hexdigit());
4030 /// assert!(!g.is_ascii_hexdigit());
4031 /// assert!(zero.is_ascii_hexdigit());
4032 /// assert!(!percent.is_ascii_hexdigit());
4033 /// assert!(!space.is_ascii_hexdigit());
4034 /// assert!(!lf.is_ascii_hexdigit());
4035 /// assert!(!esc.is_ascii_hexdigit());
4037 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4039 pub fn is_ascii_hexdigit(&self) -> bool {
4040 if *self >= 0x80 { return false }
4041 match ASCII_CHARACTER_CLASS[*self as usize] {
4042 D | Lx | Ux => true,
4047 /// Checks if the value is an ASCII punctuation character:
4049 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
4050 /// - U+003A ... U+0040 `: ; < = > ? @`, or
4051 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
4052 /// - U+007B ... U+007E `{ | } ~`
4057 /// let uppercase_a = b'A';
4058 /// let uppercase_g = b'G';
4061 /// let zero = b'0';
4062 /// let percent = b'%';
4063 /// let space = b' ';
4065 /// let esc = 0x1b_u8;
4067 /// assert!(!uppercase_a.is_ascii_punctuation());
4068 /// assert!(!uppercase_g.is_ascii_punctuation());
4069 /// assert!(!a.is_ascii_punctuation());
4070 /// assert!(!g.is_ascii_punctuation());
4071 /// assert!(!zero.is_ascii_punctuation());
4072 /// assert!(percent.is_ascii_punctuation());
4073 /// assert!(!space.is_ascii_punctuation());
4074 /// assert!(!lf.is_ascii_punctuation());
4075 /// assert!(!esc.is_ascii_punctuation());
4077 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4079 pub fn is_ascii_punctuation(&self) -> bool {
4080 if *self >= 0x80 { return false }
4081 match ASCII_CHARACTER_CLASS[*self as usize] {
4087 /// Checks if the value is an ASCII graphic character:
4088 /// U+0021 '!' ... U+007E '~'.
4093 /// let uppercase_a = b'A';
4094 /// let uppercase_g = b'G';
4097 /// let zero = b'0';
4098 /// let percent = b'%';
4099 /// let space = b' ';
4101 /// let esc = 0x1b_u8;
4103 /// assert!(uppercase_a.is_ascii_graphic());
4104 /// assert!(uppercase_g.is_ascii_graphic());
4105 /// assert!(a.is_ascii_graphic());
4106 /// assert!(g.is_ascii_graphic());
4107 /// assert!(zero.is_ascii_graphic());
4108 /// assert!(percent.is_ascii_graphic());
4109 /// assert!(!space.is_ascii_graphic());
4110 /// assert!(!lf.is_ascii_graphic());
4111 /// assert!(!esc.is_ascii_graphic());
4113 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4115 pub fn is_ascii_graphic(&self) -> bool {
4116 if *self >= 0x80 { return false; }
4117 match ASCII_CHARACTER_CLASS[*self as usize] {
4118 Ux | U | Lx | L | D | P => true,
4123 /// Checks if the value is an ASCII whitespace character:
4124 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4125 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4127 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4128 /// whitespace][infra-aw]. There are several other definitions in
4129 /// wide use. For instance, [the POSIX locale][pct] includes
4130 /// U+000B VERTICAL TAB as well as all the above characters,
4131 /// but—from the very same specification—[the default rule for
4132 /// "field splitting" in the Bourne shell][bfs] considers *only*
4133 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4135 /// If you are writing a program that will process an existing
4136 /// file format, check what that format's definition of whitespace is
4137 /// before using this function.
4139 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4140 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4141 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4146 /// let uppercase_a = b'A';
4147 /// let uppercase_g = b'G';
4150 /// let zero = b'0';
4151 /// let percent = b'%';
4152 /// let space = b' ';
4154 /// let esc = 0x1b_u8;
4156 /// assert!(!uppercase_a.is_ascii_whitespace());
4157 /// assert!(!uppercase_g.is_ascii_whitespace());
4158 /// assert!(!a.is_ascii_whitespace());
4159 /// assert!(!g.is_ascii_whitespace());
4160 /// assert!(!zero.is_ascii_whitespace());
4161 /// assert!(!percent.is_ascii_whitespace());
4162 /// assert!(space.is_ascii_whitespace());
4163 /// assert!(lf.is_ascii_whitespace());
4164 /// assert!(!esc.is_ascii_whitespace());
4166 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4168 pub fn is_ascii_whitespace(&self) -> bool {
4169 if *self >= 0x80 { return false; }
4170 match ASCII_CHARACTER_CLASS[*self as usize] {
4176 /// Checks if the value is an ASCII control character:
4177 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4178 /// Note that most ASCII whitespace characters are control
4179 /// characters, but SPACE is not.
4184 /// let uppercase_a = b'A';
4185 /// let uppercase_g = b'G';
4188 /// let zero = b'0';
4189 /// let percent = b'%';
4190 /// let space = b' ';
4192 /// let esc = 0x1b_u8;
4194 /// assert!(!uppercase_a.is_ascii_control());
4195 /// assert!(!uppercase_g.is_ascii_control());
4196 /// assert!(!a.is_ascii_control());
4197 /// assert!(!g.is_ascii_control());
4198 /// assert!(!zero.is_ascii_control());
4199 /// assert!(!percent.is_ascii_control());
4200 /// assert!(!space.is_ascii_control());
4201 /// assert!(lf.is_ascii_control());
4202 /// assert!(esc.is_ascii_control());
4204 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4206 pub fn is_ascii_control(&self) -> bool {
4207 if *self >= 0x80 { return false; }
4208 match ASCII_CHARACTER_CLASS[*self as usize] {
4217 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48" }
4222 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4223 "0x78563412", "0x1e6a2c48" }
4228 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4229 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48" }
4234 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4235 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4236 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48" }
4239 #[cfg(target_pointer_width = "16")]
4242 uint_impl! { usize, u16, 16, 65536, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48" }
4244 #[cfg(target_pointer_width = "32")]
4247 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4248 "0x78563412", "0x1e6a2c48" }
4251 #[cfg(target_pointer_width = "64")]
4254 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4255 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48" }
4258 /// A classification of floating point numbers.
4260 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4261 /// their documentation for more.
4263 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4264 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4269 /// use std::num::FpCategory;
4272 /// let num = 12.4_f32;
4273 /// let inf = f32::INFINITY;
4274 /// let zero = 0f32;
4275 /// let sub: f32 = 1.1754942e-38;
4276 /// let nan = f32::NAN;
4278 /// assert_eq!(num.classify(), FpCategory::Normal);
4279 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4280 /// assert_eq!(zero.classify(), FpCategory::Zero);
4281 /// assert_eq!(nan.classify(), FpCategory::Nan);
4282 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4284 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4285 #[stable(feature = "rust1", since = "1.0.0")]
4286 pub enum FpCategory {
4287 /// "Not a Number", often obtained by dividing by zero.
4288 #[stable(feature = "rust1", since = "1.0.0")]
4291 /// Positive or negative infinity.
4292 #[stable(feature = "rust1", since = "1.0.0")]
4295 /// Positive or negative zero.
4296 #[stable(feature = "rust1", since = "1.0.0")]
4299 /// De-normalized floating point representation (less precise than `Normal`).
4300 #[stable(feature = "rust1", since = "1.0.0")]
4303 /// A regular floating point number.
4304 #[stable(feature = "rust1", since = "1.0.0")]
4308 macro_rules! from_str_radix_int_impl {
4310 #[stable(feature = "rust1", since = "1.0.0")]
4311 impl FromStr for $t {
4312 type Err = ParseIntError;
4313 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4314 from_str_radix(src, 10)
4319 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4321 /// The error type returned when a checked integral type conversion fails.
4322 #[unstable(feature = "try_from", issue = "33417")]
4323 #[derive(Debug, Copy, Clone)]
4324 pub struct TryFromIntError(());
4326 impl TryFromIntError {
4327 #[unstable(feature = "int_error_internals",
4328 reason = "available through Error trait and this method should \
4329 not be exposed publicly",
4332 pub fn __description(&self) -> &str {
4333 "out of range integral type conversion attempted"
4337 #[unstable(feature = "try_from", issue = "33417")]
4338 impl fmt::Display for TryFromIntError {
4339 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4340 self.__description().fmt(fmt)
4344 #[unstable(feature = "try_from", issue = "33417")]
4345 impl From<!> for TryFromIntError {
4346 fn from(never: !) -> TryFromIntError {
4351 // no possible bounds violation
4352 macro_rules! try_from_unbounded {
4353 ($source:ty, $($target:ty),*) => {$(
4354 #[unstable(feature = "try_from", issue = "33417")]
4355 impl TryFrom<$source> for $target {
4356 type Error = TryFromIntError;
4359 fn try_from(value: $source) -> Result<Self, Self::Error> {
4360 Ok(value as $target)
4366 // only negative bounds
4367 macro_rules! try_from_lower_bounded {
4368 ($source:ty, $($target:ty),*) => {$(
4369 #[unstable(feature = "try_from", issue = "33417")]
4370 impl TryFrom<$source> for $target {
4371 type Error = TryFromIntError;
4374 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4378 Err(TryFromIntError(()))
4385 // unsigned to signed (only positive bound)
4386 macro_rules! try_from_upper_bounded {
4387 ($source:ty, $($target:ty),*) => {$(
4388 #[unstable(feature = "try_from", issue = "33417")]
4389 impl TryFrom<$source> for $target {
4390 type Error = TryFromIntError;
4393 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4394 if u > (<$target>::max_value() as $source) {
4395 Err(TryFromIntError(()))
4405 macro_rules! try_from_both_bounded {
4406 ($source:ty, $($target:ty),*) => {$(
4407 #[unstable(feature = "try_from", issue = "33417")]
4408 impl TryFrom<$source> for $target {
4409 type Error = TryFromIntError;
4412 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4413 let min = <$target>::min_value() as $source;
4414 let max = <$target>::max_value() as $source;
4415 if u < min || u > max {
4416 Err(TryFromIntError(()))
4426 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4427 $mac!($target, $source);
4431 /// intra-sign conversions
4432 try_from_upper_bounded!(u16, u8);
4433 try_from_upper_bounded!(u32, u16, u8);
4434 try_from_upper_bounded!(u64, u32, u16, u8);
4435 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4437 try_from_both_bounded!(i16, i8);
4438 try_from_both_bounded!(i32, i16, i8);
4439 try_from_both_bounded!(i64, i32, i16, i8);
4440 try_from_both_bounded!(i128, i64, i32, i16, i8);
4442 // unsigned-to-signed
4443 try_from_upper_bounded!(u8, i8);
4444 try_from_upper_bounded!(u16, i8, i16);
4445 try_from_upper_bounded!(u32, i8, i16, i32);
4446 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4447 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4449 // signed-to-unsigned
4450 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4451 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4452 try_from_lower_bounded!(i32, u32, u64, u128);
4453 try_from_lower_bounded!(i64, u64, u128);
4454 try_from_lower_bounded!(i128, u128);
4455 try_from_both_bounded!(i16, u8);
4456 try_from_both_bounded!(i32, u16, u8);
4457 try_from_both_bounded!(i64, u32, u16, u8);
4458 try_from_both_bounded!(i128, u64, u32, u16, u8);
4461 try_from_upper_bounded!(usize, isize);
4462 try_from_lower_bounded!(isize, usize);
4464 #[cfg(target_pointer_width = "16")]
4465 mod ptr_try_from_impls {
4466 use super::TryFromIntError;
4467 use convert::TryFrom;
4469 try_from_upper_bounded!(usize, u8);
4470 try_from_unbounded!(usize, u16, u32, u64, u128);
4471 try_from_upper_bounded!(usize, i8, i16);
4472 try_from_unbounded!(usize, i32, i64, i128);
4474 try_from_both_bounded!(isize, u8);
4475 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4476 try_from_both_bounded!(isize, i8);
4477 try_from_unbounded!(isize, i16, i32, i64, i128);
4479 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4480 rev!(try_from_lower_bounded, usize, i8, i16);
4481 rev!(try_from_both_bounded, usize, i32, i64, i128);
4483 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4484 rev!(try_from_both_bounded, isize, i32, i64, i128);
4487 #[cfg(target_pointer_width = "32")]
4488 mod ptr_try_from_impls {
4489 use super::TryFromIntError;
4490 use convert::TryFrom;
4492 try_from_upper_bounded!(usize, u8, u16);
4493 try_from_unbounded!(usize, u32, u64, u128);
4494 try_from_upper_bounded!(usize, i8, i16, i32);
4495 try_from_unbounded!(usize, i64, i128);
4497 try_from_both_bounded!(isize, u8, u16);
4498 try_from_lower_bounded!(isize, u32, u64, u128);
4499 try_from_both_bounded!(isize, i8, i16);
4500 try_from_unbounded!(isize, i32, i64, i128);
4502 rev!(try_from_unbounded, usize, u32);
4503 rev!(try_from_upper_bounded, usize, u64, u128);
4504 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4505 rev!(try_from_both_bounded, usize, i64, i128);
4507 rev!(try_from_unbounded, isize, u16);
4508 rev!(try_from_upper_bounded, isize, u32, u64, u128);
4509 rev!(try_from_unbounded, isize, i32);
4510 rev!(try_from_both_bounded, isize, i64, i128);
4513 #[cfg(target_pointer_width = "64")]
4514 mod ptr_try_from_impls {
4515 use super::TryFromIntError;
4516 use convert::TryFrom;
4518 try_from_upper_bounded!(usize, u8, u16, u32);
4519 try_from_unbounded!(usize, u64, u128);
4520 try_from_upper_bounded!(usize, i8, i16, i32, i64);
4521 try_from_unbounded!(usize, i128);
4523 try_from_both_bounded!(isize, u8, u16, u32);
4524 try_from_lower_bounded!(isize, u64, u128);
4525 try_from_both_bounded!(isize, i8, i16, i32);
4526 try_from_unbounded!(isize, i64, i128);
4528 rev!(try_from_unbounded, usize, u32, u64);
4529 rev!(try_from_upper_bounded, usize, u128);
4530 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4531 rev!(try_from_both_bounded, usize, i128);
4533 rev!(try_from_unbounded, isize, u16, u32);
4534 rev!(try_from_upper_bounded, isize, u64, u128);
4535 rev!(try_from_unbounded, isize, i32, i64);
4536 rev!(try_from_both_bounded, isize, i128);
4540 trait FromStrRadixHelper: PartialOrd + Copy {
4541 fn min_value() -> Self;
4542 fn max_value() -> Self;
4543 fn from_u32(u: u32) -> Self;
4544 fn checked_mul(&self, other: u32) -> Option<Self>;
4545 fn checked_sub(&self, other: u32) -> Option<Self>;
4546 fn checked_add(&self, other: u32) -> Option<Self>;
4550 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4552 fn min_value() -> Self { Self::min_value() }
4554 fn max_value() -> Self { Self::max_value() }
4556 fn from_u32(u: u32) -> Self { u as Self }
4558 fn checked_mul(&self, other: u32) -> Option<Self> {
4559 Self::checked_mul(*self, other as Self)
4562 fn checked_sub(&self, other: u32) -> Option<Self> {
4563 Self::checked_sub(*self, other as Self)
4566 fn checked_add(&self, other: u32) -> Option<Self> {
4567 Self::checked_add(*self, other as Self)
4571 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4573 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4574 use self::IntErrorKind::*;
4575 use self::ParseIntError as PIE;
4577 assert!(radix >= 2 && radix <= 36,
4578 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4582 return Err(PIE { kind: Empty });
4585 let is_signed_ty = T::from_u32(0) > T::min_value();
4587 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4588 // and cast them to chars. .to_digit() will safely return None for anything
4589 // other than a valid ascii digit for the given radix, including the first-byte
4590 // of multi-byte sequences
4591 let src = src.as_bytes();
4593 let (is_positive, digits) = match src[0] {
4594 b'+' => (true, &src[1..]),
4595 b'-' if is_signed_ty => (false, &src[1..]),
4599 if digits.is_empty() {
4600 return Err(PIE { kind: Empty });
4603 let mut result = T::from_u32(0);
4605 // The number is positive
4607 let x = match (c as char).to_digit(radix) {
4609 None => return Err(PIE { kind: InvalidDigit }),
4611 result = match result.checked_mul(radix) {
4612 Some(result) => result,
4613 None => return Err(PIE { kind: Overflow }),
4615 result = match result.checked_add(x) {
4616 Some(result) => result,
4617 None => return Err(PIE { kind: Overflow }),
4621 // The number is negative
4623 let x = match (c as char).to_digit(radix) {
4625 None => return Err(PIE { kind: InvalidDigit }),
4627 result = match result.checked_mul(radix) {
4628 Some(result) => result,
4629 None => return Err(PIE { kind: Underflow }),
4631 result = match result.checked_sub(x) {
4632 Some(result) => result,
4633 None => return Err(PIE { kind: Underflow }),
4640 /// An error which can be returned when parsing an integer.
4642 /// This error is used as the error type for the `from_str_radix()` functions
4643 /// on the primitive integer types, such as [`i8::from_str_radix`].
4645 /// # Potential causes
4647 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
4648 /// in the string e.g. when it is obtained from the standard input.
4649 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
4651 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
4652 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
4653 #[derive(Debug, Clone, PartialEq, Eq)]
4654 #[stable(feature = "rust1", since = "1.0.0")]
4655 pub struct ParseIntError {
4659 #[derive(Debug, Clone, PartialEq, Eq)]
4667 impl ParseIntError {
4668 #[unstable(feature = "int_error_internals",
4669 reason = "available through Error trait and this method should \
4670 not be exposed publicly",
4673 pub fn __description(&self) -> &str {
4675 IntErrorKind::Empty => "cannot parse integer from empty string",
4676 IntErrorKind::InvalidDigit => "invalid digit found in string",
4677 IntErrorKind::Overflow => "number too large to fit in target type",
4678 IntErrorKind::Underflow => "number too small to fit in target type",
4683 #[stable(feature = "rust1", since = "1.0.0")]
4684 impl fmt::Display for ParseIntError {
4685 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4686 self.__description().fmt(f)
4690 #[stable(feature = "rust1", since = "1.0.0")]
4691 pub use num::dec2flt::ParseFloatError;
4693 // Conversion traits for primitive integer and float types
4694 // Conversions T -> T are covered by a blanket impl and therefore excluded
4695 // Some conversions from and to usize/isize are not implemented due to portability concerns
4696 macro_rules! impl_from {
4697 ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
4700 impl From<$Small> for $Large {
4702 fn from(small: $Small) -> $Large {
4707 ($Small: ty, $Large: ty, #[$attr:meta]) => {
4711 concat!("Converts `",
4719 macro_rules! impl_from_bool {
4720 ($target: ty, #[$attr:meta]) => {
4721 impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
4722 stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
4728 assert_eq!(", stringify!($target), "::from(true), 1);
4729 assert_eq!(", stringify!($target), "::from(false), 0);
4735 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
4736 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
4737 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
4738 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
4739 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
4740 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
4741 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
4742 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
4743 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
4744 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
4745 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
4746 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
4748 // Unsigned -> Unsigned
4749 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4750 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4751 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4752 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
4753 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4754 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4755 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4756 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
4757 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4758 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
4759 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
4762 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4763 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4764 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4765 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4766 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4767 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4768 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4769 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4770 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4771 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4772 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4774 // Unsigned -> Signed
4775 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4776 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4777 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4778 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4779 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4780 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4781 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4782 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4783 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4784 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4786 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
4787 // which imply that pointer-sized integers must be at least 16 bits:
4788 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
4789 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4790 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4791 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4793 // RISC-V defines the possibility of a 128-bit address space (RV128).
4795 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
4796 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
4797 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
4800 // Note: integers can only be represented with full precision in a float if
4801 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4802 // Lossy float conversions are not implemented at this time.
4805 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4806 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4807 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4808 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4809 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4811 // Unsigned -> Float
4812 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4813 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4814 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4815 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4816 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4819 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4821 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4822 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4823 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4824 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4825 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4826 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4827 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4828 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4829 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4832 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4833 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4834 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4837 b'[', b'\\', b']', b'^', b'_',
4838 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4839 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4840 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4841 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4842 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4843 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4844 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4845 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4846 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4847 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4848 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4849 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4850 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4851 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4852 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4853 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4854 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4855 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4856 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4857 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4860 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4861 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4862 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4863 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4864 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4865 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4866 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4867 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4868 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4869 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4870 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4871 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4872 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4875 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4876 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4877 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4880 b'{', b'|', b'}', b'~', 0x7f,
4881 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4882 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4883 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4884 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4885 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4886 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4887 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4888 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4889 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4890 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4891 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4892 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4893 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4894 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4895 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4896 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4899 enum AsciiCharacterClass {
4901 Cw, // control whitespace
4905 Lx, // lowercase hex digit
4907 Ux, // uppercase hex digit
4910 use self::AsciiCharacterClass::*;
4912 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4913 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4914 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4915 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4916 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4917 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4918 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4919 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4920 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4921 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_