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")]
20 /// Provides intentionally-wrapped arithmetic on `T`.
22 /// Operations like `+` on `u32` values is intended to never overflow,
23 /// and in some debug configurations overflow is detected and results
24 /// in a panic. While most arithmetic falls into this category, some
25 /// code explicitly expects and relies upon modular arithmetic (e.g.,
28 /// Wrapping arithmetic can be achieved either through methods like
29 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
30 /// all standard arithmetic operations on the underlying value are
31 /// intended to have wrapping semantics.
36 /// use std::num::Wrapping;
38 /// let zero = Wrapping(0u32);
39 /// let one = Wrapping(1u32);
41 /// assert_eq!(std::u32::MAX, (zero - one).0);
43 #[stable(feature = "rust1", since = "1.0.0")]
44 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
45 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
48 #[stable(feature = "rust1", since = "1.0.0")]
49 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
50 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55 #[stable(feature = "wrapping_display", since = "1.10.0")]
56 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
57 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
63 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
64 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
70 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
71 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
76 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
77 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
78 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
83 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
84 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
85 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 // All these modules are technically private and only exposed for coretests:
98 // `Int` + `SignedInt` implemented for signed integers
99 macro_rules! int_impl {
100 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr,
101 $add_with_overflow:path,
102 $sub_with_overflow:path,
103 $mul_with_overflow:path) => {
104 /// Returns the smallest value that can be represented by this integer type.
109 /// assert_eq!(i8::min_value(), -128);
111 #[stable(feature = "rust1", since = "1.0.0")]
113 pub const fn min_value() -> Self {
114 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
117 /// Returns the largest value that can be represented by this integer type.
122 /// assert_eq!(i8::max_value(), 127);
124 #[stable(feature = "rust1", since = "1.0.0")]
126 pub const fn max_value() -> Self {
130 /// Converts a string slice in a given base to an integer.
132 /// Leading and trailing whitespace represent an error.
139 /// assert_eq!(i32::from_str_radix("A", 16), Ok(10));
141 #[stable(feature = "rust1", since = "1.0.0")]
142 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
143 from_str_radix(src, radix)
146 /// Returns the number of ones in the binary representation of `self`.
153 /// let n = -0b1000_0000i8;
155 /// assert_eq!(n.count_ones(), 1);
157 #[stable(feature = "rust1", since = "1.0.0")]
159 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
161 /// Returns the number of zeros in the binary representation of `self`.
168 /// let n = -0b1000_0000i8;
170 /// assert_eq!(n.count_zeros(), 7);
172 #[stable(feature = "rust1", since = "1.0.0")]
174 pub fn count_zeros(self) -> u32 {
178 /// Returns the number of leading zeros in the binary representation
188 /// assert_eq!(n.leading_zeros(), 0);
190 #[stable(feature = "rust1", since = "1.0.0")]
192 pub fn leading_zeros(self) -> u32 {
193 (self as $UnsignedT).leading_zeros()
196 /// Returns the number of trailing zeros in the binary representation
206 /// assert_eq!(n.trailing_zeros(), 2);
208 #[stable(feature = "rust1", since = "1.0.0")]
210 pub fn trailing_zeros(self) -> u32 {
211 (self as $UnsignedT).trailing_zeros()
214 /// Shifts the bits to the left by a specified amount, `n`,
215 /// wrapping the truncated bits to the end of the resulting integer.
217 /// Please note this isn't the same operation as `<<`!
224 /// let n = 0x0123456789ABCDEFi64;
225 /// let m = -0x76543210FEDCBA99i64;
227 /// assert_eq!(n.rotate_left(32), m);
229 #[stable(feature = "rust1", since = "1.0.0")]
231 pub fn rotate_left(self, n: u32) -> Self {
232 (self as $UnsignedT).rotate_left(n) as Self
235 /// Shifts the bits to the right by a specified amount, `n`,
236 /// wrapping the truncated bits to the beginning of the resulting
239 /// Please note this isn't the same operation as `>>`!
246 /// let n = 0x0123456789ABCDEFi64;
247 /// let m = -0xFEDCBA987654322i64;
249 /// assert_eq!(n.rotate_right(4), m);
251 #[stable(feature = "rust1", since = "1.0.0")]
253 pub fn rotate_right(self, n: u32) -> Self {
254 (self as $UnsignedT).rotate_right(n) as Self
257 /// Reverses the byte order of the integer.
264 /// let n = 0x0123456789ABCDEFi64;
265 /// let m = -0x1032547698BADCFFi64;
267 /// assert_eq!(n.swap_bytes(), m);
269 #[stable(feature = "rust1", since = "1.0.0")]
271 pub fn swap_bytes(self) -> Self {
272 (self as $UnsignedT).swap_bytes() as Self
275 /// Converts an integer from big endian to the target's endianness.
277 /// On big endian this is a no-op. On little endian the bytes are
285 /// let n = 0x0123456789ABCDEFi64;
287 /// if cfg!(target_endian = "big") {
288 /// assert_eq!(i64::from_be(n), n)
290 /// assert_eq!(i64::from_be(n), n.swap_bytes())
293 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn from_be(x: Self) -> Self {
296 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
299 /// Converts an integer from little endian to the target's endianness.
301 /// On little endian this is a no-op. On big endian the bytes are
309 /// let n = 0x0123456789ABCDEFi64;
311 /// if cfg!(target_endian = "little") {
312 /// assert_eq!(i64::from_le(n), n)
314 /// assert_eq!(i64::from_le(n), n.swap_bytes())
317 #[stable(feature = "rust1", since = "1.0.0")]
319 pub fn from_le(x: Self) -> Self {
320 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
323 /// Converts `self` to big endian from the target's endianness.
325 /// On big endian this is a no-op. On little endian the bytes are
333 /// let n = 0x0123456789ABCDEFi64;
335 /// if cfg!(target_endian = "big") {
336 /// assert_eq!(n.to_be(), n)
338 /// assert_eq!(n.to_be(), n.swap_bytes())
341 #[stable(feature = "rust1", since = "1.0.0")]
343 pub fn to_be(self) -> Self { // or not to be?
344 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
347 /// Converts `self` to little endian from the target's endianness.
349 /// On little endian this is a no-op. On big endian the bytes are
357 /// let n = 0x0123456789ABCDEFi64;
359 /// if cfg!(target_endian = "little") {
360 /// assert_eq!(n.to_le(), n)
362 /// assert_eq!(n.to_le(), n.swap_bytes())
365 #[stable(feature = "rust1", since = "1.0.0")]
367 pub fn to_le(self) -> Self {
368 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
371 /// Checked integer addition. Computes `self + other`, returning `None`
372 /// if overflow occurred.
379 /// assert_eq!(7i16.checked_add(32760), Some(32767));
380 /// assert_eq!(8i16.checked_add(32760), None);
382 #[stable(feature = "rust1", since = "1.0.0")]
384 pub fn checked_add(self, other: Self) -> Option<Self> {
385 let (a, b) = self.overflowing_add(other);
386 if b {None} else {Some(a)}
389 /// Checked integer subtraction. Computes `self - other`, returning
390 /// `None` if underflow occurred.
397 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
398 /// assert_eq!((-128i8).checked_sub(1), None);
400 #[stable(feature = "rust1", since = "1.0.0")]
402 pub fn checked_sub(self, other: Self) -> Option<Self> {
403 let (a, b) = self.overflowing_sub(other);
404 if b {None} else {Some(a)}
407 /// Checked integer multiplication. Computes `self * other`, returning
408 /// `None` if underflow or overflow occurred.
415 /// assert_eq!(6i8.checked_mul(21), Some(126));
416 /// assert_eq!(6i8.checked_mul(22), None);
418 #[stable(feature = "rust1", since = "1.0.0")]
420 pub fn checked_mul(self, other: Self) -> Option<Self> {
421 let (a, b) = self.overflowing_mul(other);
422 if b {None} else {Some(a)}
425 /// Checked integer division. Computes `self / other`, returning `None`
426 /// if `other == 0` or the operation results in underflow or overflow.
433 /// assert_eq!((-127i8).checked_div(-1), Some(127));
434 /// assert_eq!((-128i8).checked_div(-1), None);
435 /// assert_eq!((1i8).checked_div(0), None);
437 #[stable(feature = "rust1", since = "1.0.0")]
439 pub fn checked_div(self, other: Self) -> Option<Self> {
440 if other == 0 || (self == Self::min_value() && other == -1) {
443 Some(unsafe { intrinsics::unchecked_div(self, other) })
447 /// Checked integer remainder. Computes `self % other`, returning `None`
448 /// if `other == 0` or the operation results in underflow or overflow.
457 /// assert_eq!(5i32.checked_rem(2), Some(1));
458 /// assert_eq!(5i32.checked_rem(0), None);
459 /// assert_eq!(i32::MIN.checked_rem(-1), None);
461 #[stable(feature = "wrapping", since = "1.7.0")]
463 pub fn checked_rem(self, other: Self) -> Option<Self> {
464 if other == 0 || (self == Self::min_value() && other == -1) {
467 Some(unsafe { intrinsics::unchecked_rem(self, other) })
471 /// Checked negation. Computes `-self`, returning `None` if `self ==
481 /// assert_eq!(5i32.checked_neg(), Some(-5));
482 /// assert_eq!(i32::MIN.checked_neg(), None);
484 #[stable(feature = "wrapping", since = "1.7.0")]
486 pub fn checked_neg(self) -> Option<Self> {
487 let (a, b) = self.overflowing_neg();
488 if b {None} else {Some(a)}
491 /// Checked shift left. Computes `self << rhs`, returning `None`
492 /// if `rhs` is larger than or equal to the number of bits in `self`.
499 /// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
500 /// assert_eq!(0x10i32.checked_shl(33), None);
502 #[stable(feature = "wrapping", since = "1.7.0")]
504 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
505 let (a, b) = self.overflowing_shl(rhs);
506 if b {None} else {Some(a)}
509 /// Checked shift right. Computes `self >> rhs`, returning `None`
510 /// if `rhs` is larger than or equal to the number of bits in `self`.
517 /// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
518 /// assert_eq!(0x10i32.checked_shr(33), None);
520 #[stable(feature = "wrapping", since = "1.7.0")]
522 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
523 let (a, b) = self.overflowing_shr(rhs);
524 if b {None} else {Some(a)}
527 /// Checked absolute value. Computes `self.abs()`, returning `None` if
537 /// assert_eq!((-5i32).checked_abs(), Some(5));
538 /// assert_eq!(i32::MIN.checked_abs(), None);
540 #[stable(feature = "no_panic_abs", since = "1.13.0")]
542 pub fn checked_abs(self) -> Option<Self> {
543 if self.is_negative() {
550 /// Saturating integer addition. Computes `self + other`, saturating at
551 /// the numeric bounds instead of overflowing.
558 /// assert_eq!(100i8.saturating_add(1), 101);
559 /// assert_eq!(100i8.saturating_add(127), 127);
561 #[stable(feature = "rust1", since = "1.0.0")]
563 pub fn saturating_add(self, other: Self) -> Self {
564 match self.checked_add(other) {
566 None if other >= 0 => Self::max_value(),
567 None => Self::min_value(),
571 /// Saturating integer subtraction. Computes `self - other`, saturating
572 /// at the numeric bounds instead of overflowing.
579 /// assert_eq!(100i8.saturating_sub(127), -27);
580 /// assert_eq!((-100i8).saturating_sub(127), -128);
582 #[stable(feature = "rust1", since = "1.0.0")]
584 pub fn saturating_sub(self, other: Self) -> Self {
585 match self.checked_sub(other) {
587 None if other >= 0 => Self::min_value(),
588 None => Self::max_value(),
592 /// Saturating integer multiplication. Computes `self * other`,
593 /// saturating at the numeric bounds instead of overflowing.
602 /// assert_eq!(100i32.saturating_mul(127), 12700);
603 /// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
604 /// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
606 #[stable(feature = "wrapping", since = "1.7.0")]
608 pub fn saturating_mul(self, other: Self) -> Self {
609 self.checked_mul(other).unwrap_or_else(|| {
610 if (self < 0 && other < 0) || (self > 0 && other > 0) {
618 /// Wrapping (modular) addition. Computes `self + other`,
619 /// wrapping around at the boundary of the type.
626 /// assert_eq!(100i8.wrapping_add(27), 127);
627 /// assert_eq!(100i8.wrapping_add(127), -29);
629 #[stable(feature = "rust1", since = "1.0.0")]
631 pub fn wrapping_add(self, rhs: Self) -> Self {
633 intrinsics::overflowing_add(self, rhs)
637 /// Wrapping (modular) subtraction. Computes `self - other`,
638 /// wrapping around at the boundary of the type.
645 /// assert_eq!(0i8.wrapping_sub(127), -127);
646 /// assert_eq!((-2i8).wrapping_sub(127), 127);
648 #[stable(feature = "rust1", since = "1.0.0")]
650 pub fn wrapping_sub(self, rhs: Self) -> Self {
652 intrinsics::overflowing_sub(self, rhs)
656 /// Wrapping (modular) multiplication. Computes `self *
657 /// other`, wrapping around at the boundary of the type.
664 /// assert_eq!(10i8.wrapping_mul(12), 120);
665 /// assert_eq!(11i8.wrapping_mul(12), -124);
667 #[stable(feature = "rust1", since = "1.0.0")]
669 pub fn wrapping_mul(self, rhs: Self) -> Self {
671 intrinsics::overflowing_mul(self, rhs)
675 /// Wrapping (modular) division. Computes `self / other`,
676 /// wrapping around at the boundary of the type.
678 /// The only case where such wrapping can occur is when one
679 /// divides `MIN / -1` on a signed type (where `MIN` is the
680 /// negative minimal value for the type); this is equivalent
681 /// to `-MIN`, a positive value that is too large to represent
682 /// in the type. In such a case, this function returns `MIN`
687 /// This function will panic if `rhs` is 0.
694 /// assert_eq!(100u8.wrapping_div(10), 10);
695 /// assert_eq!((-128i8).wrapping_div(-1), -128);
697 #[stable(feature = "num_wrapping", since = "1.2.0")]
699 pub fn wrapping_div(self, rhs: Self) -> Self {
700 self.overflowing_div(rhs).0
703 /// Wrapping (modular) remainder. Computes `self % other`,
704 /// wrapping around at the boundary of the type.
706 /// Such wrap-around never actually occurs mathematically;
707 /// implementation artifacts make `x % y` invalid for `MIN /
708 /// -1` on a signed type (where `MIN` is the negative
709 /// minimal value). In such a case, this function returns `0`.
713 /// This function will panic if `rhs` is 0.
720 /// assert_eq!(100i8.wrapping_rem(10), 0);
721 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
723 #[stable(feature = "num_wrapping", since = "1.2.0")]
725 pub fn wrapping_rem(self, rhs: Self) -> Self {
726 self.overflowing_rem(rhs).0
729 /// Wrapping (modular) negation. Computes `-self`,
730 /// wrapping around at the boundary of the type.
732 /// The only case where such wrapping can occur is when one
733 /// negates `MIN` on a signed type (where `MIN` is the
734 /// negative minimal value for the type); this is a positive
735 /// value that is too large to represent in the type. In such
736 /// a case, this function returns `MIN` itself.
743 /// assert_eq!(100i8.wrapping_neg(), -100);
744 /// assert_eq!((-128i8).wrapping_neg(), -128);
746 #[stable(feature = "num_wrapping", since = "1.2.0")]
748 pub fn wrapping_neg(self) -> Self {
749 self.overflowing_neg().0
752 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
753 /// where `mask` removes any high-order bits of `rhs` that
754 /// would cause the shift to exceed the bitwidth of the type.
756 /// Note that this is *not* the same as a rotate-left; the
757 /// RHS of a wrapping shift-left is restricted to the range
758 /// of the type, rather than the bits shifted out of the LHS
759 /// being returned to the other end. The primitive integer
760 /// types all implement a `rotate_left` function, which may
761 /// be what you want instead.
768 /// assert_eq!((-1i8).wrapping_shl(7), -128);
769 /// assert_eq!((-1i8).wrapping_shl(8), -1);
771 #[stable(feature = "num_wrapping", since = "1.2.0")]
773 pub fn wrapping_shl(self, rhs: u32) -> Self {
775 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
779 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
780 /// where `mask` removes any high-order bits of `rhs` that
781 /// would cause the shift to exceed the bitwidth of the type.
783 /// Note that this is *not* the same as a rotate-right; the
784 /// RHS of a wrapping shift-right is restricted to the range
785 /// of the type, rather than the bits shifted out of the LHS
786 /// being returned to the other end. The primitive integer
787 /// types all implement a `rotate_right` function, which may
788 /// be what you want instead.
795 /// assert_eq!((-128i8).wrapping_shr(7), -1);
796 /// assert_eq!((-128i8).wrapping_shr(8), -128);
798 #[stable(feature = "num_wrapping", since = "1.2.0")]
800 pub fn wrapping_shr(self, rhs: u32) -> Self {
802 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
806 /// Wrapping (modular) absolute value. Computes `self.abs()`,
807 /// wrapping around at the boundary of the type.
809 /// The only case where such wrapping can occur is when one takes
810 /// the absolute value of the negative minimal value for the type
811 /// this is a positive value that is too large to represent in the
812 /// type. In such a case, this function returns `MIN` itself.
819 /// assert_eq!(100i8.wrapping_abs(), 100);
820 /// assert_eq!((-100i8).wrapping_abs(), 100);
821 /// assert_eq!((-128i8).wrapping_abs(), -128);
822 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
824 #[stable(feature = "no_panic_abs", since = "1.13.0")]
826 pub fn wrapping_abs(self) -> Self {
827 if self.is_negative() {
834 /// Calculates `self` + `rhs`
836 /// Returns a tuple of the addition along with a boolean indicating
837 /// whether an arithmetic overflow would occur. If an overflow would
838 /// have occurred then the wrapped value is returned.
847 /// assert_eq!(5i32.overflowing_add(2), (7, false));
848 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
851 #[stable(feature = "wrapping", since = "1.7.0")]
852 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
854 let (a, b) = $add_with_overflow(self as $ActualT,
860 /// Calculates `self` - `rhs`
862 /// Returns a tuple of the subtraction along with a boolean indicating
863 /// whether an arithmetic overflow would occur. If an overflow would
864 /// have occurred then the wrapped value is returned.
873 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
874 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
877 #[stable(feature = "wrapping", since = "1.7.0")]
878 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
880 let (a, b) = $sub_with_overflow(self as $ActualT,
886 /// Calculates the multiplication of `self` and `rhs`.
888 /// Returns a tuple of the multiplication along with a boolean
889 /// indicating whether an arithmetic overflow would occur. If an
890 /// overflow would have occurred then the wrapped value is returned.
897 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
898 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
901 #[stable(feature = "wrapping", since = "1.7.0")]
902 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
904 let (a, b) = $mul_with_overflow(self as $ActualT,
910 /// Calculates the divisor when `self` is divided by `rhs`.
912 /// Returns a tuple of the divisor along with a boolean indicating
913 /// whether an arithmetic overflow would occur. If an overflow would
914 /// occur then self is returned.
918 /// This function will panic if `rhs` is 0.
927 /// assert_eq!(5i32.overflowing_div(2), (2, false));
928 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
931 #[stable(feature = "wrapping", since = "1.7.0")]
932 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
933 if self == Self::min_value() && rhs == -1 {
940 /// Calculates the remainder when `self` is divided by `rhs`.
942 /// Returns a tuple of the remainder after dividing along with a boolean
943 /// indicating whether an arithmetic overflow would occur. If an
944 /// overflow would occur then 0 is returned.
948 /// This function will panic if `rhs` is 0.
957 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
958 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
961 #[stable(feature = "wrapping", since = "1.7.0")]
962 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
963 if self == Self::min_value() && rhs == -1 {
970 /// Negates self, overflowing if this is equal to the minimum value.
972 /// Returns a tuple of the negated version of self along with a boolean
973 /// indicating whether an overflow happened. If `self` is the minimum
974 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
975 /// value will be returned again and `true` will be returned for an
976 /// overflow happening.
985 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
986 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
989 #[stable(feature = "wrapping", since = "1.7.0")]
990 pub fn overflowing_neg(self) -> (Self, bool) {
991 if self == Self::min_value() {
992 (Self::min_value(), true)
998 /// Shifts self left by `rhs` bits.
1000 /// Returns a tuple of the shifted version of self along with a boolean
1001 /// indicating whether the shift value was larger than or equal to the
1002 /// number of bits. If the shift value is too large, then value is
1003 /// masked (N-1) where N is the number of bits, and this value is then
1004 /// used to perform the shift.
1011 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
1012 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
1015 #[stable(feature = "wrapping", since = "1.7.0")]
1016 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1017 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1020 /// Shifts self right by `rhs` bits.
1022 /// Returns a tuple of the shifted version of self along with a boolean
1023 /// indicating whether the shift value was larger than or equal to the
1024 /// number of bits. If the shift value is too large, then value is
1025 /// masked (N-1) where N is the number of bits, and this value is then
1026 /// used to perform the shift.
1033 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
1034 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1037 #[stable(feature = "wrapping", since = "1.7.0")]
1038 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1039 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1042 /// Computes the absolute value of `self`.
1044 /// Returns a tuple of the absolute version of self along with a
1045 /// boolean indicating whether an overflow happened. If self is the
1046 /// minimum value (e.g. i32::MIN for values of type i32), then the
1047 /// minimum value will be returned again and true will be returned for
1048 /// an overflow happening.
1055 /// assert_eq!(10i8.overflowing_abs(), (10,false));
1056 /// assert_eq!((-10i8).overflowing_abs(), (10,false));
1057 /// assert_eq!((-128i8).overflowing_abs(), (-128,true));
1059 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1061 pub fn overflowing_abs(self) -> (Self, bool) {
1062 if self.is_negative() {
1063 self.overflowing_neg()
1069 /// Raises self to the power of `exp`, using exponentiation by squaring.
1076 /// let x: i32 = 2; // or any other integer type
1078 /// assert_eq!(x.pow(4), 16);
1080 #[stable(feature = "rust1", since = "1.0.0")]
1082 #[rustc_inherit_overflow_checks]
1083 pub fn pow(self, mut exp: u32) -> Self {
1084 let mut base = self;
1095 // Deal with the final bit of the exponent separately, since
1096 // squaring the base afterwards is not necessary and may cause a
1097 // needless overflow.
1105 /// Computes the absolute value of `self`.
1107 /// # Overflow behavior
1109 /// The absolute value of `i32::min_value()` cannot be represented as an
1110 /// `i32`, and attempting to calculate it will cause an overflow. This
1111 /// means that code in debug mode will trigger a panic on this case and
1112 /// optimized code will return `i32::min_value()` without a panic.
1119 /// assert_eq!(10i8.abs(), 10);
1120 /// assert_eq!((-10i8).abs(), 10);
1122 #[stable(feature = "rust1", since = "1.0.0")]
1124 #[rustc_inherit_overflow_checks]
1125 pub fn abs(self) -> Self {
1126 if self.is_negative() {
1127 // Note that the #[inline] above means that the overflow
1128 // semantics of this negation depend on the crate we're being
1136 /// Returns a number representing sign of `self`.
1138 /// - `0` if the number is zero
1139 /// - `1` if the number is positive
1140 /// - `-1` if the number is negative
1147 /// assert_eq!(10i8.signum(), 1);
1148 /// assert_eq!(0i8.signum(), 0);
1149 /// assert_eq!((-10i8).signum(), -1);
1151 #[stable(feature = "rust1", since = "1.0.0")]
1153 pub fn signum(self) -> Self {
1161 /// Returns `true` if `self` is positive and `false` if the number
1162 /// is zero or negative.
1169 /// assert!(10i8.is_positive());
1170 /// assert!(!(-10i8).is_positive());
1172 #[stable(feature = "rust1", since = "1.0.0")]
1174 pub fn is_positive(self) -> bool { self > 0 }
1176 /// Returns `true` if `self` is negative and `false` if the number
1177 /// is zero or positive.
1184 /// assert!((-10i8).is_negative());
1185 /// assert!(!10i8.is_negative());
1187 #[stable(feature = "rust1", since = "1.0.0")]
1189 pub fn is_negative(self) -> bool { self < 0 }
1195 int_impl! { i8, i8, u8, 8,
1196 intrinsics::add_with_overflow,
1197 intrinsics::sub_with_overflow,
1198 intrinsics::mul_with_overflow }
1203 int_impl! { i16, i16, u16, 16,
1204 intrinsics::add_with_overflow,
1205 intrinsics::sub_with_overflow,
1206 intrinsics::mul_with_overflow }
1211 int_impl! { i32, i32, u32, 32,
1212 intrinsics::add_with_overflow,
1213 intrinsics::sub_with_overflow,
1214 intrinsics::mul_with_overflow }
1219 int_impl! { i64, i64, u64, 64,
1220 intrinsics::add_with_overflow,
1221 intrinsics::sub_with_overflow,
1222 intrinsics::mul_with_overflow }
1227 int_impl! { i128, i128, u128, 128,
1228 intrinsics::add_with_overflow,
1229 intrinsics::sub_with_overflow,
1230 intrinsics::mul_with_overflow }
1233 #[cfg(target_pointer_width = "16")]
1236 int_impl! { isize, i16, u16, 16,
1237 intrinsics::add_with_overflow,
1238 intrinsics::sub_with_overflow,
1239 intrinsics::mul_with_overflow }
1242 #[cfg(target_pointer_width = "32")]
1245 int_impl! { isize, i32, u32, 32,
1246 intrinsics::add_with_overflow,
1247 intrinsics::sub_with_overflow,
1248 intrinsics::mul_with_overflow }
1251 #[cfg(target_pointer_width = "64")]
1254 int_impl! { isize, i64, u64, 64,
1255 intrinsics::add_with_overflow,
1256 intrinsics::sub_with_overflow,
1257 intrinsics::mul_with_overflow }
1260 // `Int` + `UnsignedInt` implemented for unsigned integers
1261 macro_rules! uint_impl {
1262 ($SelfT:ty, $ActualT:ty, $BITS:expr,
1268 $add_with_overflow:path,
1269 $sub_with_overflow:path,
1270 $mul_with_overflow:path) => {
1271 /// Returns the smallest value that can be represented by this integer type.
1276 /// assert_eq!(u8::min_value(), 0);
1278 #[stable(feature = "rust1", since = "1.0.0")]
1280 pub const fn min_value() -> Self { 0 }
1282 /// Returns the largest value that can be represented by this integer type.
1287 /// assert_eq!(u8::max_value(), 255);
1289 #[stable(feature = "rust1", since = "1.0.0")]
1291 pub const fn max_value() -> Self { !0 }
1293 /// Converts a string slice in a given base to an integer.
1295 /// Leading and trailing whitespace represent an error.
1302 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1306 from_str_radix(src, radix)
1309 /// Returns the number of ones in the binary representation of `self`.
1316 /// let n = 0b01001100u8;
1318 /// assert_eq!(n.count_ones(), 3);
1320 #[stable(feature = "rust1", since = "1.0.0")]
1322 pub fn count_ones(self) -> u32 {
1323 unsafe { $ctpop(self as $ActualT) as u32 }
1326 /// Returns the number of zeros in the binary representation of `self`.
1333 /// let n = 0b01001100u8;
1335 /// assert_eq!(n.count_zeros(), 5);
1337 #[stable(feature = "rust1", since = "1.0.0")]
1339 pub fn count_zeros(self) -> u32 {
1340 (!self).count_ones()
1343 /// Returns the number of leading zeros in the binary representation
1351 /// let n = 0b0101000u16;
1353 /// assert_eq!(n.leading_zeros(), 10);
1355 #[stable(feature = "rust1", since = "1.0.0")]
1357 pub fn leading_zeros(self) -> u32 {
1358 unsafe { $ctlz(self as $ActualT) as u32 }
1361 /// Returns the number of trailing zeros in the binary representation
1369 /// let n = 0b0101000u16;
1371 /// assert_eq!(n.trailing_zeros(), 3);
1373 #[stable(feature = "rust1", since = "1.0.0")]
1375 pub fn trailing_zeros(self) -> u32 {
1376 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1377 // emits two conditional moves on x86_64. By promoting the value to
1378 // u16 and setting bit 8, we get better code without any conditional
1380 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1381 // pending, remove this workaround once LLVM generates better code
1385 intrinsics::cttz(self as u16 | 0x100) as u32
1387 intrinsics::cttz(self) as u32
1392 /// Shifts the bits to the left by a specified amount, `n`,
1393 /// wrapping the truncated bits to the end of the resulting integer.
1395 /// Please note this isn't the same operation as `<<`!
1402 /// let n = 0x0123456789ABCDEFu64;
1403 /// let m = 0x3456789ABCDEF012u64;
1405 /// assert_eq!(n.rotate_left(12), m);
1407 #[stable(feature = "rust1", since = "1.0.0")]
1409 pub fn rotate_left(self, n: u32) -> Self {
1410 // Protect against undefined behaviour for over-long bit shifts
1412 (self << n) | (self >> (($BITS - n) % $BITS))
1415 /// Shifts the bits to the right by a specified amount, `n`,
1416 /// wrapping the truncated bits to the beginning of the resulting
1419 /// Please note this isn't the same operation as `>>`!
1426 /// let n = 0x0123456789ABCDEFu64;
1427 /// let m = 0xDEF0123456789ABCu64;
1429 /// assert_eq!(n.rotate_right(12), m);
1431 #[stable(feature = "rust1", since = "1.0.0")]
1433 pub fn rotate_right(self, n: u32) -> Self {
1434 // Protect against undefined behaviour for over-long bit shifts
1436 (self >> n) | (self << (($BITS - n) % $BITS))
1439 /// Reverses the byte order of the integer.
1446 /// let n = 0x0123456789ABCDEFu64;
1447 /// let m = 0xEFCDAB8967452301u64;
1449 /// assert_eq!(n.swap_bytes(), m);
1451 #[stable(feature = "rust1", since = "1.0.0")]
1453 pub fn swap_bytes(self) -> Self {
1454 unsafe { $bswap(self as $ActualT) as Self }
1457 /// Converts an integer from big endian to the target's endianness.
1459 /// On big endian this is a no-op. On little endian the bytes are
1467 /// let n = 0x0123456789ABCDEFu64;
1469 /// if cfg!(target_endian = "big") {
1470 /// assert_eq!(u64::from_be(n), n)
1472 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1475 #[stable(feature = "rust1", since = "1.0.0")]
1477 pub fn from_be(x: Self) -> Self {
1478 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1481 /// Converts an integer from little endian to the target's endianness.
1483 /// On little endian this is a no-op. On big endian the bytes are
1491 /// let n = 0x0123456789ABCDEFu64;
1493 /// if cfg!(target_endian = "little") {
1494 /// assert_eq!(u64::from_le(n), n)
1496 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1499 #[stable(feature = "rust1", since = "1.0.0")]
1501 pub fn from_le(x: Self) -> Self {
1502 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1505 /// Converts `self` to big endian from the target's endianness.
1507 /// On big endian this is a no-op. On little endian the bytes are
1515 /// let n = 0x0123456789ABCDEFu64;
1517 /// if cfg!(target_endian = "big") {
1518 /// assert_eq!(n.to_be(), n)
1520 /// assert_eq!(n.to_be(), n.swap_bytes())
1523 #[stable(feature = "rust1", since = "1.0.0")]
1525 pub fn to_be(self) -> Self { // or not to be?
1526 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1529 /// Converts `self` to little endian from the target's endianness.
1531 /// On little endian this is a no-op. On big endian the bytes are
1539 /// let n = 0x0123456789ABCDEFu64;
1541 /// if cfg!(target_endian = "little") {
1542 /// assert_eq!(n.to_le(), n)
1544 /// assert_eq!(n.to_le(), n.swap_bytes())
1547 #[stable(feature = "rust1", since = "1.0.0")]
1549 pub fn to_le(self) -> Self {
1550 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1553 /// Checked integer addition. Computes `self + other`, returning `None`
1554 /// if overflow occurred.
1561 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1562 /// assert_eq!(6u16.checked_add(65530), None);
1564 #[stable(feature = "rust1", since = "1.0.0")]
1566 pub fn checked_add(self, other: Self) -> Option<Self> {
1567 let (a, b) = self.overflowing_add(other);
1568 if b {None} else {Some(a)}
1571 /// Checked integer subtraction. Computes `self - other`, returning
1572 /// `None` if underflow occurred.
1579 /// assert_eq!(1u8.checked_sub(1), Some(0));
1580 /// assert_eq!(0u8.checked_sub(1), None);
1582 #[stable(feature = "rust1", since = "1.0.0")]
1584 pub fn checked_sub(self, other: Self) -> Option<Self> {
1585 let (a, b) = self.overflowing_sub(other);
1586 if b {None} else {Some(a)}
1589 /// Checked integer multiplication. Computes `self * other`, returning
1590 /// `None` if underflow or overflow occurred.
1597 /// assert_eq!(5u8.checked_mul(51), Some(255));
1598 /// assert_eq!(5u8.checked_mul(52), None);
1600 #[stable(feature = "rust1", since = "1.0.0")]
1602 pub fn checked_mul(self, other: Self) -> Option<Self> {
1603 let (a, b) = self.overflowing_mul(other);
1604 if b {None} else {Some(a)}
1607 /// Checked integer division. Computes `self / other`, returning `None`
1608 /// if `other == 0` or the operation results in underflow or overflow.
1615 /// assert_eq!(128u8.checked_div(2), Some(64));
1616 /// assert_eq!(1u8.checked_div(0), None);
1618 #[stable(feature = "rust1", since = "1.0.0")]
1620 pub fn checked_div(self, other: Self) -> Option<Self> {
1623 other => Some(unsafe { intrinsics::unchecked_div(self, other) }),
1627 /// Checked integer remainder. Computes `self % other`, returning `None`
1628 /// if `other == 0` or the operation results in underflow or overflow.
1635 /// assert_eq!(5u32.checked_rem(2), Some(1));
1636 /// assert_eq!(5u32.checked_rem(0), None);
1638 #[stable(feature = "wrapping", since = "1.7.0")]
1640 pub fn checked_rem(self, other: Self) -> Option<Self> {
1644 Some(unsafe { intrinsics::unchecked_rem(self, other) })
1648 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1651 /// Note that negating any positive integer will overflow.
1658 /// assert_eq!(0u32.checked_neg(), Some(0));
1659 /// assert_eq!(1u32.checked_neg(), None);
1661 #[stable(feature = "wrapping", since = "1.7.0")]
1663 pub fn checked_neg(self) -> Option<Self> {
1664 let (a, b) = self.overflowing_neg();
1665 if b {None} else {Some(a)}
1668 /// Checked shift left. Computes `self << rhs`, returning `None`
1669 /// if `rhs` is larger than or equal to the number of bits in `self`.
1676 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1677 /// assert_eq!(0x10u32.checked_shl(33), None);
1679 #[stable(feature = "wrapping", since = "1.7.0")]
1681 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1682 let (a, b) = self.overflowing_shl(rhs);
1683 if b {None} else {Some(a)}
1686 /// Checked shift right. Computes `self >> rhs`, returning `None`
1687 /// if `rhs` is larger than or equal to the number of bits in `self`.
1694 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1695 /// assert_eq!(0x10u32.checked_shr(33), None);
1697 #[stable(feature = "wrapping", since = "1.7.0")]
1699 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1700 let (a, b) = self.overflowing_shr(rhs);
1701 if b {None} else {Some(a)}
1704 /// Saturating integer addition. Computes `self + other`, saturating at
1705 /// the numeric bounds instead of overflowing.
1712 /// assert_eq!(100u8.saturating_add(1), 101);
1713 /// assert_eq!(200u8.saturating_add(127), 255);
1715 #[stable(feature = "rust1", since = "1.0.0")]
1717 pub fn saturating_add(self, other: Self) -> Self {
1718 match self.checked_add(other) {
1720 None => Self::max_value(),
1724 /// Saturating integer subtraction. Computes `self - other`, saturating
1725 /// at the numeric bounds instead of overflowing.
1732 /// assert_eq!(100u8.saturating_sub(27), 73);
1733 /// assert_eq!(13u8.saturating_sub(127), 0);
1735 #[stable(feature = "rust1", since = "1.0.0")]
1737 pub fn saturating_sub(self, other: Self) -> Self {
1738 match self.checked_sub(other) {
1740 None => Self::min_value(),
1744 /// Saturating integer multiplication. Computes `self * other`,
1745 /// saturating at the numeric bounds instead of overflowing.
1754 /// assert_eq!(100u32.saturating_mul(127), 12700);
1755 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1757 #[stable(feature = "wrapping", since = "1.7.0")]
1759 pub fn saturating_mul(self, other: Self) -> Self {
1760 self.checked_mul(other).unwrap_or(Self::max_value())
1763 /// Wrapping (modular) addition. Computes `self + other`,
1764 /// wrapping around at the boundary of the type.
1771 /// assert_eq!(200u8.wrapping_add(55), 255);
1772 /// assert_eq!(200u8.wrapping_add(155), 99);
1774 #[stable(feature = "rust1", since = "1.0.0")]
1776 pub fn wrapping_add(self, rhs: Self) -> Self {
1778 intrinsics::overflowing_add(self, rhs)
1782 /// Wrapping (modular) subtraction. Computes `self - other`,
1783 /// wrapping around at the boundary of the type.
1790 /// assert_eq!(100u8.wrapping_sub(100), 0);
1791 /// assert_eq!(100u8.wrapping_sub(155), 201);
1793 #[stable(feature = "rust1", since = "1.0.0")]
1795 pub fn wrapping_sub(self, rhs: Self) -> Self {
1797 intrinsics::overflowing_sub(self, rhs)
1801 /// Wrapping (modular) multiplication. Computes `self *
1802 /// other`, wrapping around at the boundary of the type.
1809 /// assert_eq!(10u8.wrapping_mul(12), 120);
1810 /// assert_eq!(25u8.wrapping_mul(12), 44);
1812 #[stable(feature = "rust1", since = "1.0.0")]
1814 pub fn wrapping_mul(self, rhs: Self) -> Self {
1816 intrinsics::overflowing_mul(self, rhs)
1820 /// Wrapping (modular) division. Computes `self / other`.
1821 /// Wrapped division on unsigned types is just normal division.
1822 /// There's no way wrapping could ever happen.
1823 /// This function exists, so that all operations
1824 /// are accounted for in the wrapping operations.
1831 /// assert_eq!(100u8.wrapping_div(10), 10);
1833 #[stable(feature = "num_wrapping", since = "1.2.0")]
1835 pub fn wrapping_div(self, rhs: Self) -> Self {
1839 /// Wrapping (modular) remainder. Computes `self % other`.
1840 /// Wrapped remainder calculation on unsigned types is
1841 /// just the regular remainder calculation.
1842 /// There's no way wrapping could ever happen.
1843 /// This function exists, so that all operations
1844 /// are accounted for in the wrapping operations.
1851 /// assert_eq!(100u8.wrapping_rem(10), 0);
1853 #[stable(feature = "num_wrapping", since = "1.2.0")]
1855 pub fn wrapping_rem(self, rhs: Self) -> Self {
1859 /// Wrapping (modular) negation. Computes `-self`,
1860 /// wrapping around at the boundary of the type.
1862 /// Since unsigned types do not have negative equivalents
1863 /// all applications of this function will wrap (except for `-0`).
1864 /// For values smaller than the corresponding signed type's maximum
1865 /// the result is the same as casting the corresponding signed value.
1866 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1867 /// `MAX` is the corresponding signed type's maximum.
1874 /// assert_eq!(100u8.wrapping_neg(), 156);
1875 /// assert_eq!(0u8.wrapping_neg(), 0);
1876 /// assert_eq!(180u8.wrapping_neg(), 76);
1877 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1879 #[stable(feature = "num_wrapping", since = "1.2.0")]
1881 pub fn wrapping_neg(self) -> Self {
1882 self.overflowing_neg().0
1885 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1886 /// where `mask` removes any high-order bits of `rhs` that
1887 /// would cause the shift to exceed the bitwidth of the type.
1889 /// Note that this is *not* the same as a rotate-left; the
1890 /// RHS of a wrapping shift-left is restricted to the range
1891 /// of the type, rather than the bits shifted out of the LHS
1892 /// being returned to the other end. The primitive integer
1893 /// types all implement a `rotate_left` function, which may
1894 /// be what you want instead.
1901 /// assert_eq!(1u8.wrapping_shl(7), 128);
1902 /// assert_eq!(1u8.wrapping_shl(8), 1);
1904 #[stable(feature = "num_wrapping", since = "1.2.0")]
1906 pub fn wrapping_shl(self, rhs: u32) -> Self {
1908 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1912 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1913 /// where `mask` removes any high-order bits of `rhs` that
1914 /// would cause the shift to exceed the bitwidth of the type.
1916 /// Note that this is *not* the same as a rotate-right; the
1917 /// RHS of a wrapping shift-right is restricted to the range
1918 /// of the type, rather than the bits shifted out of the LHS
1919 /// being returned to the other end. The primitive integer
1920 /// types all implement a `rotate_right` function, which may
1921 /// be what you want instead.
1928 /// assert_eq!(128u8.wrapping_shr(7), 1);
1929 /// assert_eq!(128u8.wrapping_shr(8), 128);
1931 #[stable(feature = "num_wrapping", since = "1.2.0")]
1933 pub fn wrapping_shr(self, rhs: u32) -> Self {
1935 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1939 /// Calculates `self` + `rhs`
1941 /// Returns a tuple of the addition along with a boolean indicating
1942 /// whether an arithmetic overflow would occur. If an overflow would
1943 /// have occurred then the wrapped value is returned.
1952 /// assert_eq!(5u32.overflowing_add(2), (7, false));
1953 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
1956 #[stable(feature = "wrapping", since = "1.7.0")]
1957 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1959 let (a, b) = $add_with_overflow(self as $ActualT,
1965 /// Calculates `self` - `rhs`
1967 /// Returns a tuple of the subtraction along with a boolean indicating
1968 /// whether an arithmetic overflow would occur. If an overflow would
1969 /// have occurred then the wrapped value is returned.
1978 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
1979 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
1982 #[stable(feature = "wrapping", since = "1.7.0")]
1983 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1985 let (a, b) = $sub_with_overflow(self as $ActualT,
1991 /// Calculates the multiplication of `self` and `rhs`.
1993 /// Returns a tuple of the multiplication along with a boolean
1994 /// indicating whether an arithmetic overflow would occur. If an
1995 /// overflow would have occurred then the wrapped value is returned.
2002 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2003 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2006 #[stable(feature = "wrapping", since = "1.7.0")]
2007 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2009 let (a, b) = $mul_with_overflow(self as $ActualT,
2015 /// Calculates the divisor when `self` is divided by `rhs`.
2017 /// Returns a tuple of the divisor along with a boolean indicating
2018 /// whether an arithmetic overflow would occur. Note that for unsigned
2019 /// integers overflow never occurs, so the second value is always
2024 /// This function will panic if `rhs` is 0.
2031 /// assert_eq!(5u32.overflowing_div(2), (2, false));
2034 #[stable(feature = "wrapping", since = "1.7.0")]
2035 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2039 /// Calculates the remainder when `self` is divided by `rhs`.
2041 /// Returns a tuple of the remainder after dividing along with a boolean
2042 /// indicating whether an arithmetic overflow would occur. Note that for
2043 /// unsigned integers overflow never occurs, so the second value is
2048 /// This function will panic if `rhs` is 0.
2055 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
2058 #[stable(feature = "wrapping", since = "1.7.0")]
2059 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2063 /// Negates self in an overflowing fashion.
2065 /// Returns `!self + 1` using wrapping operations to return the value
2066 /// that represents the negation of this unsigned value. Note that for
2067 /// positive unsigned values overflow always occurs, but negating 0 does
2075 /// assert_eq!(0u32.overflowing_neg(), (0, false));
2076 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
2079 #[stable(feature = "wrapping", since = "1.7.0")]
2080 pub fn overflowing_neg(self) -> (Self, bool) {
2081 ((!self).wrapping_add(1), self != 0)
2084 /// Shifts self left by `rhs` bits.
2086 /// Returns a tuple of the shifted version of self along with a boolean
2087 /// indicating whether the shift value was larger than or equal to the
2088 /// number of bits. If the shift value is too large, then value is
2089 /// masked (N-1) where N is the number of bits, and this value is then
2090 /// used to perform the shift.
2097 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
2098 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
2101 #[stable(feature = "wrapping", since = "1.7.0")]
2102 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2103 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
2106 /// Shifts self right by `rhs` bits.
2108 /// Returns a tuple of the shifted version of self along with a boolean
2109 /// indicating whether the shift value was larger than or equal to the
2110 /// number of bits. If the shift value is too large, then value is
2111 /// masked (N-1) where N is the number of bits, and this value is then
2112 /// used to perform the shift.
2119 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
2120 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2123 #[stable(feature = "wrapping", since = "1.7.0")]
2124 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2125 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
2129 /// Raises self to the power of `exp`, using exponentiation by squaring.
2136 /// assert_eq!(2u32.pow(4), 16);
2138 #[stable(feature = "rust1", since = "1.0.0")]
2140 #[rustc_inherit_overflow_checks]
2141 pub fn pow(self, mut exp: u32) -> Self {
2142 let mut base = self;
2153 // Deal with the final bit of the exponent separately, since
2154 // squaring the base afterwards is not necessary and may cause a
2155 // needless overflow.
2163 /// Returns `true` if and only if `self == 2^k` for some `k`.
2170 /// assert!(16u8.is_power_of_two());
2171 /// assert!(!10u8.is_power_of_two());
2173 #[stable(feature = "rust1", since = "1.0.0")]
2175 pub fn is_power_of_two(self) -> bool {
2176 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2179 // Returns one less than next power of two.
2180 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2182 // 8u8.one_less_than_next_power_of_two() == 7
2183 // 6u8.one_less_than_next_power_of_two() == 7
2185 // This method cannot overflow, as in the `next_power_of_two`
2186 // overflow cases it instead ends up returning the maximum value
2187 // of the type, and can return 0 for 0.
2189 fn one_less_than_next_power_of_two(self) -> Self {
2190 if self <= 1 { return 0; }
2192 // Because `p > 0`, it cannot consist entirely of leading zeros.
2193 // That means the shift is always in-bounds, and some processors
2194 // (such as intel pre-haswell) have more efficient ctlz
2195 // intrinsics when the argument is non-zero.
2197 let z = unsafe { $ctlz_nonzero(p) };
2198 <$SelfT>::max_value() >> z
2201 /// Returns the smallest power of two greater than or equal to `self`.
2203 /// When return value overflows (i.e. `self > (1 << (N-1))` for type
2204 /// `uN`), it panics in debug mode and return value is wrapped to 0 in
2205 /// release mode (the only situation in which method can return 0).
2212 /// assert_eq!(2u8.next_power_of_two(), 2);
2213 /// assert_eq!(3u8.next_power_of_two(), 4);
2215 #[stable(feature = "rust1", since = "1.0.0")]
2217 pub fn next_power_of_two(self) -> Self {
2218 self.one_less_than_next_power_of_two() + 1
2221 /// Returns the smallest power of two greater than or equal to `n`. If
2222 /// the next power of two is greater than the type's maximum value,
2223 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2230 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2231 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2232 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2234 #[stable(feature = "rust1", since = "1.0.0")]
2235 pub fn checked_next_power_of_two(self) -> Option<Self> {
2236 self.one_less_than_next_power_of_two().checked_add(1)
2243 uint_impl! { u8, u8, 8,
2246 intrinsics::ctlz_nonzero,
2249 intrinsics::add_with_overflow,
2250 intrinsics::sub_with_overflow,
2251 intrinsics::mul_with_overflow }
2256 uint_impl! { u16, u16, 16,
2259 intrinsics::ctlz_nonzero,
2262 intrinsics::add_with_overflow,
2263 intrinsics::sub_with_overflow,
2264 intrinsics::mul_with_overflow }
2269 uint_impl! { u32, u32, 32,
2272 intrinsics::ctlz_nonzero,
2275 intrinsics::add_with_overflow,
2276 intrinsics::sub_with_overflow,
2277 intrinsics::mul_with_overflow }
2282 uint_impl! { u64, u64, 64,
2285 intrinsics::ctlz_nonzero,
2288 intrinsics::add_with_overflow,
2289 intrinsics::sub_with_overflow,
2290 intrinsics::mul_with_overflow }
2295 uint_impl! { u128, u128, 128,
2298 intrinsics::ctlz_nonzero,
2301 intrinsics::add_with_overflow,
2302 intrinsics::sub_with_overflow,
2303 intrinsics::mul_with_overflow }
2306 #[cfg(target_pointer_width = "16")]
2309 uint_impl! { usize, u16, 16,
2312 intrinsics::ctlz_nonzero,
2315 intrinsics::add_with_overflow,
2316 intrinsics::sub_with_overflow,
2317 intrinsics::mul_with_overflow }
2319 #[cfg(target_pointer_width = "32")]
2322 uint_impl! { usize, u32, 32,
2325 intrinsics::ctlz_nonzero,
2328 intrinsics::add_with_overflow,
2329 intrinsics::sub_with_overflow,
2330 intrinsics::mul_with_overflow }
2333 #[cfg(target_pointer_width = "64")]
2336 uint_impl! { usize, u64, 64,
2339 intrinsics::ctlz_nonzero,
2342 intrinsics::add_with_overflow,
2343 intrinsics::sub_with_overflow,
2344 intrinsics::mul_with_overflow }
2347 /// A classification of floating point numbers.
2349 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
2350 /// their documentation for more.
2352 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
2353 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
2358 /// use std::num::FpCategory;
2361 /// let num = 12.4_f32;
2362 /// let inf = f32::INFINITY;
2363 /// let zero = 0f32;
2364 /// let sub: f32 = 1.1754942e-38;
2365 /// let nan = f32::NAN;
2367 /// assert_eq!(num.classify(), FpCategory::Normal);
2368 /// assert_eq!(inf.classify(), FpCategory::Infinite);
2369 /// assert_eq!(zero.classify(), FpCategory::Zero);
2370 /// assert_eq!(nan.classify(), FpCategory::Nan);
2371 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
2373 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2374 #[stable(feature = "rust1", since = "1.0.0")]
2375 pub enum FpCategory {
2376 /// "Not a Number", often obtained by dividing by zero.
2377 #[stable(feature = "rust1", since = "1.0.0")]
2380 /// Positive or negative infinity.
2381 #[stable(feature = "rust1", since = "1.0.0")]
2384 /// Positive or negative zero.
2385 #[stable(feature = "rust1", since = "1.0.0")]
2388 /// De-normalized floating point representation (less precise than `Normal`).
2389 #[stable(feature = "rust1", since = "1.0.0")]
2392 /// A regular floating point number.
2393 #[stable(feature = "rust1", since = "1.0.0")]
2397 /// A built-in floating point number.
2399 #[unstable(feature = "core_float",
2400 reason = "stable interface is via `impl f{32,64}` in later crates",
2402 pub trait Float: Sized {
2403 /// Returns `true` if this value is NaN and false otherwise.
2404 #[stable(feature = "core", since = "1.6.0")]
2405 fn is_nan(self) -> bool;
2406 /// Returns `true` if this value is positive infinity or negative infinity and
2407 /// false otherwise.
2408 #[stable(feature = "core", since = "1.6.0")]
2409 fn is_infinite(self) -> bool;
2410 /// Returns `true` if this number is neither infinite nor NaN.
2411 #[stable(feature = "core", since = "1.6.0")]
2412 fn is_finite(self) -> bool;
2413 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
2414 #[stable(feature = "core", since = "1.6.0")]
2415 fn is_normal(self) -> bool;
2416 /// Returns the category that this number falls into.
2417 #[stable(feature = "core", since = "1.6.0")]
2418 fn classify(self) -> FpCategory;
2420 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2421 /// number is `Float::nan()`.
2422 #[stable(feature = "core", since = "1.6.0")]
2423 fn abs(self) -> Self;
2424 /// Returns a number that represents the sign of `self`.
2426 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2427 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2428 /// - `Float::nan()` if the number is `Float::nan()`
2429 #[stable(feature = "core", since = "1.6.0")]
2430 fn signum(self) -> Self;
2432 /// Returns `true` if `self` is positive, including `+0.0` and
2433 /// `Float::infinity()`.
2434 #[stable(feature = "core", since = "1.6.0")]
2435 fn is_sign_positive(self) -> bool;
2436 /// Returns `true` if `self` is negative, including `-0.0` and
2437 /// `Float::neg_infinity()`.
2438 #[stable(feature = "core", since = "1.6.0")]
2439 fn is_sign_negative(self) -> bool;
2441 /// Take the reciprocal (inverse) of a number, `1/x`.
2442 #[stable(feature = "core", since = "1.6.0")]
2443 fn recip(self) -> Self;
2445 /// Raise a number to an integer power.
2447 /// Using this function is generally faster than using `powf`
2448 #[stable(feature = "core", since = "1.6.0")]
2449 fn powi(self, n: i32) -> Self;
2451 /// Convert radians to degrees.
2452 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2453 fn to_degrees(self) -> Self;
2454 /// Convert degrees to radians.
2455 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2456 fn to_radians(self) -> Self;
2458 /// Returns the maximum of the two numbers.
2459 #[stable(feature = "core_float_min_max", since="1.20.0")]
2460 fn max(self, other: Self) -> Self;
2461 /// Returns the minimum of the two numbers.
2462 #[stable(feature = "core_float_min_max", since="1.20.0")]
2463 fn min(self, other: Self) -> Self;
2466 macro_rules! from_str_radix_int_impl {
2468 #[stable(feature = "rust1", since = "1.0.0")]
2469 impl FromStr for $t {
2470 type Err = ParseIntError;
2471 fn from_str(src: &str) -> Result<Self, ParseIntError> {
2472 from_str_radix(src, 10)
2477 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
2479 /// The error type returned when a checked integral type conversion fails.
2480 #[unstable(feature = "try_from", issue = "33417")]
2481 #[derive(Debug, Copy, Clone)]
2482 pub struct TryFromIntError(());
2484 impl TryFromIntError {
2485 #[unstable(feature = "int_error_internals",
2486 reason = "available through Error trait and this method should \
2487 not be exposed publicly",
2490 pub fn __description(&self) -> &str {
2491 "out of range integral type conversion attempted"
2495 #[unstable(feature = "try_from", issue = "33417")]
2496 impl fmt::Display for TryFromIntError {
2497 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2498 self.__description().fmt(fmt)
2502 // no possible bounds violation
2503 macro_rules! try_from_unbounded {
2504 ($source:ty, $($target:ty),*) => {$(
2505 #[unstable(feature = "try_from", issue = "33417")]
2506 impl TryFrom<$source> for $target {
2507 type Error = TryFromIntError;
2510 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2517 // only negative bounds
2518 macro_rules! try_from_lower_bounded {
2519 ($source:ty, $($target:ty),*) => {$(
2520 #[unstable(feature = "try_from", issue = "33417")]
2521 impl TryFrom<$source> for $target {
2522 type Error = TryFromIntError;
2525 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2529 Err(TryFromIntError(()))
2536 // unsigned to signed (only positive bound)
2537 macro_rules! try_from_upper_bounded {
2538 ($source:ty, $($target:ty),*) => {$(
2539 #[unstable(feature = "try_from", issue = "33417")]
2540 impl TryFrom<$source> for $target {
2541 type Error = TryFromIntError;
2544 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2545 if u > (<$target>::max_value() as $source) {
2546 Err(TryFromIntError(()))
2556 macro_rules! try_from_both_bounded {
2557 ($source:ty, $($target:ty),*) => {$(
2558 #[unstable(feature = "try_from", issue = "33417")]
2559 impl TryFrom<$source> for $target {
2560 type Error = TryFromIntError;
2563 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2564 let min = <$target>::min_value() as $source;
2565 let max = <$target>::max_value() as $source;
2566 if u < min || u > max {
2567 Err(TryFromIntError(()))
2577 ($mac:ident, $source:ty, $($target:ty),*) => {$(
2578 $mac!($target, $source);
2582 /// intra-sign conversions
2583 try_from_unbounded!(u8, u8, u16, u32, u64, u128);
2584 try_from_unbounded!(u16, u16, u32, u64, u128);
2585 try_from_unbounded!(u32, u32, u64, u128);
2586 try_from_unbounded!(u64, u64, u128);
2587 try_from_unbounded!(u128, u128);
2588 try_from_upper_bounded!(u16, u8);
2589 try_from_upper_bounded!(u32, u16, u8);
2590 try_from_upper_bounded!(u64, u32, u16, u8);
2591 try_from_upper_bounded!(u128, u64, u32, u16, u8);
2593 try_from_unbounded!(i8, i8, i16, i32, i64, i128);
2594 try_from_unbounded!(i16, i16, i32, i64, i128);
2595 try_from_unbounded!(i32, i32, i64, i128);
2596 try_from_unbounded!(i64, i64, i128);
2597 try_from_unbounded!(i128, i128);
2598 try_from_both_bounded!(i16, i8);
2599 try_from_both_bounded!(i32, i16, i8);
2600 try_from_both_bounded!(i64, i32, i16, i8);
2601 try_from_both_bounded!(i128, i64, i32, i16, i8);
2603 // unsigned-to-signed
2604 try_from_unbounded!(u8, i16, i32, i64, i128);
2605 try_from_unbounded!(u16, i32, i64, i128);
2606 try_from_unbounded!(u32, i64, i128);
2607 try_from_unbounded!(u64, i128);
2608 try_from_upper_bounded!(u8, i8);
2609 try_from_upper_bounded!(u16, i8, i16);
2610 try_from_upper_bounded!(u32, i8, i16, i32);
2611 try_from_upper_bounded!(u64, i8, i16, i32, i64);
2612 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
2614 // signed-to-unsigned
2615 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
2616 try_from_lower_bounded!(i16, u16, u32, u64, u128);
2617 try_from_lower_bounded!(i32, u32, u64, u128);
2618 try_from_lower_bounded!(i64, u64, u128);
2619 try_from_lower_bounded!(i128, u128);
2620 try_from_both_bounded!(i16, u8);
2621 try_from_both_bounded!(i32, u16, u8);
2622 try_from_both_bounded!(i64, u32, u16, u8);
2623 try_from_both_bounded!(i128, u64, u32, u16, u8);
2626 try_from_unbounded!(usize, usize);
2627 try_from_upper_bounded!(usize, isize);
2628 try_from_lower_bounded!(isize, usize);
2629 try_from_unbounded!(isize, isize);
2631 #[cfg(target_pointer_width = "16")]
2632 mod ptr_try_from_impls {
2633 use super::TryFromIntError;
2634 use convert::TryFrom;
2636 try_from_upper_bounded!(usize, u8);
2637 try_from_unbounded!(usize, u16, u32, u64, u128);
2638 try_from_upper_bounded!(usize, i8, i16);
2639 try_from_unbounded!(usize, i32, i64, i128);
2641 try_from_both_bounded!(isize, u8);
2642 try_from_lower_bounded!(isize, u16, u32, u64, u128);
2643 try_from_both_bounded!(isize, i8);
2644 try_from_unbounded!(isize, i16, i32, i64, i128);
2646 rev!(try_from_unbounded, usize, u8, u16);
2647 rev!(try_from_upper_bounded, usize, u32, u64, u128);
2648 rev!(try_from_lower_bounded, usize, i8, i16);
2649 rev!(try_from_both_bounded, usize, i32, i64, i128);
2651 rev!(try_from_unbounded, isize, u8);
2652 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
2653 rev!(try_from_unbounded, isize, i8, i16);
2654 rev!(try_from_both_bounded, isize, i32, i64, i128);
2657 #[cfg(target_pointer_width = "32")]
2658 mod ptr_try_from_impls {
2659 use super::TryFromIntError;
2660 use convert::TryFrom;
2662 try_from_upper_bounded!(usize, u8, u16);
2663 try_from_unbounded!(usize, u32, u64, u128);
2664 try_from_upper_bounded!(usize, i8, i16, i32);
2665 try_from_unbounded!(usize, i64, i128);
2667 try_from_both_bounded!(isize, u8, u16);
2668 try_from_lower_bounded!(isize, u32, u64, u128);
2669 try_from_both_bounded!(isize, i8, i16);
2670 try_from_unbounded!(isize, i32, i64, i128);
2672 rev!(try_from_unbounded, usize, u8, u16, u32);
2673 rev!(try_from_upper_bounded, usize, u64, u128);
2674 rev!(try_from_lower_bounded, usize, i8, i16, i32);
2675 rev!(try_from_both_bounded, usize, i64, i128);
2677 rev!(try_from_unbounded, isize, u8, u16);
2678 rev!(try_from_upper_bounded, isize, u32, u64, u128);
2679 rev!(try_from_unbounded, isize, i8, i16, i32);
2680 rev!(try_from_both_bounded, isize, i64, i128);
2683 #[cfg(target_pointer_width = "64")]
2684 mod ptr_try_from_impls {
2685 use super::TryFromIntError;
2686 use convert::TryFrom;
2688 try_from_upper_bounded!(usize, u8, u16, u32);
2689 try_from_unbounded!(usize, u64, u128);
2690 try_from_upper_bounded!(usize, i8, i16, i32, i64);
2691 try_from_unbounded!(usize, i128);
2693 try_from_both_bounded!(isize, u8, u16, u32);
2694 try_from_lower_bounded!(isize, u64, u128);
2695 try_from_both_bounded!(isize, i8, i16, i32);
2696 try_from_unbounded!(isize, i64, i128);
2698 rev!(try_from_unbounded, usize, u8, u16, u32, u64);
2699 rev!(try_from_upper_bounded, usize, u128);
2700 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
2701 rev!(try_from_both_bounded, usize, i128);
2703 rev!(try_from_unbounded, isize, u8, u16, u32);
2704 rev!(try_from_upper_bounded, isize, u64, u128);
2705 rev!(try_from_unbounded, isize, i8, i16, i32, i64);
2706 rev!(try_from_both_bounded, isize, i128);
2710 trait FromStrRadixHelper: PartialOrd + Copy {
2711 fn min_value() -> Self;
2712 fn max_value() -> Self;
2713 fn from_u32(u: u32) -> Self;
2714 fn checked_mul(&self, other: u32) -> Option<Self>;
2715 fn checked_sub(&self, other: u32) -> Option<Self>;
2716 fn checked_add(&self, other: u32) -> Option<Self>;
2720 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
2722 fn min_value() -> Self { Self::min_value() }
2724 fn max_value() -> Self { Self::max_value() }
2726 fn from_u32(u: u32) -> Self { u as Self }
2728 fn checked_mul(&self, other: u32) -> Option<Self> {
2729 Self::checked_mul(*self, other as Self)
2732 fn checked_sub(&self, other: u32) -> Option<Self> {
2733 Self::checked_sub(*self, other as Self)
2736 fn checked_add(&self, other: u32) -> Option<Self> {
2737 Self::checked_add(*self, other as Self)
2741 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
2743 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
2744 use self::IntErrorKind::*;
2745 use self::ParseIntError as PIE;
2747 assert!(radix >= 2 && radix <= 36,
2748 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2752 return Err(PIE { kind: Empty });
2755 let is_signed_ty = T::from_u32(0) > T::min_value();
2757 // all valid digits are ascii, so we will just iterate over the utf8 bytes
2758 // and cast them to chars. .to_digit() will safely return None for anything
2759 // other than a valid ascii digit for the given radix, including the first-byte
2760 // of multi-byte sequences
2761 let src = src.as_bytes();
2763 let (is_positive, digits) = match src[0] {
2764 b'+' => (true, &src[1..]),
2765 b'-' if is_signed_ty => (false, &src[1..]),
2769 if digits.is_empty() {
2770 return Err(PIE { kind: Empty });
2773 let mut result = T::from_u32(0);
2775 // The number is positive
2777 let x = match (c as char).to_digit(radix) {
2779 None => return Err(PIE { kind: InvalidDigit }),
2781 result = match result.checked_mul(radix) {
2782 Some(result) => result,
2783 None => return Err(PIE { kind: Overflow }),
2785 result = match result.checked_add(x) {
2786 Some(result) => result,
2787 None => return Err(PIE { kind: Overflow }),
2791 // The number is negative
2793 let x = match (c as char).to_digit(radix) {
2795 None => return Err(PIE { kind: InvalidDigit }),
2797 result = match result.checked_mul(radix) {
2798 Some(result) => result,
2799 None => return Err(PIE { kind: Underflow }),
2801 result = match result.checked_sub(x) {
2802 Some(result) => result,
2803 None => return Err(PIE { kind: Underflow }),
2810 /// An error which can be returned when parsing an integer.
2812 /// This error is used as the error type for the `from_str_radix()` functions
2813 /// on the primitive integer types, such as [`i8::from_str_radix`].
2815 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
2816 #[derive(Debug, Clone, PartialEq, Eq)]
2817 #[stable(feature = "rust1", since = "1.0.0")]
2818 pub struct ParseIntError {
2822 #[derive(Debug, Clone, PartialEq, Eq)]
2830 impl ParseIntError {
2831 #[unstable(feature = "int_error_internals",
2832 reason = "available through Error trait and this method should \
2833 not be exposed publicly",
2836 pub fn __description(&self) -> &str {
2838 IntErrorKind::Empty => "cannot parse integer from empty string",
2839 IntErrorKind::InvalidDigit => "invalid digit found in string",
2840 IntErrorKind::Overflow => "number too large to fit in target type",
2841 IntErrorKind::Underflow => "number too small to fit in target type",
2846 #[stable(feature = "rust1", since = "1.0.0")]
2847 impl fmt::Display for ParseIntError {
2848 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2849 self.__description().fmt(f)
2853 #[stable(feature = "rust1", since = "1.0.0")]
2854 pub use num::dec2flt::ParseFloatError;
2856 // Conversion traits for primitive integer and float types
2857 // Conversions T -> T are covered by a blanket impl and therefore excluded
2858 // Some conversions from and to usize/isize are not implemented due to portability concerns
2859 macro_rules! impl_from {
2860 ($Small: ty, $Large: ty, #[$attr:meta]) => {
2862 impl From<$Small> for $Large {
2864 fn from(small: $Small) -> $Large {
2871 // Unsigned -> Unsigned
2872 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2873 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2874 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2875 impl_from! { u8, u128, #[unstable(feature = "i128", issue = "35118")] }
2876 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2877 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2878 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2879 impl_from! { u16, u128, #[unstable(feature = "i128", issue = "35118")] }
2880 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2881 impl_from! { u32, u128, #[unstable(feature = "i128", issue = "35118")] }
2882 impl_from! { u64, u128, #[unstable(feature = "i128", issue = "35118")] }
2885 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2886 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2887 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2888 impl_from! { i8, i128, #[unstable(feature = "i128", issue = "35118")] }
2889 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2890 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2891 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2892 impl_from! { i16, i128, #[unstable(feature = "i128", issue = "35118")] }
2893 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2894 impl_from! { i32, i128, #[unstable(feature = "i128", issue = "35118")] }
2895 impl_from! { i64, i128, #[unstable(feature = "i128", issue = "35118")] }
2897 // Unsigned -> Signed
2898 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2899 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2900 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2901 impl_from! { u8, i128, #[unstable(feature = "i128", issue = "35118")] }
2902 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2903 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2904 impl_from! { u16, i128, #[unstable(feature = "i128", issue = "35118")] }
2905 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2906 impl_from! { u32, i128, #[unstable(feature = "i128", issue = "35118")] }
2907 impl_from! { u64, i128, #[unstable(feature = "i128", issue = "35118")] }
2909 // Note: integers can only be represented with full precision in a float if
2910 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2911 // Lossy float conversions are not implemented at this time.
2914 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2915 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2916 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2917 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2918 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2920 // Unsigned -> Float
2921 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2922 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2923 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2924 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2925 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2928 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }