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")]
15 use convert::{Infallible, TryFrom};
21 /// Provides intentionally-wrapped arithmetic on `T`.
23 /// Operations like `+` on `u32` values is intended to never overflow,
24 /// and in some debug configurations overflow is detected and results
25 /// in a panic. While most arithmetic falls into this category, some
26 /// code explicitly expects and relies upon modular arithmetic (e.g.,
29 /// Wrapping arithmetic can be achieved either through methods like
30 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
31 /// all standard arithmetic operations on the underlying value are
32 /// intended to have wrapping semantics.
37 /// use std::num::Wrapping;
39 /// let zero = Wrapping(0u32);
40 /// let one = Wrapping(1u32);
42 /// assert_eq!(std::u32::MAX, (zero - one).0);
44 #[stable(feature = "rust1", since = "1.0.0")]
45 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
46 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
49 #[stable(feature = "rust1", since = "1.0.0")]
50 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56 #[stable(feature = "wrapping_display", since = "1.10.0")]
57 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
58 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
64 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
65 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
71 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
72 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
77 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
78 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
79 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
85 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
86 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93 // All these modules are technically private and only exposed for coretests:
99 macro_rules! doc_comment {
100 ($x:expr, $($tt:tt)*) => {
106 // `Int` + `SignedInt` implemented for signed integers
107 macro_rules! int_impl {
108 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
109 $EndFeature:expr) => {
111 concat!("Returns the smallest value that can be represented by this integer type.
118 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
121 #[stable(feature = "rust1", since = "1.0.0")]
123 pub const fn min_value() -> Self {
124 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
129 concat!("Returns the largest value that can be represented by this integer type.
136 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
139 #[stable(feature = "rust1", since = "1.0.0")]
141 pub const fn max_value() -> Self {
147 concat!("Converts a string slice in a given base to an integer.
149 The string is expected to be an optional `+` or `-` sign followed by digits.
150 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
151 depending on `radix`:
159 This function panics if `radix` is not in the range from 2 to 36.
166 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
169 #[stable(feature = "rust1", since = "1.0.0")]
170 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
171 from_str_radix(src, radix)
176 concat!("Returns the number of ones in the binary representation of `self`.
183 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
185 assert_eq!(n.count_ones(), 1);",
189 #[stable(feature = "rust1", since = "1.0.0")]
191 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
195 concat!("Returns the number of zeros in the binary representation of `self`.
202 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
204 #[stable(feature = "rust1", since = "1.0.0")]
206 pub fn count_zeros(self) -> u32 {
212 concat!("Returns the number of leading zeros in the binary representation of `self`.
219 ", $Feature, "let n = -1", stringify!($SelfT), ";
221 assert_eq!(n.leading_zeros(), 0);",
224 #[stable(feature = "rust1", since = "1.0.0")]
226 pub fn leading_zeros(self) -> u32 {
227 (self as $UnsignedT).leading_zeros()
232 concat!("Returns the number of trailing zeros in the binary representation of `self`.
239 ", $Feature, "let n = -4", stringify!($SelfT), ";
241 assert_eq!(n.trailing_zeros(), 2);",
244 #[stable(feature = "rust1", since = "1.0.0")]
246 pub fn trailing_zeros(self) -> u32 {
247 (self as $UnsignedT).trailing_zeros()
251 /// Shifts the bits to the left by a specified amount, `n`,
252 /// wrapping the truncated bits to the end of the resulting integer.
254 /// Please note this isn't the same operation as `<<`!
258 /// Please note that this example is shared between integer types.
259 /// Which explains why `i64` is used here.
264 /// let n = 0x0123456789ABCDEFi64;
265 /// let m = -0x76543210FEDCBA99i64;
267 /// assert_eq!(n.rotate_left(32), m);
269 #[stable(feature = "rust1", since = "1.0.0")]
271 pub fn rotate_left(self, n: u32) -> Self {
272 (self as $UnsignedT).rotate_left(n) as Self
275 /// Shifts the bits to the right by a specified amount, `n`,
276 /// wrapping the truncated bits to the beginning of the resulting
279 /// Please note this isn't the same operation as `>>`!
283 /// Please note that this example is shared between integer types.
284 /// Which explains why `i64` is used here.
289 /// let n = 0x0123456789ABCDEFi64;
290 /// let m = -0xFEDCBA987654322i64;
292 /// assert_eq!(n.rotate_right(4), m);
294 #[stable(feature = "rust1", since = "1.0.0")]
296 pub fn rotate_right(self, n: u32) -> Self {
297 (self as $UnsignedT).rotate_right(n) as Self
300 /// Reverses the byte order of the integer.
304 /// Please note that this example is shared between integer types.
305 /// Which explains why `i16` is used here.
310 /// let n: i16 = 0b0000000_01010101;
311 /// assert_eq!(n, 85);
313 /// let m = n.swap_bytes();
315 /// assert_eq!(m, 0b01010101_00000000);
316 /// assert_eq!(m, 21760);
318 #[stable(feature = "rust1", since = "1.0.0")]
320 pub fn swap_bytes(self) -> Self {
321 (self as $UnsignedT).swap_bytes() as Self
325 concat!("Converts an integer from big endian to the target's endianness.
327 On big endian this is a no-op. On little endian the bytes are swapped.
334 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
336 if cfg!(target_endian = \"big\") {
337 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
339 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
343 #[stable(feature = "rust1", since = "1.0.0")]
345 pub fn from_be(x: Self) -> Self {
346 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
351 concat!("Converts an integer from little endian to the target's endianness.
353 On little endian this is a no-op. On big endian the bytes are swapped.
360 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
362 if cfg!(target_endian = \"little\") {
363 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
365 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
369 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn from_le(x: Self) -> Self {
372 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
377 concat!("Converts `self` to big endian from the target's endianness.
379 On big endian this is a no-op. On little endian the bytes are swapped.
386 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
388 if cfg!(target_endian = \"big\") {
389 assert_eq!(n.to_be(), n)
391 assert_eq!(n.to_be(), n.swap_bytes())
395 #[stable(feature = "rust1", since = "1.0.0")]
397 pub fn to_be(self) -> Self { // or not to be?
398 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
403 concat!("Converts `self` to little endian from the target's endianness.
405 On little endian this is a no-op. On big endian the bytes are swapped.
412 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
414 if cfg!(target_endian = \"little\") {
415 assert_eq!(n.to_le(), n)
417 assert_eq!(n.to_le(), n.swap_bytes())
421 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn to_le(self) -> Self {
424 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
429 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
430 if overflow occurred.
437 ", $Feature, "assert_eq!((", stringify!($SelfT),
438 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
439 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
442 #[stable(feature = "rust1", since = "1.0.0")]
444 pub fn checked_add(self, rhs: Self) -> Option<Self> {
445 let (a, b) = self.overflowing_add(rhs);
446 if b {None} else {Some(a)}
451 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
459 ", $Feature, "assert_eq!((", stringify!($SelfT),
460 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
461 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
464 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
467 let (a, b) = self.overflowing_sub(rhs);
468 if b {None} else {Some(a)}
473 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
481 ", $Feature, "assert_eq!(", stringify!($SelfT),
482 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
483 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
486 #[stable(feature = "rust1", since = "1.0.0")]
488 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
489 let (a, b) = self.overflowing_mul(rhs);
490 if b {None} else {Some(a)}
495 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
496 or the division results in overflow.
503 ", $Feature, "assert_eq!((", stringify!($SelfT),
504 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
505 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
506 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
509 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn checked_div(self, rhs: Self) -> Option<Self> {
512 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
515 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
521 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
522 `rhs == 0` or the division results in overflow.
529 ", $Feature, "use std::", stringify!($SelfT), ";
531 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
532 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
533 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
536 #[stable(feature = "wrapping", since = "1.7.0")]
538 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
539 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
542 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
548 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
555 ", $Feature, "use std::", stringify!($SelfT), ";
557 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
558 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
561 #[stable(feature = "wrapping", since = "1.7.0")]
563 pub fn checked_neg(self) -> Option<Self> {
564 let (a, b) = self.overflowing_neg();
565 if b {None} else {Some(a)}
570 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
571 than or equal to the number of bits in `self`.
578 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
579 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
582 #[stable(feature = "wrapping", since = "1.7.0")]
584 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
585 let (a, b) = self.overflowing_shl(rhs);
586 if b {None} else {Some(a)}
591 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
592 larger than or equal to the number of bits in `self`.
599 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
600 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
603 #[stable(feature = "wrapping", since = "1.7.0")]
605 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
606 let (a, b) = self.overflowing_shr(rhs);
607 if b {None} else {Some(a)}
612 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
620 ", $Feature, "use std::", stringify!($SelfT), ";
622 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
623 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
626 #[stable(feature = "no_panic_abs", since = "1.13.0")]
628 pub fn checked_abs(self) -> Option<Self> {
629 if self.is_negative() {
638 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
639 bounds instead of overflowing.
646 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
647 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
651 #[stable(feature = "rust1", since = "1.0.0")]
653 pub fn saturating_add(self, rhs: Self) -> Self {
654 match self.checked_add(rhs) {
656 None if rhs >= 0 => Self::max_value(),
657 None => Self::min_value(),
663 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
664 numeric bounds instead of overflowing.
671 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
672 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
676 #[stable(feature = "rust1", since = "1.0.0")]
678 pub fn saturating_sub(self, rhs: Self) -> Self {
679 match self.checked_sub(rhs) {
681 None if rhs >= 0 => Self::min_value(),
682 None => Self::max_value(),
688 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
689 numeric bounds instead of overflowing.
696 ", $Feature, "use std::", stringify!($SelfT), ";
698 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
699 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
700 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
703 #[stable(feature = "wrapping", since = "1.7.0")]
705 pub fn saturating_mul(self, rhs: Self) -> Self {
706 self.checked_mul(rhs).unwrap_or_else(|| {
707 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
717 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
718 boundary of the type.
725 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
726 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
727 "::min_value() + 1);",
730 #[stable(feature = "rust1", since = "1.0.0")]
732 pub fn wrapping_add(self, rhs: Self) -> Self {
734 intrinsics::overflowing_add(self, rhs)
740 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
741 boundary of the type.
748 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
749 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
750 stringify!($SelfT), "::max_value());",
753 #[stable(feature = "rust1", since = "1.0.0")]
755 pub fn wrapping_sub(self, rhs: Self) -> Self {
757 intrinsics::overflowing_sub(self, rhs)
763 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
764 the boundary of the type.
771 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
772 assert_eq!(11i8.wrapping_mul(12), -124);",
775 #[stable(feature = "rust1", since = "1.0.0")]
777 pub fn wrapping_mul(self, rhs: Self) -> Self {
779 intrinsics::overflowing_mul(self, rhs)
785 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
786 boundary of the type.
788 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
789 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
790 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
794 This function will panic if `rhs` is 0.
801 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
802 assert_eq!((-128i8).wrapping_div(-1), -128);",
805 #[stable(feature = "num_wrapping", since = "1.2.0")]
807 pub fn wrapping_div(self, rhs: Self) -> Self {
808 self.overflowing_div(rhs).0
813 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
814 boundary of the type.
816 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
817 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
818 this function returns `0`.
822 This function will panic if `rhs` is 0.
829 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
830 assert_eq!((-128i8).wrapping_rem(-1), 0);",
833 #[stable(feature = "num_wrapping", since = "1.2.0")]
835 pub fn wrapping_rem(self, rhs: Self) -> Self {
836 self.overflowing_rem(rhs).0
841 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
844 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
845 is the negative minimal value for the type); this is a positive value that is too large to represent
846 in the type. In such a case, this function returns `MIN` itself.
853 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
854 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
858 #[stable(feature = "num_wrapping", since = "1.2.0")]
860 pub fn wrapping_neg(self) -> Self {
861 self.overflowing_neg().0
866 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
867 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
869 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
870 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
871 The primitive integer types all implement a `rotate_left` function, which may be what you want
879 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
880 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
883 #[stable(feature = "num_wrapping", since = "1.2.0")]
885 pub fn wrapping_shl(self, rhs: u32) -> Self {
887 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
893 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
894 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
896 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
897 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
898 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
906 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
907 assert_eq!((-128i16).wrapping_shr(64), -128);",
910 #[stable(feature = "num_wrapping", since = "1.2.0")]
912 pub fn wrapping_shr(self, rhs: u32) -> Self {
914 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
920 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
921 the boundary of the type.
923 The only case where such wrapping can occur is when one takes the absolute value of the negative
924 minimal value for the type this is a positive value that is too large to represent in the type. In
925 such a case, this function returns `MIN` itself.
932 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
933 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
934 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
936 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
939 #[stable(feature = "no_panic_abs", since = "1.13.0")]
941 pub fn wrapping_abs(self) -> Self {
942 if self.is_negative() {
951 concat!("Calculates `self` + `rhs`
953 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
954 occur. If an overflow would have occurred then the wrapped value is returned.
961 ", $Feature, "use std::", stringify!($SelfT), ";
963 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
964 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
965 "::MIN, true));", $EndFeature, "
968 #[stable(feature = "wrapping", since = "1.7.0")]
969 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
970 let (a, b) = unsafe {
971 intrinsics::add_with_overflow(self as $ActualT,
979 concat!("Calculates `self` - `rhs`
981 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
982 would occur. If an overflow would have occurred then the wrapped value is returned.
989 ", $Feature, "use std::", stringify!($SelfT), ";
991 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
992 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
993 "::MAX, true));", $EndFeature, "
996 #[stable(feature = "wrapping", since = "1.7.0")]
997 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
998 let (a, b) = unsafe {
999 intrinsics::sub_with_overflow(self as $ActualT,
1007 concat!("Calculates the multiplication of `self` and `rhs`.
1009 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1010 would occur. If an overflow would have occurred then the wrapped value is returned.
1017 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1018 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1022 #[stable(feature = "wrapping", since = "1.7.0")]
1023 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1024 let (a, b) = unsafe {
1025 intrinsics::mul_with_overflow(self as $ActualT,
1033 concat!("Calculates the divisor when `self` is divided by `rhs`.
1035 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1036 occur. If an overflow would occur then self is returned.
1040 This function will panic if `rhs` is 0.
1047 ", $Feature, "use std::", stringify!($SelfT), ";
1049 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1050 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1055 #[stable(feature = "wrapping", since = "1.7.0")]
1056 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1057 if self == Self::min_value() && rhs == -1 {
1066 concat!("Calculates the remainder when `self` is divided by `rhs`.
1068 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1069 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1073 This function will panic if `rhs` is 0.
1080 ", $Feature, "use std::", stringify!($SelfT), ";
1082 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1083 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1087 #[stable(feature = "wrapping", since = "1.7.0")]
1088 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1089 if self == Self::min_value() && rhs == -1 {
1098 concat!("Negates self, overflowing if this is equal to the minimum value.
1100 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1101 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1102 minimum value will be returned again and `true` will be returned for an overflow happening.
1109 ", $Feature, "use std::", stringify!($SelfT), ";
1111 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1112 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1113 "::MIN, true));", $EndFeature, "
1116 #[stable(feature = "wrapping", since = "1.7.0")]
1117 pub fn overflowing_neg(self) -> (Self, bool) {
1118 if self == Self::min_value() {
1119 (Self::min_value(), true)
1127 concat!("Shifts self left by `rhs` bits.
1129 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1130 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1131 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1138 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1139 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1143 #[stable(feature = "wrapping", since = "1.7.0")]
1144 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1145 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1150 concat!("Shifts self right by `rhs` bits.
1152 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1153 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1154 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1161 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1162 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1166 #[stable(feature = "wrapping", since = "1.7.0")]
1167 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1168 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1173 concat!("Computes the absolute value of `self`.
1175 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1176 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1177 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1178 for an overflow happening.
1185 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1186 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1187 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1188 "::min_value(), true));",
1191 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1193 pub fn overflowing_abs(self) -> (Self, bool) {
1194 if self.is_negative() {
1195 self.overflowing_neg()
1203 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1210 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1212 assert_eq!(x.pow(5), 32);",
1215 #[stable(feature = "rust1", since = "1.0.0")]
1217 #[rustc_inherit_overflow_checks]
1218 pub fn pow(self, mut exp: u32) -> Self {
1219 let mut base = self;
1230 // Deal with the final bit of the exponent separately, since
1231 // squaring the base afterwards is not necessary and may cause a
1232 // needless overflow.
1242 concat!("Computes the absolute value of `self`.
1246 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1247 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1248 code in debug mode will trigger a panic on this case and optimized code will return `",
1249 stringify!($SelfT), "::min_value()` without a panic.
1256 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1257 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1260 #[stable(feature = "rust1", since = "1.0.0")]
1262 #[rustc_inherit_overflow_checks]
1263 pub fn abs(self) -> Self {
1264 if self.is_negative() {
1265 // Note that the #[inline] above means that the overflow
1266 // semantics of this negation depend on the crate we're being
1276 concat!("Returns a number representing sign of `self`.
1278 - `0` if the number is zero
1279 - `1` if the number is positive
1280 - `-1` if the number is negative
1287 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1288 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1289 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1292 #[stable(feature = "rust1", since = "1.0.0")]
1294 pub fn signum(self) -> Self {
1304 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1312 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1313 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1316 #[stable(feature = "rust1", since = "1.0.0")]
1318 pub fn is_positive(self) -> bool { self > 0 }
1322 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1330 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1331 assert!(!10", stringify!($SelfT), ".is_negative());",
1334 #[stable(feature = "rust1", since = "1.0.0")]
1336 pub fn is_negative(self) -> bool { self < 0 }
1343 int_impl! { i8, i8, u8, 8, -128, 127, "", "" }
1348 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "" }
1353 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "" }
1358 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1363 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
1364 170141183460469231731687303715884105727, "#![feature(i128_type)]
1371 #[cfg(target_pointer_width = "16")]
1374 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "" }
1377 #[cfg(target_pointer_width = "32")]
1380 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "" }
1383 #[cfg(target_pointer_width = "64")]
1386 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1389 // `Int` + `UnsignedInt` implemented for unsigned integers
1390 macro_rules! uint_impl {
1391 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr) => {
1393 concat!("Returns the smallest value that can be represented by this integer type.
1400 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
1402 #[stable(feature = "rust1", since = "1.0.0")]
1404 pub const fn min_value() -> Self { 0 }
1408 concat!("Returns the largest value that can be represented by this integer type.
1415 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
1416 stringify!($MaxV), ");", $EndFeature, "
1418 #[stable(feature = "rust1", since = "1.0.0")]
1420 pub const fn max_value() -> Self { !0 }
1424 concat!("Converts a string slice in a given base to an integer.
1426 The string is expected to be an optional `+` sign
1428 Leading and trailing whitespace represent an error.
1429 Digits are a subset of these characters, depending on `radix`:
1437 This function panics if `radix` is not in the range from 2 to 36.
1444 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1449 from_str_radix(src, radix)
1454 concat!("Returns the number of ones in the binary representation of `self`.
1461 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
1463 assert_eq!(n.count_ones(), 3);", $EndFeature, "
1465 #[stable(feature = "rust1", since = "1.0.0")]
1467 pub fn count_ones(self) -> u32 {
1468 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
1473 concat!("Returns the number of zeros in the binary representation of `self`.
1480 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
1482 #[stable(feature = "rust1", since = "1.0.0")]
1484 pub fn count_zeros(self) -> u32 {
1485 (!self).count_ones()
1490 concat!("Returns the number of leading zeros in the binary representation of `self`.
1497 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
1499 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
1501 #[stable(feature = "rust1", since = "1.0.0")]
1503 pub fn leading_zeros(self) -> u32 {
1504 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
1509 concat!("Returns the number of trailing zeros in the binary representation
1517 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
1519 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
1521 #[stable(feature = "rust1", since = "1.0.0")]
1523 pub fn trailing_zeros(self) -> u32 {
1524 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1525 // emits two conditional moves on x86_64. By promoting the value to
1526 // u16 and setting bit 8, we get better code without any conditional
1528 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1529 // pending, remove this workaround once LLVM generates better code
1533 intrinsics::cttz(self as u16 | 0x100) as u32
1535 intrinsics::cttz(self) as u32
1541 /// Shifts the bits to the left by a specified amount, `n`,
1542 /// wrapping the truncated bits to the end of the resulting integer.
1544 /// Please note this isn't the same operation as `<<`!
1550 /// Please note that this example is shared between integer types.
1551 /// Which explains why `u64` is used here.
1554 /// let n = 0x0123456789ABCDEFu64;
1555 /// let m = 0x3456789ABCDEF012u64;
1557 /// assert_eq!(n.rotate_left(12), m);
1559 #[stable(feature = "rust1", since = "1.0.0")]
1561 pub fn rotate_left(self, n: u32) -> Self {
1562 // Protect against undefined behaviour for over-long bit shifts
1564 (self << n) | (self >> (($BITS - n) % $BITS))
1567 /// Shifts the bits to the right by a specified amount, `n`,
1568 /// wrapping the truncated bits to the beginning of the resulting
1571 /// Please note this isn't the same operation as `>>`!
1577 /// Please note that this example is shared between integer types.
1578 /// Which explains why `u64` is used here.
1581 /// let n = 0x0123456789ABCDEFu64;
1582 /// let m = 0xDEF0123456789ABCu64;
1584 /// assert_eq!(n.rotate_right(12), m);
1586 #[stable(feature = "rust1", since = "1.0.0")]
1588 pub fn rotate_right(self, n: u32) -> Self {
1589 // Protect against undefined behaviour for over-long bit shifts
1591 (self >> n) | (self << (($BITS - n) % $BITS))
1594 /// Reverses the byte order of the integer.
1600 /// Please note that this example is shared between integer types.
1601 /// Which explains why `u16` is used here.
1604 /// let n: u16 = 0b0000000_01010101;
1605 /// assert_eq!(n, 85);
1607 /// let m = n.swap_bytes();
1609 /// assert_eq!(m, 0b01010101_00000000);
1610 /// assert_eq!(m, 21760);
1612 #[stable(feature = "rust1", since = "1.0.0")]
1614 pub fn swap_bytes(self) -> Self {
1615 unsafe { intrinsics::bswap(self as $ActualT) as Self }
1619 concat!("Converts an integer from big endian to the target's endianness.
1621 On big endian this is a no-op. On little endian the bytes are
1629 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1631 if cfg!(target_endian = \"big\") {
1632 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
1634 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
1637 #[stable(feature = "rust1", since = "1.0.0")]
1639 pub fn from_be(x: Self) -> Self {
1640 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1645 concat!("Converts an integer from little endian to the target's endianness.
1647 On little endian this is a no-op. On big endian the bytes are
1655 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1657 if cfg!(target_endian = \"little\") {
1658 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
1660 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
1663 #[stable(feature = "rust1", since = "1.0.0")]
1665 pub fn from_le(x: Self) -> Self {
1666 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1671 concat!("Converts `self` to big endian from the target's endianness.
1673 On big endian this is a no-op. On little endian the bytes are
1681 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1683 if cfg!(target_endian = \"big\") {
1684 assert_eq!(n.to_be(), n)
1686 assert_eq!(n.to_be(), n.swap_bytes())
1689 #[stable(feature = "rust1", since = "1.0.0")]
1691 pub fn to_be(self) -> Self { // or not to be?
1692 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1697 concat!("Converts `self` to little endian from the target's endianness.
1699 On little endian this is a no-op. On big endian the bytes are
1707 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1709 if cfg!(target_endian = \"little\") {
1710 assert_eq!(n.to_le(), n)
1712 assert_eq!(n.to_le(), n.swap_bytes())
1715 #[stable(feature = "rust1", since = "1.0.0")]
1717 pub fn to_le(self) -> Self {
1718 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1723 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
1724 if overflow occurred.
1731 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
1732 "Some(", stringify!($SelfT), "::max_value() - 1));
1733 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3),None);", $EndFeature, "
1735 #[stable(feature = "rust1", since = "1.0.0")]
1737 pub fn checked_add(self, rhs: Self) -> Option<Self> {
1738 let (a, b) = self.overflowing_add(rhs);
1739 if b {None} else {Some(a)}
1744 concat!("Checked integer subtraction. Computes `self - rhs`, returning
1745 `None` if overflow occurred.
1752 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
1753 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
1755 #[stable(feature = "rust1", since = "1.0.0")]
1757 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
1758 let (a, b) = self.overflowing_sub(rhs);
1759 if b {None} else {Some(a)}
1764 concat!("Checked integer multiplication. Computes `self * rhs`, returning
1765 `None` if overflow occurred.
1772 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
1773 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
1775 #[stable(feature = "rust1", since = "1.0.0")]
1777 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
1778 let (a, b) = self.overflowing_mul(rhs);
1779 if b {None} else {Some(a)}
1784 concat!("Checked integer division. Computes `self / rhs`, returning `None`
1792 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
1793 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
1795 #[stable(feature = "rust1", since = "1.0.0")]
1797 pub fn checked_div(self, rhs: Self) -> Option<Self> {
1800 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
1806 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
1814 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
1815 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
1817 #[stable(feature = "wrapping", since = "1.7.0")]
1819 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
1823 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
1829 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
1832 Note that negating any positive integer will overflow.
1839 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
1840 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
1842 #[stable(feature = "wrapping", since = "1.7.0")]
1844 pub fn checked_neg(self) -> Option<Self> {
1845 let (a, b) = self.overflowing_neg();
1846 if b {None} else {Some(a)}
1851 concat!("Checked shift left. Computes `self << rhs`, returning `None`
1852 if `rhs` is larger than or equal to the number of bits in `self`.
1859 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
1860 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
1862 #[stable(feature = "wrapping", since = "1.7.0")]
1864 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1865 let (a, b) = self.overflowing_shl(rhs);
1866 if b {None} else {Some(a)}
1871 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
1872 if `rhs` is larger than or equal to the number of bits in `self`.
1879 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
1880 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
1882 #[stable(feature = "wrapping", since = "1.7.0")]
1884 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1885 let (a, b) = self.overflowing_shr(rhs);
1886 if b {None} else {Some(a)}
1891 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
1892 the numeric bounds instead of overflowing.
1899 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
1900 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
1902 #[stable(feature = "rust1", since = "1.0.0")]
1904 pub fn saturating_add(self, rhs: Self) -> Self {
1905 match self.checked_add(rhs) {
1907 None => Self::max_value(),
1913 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
1914 at the numeric bounds instead of overflowing.
1921 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
1922 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
1924 #[stable(feature = "rust1", since = "1.0.0")]
1926 pub fn saturating_sub(self, rhs: Self) -> Self {
1927 match self.checked_sub(rhs) {
1929 None => Self::min_value(),
1935 concat!("Saturating integer multiplication. Computes `self * rhs`,
1936 saturating at the numeric bounds instead of overflowing.
1943 ", $Feature, "use std::", stringify!($SelfT), ";
1945 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
1946 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
1947 "::MAX);", $EndFeature, "
1949 #[stable(feature = "wrapping", since = "1.7.0")]
1951 pub fn saturating_mul(self, rhs: Self) -> Self {
1952 self.checked_mul(rhs).unwrap_or(Self::max_value())
1957 concat!("Wrapping (modular) addition. Computes `self + rhs`,
1958 wrapping around at the boundary of the type.
1965 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
1966 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
1969 #[stable(feature = "rust1", since = "1.0.0")]
1971 pub fn wrapping_add(self, rhs: Self) -> Self {
1973 intrinsics::overflowing_add(self, rhs)
1979 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
1980 wrapping around at the boundary of the type.
1987 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
1988 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
1991 #[stable(feature = "rust1", since = "1.0.0")]
1993 pub fn wrapping_sub(self, rhs: Self) -> Self {
1995 intrinsics::overflowing_sub(self, rhs)
2000 /// Wrapping (modular) multiplication. Computes `self *
2001 /// rhs`, wrapping around at the boundary of the type.
2007 /// Please note that this example is shared between integer types.
2008 /// Which explains why `u8` is used here.
2011 /// assert_eq!(10u8.wrapping_mul(12), 120);
2012 /// assert_eq!(25u8.wrapping_mul(12), 44);
2014 #[stable(feature = "rust1", since = "1.0.0")]
2016 pub fn wrapping_mul(self, rhs: Self) -> Self {
2018 intrinsics::overflowing_mul(self, rhs)
2023 concat!("Wrapping (modular) division. Computes `self / rhs`.
2024 Wrapped division on unsigned types is just normal division.
2025 There's no way wrapping could ever happen.
2026 This function exists, so that all operations
2027 are accounted for in the wrapping operations.
2034 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2036 #[stable(feature = "num_wrapping", since = "1.2.0")]
2038 pub fn wrapping_div(self, rhs: Self) -> Self {
2044 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2045 Wrapped remainder calculation on unsigned types is
2046 just the regular remainder calculation.
2047 There's no way wrapping could ever happen.
2048 This function exists, so that all operations
2049 are accounted for in the wrapping operations.
2056 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2058 #[stable(feature = "num_wrapping", since = "1.2.0")]
2060 pub fn wrapping_rem(self, rhs: Self) -> Self {
2065 /// Wrapping (modular) negation. Computes `-self`,
2066 /// wrapping around at the boundary of the type.
2068 /// Since unsigned types do not have negative equivalents
2069 /// all applications of this function will wrap (except for `-0`).
2070 /// For values smaller than the corresponding signed type's maximum
2071 /// the result is the same as casting the corresponding signed value.
2072 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2073 /// `MAX` is the corresponding signed type's maximum.
2079 /// Please note that this example is shared between integer types.
2080 /// Which explains why `i8` is used here.
2083 /// assert_eq!(100i8.wrapping_neg(), -100);
2084 /// assert_eq!((-128i8).wrapping_neg(), -128);
2086 #[stable(feature = "num_wrapping", since = "1.2.0")]
2088 pub fn wrapping_neg(self) -> Self {
2089 self.overflowing_neg().0
2093 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2094 where `mask` removes any high-order bits of `rhs` that
2095 would cause the shift to exceed the bitwidth of the type.
2097 Note that this is *not* the same as a rotate-left; the
2098 RHS of a wrapping shift-left is restricted to the range
2099 of the type, rather than the bits shifted out of the LHS
2100 being returned to the other end. The primitive integer
2101 types all implement a `rotate_left` function, which may
2102 be what you want instead.
2109 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2110 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2112 #[stable(feature = "num_wrapping", since = "1.2.0")]
2114 pub fn wrapping_shl(self, rhs: u32) -> Self {
2116 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
2122 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2123 where `mask` removes any high-order bits of `rhs` that
2124 would cause the shift to exceed the bitwidth of the type.
2126 Note that this is *not* the same as a rotate-right; the
2127 RHS of a wrapping shift-right is restricted to the range
2128 of the type, rather than the bits shifted out of the LHS
2129 being returned to the other end. The primitive integer
2130 types all implement a `rotate_right` function, which may
2131 be what you want instead.
2138 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
2139 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
2141 #[stable(feature = "num_wrapping", since = "1.2.0")]
2143 pub fn wrapping_shr(self, rhs: u32) -> Self {
2145 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
2151 concat!("Calculates `self` + `rhs`
2153 Returns a tuple of the addition along with a boolean indicating
2154 whether an arithmetic overflow would occur. If an overflow would
2155 have occurred then the wrapped value is returned.
2162 ", $Feature, "use std::", stringify!($SelfT), ";
2164 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
2165 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
2168 #[stable(feature = "wrapping", since = "1.7.0")]
2169 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2170 let (a, b) = unsafe {
2171 intrinsics::add_with_overflow(self as $ActualT,
2179 concat!("Calculates `self` - `rhs`
2181 Returns a tuple of the subtraction along with a boolean indicating
2182 whether an arithmetic overflow would occur. If an overflow would
2183 have occurred then the wrapped value is returned.
2190 ", $Feature, "use std::", stringify!($SelfT), ";
2192 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
2193 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
2197 #[stable(feature = "wrapping", since = "1.7.0")]
2198 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2199 let (a, b) = unsafe {
2200 intrinsics::sub_with_overflow(self as $ActualT,
2207 /// Calculates the multiplication of `self` and `rhs`.
2209 /// Returns a tuple of the multiplication along with a boolean
2210 /// indicating whether an arithmetic overflow would occur. If an
2211 /// overflow would have occurred then the wrapped value is returned.
2217 /// Please note that this example is shared between integer types.
2218 /// Which explains why `u32` is used here.
2221 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2222 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2225 #[stable(feature = "wrapping", since = "1.7.0")]
2226 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2227 let (a, b) = unsafe {
2228 intrinsics::mul_with_overflow(self as $ActualT,
2235 concat!("Calculates the divisor when `self` is divided by `rhs`.
2237 Returns a tuple of the divisor along with a boolean indicating
2238 whether an arithmetic overflow would occur. Note that for unsigned
2239 integers overflow never occurs, so the second value is always
2244 This function will panic if `rhs` is 0.
2251 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
2254 #[stable(feature = "wrapping", since = "1.7.0")]
2255 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2261 concat!("Calculates the remainder when `self` is divided by `rhs`.
2263 Returns a tuple of the remainder after dividing along with a boolean
2264 indicating whether an arithmetic overflow would occur. Note that for
2265 unsigned integers overflow never occurs, so the second value is
2270 This function will panic if `rhs` is 0.
2277 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
2280 #[stable(feature = "wrapping", since = "1.7.0")]
2281 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2287 concat!("Negates self in an overflowing fashion.
2289 Returns `!self + 1` using wrapping operations to return the value
2290 that represents the negation of this unsigned value. Note that for
2291 positive unsigned values overflow always occurs, but negating 0 does
2299 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
2300 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
2301 ", true));", $EndFeature, "
2304 #[stable(feature = "wrapping", since = "1.7.0")]
2305 pub fn overflowing_neg(self) -> (Self, bool) {
2306 ((!self).wrapping_add(1), self != 0)
2311 concat!("Shifts self left by `rhs` bits.
2313 Returns a tuple of the shifted version of self along with a boolean
2314 indicating whether the shift value was larger than or equal to the
2315 number of bits. If the shift value is too large, then value is
2316 masked (N-1) where N is the number of bits, and this value is then
2317 used to perform the shift.
2324 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
2325 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
2328 #[stable(feature = "wrapping", since = "1.7.0")]
2329 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2330 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
2335 concat!("Shifts self right by `rhs` bits.
2337 Returns a tuple of the shifted version of self along with a boolean
2338 indicating whether the shift value was larger than or equal to the
2339 number of bits. If the shift value is too large, then value is
2340 masked (N-1) where N is the number of bits, and this value is then
2341 used to perform the shift.
2348 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
2349 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
2352 #[stable(feature = "wrapping", since = "1.7.0")]
2353 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2354 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
2360 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2367 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
2369 #[stable(feature = "rust1", since = "1.0.0")]
2371 #[rustc_inherit_overflow_checks]
2372 pub fn pow(self, mut exp: u32) -> Self {
2373 let mut base = self;
2384 // Deal with the final bit of the exponent separately, since
2385 // squaring the base afterwards is not necessary and may cause a
2386 // needless overflow.
2396 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
2403 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
2404 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
2406 #[stable(feature = "rust1", since = "1.0.0")]
2408 pub fn is_power_of_two(self) -> bool {
2409 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2413 // Returns one less than next power of two.
2414 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2416 // 8u8.one_less_than_next_power_of_two() == 7
2417 // 6u8.one_less_than_next_power_of_two() == 7
2419 // This method cannot overflow, as in the `next_power_of_two`
2420 // overflow cases it instead ends up returning the maximum value
2421 // of the type, and can return 0 for 0.
2423 fn one_less_than_next_power_of_two(self) -> Self {
2424 if self <= 1 { return 0; }
2426 // Because `p > 0`, it cannot consist entirely of leading zeros.
2427 // That means the shift is always in-bounds, and some processors
2428 // (such as intel pre-haswell) have more efficient ctlz
2429 // intrinsics when the argument is non-zero.
2431 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2432 <$SelfT>::max_value() >> z
2436 concat!("Returns the smallest power of two greater than or equal to `self`.
2438 When return value overflows (i.e. `self > (1 << (N-1))` for type
2439 `uN`), it panics in debug mode and return value is wrapped to 0 in
2440 release mode (the only situation in which method can return 0).
2447 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
2448 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
2450 #[stable(feature = "rust1", since = "1.0.0")]
2452 pub fn next_power_of_two(self) -> Self {
2453 // Call the trait to get overflow checks
2454 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
2459 concat!("Returns the smallest power of two greater than or equal to `n`. If
2460 the next power of two is greater than the type's maximum value,
2461 `None` is returned, otherwise the power of two is wrapped in `Some`.
2468 ", $Feature, "assert_eq!(2", stringify!($SelfT),
2469 ".checked_next_power_of_two(), Some(2));
2470 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
2471 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
2474 #[stable(feature = "rust1", since = "1.0.0")]
2475 pub fn checked_next_power_of_two(self) -> Option<Self> {
2476 self.one_less_than_next_power_of_two().checked_add(1)
2484 uint_impl! { u8, u8, 8, 255, "", "" }
2487 /// Checks if the value is within the ASCII range.
2492 /// let ascii = 97u8;
2493 /// let non_ascii = 150u8;
2495 /// assert!(ascii.is_ascii());
2496 /// assert!(!non_ascii.is_ascii());
2498 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2500 pub fn is_ascii(&self) -> bool {
2504 /// Makes a copy of the value in its ASCII upper case equivalent.
2506 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2507 /// but non-ASCII letters are unchanged.
2509 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
2514 /// let lowercase_a = 97u8;
2516 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
2519 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
2520 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2522 pub fn to_ascii_uppercase(&self) -> u8 {
2523 ASCII_UPPERCASE_MAP[*self as usize]
2526 /// Makes a copy of the value in its ASCII lower case equivalent.
2528 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2529 /// but non-ASCII letters are unchanged.
2531 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
2536 /// let uppercase_a = 65u8;
2538 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
2541 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
2542 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2544 pub fn to_ascii_lowercase(&self) -> u8 {
2545 ASCII_LOWERCASE_MAP[*self as usize]
2548 /// Checks that two values are an ASCII case-insensitive match.
2550 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
2555 /// let lowercase_a = 97u8;
2556 /// let uppercase_a = 65u8;
2558 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
2560 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2562 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
2563 self.to_ascii_lowercase() == other.to_ascii_lowercase()
2566 /// Converts this value to its ASCII upper case equivalent in-place.
2568 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2569 /// but non-ASCII letters are unchanged.
2571 /// To return a new uppercased value without modifying the existing one, use
2572 /// [`to_ascii_uppercase`].
2577 /// let mut byte = b'a';
2579 /// byte.make_ascii_uppercase();
2581 /// assert_eq!(b'A', byte);
2584 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2585 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2587 pub fn make_ascii_uppercase(&mut self) {
2588 *self = self.to_ascii_uppercase();
2591 /// Converts this value to its ASCII lower case equivalent in-place.
2593 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2594 /// but non-ASCII letters are unchanged.
2596 /// To return a new lowercased value without modifying the existing one, use
2597 /// [`to_ascii_lowercase`].
2602 /// let mut byte = b'A';
2604 /// byte.make_ascii_lowercase();
2606 /// assert_eq!(b'a', byte);
2609 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2610 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2612 pub fn make_ascii_lowercase(&mut self) {
2613 *self = self.to_ascii_lowercase();
2616 /// Checks if the value is an ASCII alphabetic character:
2618 /// - U+0041 'A' ... U+005A 'Z', or
2619 /// - U+0061 'a' ... U+007A 'z'.
2624 /// #![feature(ascii_ctype)]
2626 /// let uppercase_a = b'A';
2627 /// let uppercase_g = b'G';
2630 /// let zero = b'0';
2631 /// let percent = b'%';
2632 /// let space = b' ';
2634 /// let esc = 0x1b_u8;
2636 /// assert!(uppercase_a.is_ascii_alphabetic());
2637 /// assert!(uppercase_g.is_ascii_alphabetic());
2638 /// assert!(a.is_ascii_alphabetic());
2639 /// assert!(g.is_ascii_alphabetic());
2640 /// assert!(!zero.is_ascii_alphabetic());
2641 /// assert!(!percent.is_ascii_alphabetic());
2642 /// assert!(!space.is_ascii_alphabetic());
2643 /// assert!(!lf.is_ascii_alphabetic());
2644 /// assert!(!esc.is_ascii_alphabetic());
2646 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2648 pub fn is_ascii_alphabetic(&self) -> bool {
2649 if *self >= 0x80 { return false; }
2650 match ASCII_CHARACTER_CLASS[*self as usize] {
2651 L | Lx | U | Ux => true,
2656 /// Checks if the value is an ASCII uppercase character:
2657 /// U+0041 'A' ... U+005A 'Z'.
2662 /// #![feature(ascii_ctype)]
2664 /// let uppercase_a = b'A';
2665 /// let uppercase_g = b'G';
2668 /// let zero = b'0';
2669 /// let percent = b'%';
2670 /// let space = b' ';
2672 /// let esc = 0x1b_u8;
2674 /// assert!(uppercase_a.is_ascii_uppercase());
2675 /// assert!(uppercase_g.is_ascii_uppercase());
2676 /// assert!(!a.is_ascii_uppercase());
2677 /// assert!(!g.is_ascii_uppercase());
2678 /// assert!(!zero.is_ascii_uppercase());
2679 /// assert!(!percent.is_ascii_uppercase());
2680 /// assert!(!space.is_ascii_uppercase());
2681 /// assert!(!lf.is_ascii_uppercase());
2682 /// assert!(!esc.is_ascii_uppercase());
2684 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2686 pub fn is_ascii_uppercase(&self) -> bool {
2687 if *self >= 0x80 { return false }
2688 match ASCII_CHARACTER_CLASS[*self as usize] {
2694 /// Checks if the value is an ASCII lowercase character:
2695 /// U+0061 'a' ... U+007A 'z'.
2700 /// #![feature(ascii_ctype)]
2702 /// let uppercase_a = b'A';
2703 /// let uppercase_g = b'G';
2706 /// let zero = b'0';
2707 /// let percent = b'%';
2708 /// let space = b' ';
2710 /// let esc = 0x1b_u8;
2712 /// assert!(!uppercase_a.is_ascii_lowercase());
2713 /// assert!(!uppercase_g.is_ascii_lowercase());
2714 /// assert!(a.is_ascii_lowercase());
2715 /// assert!(g.is_ascii_lowercase());
2716 /// assert!(!zero.is_ascii_lowercase());
2717 /// assert!(!percent.is_ascii_lowercase());
2718 /// assert!(!space.is_ascii_lowercase());
2719 /// assert!(!lf.is_ascii_lowercase());
2720 /// assert!(!esc.is_ascii_lowercase());
2722 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2724 pub fn is_ascii_lowercase(&self) -> bool {
2725 if *self >= 0x80 { return false }
2726 match ASCII_CHARACTER_CLASS[*self as usize] {
2732 /// Checks if the value is an ASCII alphanumeric character:
2734 /// - U+0041 'A' ... U+005A 'Z', or
2735 /// - U+0061 'a' ... U+007A 'z', or
2736 /// - U+0030 '0' ... U+0039 '9'.
2741 /// #![feature(ascii_ctype)]
2743 /// let uppercase_a = b'A';
2744 /// let uppercase_g = b'G';
2747 /// let zero = b'0';
2748 /// let percent = b'%';
2749 /// let space = b' ';
2751 /// let esc = 0x1b_u8;
2753 /// assert!(uppercase_a.is_ascii_alphanumeric());
2754 /// assert!(uppercase_g.is_ascii_alphanumeric());
2755 /// assert!(a.is_ascii_alphanumeric());
2756 /// assert!(g.is_ascii_alphanumeric());
2757 /// assert!(zero.is_ascii_alphanumeric());
2758 /// assert!(!percent.is_ascii_alphanumeric());
2759 /// assert!(!space.is_ascii_alphanumeric());
2760 /// assert!(!lf.is_ascii_alphanumeric());
2761 /// assert!(!esc.is_ascii_alphanumeric());
2763 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2765 pub fn is_ascii_alphanumeric(&self) -> bool {
2766 if *self >= 0x80 { return false }
2767 match ASCII_CHARACTER_CLASS[*self as usize] {
2768 D | L | Lx | U | Ux => true,
2773 /// Checks if the value is an ASCII decimal digit:
2774 /// U+0030 '0' ... U+0039 '9'.
2779 /// #![feature(ascii_ctype)]
2781 /// let uppercase_a = b'A';
2782 /// let uppercase_g = b'G';
2785 /// let zero = b'0';
2786 /// let percent = b'%';
2787 /// let space = b' ';
2789 /// let esc = 0x1b_u8;
2791 /// assert!(!uppercase_a.is_ascii_digit());
2792 /// assert!(!uppercase_g.is_ascii_digit());
2793 /// assert!(!a.is_ascii_digit());
2794 /// assert!(!g.is_ascii_digit());
2795 /// assert!(zero.is_ascii_digit());
2796 /// assert!(!percent.is_ascii_digit());
2797 /// assert!(!space.is_ascii_digit());
2798 /// assert!(!lf.is_ascii_digit());
2799 /// assert!(!esc.is_ascii_digit());
2801 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2803 pub fn is_ascii_digit(&self) -> bool {
2804 if *self >= 0x80 { return false }
2805 match ASCII_CHARACTER_CLASS[*self as usize] {
2811 /// Checks if the value is an ASCII hexadecimal digit:
2813 /// - U+0030 '0' ... U+0039 '9', or
2814 /// - U+0041 'A' ... U+0046 'F', or
2815 /// - U+0061 'a' ... U+0066 'f'.
2820 /// #![feature(ascii_ctype)]
2822 /// let uppercase_a = b'A';
2823 /// let uppercase_g = b'G';
2826 /// let zero = b'0';
2827 /// let percent = b'%';
2828 /// let space = b' ';
2830 /// let esc = 0x1b_u8;
2832 /// assert!(uppercase_a.is_ascii_hexdigit());
2833 /// assert!(!uppercase_g.is_ascii_hexdigit());
2834 /// assert!(a.is_ascii_hexdigit());
2835 /// assert!(!g.is_ascii_hexdigit());
2836 /// assert!(zero.is_ascii_hexdigit());
2837 /// assert!(!percent.is_ascii_hexdigit());
2838 /// assert!(!space.is_ascii_hexdigit());
2839 /// assert!(!lf.is_ascii_hexdigit());
2840 /// assert!(!esc.is_ascii_hexdigit());
2842 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2844 pub fn is_ascii_hexdigit(&self) -> bool {
2845 if *self >= 0x80 { return false }
2846 match ASCII_CHARACTER_CLASS[*self as usize] {
2847 D | Lx | Ux => true,
2852 /// Checks if the value is an ASCII punctuation character:
2854 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
2855 /// - U+003A ... U+0040 `: ; < = > ? @`, or
2856 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
2857 /// - U+007B ... U+007E `{ | } ~`
2862 /// #![feature(ascii_ctype)]
2864 /// let uppercase_a = b'A';
2865 /// let uppercase_g = b'G';
2868 /// let zero = b'0';
2869 /// let percent = b'%';
2870 /// let space = b' ';
2872 /// let esc = 0x1b_u8;
2874 /// assert!(!uppercase_a.is_ascii_punctuation());
2875 /// assert!(!uppercase_g.is_ascii_punctuation());
2876 /// assert!(!a.is_ascii_punctuation());
2877 /// assert!(!g.is_ascii_punctuation());
2878 /// assert!(!zero.is_ascii_punctuation());
2879 /// assert!(percent.is_ascii_punctuation());
2880 /// assert!(!space.is_ascii_punctuation());
2881 /// assert!(!lf.is_ascii_punctuation());
2882 /// assert!(!esc.is_ascii_punctuation());
2884 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2886 pub fn is_ascii_punctuation(&self) -> bool {
2887 if *self >= 0x80 { return false }
2888 match ASCII_CHARACTER_CLASS[*self as usize] {
2894 /// Checks if the value is an ASCII graphic character:
2895 /// U+0021 '!' ... U+007E '~'.
2900 /// #![feature(ascii_ctype)]
2902 /// let uppercase_a = b'A';
2903 /// let uppercase_g = b'G';
2906 /// let zero = b'0';
2907 /// let percent = b'%';
2908 /// let space = b' ';
2910 /// let esc = 0x1b_u8;
2912 /// assert!(uppercase_a.is_ascii_graphic());
2913 /// assert!(uppercase_g.is_ascii_graphic());
2914 /// assert!(a.is_ascii_graphic());
2915 /// assert!(g.is_ascii_graphic());
2916 /// assert!(zero.is_ascii_graphic());
2917 /// assert!(percent.is_ascii_graphic());
2918 /// assert!(!space.is_ascii_graphic());
2919 /// assert!(!lf.is_ascii_graphic());
2920 /// assert!(!esc.is_ascii_graphic());
2922 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2924 pub fn is_ascii_graphic(&self) -> bool {
2925 if *self >= 0x80 { return false; }
2926 match ASCII_CHARACTER_CLASS[*self as usize] {
2927 Ux | U | Lx | L | D | P => true,
2932 /// Checks if the value is an ASCII whitespace character:
2933 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
2934 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
2936 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
2937 /// whitespace][infra-aw]. There are several other definitions in
2938 /// wide use. For instance, [the POSIX locale][pct] includes
2939 /// U+000B VERTICAL TAB as well as all the above characters,
2940 /// but—from the very same specification—[the default rule for
2941 /// "field splitting" in the Bourne shell][bfs] considers *only*
2942 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
2944 /// If you are writing a program that will process an existing
2945 /// file format, check what that format's definition of whitespace is
2946 /// before using this function.
2948 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
2949 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
2950 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
2955 /// #![feature(ascii_ctype)]
2957 /// let uppercase_a = b'A';
2958 /// let uppercase_g = b'G';
2961 /// let zero = b'0';
2962 /// let percent = b'%';
2963 /// let space = b' ';
2965 /// let esc = 0x1b_u8;
2967 /// assert!(!uppercase_a.is_ascii_whitespace());
2968 /// assert!(!uppercase_g.is_ascii_whitespace());
2969 /// assert!(!a.is_ascii_whitespace());
2970 /// assert!(!g.is_ascii_whitespace());
2971 /// assert!(!zero.is_ascii_whitespace());
2972 /// assert!(!percent.is_ascii_whitespace());
2973 /// assert!(space.is_ascii_whitespace());
2974 /// assert!(lf.is_ascii_whitespace());
2975 /// assert!(!esc.is_ascii_whitespace());
2977 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2979 pub fn is_ascii_whitespace(&self) -> bool {
2980 if *self >= 0x80 { return false; }
2981 match ASCII_CHARACTER_CLASS[*self as usize] {
2987 /// Checks if the value is an ASCII control character:
2988 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
2989 /// Note that most ASCII whitespace characters are control
2990 /// characters, but SPACE is not.
2995 /// #![feature(ascii_ctype)]
2997 /// let uppercase_a = b'A';
2998 /// let uppercase_g = b'G';
3001 /// let zero = b'0';
3002 /// let percent = b'%';
3003 /// let space = b' ';
3005 /// let esc = 0x1b_u8;
3007 /// assert!(!uppercase_a.is_ascii_control());
3008 /// assert!(!uppercase_g.is_ascii_control());
3009 /// assert!(!a.is_ascii_control());
3010 /// assert!(!g.is_ascii_control());
3011 /// assert!(!zero.is_ascii_control());
3012 /// assert!(!percent.is_ascii_control());
3013 /// assert!(!space.is_ascii_control());
3014 /// assert!(lf.is_ascii_control());
3015 /// assert!(esc.is_ascii_control());
3017 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3019 pub fn is_ascii_control(&self) -> bool {
3020 if *self >= 0x80 { return false; }
3021 match ASCII_CHARACTER_CLASS[*self as usize] {
3030 uint_impl! { u16, u16, 16, 65535, "", "" }
3035 uint_impl! { u32, u32, 32, 4294967295, "", "" }
3040 uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
3045 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "#![feature(i128_type)]
3053 #[cfg(target_pointer_width = "16")]
3056 uint_impl! { usize, u16, 16, 65536, "", "" }
3058 #[cfg(target_pointer_width = "32")]
3061 uint_impl! { usize, u32, 32, 4294967295, "", "" }
3064 #[cfg(target_pointer_width = "64")]
3067 uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
3070 /// A classification of floating point numbers.
3072 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
3073 /// their documentation for more.
3075 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
3076 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
3081 /// use std::num::FpCategory;
3084 /// let num = 12.4_f32;
3085 /// let inf = f32::INFINITY;
3086 /// let zero = 0f32;
3087 /// let sub: f32 = 1.1754942e-38;
3088 /// let nan = f32::NAN;
3090 /// assert_eq!(num.classify(), FpCategory::Normal);
3091 /// assert_eq!(inf.classify(), FpCategory::Infinite);
3092 /// assert_eq!(zero.classify(), FpCategory::Zero);
3093 /// assert_eq!(nan.classify(), FpCategory::Nan);
3094 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
3096 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
3097 #[stable(feature = "rust1", since = "1.0.0")]
3098 pub enum FpCategory {
3099 /// "Not a Number", often obtained by dividing by zero.
3100 #[stable(feature = "rust1", since = "1.0.0")]
3103 /// Positive or negative infinity.
3104 #[stable(feature = "rust1", since = "1.0.0")]
3107 /// Positive or negative zero.
3108 #[stable(feature = "rust1", since = "1.0.0")]
3111 /// De-normalized floating point representation (less precise than `Normal`).
3112 #[stable(feature = "rust1", since = "1.0.0")]
3115 /// A regular floating point number.
3116 #[stable(feature = "rust1", since = "1.0.0")]
3120 /// A built-in floating point number.
3122 #[unstable(feature = "core_float",
3123 reason = "stable interface is via `impl f{32,64}` in later crates",
3125 pub trait Float: Sized {
3126 /// Type used by `to_bits` and `from_bits`.
3127 #[stable(feature = "core_float_bits", since = "1.25.0")]
3130 /// Returns `true` if this value is NaN and false otherwise.
3131 #[stable(feature = "core", since = "1.6.0")]
3132 fn is_nan(self) -> bool;
3133 /// Returns `true` if this value is positive infinity or negative infinity and
3134 /// false otherwise.
3135 #[stable(feature = "core", since = "1.6.0")]
3136 fn is_infinite(self) -> bool;
3137 /// Returns `true` if this number is neither infinite nor NaN.
3138 #[stable(feature = "core", since = "1.6.0")]
3139 fn is_finite(self) -> bool;
3140 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
3141 #[stable(feature = "core", since = "1.6.0")]
3142 fn is_normal(self) -> bool;
3143 /// Returns the category that this number falls into.
3144 #[stable(feature = "core", since = "1.6.0")]
3145 fn classify(self) -> FpCategory;
3147 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
3148 /// number is `Float::nan()`.
3149 #[stable(feature = "core", since = "1.6.0")]
3150 fn abs(self) -> Self;
3151 /// Returns a number that represents the sign of `self`.
3153 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
3154 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
3155 /// - `Float::nan()` if the number is `Float::nan()`
3156 #[stable(feature = "core", since = "1.6.0")]
3157 fn signum(self) -> Self;
3159 /// Returns `true` if `self` is positive, including `+0.0` and
3160 /// `Float::infinity()`.
3161 #[stable(feature = "core", since = "1.6.0")]
3162 fn is_sign_positive(self) -> bool;
3163 /// Returns `true` if `self` is negative, including `-0.0` and
3164 /// `Float::neg_infinity()`.
3165 #[stable(feature = "core", since = "1.6.0")]
3166 fn is_sign_negative(self) -> bool;
3168 /// Take the reciprocal (inverse) of a number, `1/x`.
3169 #[stable(feature = "core", since = "1.6.0")]
3170 fn recip(self) -> Self;
3172 /// Raise a number to an integer power.
3174 /// Using this function is generally faster than using `powf`
3175 #[stable(feature = "core", since = "1.6.0")]
3176 fn powi(self, n: i32) -> Self;
3178 /// Convert radians to degrees.
3179 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3180 fn to_degrees(self) -> Self;
3181 /// Convert degrees to radians.
3182 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3183 fn to_radians(self) -> Self;
3185 /// Returns the maximum of the two numbers.
3186 #[stable(feature = "core_float_min_max", since="1.20.0")]
3187 fn max(self, other: Self) -> Self;
3188 /// Returns the minimum of the two numbers.
3189 #[stable(feature = "core_float_min_max", since="1.20.0")]
3190 fn min(self, other: Self) -> Self;
3192 /// Raw transmutation to integer.
3193 #[stable(feature = "core_float_bits", since="1.25.0")]
3194 fn to_bits(self) -> Self::Bits;
3195 /// Raw transmutation from integer.
3196 #[stable(feature = "core_float_bits", since="1.25.0")]
3197 fn from_bits(v: Self::Bits) -> Self;
3200 macro_rules! from_str_radix_int_impl {
3202 #[stable(feature = "rust1", since = "1.0.0")]
3203 impl FromStr for $t {
3204 type Err = ParseIntError;
3205 fn from_str(src: &str) -> Result<Self, ParseIntError> {
3206 from_str_radix(src, 10)
3211 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
3213 /// The error type returned when a checked integral type conversion fails.
3214 #[unstable(feature = "try_from", issue = "33417")]
3215 #[derive(Debug, Copy, Clone)]
3216 pub struct TryFromIntError(());
3218 impl TryFromIntError {
3219 #[unstable(feature = "int_error_internals",
3220 reason = "available through Error trait and this method should \
3221 not be exposed publicly",
3224 pub fn __description(&self) -> &str {
3225 "out of range integral type conversion attempted"
3229 #[unstable(feature = "try_from", issue = "33417")]
3230 impl fmt::Display for TryFromIntError {
3231 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3232 self.__description().fmt(fmt)
3236 #[unstable(feature = "try_from", issue = "33417")]
3237 impl From<Infallible> for TryFromIntError {
3238 fn from(infallible: Infallible) -> TryFromIntError {
3244 // no possible bounds violation
3245 macro_rules! try_from_unbounded {
3246 ($source:ty, $($target:ty),*) => {$(
3247 #[unstable(feature = "try_from", issue = "33417")]
3248 impl TryFrom<$source> for $target {
3249 type Error = Infallible;
3252 fn try_from(value: $source) -> Result<Self, Self::Error> {
3253 Ok(value as $target)
3259 // only negative bounds
3260 macro_rules! try_from_lower_bounded {
3261 ($source:ty, $($target:ty),*) => {$(
3262 #[unstable(feature = "try_from", issue = "33417")]
3263 impl TryFrom<$source> for $target {
3264 type Error = TryFromIntError;
3267 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3271 Err(TryFromIntError(()))
3278 // unsigned to signed (only positive bound)
3279 macro_rules! try_from_upper_bounded {
3280 ($source:ty, $($target:ty),*) => {$(
3281 #[unstable(feature = "try_from", issue = "33417")]
3282 impl TryFrom<$source> for $target {
3283 type Error = TryFromIntError;
3286 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3287 if u > (<$target>::max_value() as $source) {
3288 Err(TryFromIntError(()))
3298 macro_rules! try_from_both_bounded {
3299 ($source:ty, $($target:ty),*) => {$(
3300 #[unstable(feature = "try_from", issue = "33417")]
3301 impl TryFrom<$source> for $target {
3302 type Error = TryFromIntError;
3305 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3306 let min = <$target>::min_value() as $source;
3307 let max = <$target>::max_value() as $source;
3308 if u < min || u > max {
3309 Err(TryFromIntError(()))
3319 ($mac:ident, $source:ty, $($target:ty),*) => {$(
3320 $mac!($target, $source);
3324 /// intra-sign conversions
3325 try_from_upper_bounded!(u16, u8);
3326 try_from_upper_bounded!(u32, u16, u8);
3327 try_from_upper_bounded!(u64, u32, u16, u8);
3328 try_from_upper_bounded!(u128, u64, u32, u16, u8);
3330 try_from_both_bounded!(i16, i8);
3331 try_from_both_bounded!(i32, i16, i8);
3332 try_from_both_bounded!(i64, i32, i16, i8);
3333 try_from_both_bounded!(i128, i64, i32, i16, i8);
3335 // unsigned-to-signed
3336 try_from_upper_bounded!(u8, i8);
3337 try_from_upper_bounded!(u16, i8, i16);
3338 try_from_upper_bounded!(u32, i8, i16, i32);
3339 try_from_upper_bounded!(u64, i8, i16, i32, i64);
3340 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
3342 // signed-to-unsigned
3343 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
3344 try_from_lower_bounded!(i16, u16, u32, u64, u128);
3345 try_from_lower_bounded!(i32, u32, u64, u128);
3346 try_from_lower_bounded!(i64, u64, u128);
3347 try_from_lower_bounded!(i128, u128);
3348 try_from_both_bounded!(i16, u8);
3349 try_from_both_bounded!(i32, u16, u8);
3350 try_from_both_bounded!(i64, u32, u16, u8);
3351 try_from_both_bounded!(i128, u64, u32, u16, u8);
3354 try_from_upper_bounded!(usize, isize);
3355 try_from_lower_bounded!(isize, usize);
3357 #[cfg(target_pointer_width = "16")]
3358 mod ptr_try_from_impls {
3359 use super::TryFromIntError;
3360 use convert::{Infallible, TryFrom};
3362 try_from_upper_bounded!(usize, u8);
3363 try_from_unbounded!(usize, u16, u32, u64, u128);
3364 try_from_upper_bounded!(usize, i8, i16);
3365 try_from_unbounded!(usize, i32, i64, i128);
3367 try_from_both_bounded!(isize, u8);
3368 try_from_lower_bounded!(isize, u16, u32, u64, u128);
3369 try_from_both_bounded!(isize, i8);
3370 try_from_unbounded!(isize, i16, i32, i64, i128);
3372 rev!(try_from_unbounded, usize, u16);
3373 rev!(try_from_upper_bounded, usize, u32, u64, u128);
3374 rev!(try_from_lower_bounded, usize, i8, i16);
3375 rev!(try_from_both_bounded, usize, i32, i64, i128);
3377 rev!(try_from_unbounded, isize, u8);
3378 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
3379 rev!(try_from_unbounded, isize, i16);
3380 rev!(try_from_both_bounded, isize, i32, i64, i128);
3383 #[cfg(target_pointer_width = "32")]
3384 mod ptr_try_from_impls {
3385 use super::TryFromIntError;
3386 use convert::{Infallible, TryFrom};
3388 try_from_upper_bounded!(usize, u8, u16);
3389 try_from_unbounded!(usize, u32, u64, u128);
3390 try_from_upper_bounded!(usize, i8, i16, i32);
3391 try_from_unbounded!(usize, i64, i128);
3393 try_from_both_bounded!(isize, u8, u16);
3394 try_from_lower_bounded!(isize, u32, u64, u128);
3395 try_from_both_bounded!(isize, i8, i16);
3396 try_from_unbounded!(isize, i32, i64, i128);
3398 rev!(try_from_unbounded, usize, u16, u32);
3399 rev!(try_from_upper_bounded, usize, u64, u128);
3400 rev!(try_from_lower_bounded, usize, i8, i16, i32);
3401 rev!(try_from_both_bounded, usize, i64, i128);
3403 rev!(try_from_unbounded, isize, u8, u16);
3404 rev!(try_from_upper_bounded, isize, u32, u64, u128);
3405 rev!(try_from_unbounded, isize, i16, i32);
3406 rev!(try_from_both_bounded, isize, i64, i128);
3409 #[cfg(target_pointer_width = "64")]
3410 mod ptr_try_from_impls {
3411 use super::TryFromIntError;
3412 use convert::{Infallible, TryFrom};
3414 try_from_upper_bounded!(usize, u8, u16, u32);
3415 try_from_unbounded!(usize, u64, u128);
3416 try_from_upper_bounded!(usize, i8, i16, i32, i64);
3417 try_from_unbounded!(usize, i128);
3419 try_from_both_bounded!(isize, u8, u16, u32);
3420 try_from_lower_bounded!(isize, u64, u128);
3421 try_from_both_bounded!(isize, i8, i16, i32);
3422 try_from_unbounded!(isize, i64, i128);
3424 rev!(try_from_unbounded, usize, u16, u32, u64);
3425 rev!(try_from_upper_bounded, usize, u128);
3426 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
3427 rev!(try_from_both_bounded, usize, i128);
3429 rev!(try_from_unbounded, isize, u8, u16, u32);
3430 rev!(try_from_upper_bounded, isize, u64, u128);
3431 rev!(try_from_unbounded, isize, i16, i32, i64);
3432 rev!(try_from_both_bounded, isize, i128);
3436 trait FromStrRadixHelper: PartialOrd + Copy {
3437 fn min_value() -> Self;
3438 fn max_value() -> Self;
3439 fn from_u32(u: u32) -> Self;
3440 fn checked_mul(&self, other: u32) -> Option<Self>;
3441 fn checked_sub(&self, other: u32) -> Option<Self>;
3442 fn checked_add(&self, other: u32) -> Option<Self>;
3446 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
3448 fn min_value() -> Self { Self::min_value() }
3450 fn max_value() -> Self { Self::max_value() }
3452 fn from_u32(u: u32) -> Self { u as Self }
3454 fn checked_mul(&self, other: u32) -> Option<Self> {
3455 Self::checked_mul(*self, other as Self)
3458 fn checked_sub(&self, other: u32) -> Option<Self> {
3459 Self::checked_sub(*self, other as Self)
3462 fn checked_add(&self, other: u32) -> Option<Self> {
3463 Self::checked_add(*self, other as Self)
3467 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
3469 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
3470 use self::IntErrorKind::*;
3471 use self::ParseIntError as PIE;
3473 assert!(radix >= 2 && radix <= 36,
3474 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
3478 return Err(PIE { kind: Empty });
3481 let is_signed_ty = T::from_u32(0) > T::min_value();
3483 // all valid digits are ascii, so we will just iterate over the utf8 bytes
3484 // and cast them to chars. .to_digit() will safely return None for anything
3485 // other than a valid ascii digit for the given radix, including the first-byte
3486 // of multi-byte sequences
3487 let src = src.as_bytes();
3489 let (is_positive, digits) = match src[0] {
3490 b'+' => (true, &src[1..]),
3491 b'-' if is_signed_ty => (false, &src[1..]),
3495 if digits.is_empty() {
3496 return Err(PIE { kind: Empty });
3499 let mut result = T::from_u32(0);
3501 // The number is positive
3503 let x = match (c as char).to_digit(radix) {
3505 None => return Err(PIE { kind: InvalidDigit }),
3507 result = match result.checked_mul(radix) {
3508 Some(result) => result,
3509 None => return Err(PIE { kind: Overflow }),
3511 result = match result.checked_add(x) {
3512 Some(result) => result,
3513 None => return Err(PIE { kind: Overflow }),
3517 // The number is negative
3519 let x = match (c as char).to_digit(radix) {
3521 None => return Err(PIE { kind: InvalidDigit }),
3523 result = match result.checked_mul(radix) {
3524 Some(result) => result,
3525 None => return Err(PIE { kind: Underflow }),
3527 result = match result.checked_sub(x) {
3528 Some(result) => result,
3529 None => return Err(PIE { kind: Underflow }),
3536 /// An error which can be returned when parsing an integer.
3538 /// This error is used as the error type for the `from_str_radix()` functions
3539 /// on the primitive integer types, such as [`i8::from_str_radix`].
3541 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
3542 #[derive(Debug, Clone, PartialEq, Eq)]
3543 #[stable(feature = "rust1", since = "1.0.0")]
3544 pub struct ParseIntError {
3548 #[derive(Debug, Clone, PartialEq, Eq)]
3556 impl ParseIntError {
3557 #[unstable(feature = "int_error_internals",
3558 reason = "available through Error trait and this method should \
3559 not be exposed publicly",
3562 pub fn __description(&self) -> &str {
3564 IntErrorKind::Empty => "cannot parse integer from empty string",
3565 IntErrorKind::InvalidDigit => "invalid digit found in string",
3566 IntErrorKind::Overflow => "number too large to fit in target type",
3567 IntErrorKind::Underflow => "number too small to fit in target type",
3572 #[stable(feature = "rust1", since = "1.0.0")]
3573 impl fmt::Display for ParseIntError {
3574 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3575 self.__description().fmt(f)
3579 #[stable(feature = "rust1", since = "1.0.0")]
3580 pub use num::dec2flt::ParseFloatError;
3582 // Conversion traits for primitive integer and float types
3583 // Conversions T -> T are covered by a blanket impl and therefore excluded
3584 // Some conversions from and to usize/isize are not implemented due to portability concerns
3585 macro_rules! impl_from {
3586 ($Small: ty, $Large: ty, #[$attr:meta]) => {
3588 impl From<$Small> for $Large {
3590 fn from(small: $Small) -> $Large {
3597 // Unsigned -> Unsigned
3598 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3599 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3600 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3601 impl_from! { u8, u128, #[unstable(feature = "i128", issue = "35118")] }
3602 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3603 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3604 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3605 impl_from! { u16, u128, #[unstable(feature = "i128", issue = "35118")] }
3606 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3607 impl_from! { u32, u128, #[unstable(feature = "i128", issue = "35118")] }
3608 impl_from! { u64, u128, #[unstable(feature = "i128", issue = "35118")] }
3611 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3612 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3613 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3614 impl_from! { i8, i128, #[unstable(feature = "i128", issue = "35118")] }
3615 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3616 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3617 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3618 impl_from! { i16, i128, #[unstable(feature = "i128", issue = "35118")] }
3619 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3620 impl_from! { i32, i128, #[unstable(feature = "i128", issue = "35118")] }
3621 impl_from! { i64, i128, #[unstable(feature = "i128", issue = "35118")] }
3623 // Unsigned -> Signed
3624 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3625 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3626 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3627 impl_from! { u8, i128, #[unstable(feature = "i128", issue = "35118")] }
3628 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3629 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3630 impl_from! { u16, i128, #[unstable(feature = "i128", issue = "35118")] }
3631 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3632 impl_from! { u32, i128, #[unstable(feature = "i128", issue = "35118")] }
3633 impl_from! { u64, i128, #[unstable(feature = "i128", issue = "35118")] }
3635 // Note: integers can only be represented with full precision in a float if
3636 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
3637 // Lossy float conversions are not implemented at this time.
3640 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3641 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3642 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3643 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3644 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3646 // Unsigned -> Float
3647 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3648 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3649 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3650 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3651 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3654 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3656 static ASCII_LOWERCASE_MAP: [u8; 256] = [
3657 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
3658 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
3659 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
3660 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
3661 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
3662 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
3663 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
3664 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
3667 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
3668 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
3669 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
3672 b'[', b'\\', b']', b'^', b'_',
3673 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
3674 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
3675 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
3676 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
3677 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
3678 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
3679 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
3680 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
3681 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
3682 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
3683 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
3684 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
3685 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
3686 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
3687 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
3688 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
3689 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
3690 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
3691 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
3692 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
3695 static ASCII_UPPERCASE_MAP: [u8; 256] = [
3696 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
3697 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
3698 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
3699 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
3700 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
3701 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
3702 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
3703 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
3704 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
3705 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
3706 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
3707 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
3710 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
3711 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
3712 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
3715 b'{', b'|', b'}', b'~', 0x7f,
3716 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
3717 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
3718 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
3719 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
3720 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
3721 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
3722 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
3723 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
3724 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
3725 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
3726 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
3727 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
3728 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
3729 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
3730 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
3731 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
3734 enum AsciiCharacterClass {
3736 Cw, // control whitespace
3740 Lx, // lowercase hex digit
3742 Ux, // uppercase hex digit
3745 use self::AsciiCharacterClass::*;
3747 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
3748 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
3749 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
3750 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
3751 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
3752 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
3753 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
3754 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
3755 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
3756 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_