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) => {
193 concat!("Returns the smallest value that can be represented by this integer type.
200 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
203 #[stable(feature = "rust1", since = "1.0.0")]
205 pub const fn min_value() -> Self {
206 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
211 concat!("Returns the largest value that can be represented by this integer type.
218 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
221 #[stable(feature = "rust1", since = "1.0.0")]
223 pub const fn max_value() -> Self {
229 concat!("Converts a string slice in a given base to an integer.
231 The string is expected to be an optional `+` or `-` sign followed by digits.
232 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
233 depending on `radix`:
241 This function panics if `radix` is not in the range from 2 to 36.
248 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
251 #[stable(feature = "rust1", since = "1.0.0")]
252 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
253 from_str_radix(src, radix)
258 concat!("Returns the number of ones in the binary representation of `self`.
265 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
267 assert_eq!(n.count_ones(), 1);",
271 #[stable(feature = "rust1", since = "1.0.0")]
272 #[rustc_const_unstable(feature = "const_int_ops")]
274 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
278 concat!("Returns the number of zeros in the binary representation of `self`.
285 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
287 #[stable(feature = "rust1", since = "1.0.0")]
288 #[rustc_const_unstable(feature = "const_int_ops")]
290 pub const fn count_zeros(self) -> u32 {
296 concat!("Returns the number of leading zeros in the binary representation of `self`.
303 ", $Feature, "let n = -1", stringify!($SelfT), ";
305 assert_eq!(n.leading_zeros(), 0);",
308 #[stable(feature = "rust1", since = "1.0.0")]
309 #[rustc_const_unstable(feature = "const_int_ops")]
311 pub const fn leading_zeros(self) -> u32 {
312 (self as $UnsignedT).leading_zeros()
317 concat!("Returns the number of trailing zeros in the binary representation of `self`.
324 ", $Feature, "let n = -4", stringify!($SelfT), ";
326 assert_eq!(n.trailing_zeros(), 2);",
329 #[stable(feature = "rust1", since = "1.0.0")]
330 #[rustc_const_unstable(feature = "const_int_ops")]
332 pub const fn trailing_zeros(self) -> u32 {
333 (self as $UnsignedT).trailing_zeros()
337 /// Shifts the bits to the left by a specified amount, `n`,
338 /// wrapping the truncated bits to the end of the resulting integer.
340 /// Please note this isn't the same operation as `<<`!
344 /// Please note that this example is shared between integer types.
345 /// Which explains why `i64` is used here.
350 /// let n = 0x0123456789ABCDEFi64;
351 /// let m = -0x76543210FEDCBA99i64;
353 /// assert_eq!(n.rotate_left(32), m);
355 #[stable(feature = "rust1", since = "1.0.0")]
357 pub fn rotate_left(self, n: u32) -> Self {
358 (self as $UnsignedT).rotate_left(n) as Self
361 /// Shifts the bits to the right by a specified amount, `n`,
362 /// wrapping the truncated bits to the beginning of the resulting
365 /// Please note this isn't the same operation as `>>`!
369 /// Please note that this example is shared between integer types.
370 /// Which explains why `i64` is used here.
375 /// let n = 0x0123456789ABCDEFi64;
376 /// let m = -0xFEDCBA987654322i64;
378 /// assert_eq!(n.rotate_right(4), m);
380 #[stable(feature = "rust1", since = "1.0.0")]
382 pub fn rotate_right(self, n: u32) -> Self {
383 (self as $UnsignedT).rotate_right(n) as Self
386 /// Reverses the byte order of the integer.
390 /// Please note that this example is shared between integer types.
391 /// Which explains why `i16` is used here.
396 /// let n: i16 = 0b0000000_01010101;
397 /// assert_eq!(n, 85);
399 /// let m = n.swap_bytes();
401 /// assert_eq!(m, 0b01010101_00000000);
402 /// assert_eq!(m, 21760);
404 #[stable(feature = "rust1", since = "1.0.0")]
405 #[rustc_const_unstable(feature = "const_int_ops")]
407 pub const fn swap_bytes(self) -> Self {
408 (self as $UnsignedT).swap_bytes() as Self
411 /// Reverses the bit pattern of the integer.
415 /// Please note that this example is shared between integer types.
416 /// Which explains why `i16` is used here.
421 /// #![feature(reverse_bits)]
423 /// let n: i16 = 0b0000000_01010101;
424 /// assert_eq!(n, 85);
426 /// let m = n.reverse_bits();
428 /// assert_eq!(m as u16, 0b10101010_00000000);
429 /// assert_eq!(m, -22016);
431 #[unstable(feature = "reverse_bits", issue = "48763")]
433 pub fn reverse_bits(self) -> Self {
434 (self as $UnsignedT).reverse_bits() as Self
438 concat!("Converts an integer from big endian to the target's endianness.
440 On big endian this is a no-op. On little endian the bytes are swapped.
447 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
449 if cfg!(target_endian = \"big\") {
450 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
452 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
456 #[stable(feature = "rust1", since = "1.0.0")]
457 #[rustc_const_unstable(feature = "const_int_ops")]
459 pub const fn from_be(x: Self) -> Self {
460 #[cfg(target_endian = "big")]
464 #[cfg(not(target_endian = "big"))]
472 concat!("Converts an integer from little endian to the target's endianness.
474 On little endian this is a no-op. On big endian the bytes are swapped.
481 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
483 if cfg!(target_endian = \"little\") {
484 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
486 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
490 #[stable(feature = "rust1", since = "1.0.0")]
491 #[rustc_const_unstable(feature = "const_int_ops")]
493 pub const fn from_le(x: Self) -> Self {
494 #[cfg(target_endian = "little")]
498 #[cfg(not(target_endian = "little"))]
506 concat!("Converts `self` to big endian from the target's endianness.
508 On big endian this is a no-op. On little endian the bytes are swapped.
515 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
517 if cfg!(target_endian = \"big\") {
518 assert_eq!(n.to_be(), n)
520 assert_eq!(n.to_be(), n.swap_bytes())
524 #[stable(feature = "rust1", since = "1.0.0")]
525 #[rustc_const_unstable(feature = "const_int_ops")]
527 pub const fn to_be(self) -> Self { // or not to be?
528 #[cfg(target_endian = "big")]
532 #[cfg(not(target_endian = "big"))]
540 concat!("Converts `self` to little endian from the target's endianness.
542 On little endian this is a no-op. On big endian the bytes are swapped.
549 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
551 if cfg!(target_endian = \"little\") {
552 assert_eq!(n.to_le(), n)
554 assert_eq!(n.to_le(), n.swap_bytes())
558 #[stable(feature = "rust1", since = "1.0.0")]
559 #[rustc_const_unstable(feature = "const_int_ops")]
561 pub const fn to_le(self) -> Self {
562 #[cfg(target_endian = "little")]
566 #[cfg(not(target_endian = "little"))]
574 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
575 if overflow occurred.
582 ", $Feature, "assert_eq!((", stringify!($SelfT),
583 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
584 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
587 #[stable(feature = "rust1", since = "1.0.0")]
589 pub fn checked_add(self, rhs: Self) -> Option<Self> {
590 let (a, b) = self.overflowing_add(rhs);
591 if b {None} else {Some(a)}
596 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
604 ", $Feature, "assert_eq!((", stringify!($SelfT),
605 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
606 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
609 #[stable(feature = "rust1", since = "1.0.0")]
611 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
612 let (a, b) = self.overflowing_sub(rhs);
613 if b {None} else {Some(a)}
618 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
626 ", $Feature, "assert_eq!(", stringify!($SelfT),
627 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
628 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
631 #[stable(feature = "rust1", since = "1.0.0")]
633 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
634 let (a, b) = self.overflowing_mul(rhs);
635 if b {None} else {Some(a)}
640 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
641 or the division results in overflow.
648 ", $Feature, "assert_eq!((", stringify!($SelfT),
649 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
650 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
651 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
654 #[stable(feature = "rust1", since = "1.0.0")]
656 pub fn checked_div(self, rhs: Self) -> Option<Self> {
657 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
660 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
666 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`,
667 returning `None` if `rhs == 0` or the division results in overflow.
674 #![feature(euclidean_division)]
675 assert_eq!((", stringify!($SelfT),
676 "::min_value() + 1).checked_div_euc(-1), Some(", stringify!($Max), "));
677 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euc(-1), None);
678 assert_eq!((1", stringify!($SelfT), ").checked_div_euc(0), None);
680 #[unstable(feature = "euclidean_division", issue = "49048")]
682 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
683 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
686 Some(self.div_euc(rhs))
692 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
693 `rhs == 0` or the division results in overflow.
700 ", $Feature, "use std::", stringify!($SelfT), ";
702 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
703 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
704 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
707 #[stable(feature = "wrapping", since = "1.7.0")]
709 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
710 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
713 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
719 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None` if
720 `rhs == 0` or the division results in overflow.
727 #![feature(euclidean_division)]
728 use std::", stringify!($SelfT), ";
730 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
731 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
732 assert_eq!(", stringify!($SelfT), "::MIN.checked_mod_euc(-1), None);
734 #[unstable(feature = "euclidean_division", issue = "49048")]
736 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
737 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
740 Some(self.mod_euc(rhs))
746 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
753 ", $Feature, "use std::", stringify!($SelfT), ";
755 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
756 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
759 #[stable(feature = "wrapping", since = "1.7.0")]
761 pub fn checked_neg(self) -> Option<Self> {
762 let (a, b) = self.overflowing_neg();
763 if b {None} else {Some(a)}
768 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
769 than or equal to the number of bits in `self`.
776 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
777 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
780 #[stable(feature = "wrapping", since = "1.7.0")]
782 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
783 let (a, b) = self.overflowing_shl(rhs);
784 if b {None} else {Some(a)}
789 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
790 larger than or equal to the number of bits in `self`.
797 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
798 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
801 #[stable(feature = "wrapping", since = "1.7.0")]
803 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
804 let (a, b) = self.overflowing_shr(rhs);
805 if b {None} else {Some(a)}
810 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
818 ", $Feature, "use std::", stringify!($SelfT), ";
820 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
821 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
824 #[stable(feature = "no_panic_abs", since = "1.13.0")]
826 pub fn checked_abs(self) -> Option<Self> {
827 if self.is_negative() {
836 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
844 #![feature(no_panic_pow)]
845 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
846 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
850 #[unstable(feature = "no_panic_pow", issue = "48320")]
852 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
854 let mut acc: Self = 1;
858 acc = acc.checked_mul(base)?;
861 base = base.checked_mul(base)?;
864 // Deal with the final bit of the exponent separately, since
865 // squaring the base afterwards is not necessary and may cause a
866 // needless overflow.
868 acc = acc.checked_mul(base)?;
876 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
877 bounds instead of overflowing.
884 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
885 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
889 #[stable(feature = "rust1", since = "1.0.0")]
891 pub fn saturating_add(self, rhs: Self) -> Self {
892 match self.checked_add(rhs) {
894 None if rhs >= 0 => Self::max_value(),
895 None => Self::min_value(),
901 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
902 numeric bounds instead of overflowing.
909 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
910 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
914 #[stable(feature = "rust1", since = "1.0.0")]
916 pub fn saturating_sub(self, rhs: Self) -> Self {
917 match self.checked_sub(rhs) {
919 None if rhs >= 0 => Self::min_value(),
920 None => Self::max_value(),
926 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
927 numeric bounds instead of overflowing.
934 ", $Feature, "use std::", stringify!($SelfT), ";
936 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
937 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
938 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
941 #[stable(feature = "wrapping", since = "1.7.0")]
943 pub fn saturating_mul(self, rhs: Self) -> Self {
944 self.checked_mul(rhs).unwrap_or_else(|| {
945 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
955 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
956 saturating at the numeric bounds instead of overflowing.
963 #![feature(no_panic_pow)]
964 ", $Feature, "use std::", stringify!($SelfT), ";
966 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
967 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
968 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
971 #[unstable(feature = "no_panic_pow", issue = "48320")]
973 pub fn saturating_pow(self, exp: u32) -> Self {
974 match self.checked_pow(exp) {
976 None if self < 0 && exp % 2 == 1 => Self::min_value(),
977 None => Self::max_value(),
983 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
984 boundary of the type.
991 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
992 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
993 "::min_value() + 1);",
996 #[stable(feature = "rust1", since = "1.0.0")]
998 pub fn wrapping_add(self, rhs: Self) -> Self {
1000 intrinsics::overflowing_add(self, rhs)
1006 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1007 boundary of the type.
1014 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1015 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1016 stringify!($SelfT), "::max_value());",
1019 #[stable(feature = "rust1", since = "1.0.0")]
1021 pub fn wrapping_sub(self, rhs: Self) -> Self {
1023 intrinsics::overflowing_sub(self, rhs)
1029 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1030 the boundary of the type.
1037 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1038 assert_eq!(11i8.wrapping_mul(12), -124);",
1041 #[stable(feature = "rust1", since = "1.0.0")]
1043 pub fn wrapping_mul(self, rhs: Self) -> Self {
1045 intrinsics::overflowing_mul(self, rhs)
1051 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1052 boundary of the type.
1054 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1055 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1056 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1060 This function will panic if `rhs` is 0.
1067 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1068 assert_eq!((-128i8).wrapping_div(-1), -128);",
1071 #[stable(feature = "num_wrapping", since = "1.2.0")]
1073 pub fn wrapping_div(self, rhs: Self) -> Self {
1074 self.overflowing_div(rhs).0
1079 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`,
1080 wrapping around at the boundary of the type.
1082 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1083 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1084 type. In this case, this method returns `MIN` itself.
1088 This function will panic if `rhs` is 0.
1095 #![feature(euclidean_division)]
1096 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
1097 assert_eq!((-128i8).wrapping_div_euc(-1), -128);
1099 #[unstable(feature = "euclidean_division", issue = "49048")]
1101 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
1102 self.overflowing_div_euc(rhs).0
1107 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1108 boundary of the type.
1110 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1111 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1112 this function returns `0`.
1116 This function will panic if `rhs` is 0.
1123 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1124 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1127 #[stable(feature = "num_wrapping", since = "1.2.0")]
1129 pub fn wrapping_rem(self, rhs: Self) -> Self {
1130 self.overflowing_rem(rhs).0
1135 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`, wrapping around at the
1136 boundary of the type.
1138 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1139 for the type). In this case, this method returns 0.
1143 This function will panic if `rhs` is 0.
1150 #![feature(euclidean_division)]
1151 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
1152 assert_eq!((-128i8).wrapping_mod_euc(-1), 0);
1154 #[unstable(feature = "euclidean_division", issue = "49048")]
1156 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
1157 self.overflowing_mod_euc(rhs).0
1162 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1165 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1166 is the negative minimal value for the type); this is a positive value that is too large to represent
1167 in the type. In such a case, this function returns `MIN` itself.
1174 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1175 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1179 #[stable(feature = "num_wrapping", since = "1.2.0")]
1181 pub fn wrapping_neg(self) -> Self {
1182 self.overflowing_neg().0
1187 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1188 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1190 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1191 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1192 The primitive integer types all implement a `rotate_left` function, which may be what you want
1200 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1201 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1204 #[stable(feature = "num_wrapping", since = "1.2.0")]
1206 pub fn wrapping_shl(self, rhs: u32) -> Self {
1208 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1214 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1215 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1217 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1218 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1219 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1227 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1228 assert_eq!((-128i16).wrapping_shr(64), -128);",
1231 #[stable(feature = "num_wrapping", since = "1.2.0")]
1233 pub fn wrapping_shr(self, rhs: u32) -> Self {
1235 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1241 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1242 the boundary of the type.
1244 The only case where such wrapping can occur is when one takes the absolute value of the negative
1245 minimal value for the type this is a positive value that is too large to represent in the type. In
1246 such a case, this function returns `MIN` itself.
1253 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1254 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1255 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1257 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1260 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1262 pub fn wrapping_abs(self) -> Self {
1263 if self.is_negative() {
1272 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1273 wrapping around at the boundary of the type.
1280 #![feature(no_panic_pow)]
1281 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1282 assert_eq!(3i8.wrapping_pow(5), -13);
1283 assert_eq!(3i8.wrapping_pow(6), -39);",
1286 #[unstable(feature = "no_panic_pow", issue = "48320")]
1288 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1289 let mut base = self;
1290 let mut acc: Self = 1;
1294 acc = acc.wrapping_mul(base);
1297 base = base.wrapping_mul(base);
1300 // Deal with the final bit of the exponent separately, since
1301 // squaring the base afterwards is not necessary and may cause a
1302 // needless overflow.
1304 acc = acc.wrapping_mul(base);
1312 concat!("Calculates `self` + `rhs`
1314 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1315 occur. If an overflow would have occurred then the wrapped value is returned.
1322 ", $Feature, "use std::", stringify!($SelfT), ";
1324 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1325 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1326 "::MIN, true));", $EndFeature, "
1329 #[stable(feature = "wrapping", since = "1.7.0")]
1330 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1331 let (a, b) = unsafe {
1332 intrinsics::add_with_overflow(self as $ActualT,
1340 concat!("Calculates `self` - `rhs`
1342 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1343 would occur. If an overflow would have occurred then the wrapped value is returned.
1350 ", $Feature, "use std::", stringify!($SelfT), ";
1352 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1353 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1354 "::MAX, true));", $EndFeature, "
1357 #[stable(feature = "wrapping", since = "1.7.0")]
1358 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1359 let (a, b) = unsafe {
1360 intrinsics::sub_with_overflow(self as $ActualT,
1368 concat!("Calculates the multiplication of `self` and `rhs`.
1370 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1371 would occur. If an overflow would have occurred then the wrapped value is returned.
1378 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1379 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1383 #[stable(feature = "wrapping", since = "1.7.0")]
1384 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1385 let (a, b) = unsafe {
1386 intrinsics::mul_with_overflow(self as $ActualT,
1394 concat!("Calculates the divisor when `self` is divided by `rhs`.
1396 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1397 occur. If an overflow would occur then self is returned.
1401 This function will panic if `rhs` is 0.
1408 ", $Feature, "use std::", stringify!($SelfT), ";
1410 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1411 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1416 #[stable(feature = "wrapping", since = "1.7.0")]
1417 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1418 if self == Self::min_value() && rhs == -1 {
1427 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
1429 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1430 occur. If an overflow would occur then `self` is returned.
1434 This function will panic if `rhs` is 0.
1441 #![feature(euclidean_division)]
1442 use std::", stringify!($SelfT), ";
1444 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
1445 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euc(-1), (", stringify!($SelfT),
1449 #[unstable(feature = "euclidean_division", issue = "49048")]
1450 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
1451 if self == Self::min_value() && rhs == -1 {
1454 (self.div_euc(rhs), false)
1460 concat!("Calculates the remainder when `self` is divided by `rhs`.
1462 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1463 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1467 This function will panic if `rhs` is 0.
1474 ", $Feature, "use std::", stringify!($SelfT), ";
1476 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1477 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1481 #[stable(feature = "wrapping", since = "1.7.0")]
1482 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1483 if self == Self::min_value() && rhs == -1 {
1493 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
1495 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1496 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1500 This function will panic if `rhs` is 0.
1507 #![feature(euclidean_division)]
1508 use std::", stringify!($SelfT), ";
1510 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
1511 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_mod_euc(-1), (0, true));
1513 #[unstable(feature = "euclidean_division", issue = "49048")]
1515 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
1516 if self == Self::min_value() && rhs == -1 {
1519 (self.mod_euc(rhs), false)
1526 concat!("Negates self, overflowing if this is equal to the minimum value.
1528 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1529 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1530 minimum value will be returned again and `true` will be returned for an overflow happening.
1537 ", $Feature, "use std::", stringify!($SelfT), ";
1539 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1540 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1541 "::MIN, true));", $EndFeature, "
1544 #[stable(feature = "wrapping", since = "1.7.0")]
1545 pub fn overflowing_neg(self) -> (Self, bool) {
1546 if self == Self::min_value() {
1547 (Self::min_value(), true)
1555 concat!("Shifts self left by `rhs` bits.
1557 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1558 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1559 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1566 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1567 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1571 #[stable(feature = "wrapping", since = "1.7.0")]
1572 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1573 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1578 concat!("Shifts self right by `rhs` bits.
1580 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1581 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1582 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1589 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1590 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1594 #[stable(feature = "wrapping", since = "1.7.0")]
1595 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1596 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1601 concat!("Computes the absolute value of `self`.
1603 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1604 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1605 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1606 for an overflow happening.
1613 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1614 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1615 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1616 "::min_value(), true));",
1619 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1621 pub fn overflowing_abs(self) -> (Self, bool) {
1622 if self.is_negative() {
1623 self.overflowing_neg()
1631 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1633 Returns a tuple of the exponentiation along with a bool indicating
1634 whether an overflow happened.
1641 #![feature(no_panic_pow)]
1642 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1643 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1646 #[unstable(feature = "no_panic_pow", issue = "48320")]
1648 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1649 let mut base = self;
1650 let mut acc: Self = 1;
1651 let mut overflown = false;
1652 // Scratch space for storing results of overflowing_mul.
1657 r = acc.overflowing_mul(base);
1662 r = base.overflowing_mul(base);
1667 // Deal with the final bit of the exponent separately, since
1668 // squaring the base afterwards is not necessary and may cause a
1669 // needless overflow.
1671 r = acc.overflowing_mul(base);
1681 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1688 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1690 assert_eq!(x.pow(5), 32);",
1693 #[stable(feature = "rust1", since = "1.0.0")]
1695 #[rustc_inherit_overflow_checks]
1696 pub fn pow(self, mut exp: u32) -> Self {
1697 let mut base = self;
1708 // Deal with the final bit of the exponent separately, since
1709 // squaring the base afterwards is not necessary and may cause a
1710 // needless overflow.
1720 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1722 This computes the integer `n` such that `self = n * rhs + self.mod_euc(rhs)`.
1723 In other words, the result is `self / rhs` rounded to the integer `n`
1724 such that `self >= n * rhs`.
1728 This function will panic if `rhs` is 0.
1735 #![feature(euclidean_division)]
1736 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1739 assert_eq!(a.div_euc(b), 1); // 7 >= 4 * 1
1740 assert_eq!(a.div_euc(-b), -1); // 7 >= -4 * -1
1741 assert_eq!((-a).div_euc(b), -2); // -7 >= 4 * -2
1742 assert_eq!((-a).div_euc(-b), 2); // -7 >= -4 * 2
1744 #[unstable(feature = "euclidean_division", issue = "49048")]
1746 #[rustc_inherit_overflow_checks]
1747 pub fn div_euc(self, rhs: Self) -> Self {
1750 return if rhs > 0 { q - 1 } else { q + 1 }
1758 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
1760 In particular, the result `n` satisfies `0 <= n < rhs.abs()`.
1764 This function will panic if `rhs` is 0.
1771 #![feature(euclidean_division)]
1772 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1775 assert_eq!(a.mod_euc(b), 3);
1776 assert_eq!((-a).mod_euc(b), 1);
1777 assert_eq!(a.mod_euc(-b), 3);
1778 assert_eq!((-a).mod_euc(-b), 1);
1780 #[unstable(feature = "euclidean_division", issue = "49048")]
1782 #[rustc_inherit_overflow_checks]
1783 pub fn mod_euc(self, rhs: Self) -> Self {
1798 concat!("Computes the absolute value of `self`.
1802 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1803 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1804 code in debug mode will trigger a panic on this case and optimized code will return `",
1805 stringify!($SelfT), "::min_value()` without a panic.
1812 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1813 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1816 #[stable(feature = "rust1", since = "1.0.0")]
1818 #[rustc_inherit_overflow_checks]
1819 pub fn abs(self) -> Self {
1820 if self.is_negative() {
1821 // Note that the #[inline] above means that the overflow
1822 // semantics of this negation depend on the crate we're being
1832 concat!("Returns a number representing sign of `self`.
1834 - `0` if the number is zero
1835 - `1` if the number is positive
1836 - `-1` if the number is negative
1843 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1844 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1845 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1848 #[stable(feature = "rust1", since = "1.0.0")]
1850 pub fn signum(self) -> Self {
1860 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1868 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1869 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1872 #[stable(feature = "rust1", since = "1.0.0")]
1874 pub fn is_positive(self) -> bool { self > 0 }
1878 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1886 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1887 assert!(!10", stringify!($SelfT), ".is_negative());",
1890 #[stable(feature = "rust1", since = "1.0.0")]
1892 pub fn is_negative(self) -> bool { self < 0 }
1895 /// Return the memory representation of this integer as a byte array in
1896 /// big-endian (network) byte order.
1901 /// #![feature(int_to_from_bytes)]
1903 /// let bytes = 0x12345678i32.to_be_bytes();
1904 /// assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);
1906 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
1908 pub fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
1909 self.to_be().to_ne_bytes()
1912 /// Return the memory representation of this integer as a byte array in
1913 /// little-endian byte order.
1918 /// #![feature(int_to_from_bytes)]
1920 /// let bytes = 0x12345678i32.to_le_bytes();
1921 /// assert_eq!(bytes, [0x78, 0x56, 0x34, 0x12]);
1923 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
1925 pub fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
1926 self.to_le().to_ne_bytes()
1929 /// Return the memory representation of this integer as a byte array in
1930 /// native byte order.
1932 /// As the target platform's native endianness is used, portable code
1933 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
1936 /// [`to_be_bytes`]: #method.to_be_bytes
1937 /// [`to_le_bytes`]: #method.to_le_bytes
1942 /// #![feature(int_to_from_bytes)]
1944 /// let bytes = i32::min_value().to_be().to_ne_bytes();
1945 /// assert_eq!(bytes, [0x80, 0, 0, 0]);
1947 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
1949 pub fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
1950 unsafe { mem::transmute(self) }
1953 /// Create an integer value from its representation as a byte array in
1959 /// #![feature(int_to_from_bytes)]
1961 /// let int = i32::from_be_bytes([0x12, 0x34, 0x56, 0x78]);
1962 /// assert_eq!(int, 0x12_34_56_78);
1964 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
1966 pub fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1967 Self::from_be(Self::from_ne_bytes(bytes))
1970 /// Create an integer value from its representation as a byte array in
1976 /// #![feature(int_to_from_bytes)]
1978 /// let int = i32::from_le_bytes([0x12, 0x34, 0x56, 0x78]);
1979 /// assert_eq!(int, 0x78_56_34_12);
1981 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
1983 pub fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1984 Self::from_le(Self::from_ne_bytes(bytes))
1987 /// Create an integer value from its memory representation as a byte
1988 /// array in native endianness.
1990 /// As the target platform's native endianness is used, portable code
1991 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1992 /// appropriate instead.
1994 /// [`from_be_bytes`]: #method.from_be_bytes
1995 /// [`from_le_bytes`]: #method.from_le_bytes
2000 /// #![feature(int_to_from_bytes)]
2002 /// let int = i32::from_be(i32::from_ne_bytes([0x80, 0, 0, 0]));
2003 /// assert_eq!(int, i32::min_value());
2005 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
2007 pub fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2008 unsafe { mem::transmute(bytes) }
2015 int_impl! { i8, i8, u8, 8, -128, 127, "", "" }
2020 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "" }
2025 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "" }
2030 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
2035 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2036 170141183460469231731687303715884105727, "", "" }
2039 #[cfg(target_pointer_width = "16")]
2042 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "" }
2045 #[cfg(target_pointer_width = "32")]
2048 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "" }
2051 #[cfg(target_pointer_width = "64")]
2054 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
2057 // Emits the correct `cttz` call, depending on the size of the type.
2058 macro_rules! uint_cttz_call {
2059 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
2060 // emits two conditional moves on x86_64. By promoting the value to
2061 // u16 and setting bit 8, we get better code without any conditional
2063 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
2064 // pending, remove this workaround once LLVM generates better code
2066 ($value:expr, 8) => { intrinsics::cttz($value as u16 | 0x100) };
2067 ($value:expr, $_BITS:expr) => { intrinsics::cttz($value) }
2070 // `Int` + `UnsignedInt` implemented for unsigned integers
2071 macro_rules! uint_impl {
2072 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr) => {
2074 concat!("Returns the smallest value that can be represented by this integer type.
2081 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2083 #[stable(feature = "rust1", since = "1.0.0")]
2085 pub const fn min_value() -> Self { 0 }
2089 concat!("Returns the largest value that can be represented by this integer type.
2096 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2097 stringify!($MaxV), ");", $EndFeature, "
2099 #[stable(feature = "rust1", since = "1.0.0")]
2101 pub const fn max_value() -> Self { !0 }
2105 concat!("Converts a string slice in a given base to an integer.
2107 The string is expected to be an optional `+` sign
2109 Leading and trailing whitespace represent an error.
2110 Digits are a subset of these characters, depending on `radix`:
2118 This function panics if `radix` is not in the range from 2 to 36.
2125 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2128 #[stable(feature = "rust1", since = "1.0.0")]
2129 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2130 from_str_radix(src, radix)
2135 concat!("Returns the number of ones in the binary representation of `self`.
2142 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2144 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 #[rustc_const_unstable(feature = "const_int_ops")]
2149 pub const fn count_ones(self) -> u32 {
2150 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
2155 concat!("Returns the number of zeros in the binary representation of `self`.
2162 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2164 #[stable(feature = "rust1", since = "1.0.0")]
2165 #[rustc_const_unstable(feature = "const_int_ops")]
2167 pub const fn count_zeros(self) -> u32 {
2168 (!self).count_ones()
2173 concat!("Returns the number of leading zeros in the binary representation of `self`.
2180 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2182 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2184 #[stable(feature = "rust1", since = "1.0.0")]
2185 #[rustc_const_unstable(feature = "const_int_ops")]
2187 pub const fn leading_zeros(self) -> u32 {
2188 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
2193 concat!("Returns the number of trailing zeros in the binary representation
2201 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2203 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2205 #[stable(feature = "rust1", since = "1.0.0")]
2206 #[rustc_const_unstable(feature = "const_int_ops")]
2208 pub const fn trailing_zeros(self) -> u32 {
2209 unsafe { uint_cttz_call!(self, $BITS) as u32 }
2213 /// Shifts the bits to the left by a specified amount, `n`,
2214 /// wrapping the truncated bits to the end of the resulting integer.
2216 /// Please note this isn't the same operation as `<<`!
2222 /// Please note that this example is shared between integer types.
2223 /// Which explains why `u64` is used here.
2226 /// let n = 0x0123456789ABCDEFu64;
2227 /// let m = 0x3456789ABCDEF012u64;
2229 /// assert_eq!(n.rotate_left(12), m);
2231 #[stable(feature = "rust1", since = "1.0.0")]
2233 pub fn rotate_left(self, n: u32) -> Self {
2234 // Protect against undefined behaviour for over-long bit shifts
2236 (self << n) | (self >> (($BITS - n) % $BITS))
2239 /// Shifts the bits to the right by a specified amount, `n`,
2240 /// wrapping the truncated bits to the beginning of the resulting
2243 /// Please note this isn't the same operation as `>>`!
2249 /// Please note that this example is shared between integer types.
2250 /// Which explains why `u64` is used here.
2253 /// let n = 0x0123456789ABCDEFu64;
2254 /// let m = 0xDEF0123456789ABCu64;
2256 /// assert_eq!(n.rotate_right(12), m);
2258 #[stable(feature = "rust1", since = "1.0.0")]
2260 pub fn rotate_right(self, n: u32) -> Self {
2261 // Protect against undefined behaviour for over-long bit shifts
2263 (self >> n) | (self << (($BITS - n) % $BITS))
2266 /// Reverses the byte order of the integer.
2272 /// Please note that this example is shared between integer types.
2273 /// Which explains why `u16` is used here.
2276 /// let n: u16 = 0b0000000_01010101;
2277 /// assert_eq!(n, 85);
2279 /// let m = n.swap_bytes();
2281 /// assert_eq!(m, 0b01010101_00000000);
2282 /// assert_eq!(m, 21760);
2284 #[stable(feature = "rust1", since = "1.0.0")]
2285 #[rustc_const_unstable(feature = "const_int_ops")]
2287 pub const fn swap_bytes(self) -> Self {
2288 unsafe { intrinsics::bswap(self as $ActualT) as Self }
2291 /// Reverses the bit pattern of the integer.
2297 /// Please note that this example is shared between integer types.
2298 /// Which explains why `u16` is used here.
2301 /// #![feature(reverse_bits)]
2303 /// let n: u16 = 0b0000000_01010101;
2304 /// assert_eq!(n, 85);
2306 /// let m = n.reverse_bits();
2308 /// assert_eq!(m, 0b10101010_00000000);
2309 /// assert_eq!(m, 43520);
2311 #[unstable(feature = "reverse_bits", issue = "48763")]
2313 pub fn reverse_bits(self) -> Self {
2314 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
2318 concat!("Converts an integer from big endian to the target's endianness.
2320 On big endian this is a no-op. On little endian the bytes are
2328 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2330 if cfg!(target_endian = \"big\") {
2331 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2333 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2336 #[stable(feature = "rust1", since = "1.0.0")]
2337 #[rustc_const_unstable(feature = "const_int_ops")]
2339 pub const fn from_be(x: Self) -> Self {
2340 #[cfg(target_endian = "big")]
2344 #[cfg(not(target_endian = "big"))]
2352 concat!("Converts an integer from little endian to the target's endianness.
2354 On little endian this is a no-op. On big endian the bytes are
2362 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2364 if cfg!(target_endian = \"little\") {
2365 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2367 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2370 #[stable(feature = "rust1", since = "1.0.0")]
2371 #[rustc_const_unstable(feature = "const_int_ops")]
2373 pub const fn from_le(x: Self) -> Self {
2374 #[cfg(target_endian = "little")]
2378 #[cfg(not(target_endian = "little"))]
2386 concat!("Converts `self` to big endian from the target's endianness.
2388 On big endian this is a no-op. On little endian the bytes are
2396 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2398 if cfg!(target_endian = \"big\") {
2399 assert_eq!(n.to_be(), n)
2401 assert_eq!(n.to_be(), n.swap_bytes())
2404 #[stable(feature = "rust1", since = "1.0.0")]
2405 #[rustc_const_unstable(feature = "const_int_ops")]
2407 pub const fn to_be(self) -> Self { // or not to be?
2408 #[cfg(target_endian = "big")]
2412 #[cfg(not(target_endian = "big"))]
2420 concat!("Converts `self` to little endian from the target's endianness.
2422 On little endian this is a no-op. On big endian the bytes are
2430 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2432 if cfg!(target_endian = \"little\") {
2433 assert_eq!(n.to_le(), n)
2435 assert_eq!(n.to_le(), n.swap_bytes())
2438 #[stable(feature = "rust1", since = "1.0.0")]
2439 #[rustc_const_unstable(feature = "const_int_ops")]
2441 pub const fn to_le(self) -> Self {
2442 #[cfg(target_endian = "little")]
2446 #[cfg(not(target_endian = "little"))]
2454 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2455 if overflow occurred.
2462 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2463 "Some(", stringify!($SelfT), "::max_value() - 1));
2464 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2466 #[stable(feature = "rust1", since = "1.0.0")]
2468 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2469 let (a, b) = self.overflowing_add(rhs);
2470 if b {None} else {Some(a)}
2475 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2476 `None` if overflow occurred.
2483 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2484 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2486 #[stable(feature = "rust1", since = "1.0.0")]
2488 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2489 let (a, b) = self.overflowing_sub(rhs);
2490 if b {None} else {Some(a)}
2495 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2496 `None` if overflow occurred.
2503 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2504 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2506 #[stable(feature = "rust1", since = "1.0.0")]
2508 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2509 let (a, b) = self.overflowing_mul(rhs);
2510 if b {None} else {Some(a)}
2515 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2523 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2524 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2526 #[stable(feature = "rust1", since = "1.0.0")]
2528 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2531 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2537 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`, returning `None`
2545 #![feature(euclidean_division)]
2546 assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2547 assert_eq!(1", stringify!($SelfT), ".checked_div_euc(0), None);
2549 #[unstable(feature = "euclidean_division", issue = "49048")]
2551 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
2555 Some(self.div_euc(rhs))
2562 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2570 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2571 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2573 #[stable(feature = "wrapping", since = "1.7.0")]
2575 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2579 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2585 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None`
2593 #![feature(euclidean_division)]
2594 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
2595 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
2597 #[unstable(feature = "euclidean_division", issue = "49048")]
2599 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
2603 Some(self.mod_euc(rhs))
2609 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2612 Note that negating any positive integer will overflow.
2619 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2620 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2622 #[stable(feature = "wrapping", since = "1.7.0")]
2624 pub fn checked_neg(self) -> Option<Self> {
2625 let (a, b) = self.overflowing_neg();
2626 if b {None} else {Some(a)}
2631 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2632 if `rhs` is larger than or equal to the number of bits in `self`.
2639 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2640 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2642 #[stable(feature = "wrapping", since = "1.7.0")]
2644 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2645 let (a, b) = self.overflowing_shl(rhs);
2646 if b {None} else {Some(a)}
2651 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2652 if `rhs` is larger than or equal to the number of bits in `self`.
2659 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2660 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2662 #[stable(feature = "wrapping", since = "1.7.0")]
2664 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2665 let (a, b) = self.overflowing_shr(rhs);
2666 if b {None} else {Some(a)}
2671 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2679 #![feature(no_panic_pow)]
2680 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2681 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2683 #[unstable(feature = "no_panic_pow", issue = "48320")]
2685 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2686 let mut base = self;
2687 let mut acc: Self = 1;
2691 acc = acc.checked_mul(base)?;
2694 base = base.checked_mul(base)?;
2697 // Deal with the final bit of the exponent separately, since
2698 // squaring the base afterwards is not necessary and may cause a
2699 // needless overflow.
2701 acc = acc.checked_mul(base)?;
2709 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2710 the numeric bounds instead of overflowing.
2717 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2718 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2720 #[stable(feature = "rust1", since = "1.0.0")]
2722 pub fn saturating_add(self, rhs: Self) -> Self {
2723 match self.checked_add(rhs) {
2725 None => Self::max_value(),
2731 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2732 at the numeric bounds instead of overflowing.
2739 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2740 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2742 #[stable(feature = "rust1", since = "1.0.0")]
2744 pub fn saturating_sub(self, rhs: Self) -> Self {
2745 match self.checked_sub(rhs) {
2747 None => Self::min_value(),
2753 concat!("Saturating integer multiplication. Computes `self * rhs`,
2754 saturating at the numeric bounds instead of overflowing.
2761 ", $Feature, "use std::", stringify!($SelfT), ";
2763 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2764 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2765 "::MAX);", $EndFeature, "
2767 #[stable(feature = "wrapping", since = "1.7.0")]
2769 pub fn saturating_mul(self, rhs: Self) -> Self {
2770 self.checked_mul(rhs).unwrap_or(Self::max_value())
2775 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2776 saturating at the numeric bounds instead of overflowing.
2783 #![feature(no_panic_pow)]
2784 ", $Feature, "use std::", stringify!($SelfT), ";
2786 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2787 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2790 #[unstable(feature = "no_panic_pow", issue = "48320")]
2792 pub fn saturating_pow(self, exp: u32) -> Self {
2793 match self.checked_pow(exp) {
2795 None => Self::max_value(),
2801 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2802 wrapping around at the boundary of the type.
2809 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2810 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2813 #[stable(feature = "rust1", since = "1.0.0")]
2815 pub fn wrapping_add(self, rhs: Self) -> Self {
2817 intrinsics::overflowing_add(self, rhs)
2823 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2824 wrapping around at the boundary of the type.
2831 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2832 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2835 #[stable(feature = "rust1", since = "1.0.0")]
2837 pub fn wrapping_sub(self, rhs: Self) -> Self {
2839 intrinsics::overflowing_sub(self, rhs)
2844 /// Wrapping (modular) multiplication. Computes `self *
2845 /// rhs`, wrapping around at the boundary of the type.
2851 /// Please note that this example is shared between integer types.
2852 /// Which explains why `u8` is used here.
2855 /// assert_eq!(10u8.wrapping_mul(12), 120);
2856 /// assert_eq!(25u8.wrapping_mul(12), 44);
2858 #[stable(feature = "rust1", since = "1.0.0")]
2860 pub fn wrapping_mul(self, rhs: Self) -> Self {
2862 intrinsics::overflowing_mul(self, rhs)
2867 concat!("Wrapping (modular) division. Computes `self / rhs`.
2868 Wrapped division on unsigned types is just normal division.
2869 There's no way wrapping could ever happen.
2870 This function exists, so that all operations
2871 are accounted for in the wrapping operations.
2878 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2880 #[stable(feature = "num_wrapping", since = "1.2.0")]
2882 pub fn wrapping_div(self, rhs: Self) -> Self {
2888 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`.
2889 Wrapped division on unsigned types is just normal division.
2890 There's no way wrapping could ever happen.
2891 This function exists, so that all operations
2892 are accounted for in the wrapping operations.
2899 #![feature(euclidean_division)]
2900 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
2902 #[unstable(feature = "euclidean_division", issue = "49048")]
2904 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
2910 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2911 Wrapped remainder calculation on unsigned types is
2912 just the regular remainder calculation.
2913 There's no way wrapping could ever happen.
2914 This function exists, so that all operations
2915 are accounted for in the wrapping operations.
2922 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2924 #[stable(feature = "num_wrapping", since = "1.2.0")]
2926 pub fn wrapping_rem(self, rhs: Self) -> Self {
2932 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`.
2933 Wrapped modulo calculation on unsigned types is
2934 just the regular remainder calculation.
2935 There's no way wrapping could ever happen.
2936 This function exists, so that all operations
2937 are accounted for in the wrapping operations.
2944 #![feature(euclidean_division)]
2945 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
2947 #[unstable(feature = "euclidean_division", issue = "49048")]
2949 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
2954 /// Wrapping (modular) negation. Computes `-self`,
2955 /// wrapping around at the boundary of the type.
2957 /// Since unsigned types do not have negative equivalents
2958 /// all applications of this function will wrap (except for `-0`).
2959 /// For values smaller than the corresponding signed type's maximum
2960 /// the result is the same as casting the corresponding signed value.
2961 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2962 /// `MAX` is the corresponding signed type's maximum.
2968 /// Please note that this example is shared between integer types.
2969 /// Which explains why `i8` is used here.
2972 /// assert_eq!(100i8.wrapping_neg(), -100);
2973 /// assert_eq!((-128i8).wrapping_neg(), -128);
2975 #[stable(feature = "num_wrapping", since = "1.2.0")]
2977 pub fn wrapping_neg(self) -> Self {
2978 self.overflowing_neg().0
2982 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2983 where `mask` removes any high-order bits of `rhs` that
2984 would cause the shift to exceed the bitwidth of the type.
2986 Note that this is *not* the same as a rotate-left; the
2987 RHS of a wrapping shift-left is restricted to the range
2988 of the type, rather than the bits shifted out of the LHS
2989 being returned to the other end. The primitive integer
2990 types all implement a `rotate_left` function, which may
2991 be what you want instead.
2998 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2999 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3001 #[stable(feature = "num_wrapping", since = "1.2.0")]
3003 pub fn wrapping_shl(self, rhs: u32) -> Self {
3005 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3011 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3012 where `mask` removes any high-order bits of `rhs` that
3013 would cause the shift to exceed the bitwidth of the type.
3015 Note that this is *not* the same as a rotate-right; the
3016 RHS of a wrapping shift-right is restricted to the range
3017 of the type, rather than the bits shifted out of the LHS
3018 being returned to the other end. The primitive integer
3019 types all implement a `rotate_right` function, which may
3020 be what you want instead.
3027 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3028 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3030 #[stable(feature = "num_wrapping", since = "1.2.0")]
3032 pub fn wrapping_shr(self, rhs: u32) -> Self {
3034 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3040 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3041 wrapping around at the boundary of the type.
3048 #![feature(no_panic_pow)]
3049 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3050 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3052 #[unstable(feature = "no_panic_pow", issue = "48320")]
3054 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3055 let mut base = self;
3056 let mut acc: Self = 1;
3060 acc = acc.wrapping_mul(base);
3063 base = base.wrapping_mul(base);
3066 // Deal with the final bit of the exponent separately, since
3067 // squaring the base afterwards is not necessary and may cause a
3068 // needless overflow.
3070 acc = acc.wrapping_mul(base);
3078 concat!("Calculates `self` + `rhs`
3080 Returns a tuple of the addition along with a boolean indicating
3081 whether an arithmetic overflow would occur. If an overflow would
3082 have occurred then the wrapped value is returned.
3089 ", $Feature, "use std::", stringify!($SelfT), ";
3091 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3092 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3095 #[stable(feature = "wrapping", since = "1.7.0")]
3096 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3097 let (a, b) = unsafe {
3098 intrinsics::add_with_overflow(self as $ActualT,
3106 concat!("Calculates `self` - `rhs`
3108 Returns a tuple of the subtraction along with a boolean indicating
3109 whether an arithmetic overflow would occur. If an overflow would
3110 have occurred then the wrapped value is returned.
3117 ", $Feature, "use std::", stringify!($SelfT), ";
3119 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3120 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3124 #[stable(feature = "wrapping", since = "1.7.0")]
3125 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3126 let (a, b) = unsafe {
3127 intrinsics::sub_with_overflow(self as $ActualT,
3134 /// Calculates the multiplication of `self` and `rhs`.
3136 /// Returns a tuple of the multiplication along with a boolean
3137 /// indicating whether an arithmetic overflow would occur. If an
3138 /// overflow would have occurred then the wrapped value is returned.
3144 /// Please note that this example is shared between integer types.
3145 /// Which explains why `u32` is used here.
3148 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3149 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3152 #[stable(feature = "wrapping", since = "1.7.0")]
3153 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3154 let (a, b) = unsafe {
3155 intrinsics::mul_with_overflow(self as $ActualT,
3162 concat!("Calculates the divisor when `self` is divided by `rhs`.
3164 Returns a tuple of the divisor along with a boolean indicating
3165 whether an arithmetic overflow would occur. Note that for unsigned
3166 integers overflow never occurs, so the second value is always
3171 This function will panic if `rhs` is 0.
3178 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3181 #[stable(feature = "wrapping", since = "1.7.0")]
3182 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3188 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
3190 Returns a tuple of the divisor along with a boolean indicating
3191 whether an arithmetic overflow would occur. Note that for unsigned
3192 integers overflow never occurs, so the second value is always
3197 This function will panic if `rhs` is 0.
3204 #![feature(euclidean_division)]
3205 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
3208 #[unstable(feature = "euclidean_division", issue = "49048")]
3209 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
3215 concat!("Calculates the remainder when `self` is divided by `rhs`.
3217 Returns a tuple of the remainder after dividing along with a boolean
3218 indicating whether an arithmetic overflow would occur. Note that for
3219 unsigned integers overflow never occurs, so the second value is
3224 This function will panic if `rhs` is 0.
3231 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3234 #[stable(feature = "wrapping", since = "1.7.0")]
3235 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3241 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
3243 Returns a tuple of the modulo after dividing along with a boolean
3244 indicating whether an arithmetic overflow would occur. Note that for
3245 unsigned integers overflow never occurs, so the second value is
3250 This function will panic if `rhs` is 0.
3257 #![feature(euclidean_division)]
3258 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
3261 #[unstable(feature = "euclidean_division", issue = "49048")]
3262 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
3268 concat!("Negates self in an overflowing fashion.
3270 Returns `!self + 1` using wrapping operations to return the value
3271 that represents the negation of this unsigned value. Note that for
3272 positive unsigned values overflow always occurs, but negating 0 does
3280 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3281 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3282 ", true));", $EndFeature, "
3285 #[stable(feature = "wrapping", since = "1.7.0")]
3286 pub fn overflowing_neg(self) -> (Self, bool) {
3287 ((!self).wrapping_add(1), self != 0)
3292 concat!("Shifts self left by `rhs` bits.
3294 Returns a tuple of the shifted version of self along with a boolean
3295 indicating whether the shift value was larger than or equal to the
3296 number of bits. If the shift value is too large, then value is
3297 masked (N-1) where N is the number of bits, and this value is then
3298 used to perform the shift.
3305 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3306 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3309 #[stable(feature = "wrapping", since = "1.7.0")]
3310 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3311 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3316 concat!("Shifts self right by `rhs` bits.
3318 Returns a tuple of the shifted version of self along with a boolean
3319 indicating whether the shift value was larger than or equal to the
3320 number of bits. If the shift value is too large, then value is
3321 masked (N-1) where N is the number of bits, and this value is then
3322 used to perform the shift.
3329 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3330 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3333 #[stable(feature = "wrapping", since = "1.7.0")]
3334 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3335 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3340 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3342 Returns a tuple of the exponentiation along with a bool indicating
3343 whether an overflow happened.
3350 #![feature(no_panic_pow)]
3351 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3352 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3354 #[unstable(feature = "no_panic_pow", issue = "48320")]
3356 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3357 let mut base = self;
3358 let mut acc: Self = 1;
3359 let mut overflown = false;
3360 // Scratch space for storing results of overflowing_mul.
3365 r = acc.overflowing_mul(base);
3370 r = base.overflowing_mul(base);
3375 // Deal with the final bit of the exponent separately, since
3376 // squaring the base afterwards is not necessary and may cause a
3377 // needless overflow.
3379 r = acc.overflowing_mul(base);
3389 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3396 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3398 #[stable(feature = "rust1", since = "1.0.0")]
3400 #[rustc_inherit_overflow_checks]
3401 pub fn pow(self, mut exp: u32) -> Self {
3402 let mut base = self;
3413 // Deal with the final bit of the exponent separately, since
3414 // squaring the base afterwards is not necessary and may cause a
3415 // needless overflow.
3425 concat!("Performs Euclidean division.
3427 For unsigned types, this is just the same as `self / rhs`.
3434 #![feature(euclidean_division)]
3435 assert_eq!(7", stringify!($SelfT), ".div_euc(4), 1); // or any other integer type
3437 #[unstable(feature = "euclidean_division", issue = "49048")]
3439 #[rustc_inherit_overflow_checks]
3440 pub fn div_euc(self, rhs: Self) -> Self {
3447 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
3449 For unsigned types, this is just the same as `self % rhs`.
3456 #![feature(euclidean_division)]
3457 assert_eq!(7", stringify!($SelfT), ".mod_euc(4), 3); // or any other integer type
3459 #[unstable(feature = "euclidean_division", issue = "49048")]
3461 #[rustc_inherit_overflow_checks]
3462 pub fn mod_euc(self, rhs: Self) -> Self {
3468 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3475 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3476 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3478 #[stable(feature = "rust1", since = "1.0.0")]
3480 pub fn is_power_of_two(self) -> bool {
3481 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3485 // Returns one less than next power of two.
3486 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3488 // 8u8.one_less_than_next_power_of_two() == 7
3489 // 6u8.one_less_than_next_power_of_two() == 7
3491 // This method cannot overflow, as in the `next_power_of_two`
3492 // overflow cases it instead ends up returning the maximum value
3493 // of the type, and can return 0 for 0.
3495 fn one_less_than_next_power_of_two(self) -> Self {
3496 if self <= 1 { return 0; }
3498 // Because `p > 0`, it cannot consist entirely of leading zeros.
3499 // That means the shift is always in-bounds, and some processors
3500 // (such as intel pre-haswell) have more efficient ctlz
3501 // intrinsics when the argument is non-zero.
3503 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3504 <$SelfT>::max_value() >> z
3508 concat!("Returns the smallest power of two greater than or equal to `self`.
3510 When return value overflows (i.e. `self > (1 << (N-1))` for type
3511 `uN`), it panics in debug mode and return value is wrapped to 0 in
3512 release mode (the only situation in which method can return 0).
3519 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3520 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3522 #[stable(feature = "rust1", since = "1.0.0")]
3524 pub fn next_power_of_two(self) -> Self {
3525 // Call the trait to get overflow checks
3526 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3531 concat!("Returns the smallest power of two greater than or equal to `n`. If
3532 the next power of two is greater than the type's maximum value,
3533 `None` is returned, otherwise the power of two is wrapped in `Some`.
3540 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3541 ".checked_next_power_of_two(), Some(2));
3542 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3543 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3546 #[stable(feature = "rust1", since = "1.0.0")]
3547 pub fn checked_next_power_of_two(self) -> Option<Self> {
3548 self.one_less_than_next_power_of_two().checked_add(1)
3553 concat!("Returns the smallest power of two greater than or equal to `n`. If
3554 the next power of two is greater than the type's maximum value,
3555 the return value is wrapped to `0`.
3562 #![feature(wrapping_next_power_of_two)]
3564 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3565 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3566 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3569 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3570 reason = "needs decision on wrapping behaviour")]
3571 pub fn wrapping_next_power_of_two(self) -> Self {
3572 self.one_less_than_next_power_of_two().wrapping_add(1)
3576 /// Return the memory representation of this integer as a byte array.
3578 /// The target platform’s native endianness is used.
3579 /// Portable code likely wants to use this after [`to_be`] or [`to_le`].
3581 /// [`to_be`]: #method.to_be
3582 /// [`to_le`]: #method.to_le
3587 /// #![feature(int_to_from_bytes)]
3589 /// let bytes = 0x1234_5678_u32.to_be().to_bytes();
3590 /// assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);
3592 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
3594 pub fn to_bytes(self) -> [u8; mem::size_of::<Self>()] {
3595 unsafe { mem::transmute(self) }
3598 /// Create an integer value from its memory representation as a byte array.
3600 /// The target platform’s native endianness is used.
3601 /// Portable code likely wants to use [`to_be`] or [`to_le`] after this.
3603 /// [`to_be`]: #method.to_be
3604 /// [`to_le`]: #method.to_le
3609 /// #![feature(int_to_from_bytes)]
3611 /// let int = u32::from_be(u32::from_bytes([0x12, 0x34, 0x56, 0x78]));
3612 /// assert_eq!(int, 0x1234_5678_u32);
3614 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
3616 pub fn from_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3617 unsafe { mem::transmute(bytes) }
3624 uint_impl! { u8, u8, 8, 255, "", "" }
3627 /// Checks if the value is within the ASCII range.
3632 /// let ascii = 97u8;
3633 /// let non_ascii = 150u8;
3635 /// assert!(ascii.is_ascii());
3636 /// assert!(!non_ascii.is_ascii());
3638 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3640 pub fn is_ascii(&self) -> bool {
3644 /// Makes a copy of the value in its ASCII upper case equivalent.
3646 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3647 /// but non-ASCII letters are unchanged.
3649 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
3654 /// let lowercase_a = 97u8;
3656 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
3659 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
3660 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3662 pub fn to_ascii_uppercase(&self) -> u8 {
3663 ASCII_UPPERCASE_MAP[*self as usize]
3666 /// Makes a copy of the value in its ASCII lower case equivalent.
3668 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3669 /// but non-ASCII letters are unchanged.
3671 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
3676 /// let uppercase_a = 65u8;
3678 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
3681 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
3682 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3684 pub fn to_ascii_lowercase(&self) -> u8 {
3685 ASCII_LOWERCASE_MAP[*self as usize]
3688 /// Checks that two values are an ASCII case-insensitive match.
3690 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3695 /// let lowercase_a = 97u8;
3696 /// let uppercase_a = 65u8;
3698 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3700 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3702 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3703 self.to_ascii_lowercase() == other.to_ascii_lowercase()
3706 /// Converts this value to its ASCII upper case equivalent in-place.
3708 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3709 /// but non-ASCII letters are unchanged.
3711 /// To return a new uppercased value without modifying the existing one, use
3712 /// [`to_ascii_uppercase`].
3717 /// let mut byte = b'a';
3719 /// byte.make_ascii_uppercase();
3721 /// assert_eq!(b'A', byte);
3724 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3725 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3727 pub fn make_ascii_uppercase(&mut self) {
3728 *self = self.to_ascii_uppercase();
3731 /// Converts this value to its ASCII lower case equivalent in-place.
3733 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3734 /// but non-ASCII letters are unchanged.
3736 /// To return a new lowercased value without modifying the existing one, use
3737 /// [`to_ascii_lowercase`].
3742 /// let mut byte = b'A';
3744 /// byte.make_ascii_lowercase();
3746 /// assert_eq!(b'a', byte);
3749 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3750 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3752 pub fn make_ascii_lowercase(&mut self) {
3753 *self = self.to_ascii_lowercase();
3756 /// Checks if the value is an ASCII alphabetic character:
3758 /// - U+0041 'A' ... U+005A 'Z', or
3759 /// - U+0061 'a' ... U+007A 'z'.
3764 /// #![feature(ascii_ctype)]
3766 /// let uppercase_a = b'A';
3767 /// let uppercase_g = b'G';
3770 /// let zero = b'0';
3771 /// let percent = b'%';
3772 /// let space = b' ';
3774 /// let esc = 0x1b_u8;
3776 /// assert!(uppercase_a.is_ascii_alphabetic());
3777 /// assert!(uppercase_g.is_ascii_alphabetic());
3778 /// assert!(a.is_ascii_alphabetic());
3779 /// assert!(g.is_ascii_alphabetic());
3780 /// assert!(!zero.is_ascii_alphabetic());
3781 /// assert!(!percent.is_ascii_alphabetic());
3782 /// assert!(!space.is_ascii_alphabetic());
3783 /// assert!(!lf.is_ascii_alphabetic());
3784 /// assert!(!esc.is_ascii_alphabetic());
3786 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3788 pub fn is_ascii_alphabetic(&self) -> bool {
3789 if *self >= 0x80 { return false; }
3790 match ASCII_CHARACTER_CLASS[*self as usize] {
3791 L | Lx | U | Ux => true,
3796 /// Checks if the value is an ASCII uppercase character:
3797 /// U+0041 'A' ... U+005A 'Z'.
3802 /// #![feature(ascii_ctype)]
3804 /// let uppercase_a = b'A';
3805 /// let uppercase_g = b'G';
3808 /// let zero = b'0';
3809 /// let percent = b'%';
3810 /// let space = b' ';
3812 /// let esc = 0x1b_u8;
3814 /// assert!(uppercase_a.is_ascii_uppercase());
3815 /// assert!(uppercase_g.is_ascii_uppercase());
3816 /// assert!(!a.is_ascii_uppercase());
3817 /// assert!(!g.is_ascii_uppercase());
3818 /// assert!(!zero.is_ascii_uppercase());
3819 /// assert!(!percent.is_ascii_uppercase());
3820 /// assert!(!space.is_ascii_uppercase());
3821 /// assert!(!lf.is_ascii_uppercase());
3822 /// assert!(!esc.is_ascii_uppercase());
3824 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3826 pub fn is_ascii_uppercase(&self) -> bool {
3827 if *self >= 0x80 { return false }
3828 match ASCII_CHARACTER_CLASS[*self as usize] {
3834 /// Checks if the value is an ASCII lowercase character:
3835 /// U+0061 'a' ... U+007A 'z'.
3840 /// #![feature(ascii_ctype)]
3842 /// let uppercase_a = b'A';
3843 /// let uppercase_g = b'G';
3846 /// let zero = b'0';
3847 /// let percent = b'%';
3848 /// let space = b' ';
3850 /// let esc = 0x1b_u8;
3852 /// assert!(!uppercase_a.is_ascii_lowercase());
3853 /// assert!(!uppercase_g.is_ascii_lowercase());
3854 /// assert!(a.is_ascii_lowercase());
3855 /// assert!(g.is_ascii_lowercase());
3856 /// assert!(!zero.is_ascii_lowercase());
3857 /// assert!(!percent.is_ascii_lowercase());
3858 /// assert!(!space.is_ascii_lowercase());
3859 /// assert!(!lf.is_ascii_lowercase());
3860 /// assert!(!esc.is_ascii_lowercase());
3862 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3864 pub fn is_ascii_lowercase(&self) -> bool {
3865 if *self >= 0x80 { return false }
3866 match ASCII_CHARACTER_CLASS[*self as usize] {
3872 /// Checks if the value is an ASCII alphanumeric character:
3874 /// - U+0041 'A' ... U+005A 'Z', or
3875 /// - U+0061 'a' ... U+007A 'z', or
3876 /// - U+0030 '0' ... U+0039 '9'.
3881 /// #![feature(ascii_ctype)]
3883 /// let uppercase_a = b'A';
3884 /// let uppercase_g = b'G';
3887 /// let zero = b'0';
3888 /// let percent = b'%';
3889 /// let space = b' ';
3891 /// let esc = 0x1b_u8;
3893 /// assert!(uppercase_a.is_ascii_alphanumeric());
3894 /// assert!(uppercase_g.is_ascii_alphanumeric());
3895 /// assert!(a.is_ascii_alphanumeric());
3896 /// assert!(g.is_ascii_alphanumeric());
3897 /// assert!(zero.is_ascii_alphanumeric());
3898 /// assert!(!percent.is_ascii_alphanumeric());
3899 /// assert!(!space.is_ascii_alphanumeric());
3900 /// assert!(!lf.is_ascii_alphanumeric());
3901 /// assert!(!esc.is_ascii_alphanumeric());
3903 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3905 pub fn is_ascii_alphanumeric(&self) -> bool {
3906 if *self >= 0x80 { return false }
3907 match ASCII_CHARACTER_CLASS[*self as usize] {
3908 D | L | Lx | U | Ux => true,
3913 /// Checks if the value is an ASCII decimal digit:
3914 /// U+0030 '0' ... U+0039 '9'.
3919 /// #![feature(ascii_ctype)]
3921 /// let uppercase_a = b'A';
3922 /// let uppercase_g = b'G';
3925 /// let zero = b'0';
3926 /// let percent = b'%';
3927 /// let space = b' ';
3929 /// let esc = 0x1b_u8;
3931 /// assert!(!uppercase_a.is_ascii_digit());
3932 /// assert!(!uppercase_g.is_ascii_digit());
3933 /// assert!(!a.is_ascii_digit());
3934 /// assert!(!g.is_ascii_digit());
3935 /// assert!(zero.is_ascii_digit());
3936 /// assert!(!percent.is_ascii_digit());
3937 /// assert!(!space.is_ascii_digit());
3938 /// assert!(!lf.is_ascii_digit());
3939 /// assert!(!esc.is_ascii_digit());
3941 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3943 pub fn is_ascii_digit(&self) -> bool {
3944 if *self >= 0x80 { return false }
3945 match ASCII_CHARACTER_CLASS[*self as usize] {
3951 /// Checks if the value is an ASCII hexadecimal digit:
3953 /// - U+0030 '0' ... U+0039 '9', or
3954 /// - U+0041 'A' ... U+0046 'F', or
3955 /// - U+0061 'a' ... U+0066 'f'.
3960 /// #![feature(ascii_ctype)]
3962 /// let uppercase_a = b'A';
3963 /// let uppercase_g = b'G';
3966 /// let zero = b'0';
3967 /// let percent = b'%';
3968 /// let space = b' ';
3970 /// let esc = 0x1b_u8;
3972 /// assert!(uppercase_a.is_ascii_hexdigit());
3973 /// assert!(!uppercase_g.is_ascii_hexdigit());
3974 /// assert!(a.is_ascii_hexdigit());
3975 /// assert!(!g.is_ascii_hexdigit());
3976 /// assert!(zero.is_ascii_hexdigit());
3977 /// assert!(!percent.is_ascii_hexdigit());
3978 /// assert!(!space.is_ascii_hexdigit());
3979 /// assert!(!lf.is_ascii_hexdigit());
3980 /// assert!(!esc.is_ascii_hexdigit());
3982 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3984 pub fn is_ascii_hexdigit(&self) -> bool {
3985 if *self >= 0x80 { return false }
3986 match ASCII_CHARACTER_CLASS[*self as usize] {
3987 D | Lx | Ux => true,
3992 /// Checks if the value is an ASCII punctuation character:
3994 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
3995 /// - U+003A ... U+0040 `: ; < = > ? @`, or
3996 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
3997 /// - U+007B ... U+007E `{ | } ~`
4002 /// #![feature(ascii_ctype)]
4004 /// let uppercase_a = b'A';
4005 /// let uppercase_g = b'G';
4008 /// let zero = b'0';
4009 /// let percent = b'%';
4010 /// let space = b' ';
4012 /// let esc = 0x1b_u8;
4014 /// assert!(!uppercase_a.is_ascii_punctuation());
4015 /// assert!(!uppercase_g.is_ascii_punctuation());
4016 /// assert!(!a.is_ascii_punctuation());
4017 /// assert!(!g.is_ascii_punctuation());
4018 /// assert!(!zero.is_ascii_punctuation());
4019 /// assert!(percent.is_ascii_punctuation());
4020 /// assert!(!space.is_ascii_punctuation());
4021 /// assert!(!lf.is_ascii_punctuation());
4022 /// assert!(!esc.is_ascii_punctuation());
4024 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4026 pub fn is_ascii_punctuation(&self) -> bool {
4027 if *self >= 0x80 { return false }
4028 match ASCII_CHARACTER_CLASS[*self as usize] {
4034 /// Checks if the value is an ASCII graphic character:
4035 /// U+0021 '!' ... U+007E '~'.
4040 /// #![feature(ascii_ctype)]
4042 /// let uppercase_a = b'A';
4043 /// let uppercase_g = b'G';
4046 /// let zero = b'0';
4047 /// let percent = b'%';
4048 /// let space = b' ';
4050 /// let esc = 0x1b_u8;
4052 /// assert!(uppercase_a.is_ascii_graphic());
4053 /// assert!(uppercase_g.is_ascii_graphic());
4054 /// assert!(a.is_ascii_graphic());
4055 /// assert!(g.is_ascii_graphic());
4056 /// assert!(zero.is_ascii_graphic());
4057 /// assert!(percent.is_ascii_graphic());
4058 /// assert!(!space.is_ascii_graphic());
4059 /// assert!(!lf.is_ascii_graphic());
4060 /// assert!(!esc.is_ascii_graphic());
4062 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4064 pub fn is_ascii_graphic(&self) -> bool {
4065 if *self >= 0x80 { return false; }
4066 match ASCII_CHARACTER_CLASS[*self as usize] {
4067 Ux | U | Lx | L | D | P => true,
4072 /// Checks if the value is an ASCII whitespace character:
4073 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4074 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4076 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4077 /// whitespace][infra-aw]. There are several other definitions in
4078 /// wide use. For instance, [the POSIX locale][pct] includes
4079 /// U+000B VERTICAL TAB as well as all the above characters,
4080 /// but—from the very same specification—[the default rule for
4081 /// "field splitting" in the Bourne shell][bfs] considers *only*
4082 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4084 /// If you are writing a program that will process an existing
4085 /// file format, check what that format's definition of whitespace is
4086 /// before using this function.
4088 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4089 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4090 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4095 /// #![feature(ascii_ctype)]
4097 /// let uppercase_a = b'A';
4098 /// let uppercase_g = b'G';
4101 /// let zero = b'0';
4102 /// let percent = b'%';
4103 /// let space = b' ';
4105 /// let esc = 0x1b_u8;
4107 /// assert!(!uppercase_a.is_ascii_whitespace());
4108 /// assert!(!uppercase_g.is_ascii_whitespace());
4109 /// assert!(!a.is_ascii_whitespace());
4110 /// assert!(!g.is_ascii_whitespace());
4111 /// assert!(!zero.is_ascii_whitespace());
4112 /// assert!(!percent.is_ascii_whitespace());
4113 /// assert!(space.is_ascii_whitespace());
4114 /// assert!(lf.is_ascii_whitespace());
4115 /// assert!(!esc.is_ascii_whitespace());
4117 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4119 pub fn is_ascii_whitespace(&self) -> bool {
4120 if *self >= 0x80 { return false; }
4121 match ASCII_CHARACTER_CLASS[*self as usize] {
4127 /// Checks if the value is an ASCII control character:
4128 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4129 /// Note that most ASCII whitespace characters are control
4130 /// characters, but SPACE is not.
4135 /// #![feature(ascii_ctype)]
4137 /// let uppercase_a = b'A';
4138 /// let uppercase_g = b'G';
4141 /// let zero = b'0';
4142 /// let percent = b'%';
4143 /// let space = b' ';
4145 /// let esc = 0x1b_u8;
4147 /// assert!(!uppercase_a.is_ascii_control());
4148 /// assert!(!uppercase_g.is_ascii_control());
4149 /// assert!(!a.is_ascii_control());
4150 /// assert!(!g.is_ascii_control());
4151 /// assert!(!zero.is_ascii_control());
4152 /// assert!(!percent.is_ascii_control());
4153 /// assert!(!space.is_ascii_control());
4154 /// assert!(lf.is_ascii_control());
4155 /// assert!(esc.is_ascii_control());
4157 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4159 pub fn is_ascii_control(&self) -> bool {
4160 if *self >= 0x80 { return false; }
4161 match ASCII_CHARACTER_CLASS[*self as usize] {
4170 uint_impl! { u16, u16, 16, 65535, "", "" }
4175 uint_impl! { u32, u32, 32, 4294967295, "", "" }
4180 uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
4185 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "" }
4188 #[cfg(target_pointer_width = "16")]
4191 uint_impl! { usize, u16, 16, 65536, "", "" }
4193 #[cfg(target_pointer_width = "32")]
4196 uint_impl! { usize, u32, 32, 4294967295, "", "" }
4199 #[cfg(target_pointer_width = "64")]
4202 uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
4205 /// A classification of floating point numbers.
4207 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4208 /// their documentation for more.
4210 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4211 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4216 /// use std::num::FpCategory;
4219 /// let num = 12.4_f32;
4220 /// let inf = f32::INFINITY;
4221 /// let zero = 0f32;
4222 /// let sub: f32 = 1.1754942e-38;
4223 /// let nan = f32::NAN;
4225 /// assert_eq!(num.classify(), FpCategory::Normal);
4226 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4227 /// assert_eq!(zero.classify(), FpCategory::Zero);
4228 /// assert_eq!(nan.classify(), FpCategory::Nan);
4229 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4231 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4232 #[stable(feature = "rust1", since = "1.0.0")]
4233 pub enum FpCategory {
4234 /// "Not a Number", often obtained by dividing by zero.
4235 #[stable(feature = "rust1", since = "1.0.0")]
4238 /// Positive or negative infinity.
4239 #[stable(feature = "rust1", since = "1.0.0")]
4242 /// Positive or negative zero.
4243 #[stable(feature = "rust1", since = "1.0.0")]
4246 /// De-normalized floating point representation (less precise than `Normal`).
4247 #[stable(feature = "rust1", since = "1.0.0")]
4250 /// A regular floating point number.
4251 #[stable(feature = "rust1", since = "1.0.0")]
4255 macro_rules! from_str_radix_int_impl {
4257 #[stable(feature = "rust1", since = "1.0.0")]
4258 impl FromStr for $t {
4259 type Err = ParseIntError;
4260 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4261 from_str_radix(src, 10)
4266 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4268 /// The error type returned when a checked integral type conversion fails.
4269 #[unstable(feature = "try_from", issue = "33417")]
4270 #[derive(Debug, Copy, Clone)]
4271 pub struct TryFromIntError(());
4273 impl TryFromIntError {
4274 #[unstable(feature = "int_error_internals",
4275 reason = "available through Error trait and this method should \
4276 not be exposed publicly",
4279 pub fn __description(&self) -> &str {
4280 "out of range integral type conversion attempted"
4284 #[unstable(feature = "try_from", issue = "33417")]
4285 impl fmt::Display for TryFromIntError {
4286 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4287 self.__description().fmt(fmt)
4291 #[unstable(feature = "try_from", issue = "33417")]
4292 impl From<!> for TryFromIntError {
4293 fn from(never: !) -> TryFromIntError {
4298 // no possible bounds violation
4299 macro_rules! try_from_unbounded {
4300 ($source:ty, $($target:ty),*) => {$(
4301 #[unstable(feature = "try_from", issue = "33417")]
4302 impl TryFrom<$source> for $target {
4303 type Error = TryFromIntError;
4306 fn try_from(value: $source) -> Result<Self, Self::Error> {
4307 Ok(value as $target)
4313 // only negative bounds
4314 macro_rules! try_from_lower_bounded {
4315 ($source:ty, $($target:ty),*) => {$(
4316 #[unstable(feature = "try_from", issue = "33417")]
4317 impl TryFrom<$source> for $target {
4318 type Error = TryFromIntError;
4321 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4325 Err(TryFromIntError(()))
4332 // unsigned to signed (only positive bound)
4333 macro_rules! try_from_upper_bounded {
4334 ($source:ty, $($target:ty),*) => {$(
4335 #[unstable(feature = "try_from", issue = "33417")]
4336 impl TryFrom<$source> for $target {
4337 type Error = TryFromIntError;
4340 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4341 if u > (<$target>::max_value() as $source) {
4342 Err(TryFromIntError(()))
4352 macro_rules! try_from_both_bounded {
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(u: $source) -> Result<$target, TryFromIntError> {
4360 let min = <$target>::min_value() as $source;
4361 let max = <$target>::max_value() as $source;
4362 if u < min || u > max {
4363 Err(TryFromIntError(()))
4373 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4374 $mac!($target, $source);
4378 /// intra-sign conversions
4379 try_from_upper_bounded!(u16, u8);
4380 try_from_upper_bounded!(u32, u16, u8);
4381 try_from_upper_bounded!(u64, u32, u16, u8);
4382 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4384 try_from_both_bounded!(i16, i8);
4385 try_from_both_bounded!(i32, i16, i8);
4386 try_from_both_bounded!(i64, i32, i16, i8);
4387 try_from_both_bounded!(i128, i64, i32, i16, i8);
4389 // unsigned-to-signed
4390 try_from_upper_bounded!(u8, i8);
4391 try_from_upper_bounded!(u16, i8, i16);
4392 try_from_upper_bounded!(u32, i8, i16, i32);
4393 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4394 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4396 // signed-to-unsigned
4397 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4398 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4399 try_from_lower_bounded!(i32, u32, u64, u128);
4400 try_from_lower_bounded!(i64, u64, u128);
4401 try_from_lower_bounded!(i128, u128);
4402 try_from_both_bounded!(i16, u8);
4403 try_from_both_bounded!(i32, u16, u8);
4404 try_from_both_bounded!(i64, u32, u16, u8);
4405 try_from_both_bounded!(i128, u64, u32, u16, u8);
4408 try_from_upper_bounded!(usize, isize);
4409 try_from_lower_bounded!(isize, usize);
4411 #[cfg(target_pointer_width = "16")]
4412 mod ptr_try_from_impls {
4413 use super::TryFromIntError;
4414 use convert::TryFrom;
4416 try_from_upper_bounded!(usize, u8);
4417 try_from_unbounded!(usize, u16, u32, u64, u128);
4418 try_from_upper_bounded!(usize, i8, i16);
4419 try_from_unbounded!(usize, i32, i64, i128);
4421 try_from_both_bounded!(isize, u8);
4422 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4423 try_from_both_bounded!(isize, i8);
4424 try_from_unbounded!(isize, i16, i32, i64, i128);
4426 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4427 rev!(try_from_lower_bounded, usize, i8, i16);
4428 rev!(try_from_both_bounded, usize, i32, i64, i128);
4430 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4431 rev!(try_from_both_bounded, isize, i32, i64, i128);
4434 #[cfg(target_pointer_width = "32")]
4435 mod ptr_try_from_impls {
4436 use super::TryFromIntError;
4437 use convert::TryFrom;
4439 try_from_upper_bounded!(usize, u8, u16);
4440 try_from_unbounded!(usize, u32, u64, u128);
4441 try_from_upper_bounded!(usize, i8, i16, i32);
4442 try_from_unbounded!(usize, i64, i128);
4444 try_from_both_bounded!(isize, u8, u16);
4445 try_from_lower_bounded!(isize, u32, u64, u128);
4446 try_from_both_bounded!(isize, i8, i16);
4447 try_from_unbounded!(isize, i32, i64, i128);
4449 rev!(try_from_unbounded, usize, u32);
4450 rev!(try_from_upper_bounded, usize, u64, u128);
4451 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4452 rev!(try_from_both_bounded, usize, i64, i128);
4454 rev!(try_from_unbounded, isize, u16);
4455 rev!(try_from_upper_bounded, isize, u32, u64, u128);
4456 rev!(try_from_unbounded, isize, i32);
4457 rev!(try_from_both_bounded, isize, i64, i128);
4460 #[cfg(target_pointer_width = "64")]
4461 mod ptr_try_from_impls {
4462 use super::TryFromIntError;
4463 use convert::TryFrom;
4465 try_from_upper_bounded!(usize, u8, u16, u32);
4466 try_from_unbounded!(usize, u64, u128);
4467 try_from_upper_bounded!(usize, i8, i16, i32, i64);
4468 try_from_unbounded!(usize, i128);
4470 try_from_both_bounded!(isize, u8, u16, u32);
4471 try_from_lower_bounded!(isize, u64, u128);
4472 try_from_both_bounded!(isize, i8, i16, i32);
4473 try_from_unbounded!(isize, i64, i128);
4475 rev!(try_from_unbounded, usize, u32, u64);
4476 rev!(try_from_upper_bounded, usize, u128);
4477 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4478 rev!(try_from_both_bounded, usize, i128);
4480 rev!(try_from_unbounded, isize, u16, u32);
4481 rev!(try_from_upper_bounded, isize, u64, u128);
4482 rev!(try_from_unbounded, isize, i32, i64);
4483 rev!(try_from_both_bounded, isize, i128);
4487 trait FromStrRadixHelper: PartialOrd + Copy {
4488 fn min_value() -> Self;
4489 fn max_value() -> Self;
4490 fn from_u32(u: u32) -> Self;
4491 fn checked_mul(&self, other: u32) -> Option<Self>;
4492 fn checked_sub(&self, other: u32) -> Option<Self>;
4493 fn checked_add(&self, other: u32) -> Option<Self>;
4497 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4499 fn min_value() -> Self { Self::min_value() }
4501 fn max_value() -> Self { Self::max_value() }
4503 fn from_u32(u: u32) -> Self { u as Self }
4505 fn checked_mul(&self, other: u32) -> Option<Self> {
4506 Self::checked_mul(*self, other as Self)
4509 fn checked_sub(&self, other: u32) -> Option<Self> {
4510 Self::checked_sub(*self, other as Self)
4513 fn checked_add(&self, other: u32) -> Option<Self> {
4514 Self::checked_add(*self, other as Self)
4518 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4520 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4521 use self::IntErrorKind::*;
4522 use self::ParseIntError as PIE;
4524 assert!(radix >= 2 && radix <= 36,
4525 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4529 return Err(PIE { kind: Empty });
4532 let is_signed_ty = T::from_u32(0) > T::min_value();
4534 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4535 // and cast them to chars. .to_digit() will safely return None for anything
4536 // other than a valid ascii digit for the given radix, including the first-byte
4537 // of multi-byte sequences
4538 let src = src.as_bytes();
4540 let (is_positive, digits) = match src[0] {
4541 b'+' => (true, &src[1..]),
4542 b'-' if is_signed_ty => (false, &src[1..]),
4546 if digits.is_empty() {
4547 return Err(PIE { kind: Empty });
4550 let mut result = T::from_u32(0);
4552 // The number is positive
4554 let x = match (c as char).to_digit(radix) {
4556 None => return Err(PIE { kind: InvalidDigit }),
4558 result = match result.checked_mul(radix) {
4559 Some(result) => result,
4560 None => return Err(PIE { kind: Overflow }),
4562 result = match result.checked_add(x) {
4563 Some(result) => result,
4564 None => return Err(PIE { kind: Overflow }),
4568 // The number is negative
4570 let x = match (c as char).to_digit(radix) {
4572 None => return Err(PIE { kind: InvalidDigit }),
4574 result = match result.checked_mul(radix) {
4575 Some(result) => result,
4576 None => return Err(PIE { kind: Underflow }),
4578 result = match result.checked_sub(x) {
4579 Some(result) => result,
4580 None => return Err(PIE { kind: Underflow }),
4587 /// An error which can be returned when parsing an integer.
4589 /// This error is used as the error type for the `from_str_radix()` functions
4590 /// on the primitive integer types, such as [`i8::from_str_radix`].
4592 /// # Potential causes
4594 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
4595 /// in the string e.g. when it is obtained from the standard input.
4596 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
4598 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
4599 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
4600 #[derive(Debug, Clone, PartialEq, Eq)]
4601 #[stable(feature = "rust1", since = "1.0.0")]
4602 pub struct ParseIntError {
4606 #[derive(Debug, Clone, PartialEq, Eq)]
4614 impl ParseIntError {
4615 #[unstable(feature = "int_error_internals",
4616 reason = "available through Error trait and this method should \
4617 not be exposed publicly",
4620 pub fn __description(&self) -> &str {
4622 IntErrorKind::Empty => "cannot parse integer from empty string",
4623 IntErrorKind::InvalidDigit => "invalid digit found in string",
4624 IntErrorKind::Overflow => "number too large to fit in target type",
4625 IntErrorKind::Underflow => "number too small to fit in target type",
4630 #[stable(feature = "rust1", since = "1.0.0")]
4631 impl fmt::Display for ParseIntError {
4632 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4633 self.__description().fmt(f)
4637 #[stable(feature = "rust1", since = "1.0.0")]
4638 pub use num::dec2flt::ParseFloatError;
4640 // Conversion traits for primitive integer and float types
4641 // Conversions T -> T are covered by a blanket impl and therefore excluded
4642 // Some conversions from and to usize/isize are not implemented due to portability concerns
4643 macro_rules! impl_from {
4644 ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
4647 impl From<$Small> for $Large {
4649 fn from(small: $Small) -> $Large {
4654 ($Small: ty, $Large: ty, #[$attr:meta]) => {
4658 concat!("Converts `",
4666 macro_rules! impl_from_bool {
4667 ($target: ty, #[$attr:meta]) => {
4668 impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
4669 stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
4675 assert_eq!(", stringify!($target), "::from(true), 1);
4676 assert_eq!(", stringify!($target), "::from(false), 0);
4682 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
4683 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
4684 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
4685 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
4686 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
4687 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
4688 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
4689 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
4690 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
4691 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
4692 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
4693 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
4695 // Unsigned -> Unsigned
4696 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4697 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4698 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4699 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
4700 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4701 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4702 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4703 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
4704 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4705 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
4706 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
4709 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4710 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4711 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4712 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4713 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4714 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4715 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4716 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4717 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4718 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4719 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4721 // Unsigned -> Signed
4722 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4723 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4724 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4725 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4726 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4727 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4728 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4729 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4730 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4731 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4733 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
4734 // which imply that pointer-sized integers must be at least 16 bits:
4735 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
4736 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4737 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4738 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4740 // RISC-V defines the possibility of a 128-bit address space (RV128).
4742 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
4743 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
4744 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
4747 // Note: integers can only be represented with full precision in a float if
4748 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4749 // Lossy float conversions are not implemented at this time.
4752 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4753 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4754 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4755 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4756 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4758 // Unsigned -> Float
4759 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4760 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4761 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4762 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4763 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4766 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4768 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4769 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4770 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4771 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4772 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4773 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4774 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4775 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4776 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4779 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4780 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4781 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4784 b'[', b'\\', b']', b'^', b'_',
4785 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4786 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4787 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4788 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4789 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4790 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4791 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4792 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4793 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4794 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4795 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4796 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4797 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4798 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4799 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4800 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4801 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4802 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4803 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4804 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4807 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4808 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4809 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4810 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4811 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4812 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4813 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4814 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4815 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4816 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4817 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4818 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4819 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4822 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4823 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4824 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4827 b'{', b'|', b'}', b'~', 0x7f,
4828 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4829 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4830 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4831 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4832 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4833 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4834 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4835 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4836 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4837 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4838 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4839 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4840 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4841 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4842 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4843 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4846 enum AsciiCharacterClass {
4848 Cw, // control whitespace
4852 Lx, // lowercase hex digit
4854 Ux, // uppercase hex digit
4857 use self::AsciiCharacterClass::*;
4859 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4860 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4861 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4862 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4863 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4864 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4865 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4866 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4867 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4868 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_