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.
136 /// This function panics if `radix` is not in the range from 2 to 36.
143 /// assert_eq!(i32::from_str_radix("A", 16), Ok(10));
145 #[stable(feature = "rust1", since = "1.0.0")]
146 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
147 from_str_radix(src, radix)
150 /// Returns the number of ones in the binary representation of `self`.
157 /// let n = -0b1000_0000i8;
159 /// assert_eq!(n.count_ones(), 1);
161 #[stable(feature = "rust1", since = "1.0.0")]
163 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
165 /// Returns the number of zeros in the binary representation of `self`.
172 /// let n = -0b1000_0000i8;
174 /// assert_eq!(n.count_zeros(), 7);
176 #[stable(feature = "rust1", since = "1.0.0")]
178 pub fn count_zeros(self) -> u32 {
182 /// Returns the number of leading zeros in the binary representation
192 /// assert_eq!(n.leading_zeros(), 0);
194 #[stable(feature = "rust1", since = "1.0.0")]
196 pub fn leading_zeros(self) -> u32 {
197 (self as $UnsignedT).leading_zeros()
200 /// Returns the number of trailing zeros in the binary representation
210 /// assert_eq!(n.trailing_zeros(), 2);
212 #[stable(feature = "rust1", since = "1.0.0")]
214 pub fn trailing_zeros(self) -> u32 {
215 (self as $UnsignedT).trailing_zeros()
218 /// Shifts the bits to the left by a specified amount, `n`,
219 /// wrapping the truncated bits to the end of the resulting integer.
221 /// Please note this isn't the same operation as `<<`!
228 /// let n = 0x0123456789ABCDEFi64;
229 /// let m = -0x76543210FEDCBA99i64;
231 /// assert_eq!(n.rotate_left(32), m);
233 #[stable(feature = "rust1", since = "1.0.0")]
235 pub fn rotate_left(self, n: u32) -> Self {
236 (self as $UnsignedT).rotate_left(n) as Self
239 /// Shifts the bits to the right by a specified amount, `n`,
240 /// wrapping the truncated bits to the beginning of the resulting
243 /// Please note this isn't the same operation as `>>`!
250 /// let n = 0x0123456789ABCDEFi64;
251 /// let m = -0xFEDCBA987654322i64;
253 /// assert_eq!(n.rotate_right(4), m);
255 #[stable(feature = "rust1", since = "1.0.0")]
257 pub fn rotate_right(self, n: u32) -> Self {
258 (self as $UnsignedT).rotate_right(n) as Self
261 /// Reverses the byte order of the integer.
268 /// let n = 0x0123456789ABCDEFi64;
269 /// let m = -0x1032547698BADCFFi64;
271 /// assert_eq!(n.swap_bytes(), m);
273 #[stable(feature = "rust1", since = "1.0.0")]
275 pub fn swap_bytes(self) -> Self {
276 (self as $UnsignedT).swap_bytes() as Self
279 /// Converts an integer from big endian to the target's endianness.
281 /// On big endian this is a no-op. On little endian the bytes are
289 /// let n = 0x0123456789ABCDEFi64;
291 /// if cfg!(target_endian = "big") {
292 /// assert_eq!(i64::from_be(n), n)
294 /// assert_eq!(i64::from_be(n), n.swap_bytes())
297 #[stable(feature = "rust1", since = "1.0.0")]
299 pub fn from_be(x: Self) -> Self {
300 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
303 /// Converts an integer from little endian to the target's endianness.
305 /// On little endian this is a no-op. On big endian the bytes are
313 /// let n = 0x0123456789ABCDEFi64;
315 /// if cfg!(target_endian = "little") {
316 /// assert_eq!(i64::from_le(n), n)
318 /// assert_eq!(i64::from_le(n), n.swap_bytes())
321 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn from_le(x: Self) -> Self {
324 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
327 /// Converts `self` to big endian from the target's endianness.
329 /// On big endian this is a no-op. On little endian the bytes are
337 /// let n = 0x0123456789ABCDEFi64;
339 /// if cfg!(target_endian = "big") {
340 /// assert_eq!(n.to_be(), n)
342 /// assert_eq!(n.to_be(), n.swap_bytes())
345 #[stable(feature = "rust1", since = "1.0.0")]
347 pub fn to_be(self) -> Self { // or not to be?
348 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
351 /// Converts `self` to little endian from the target's endianness.
353 /// On little endian this is a no-op. On big endian the bytes are
361 /// let n = 0x0123456789ABCDEFi64;
363 /// if cfg!(target_endian = "little") {
364 /// assert_eq!(n.to_le(), n)
366 /// assert_eq!(n.to_le(), n.swap_bytes())
369 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn to_le(self) -> Self {
372 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
375 /// Checked integer addition. Computes `self + other`, returning `None`
376 /// if overflow occurred.
383 /// assert_eq!(7i16.checked_add(32760), Some(32767));
384 /// assert_eq!(8i16.checked_add(32760), None);
386 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn checked_add(self, other: Self) -> Option<Self> {
389 let (a, b) = self.overflowing_add(other);
390 if b {None} else {Some(a)}
393 /// Checked integer subtraction. Computes `self - other`, returning
394 /// `None` if underflow occurred.
401 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
402 /// assert_eq!((-128i8).checked_sub(1), None);
404 #[stable(feature = "rust1", since = "1.0.0")]
406 pub fn checked_sub(self, other: Self) -> Option<Self> {
407 let (a, b) = self.overflowing_sub(other);
408 if b {None} else {Some(a)}
411 /// Checked integer multiplication. Computes `self * other`, returning
412 /// `None` if underflow or overflow occurred.
419 /// assert_eq!(6i8.checked_mul(21), Some(126));
420 /// assert_eq!(6i8.checked_mul(22), None);
422 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn checked_mul(self, other: Self) -> Option<Self> {
425 let (a, b) = self.overflowing_mul(other);
426 if b {None} else {Some(a)}
429 /// Checked integer division. Computes `self / other`, returning `None`
430 /// if `other == 0` or the operation results in underflow or overflow.
437 /// assert_eq!((-127i8).checked_div(-1), Some(127));
438 /// assert_eq!((-128i8).checked_div(-1), None);
439 /// assert_eq!((1i8).checked_div(0), None);
441 #[stable(feature = "rust1", since = "1.0.0")]
443 pub fn checked_div(self, other: Self) -> Option<Self> {
444 if other == 0 || (self == Self::min_value() && other == -1) {
447 Some(unsafe { intrinsics::unchecked_div(self, other) })
451 /// Checked integer remainder. Computes `self % other`, returning `None`
452 /// if `other == 0` or the operation results in underflow or overflow.
461 /// assert_eq!(5i32.checked_rem(2), Some(1));
462 /// assert_eq!(5i32.checked_rem(0), None);
463 /// assert_eq!(i32::MIN.checked_rem(-1), None);
465 #[stable(feature = "wrapping", since = "1.7.0")]
467 pub fn checked_rem(self, other: Self) -> Option<Self> {
468 if other == 0 || (self == Self::min_value() && other == -1) {
471 Some(unsafe { intrinsics::unchecked_rem(self, other) })
475 /// Checked negation. Computes `-self`, returning `None` if `self ==
485 /// assert_eq!(5i32.checked_neg(), Some(-5));
486 /// assert_eq!(i32::MIN.checked_neg(), None);
488 #[stable(feature = "wrapping", since = "1.7.0")]
490 pub fn checked_neg(self) -> Option<Self> {
491 let (a, b) = self.overflowing_neg();
492 if b {None} else {Some(a)}
495 /// Checked shift left. Computes `self << rhs`, returning `None`
496 /// if `rhs` is larger than or equal to the number of bits in `self`.
503 /// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
504 /// assert_eq!(0x10i32.checked_shl(33), None);
506 #[stable(feature = "wrapping", since = "1.7.0")]
508 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
509 let (a, b) = self.overflowing_shl(rhs);
510 if b {None} else {Some(a)}
513 /// Checked shift right. Computes `self >> rhs`, returning `None`
514 /// if `rhs` is larger than or equal to the number of bits in `self`.
521 /// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
522 /// assert_eq!(0x10i32.checked_shr(33), None);
524 #[stable(feature = "wrapping", since = "1.7.0")]
526 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
527 let (a, b) = self.overflowing_shr(rhs);
528 if b {None} else {Some(a)}
531 /// Checked absolute value. Computes `self.abs()`, returning `None` if
541 /// assert_eq!((-5i32).checked_abs(), Some(5));
542 /// assert_eq!(i32::MIN.checked_abs(), None);
544 #[stable(feature = "no_panic_abs", since = "1.13.0")]
546 pub fn checked_abs(self) -> Option<Self> {
547 if self.is_negative() {
554 /// Saturating integer addition. Computes `self + other`, saturating at
555 /// the numeric bounds instead of overflowing.
562 /// assert_eq!(100i8.saturating_add(1), 101);
563 /// assert_eq!(100i8.saturating_add(127), 127);
565 #[stable(feature = "rust1", since = "1.0.0")]
567 pub fn saturating_add(self, other: Self) -> Self {
568 match self.checked_add(other) {
570 None if other >= 0 => Self::max_value(),
571 None => Self::min_value(),
575 /// Saturating integer subtraction. Computes `self - other`, saturating
576 /// at the numeric bounds instead of overflowing.
583 /// assert_eq!(100i8.saturating_sub(127), -27);
584 /// assert_eq!((-100i8).saturating_sub(127), -128);
586 #[stable(feature = "rust1", since = "1.0.0")]
588 pub fn saturating_sub(self, other: Self) -> Self {
589 match self.checked_sub(other) {
591 None if other >= 0 => Self::min_value(),
592 None => Self::max_value(),
596 /// Saturating integer multiplication. Computes `self * other`,
597 /// saturating at the numeric bounds instead of overflowing.
606 /// assert_eq!(100i32.saturating_mul(127), 12700);
607 /// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
608 /// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
610 #[stable(feature = "wrapping", since = "1.7.0")]
612 pub fn saturating_mul(self, other: Self) -> Self {
613 self.checked_mul(other).unwrap_or_else(|| {
614 if (self < 0 && other < 0) || (self > 0 && other > 0) {
622 /// Wrapping (modular) addition. Computes `self + other`,
623 /// wrapping around at the boundary of the type.
630 /// assert_eq!(100i8.wrapping_add(27), 127);
631 /// assert_eq!(100i8.wrapping_add(127), -29);
633 #[stable(feature = "rust1", since = "1.0.0")]
635 pub fn wrapping_add(self, rhs: Self) -> Self {
637 intrinsics::overflowing_add(self, rhs)
641 /// Wrapping (modular) subtraction. Computes `self - other`,
642 /// wrapping around at the boundary of the type.
649 /// assert_eq!(0i8.wrapping_sub(127), -127);
650 /// assert_eq!((-2i8).wrapping_sub(127), 127);
652 #[stable(feature = "rust1", since = "1.0.0")]
654 pub fn wrapping_sub(self, rhs: Self) -> Self {
656 intrinsics::overflowing_sub(self, rhs)
660 /// Wrapping (modular) multiplication. Computes `self *
661 /// other`, wrapping around at the boundary of the type.
668 /// assert_eq!(10i8.wrapping_mul(12), 120);
669 /// assert_eq!(11i8.wrapping_mul(12), -124);
671 #[stable(feature = "rust1", since = "1.0.0")]
673 pub fn wrapping_mul(self, rhs: Self) -> Self {
675 intrinsics::overflowing_mul(self, rhs)
679 /// Wrapping (modular) division. Computes `self / other`,
680 /// wrapping around at the boundary of the type.
682 /// The only case where such wrapping can occur is when one
683 /// divides `MIN / -1` on a signed type (where `MIN` is the
684 /// negative minimal value for the type); this is equivalent
685 /// to `-MIN`, a positive value that is too large to represent
686 /// in the type. In such a case, this function returns `MIN`
691 /// This function will panic if `rhs` is 0.
698 /// assert_eq!(100u8.wrapping_div(10), 10);
699 /// assert_eq!((-128i8).wrapping_div(-1), -128);
701 #[stable(feature = "num_wrapping", since = "1.2.0")]
703 pub fn wrapping_div(self, rhs: Self) -> Self {
704 self.overflowing_div(rhs).0
707 /// Wrapping (modular) remainder. Computes `self % other`,
708 /// wrapping around at the boundary of the type.
710 /// Such wrap-around never actually occurs mathematically;
711 /// implementation artifacts make `x % y` invalid for `MIN /
712 /// -1` on a signed type (where `MIN` is the negative
713 /// minimal value). In such a case, this function returns `0`.
717 /// This function will panic if `rhs` is 0.
724 /// assert_eq!(100i8.wrapping_rem(10), 0);
725 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
727 #[stable(feature = "num_wrapping", since = "1.2.0")]
729 pub fn wrapping_rem(self, rhs: Self) -> Self {
730 self.overflowing_rem(rhs).0
733 /// Wrapping (modular) negation. Computes `-self`,
734 /// wrapping around at the boundary of the type.
736 /// The only case where such wrapping can occur is when one
737 /// negates `MIN` on a signed type (where `MIN` is the
738 /// negative minimal value for the type); this is a positive
739 /// value that is too large to represent in the type. In such
740 /// a case, this function returns `MIN` itself.
747 /// assert_eq!(100i8.wrapping_neg(), -100);
748 /// assert_eq!((-128i8).wrapping_neg(), -128);
750 #[stable(feature = "num_wrapping", since = "1.2.0")]
752 pub fn wrapping_neg(self) -> Self {
753 self.overflowing_neg().0
756 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
757 /// where `mask` removes any high-order bits of `rhs` that
758 /// would cause the shift to exceed the bitwidth of the type.
760 /// Note that this is *not* the same as a rotate-left; the
761 /// RHS of a wrapping shift-left is restricted to the range
762 /// of the type, rather than the bits shifted out of the LHS
763 /// being returned to the other end. The primitive integer
764 /// types all implement a `rotate_left` function, which may
765 /// be what you want instead.
772 /// assert_eq!((-1i8).wrapping_shl(7), -128);
773 /// assert_eq!((-1i8).wrapping_shl(8), -1);
775 #[stable(feature = "num_wrapping", since = "1.2.0")]
777 pub fn wrapping_shl(self, rhs: u32) -> Self {
779 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
783 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
784 /// where `mask` removes any high-order bits of `rhs` that
785 /// would cause the shift to exceed the bitwidth of the type.
787 /// Note that this is *not* the same as a rotate-right; the
788 /// RHS of a wrapping shift-right is restricted to the range
789 /// of the type, rather than the bits shifted out of the LHS
790 /// being returned to the other end. The primitive integer
791 /// types all implement a `rotate_right` function, which may
792 /// be what you want instead.
799 /// assert_eq!((-128i8).wrapping_shr(7), -1);
800 /// assert_eq!((-128i8).wrapping_shr(8), -128);
802 #[stable(feature = "num_wrapping", since = "1.2.0")]
804 pub fn wrapping_shr(self, rhs: u32) -> Self {
806 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
810 /// Wrapping (modular) absolute value. Computes `self.abs()`,
811 /// wrapping around at the boundary of the type.
813 /// The only case where such wrapping can occur is when one takes
814 /// the absolute value of the negative minimal value for the type
815 /// this is a positive value that is too large to represent in the
816 /// type. In such a case, this function returns `MIN` itself.
823 /// assert_eq!(100i8.wrapping_abs(), 100);
824 /// assert_eq!((-100i8).wrapping_abs(), 100);
825 /// assert_eq!((-128i8).wrapping_abs(), -128);
826 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
828 #[stable(feature = "no_panic_abs", since = "1.13.0")]
830 pub fn wrapping_abs(self) -> Self {
831 if self.is_negative() {
838 /// Calculates `self` + `rhs`
840 /// Returns a tuple of the addition along with a boolean indicating
841 /// whether an arithmetic overflow would occur. If an overflow would
842 /// have occurred then the wrapped value is returned.
851 /// assert_eq!(5i32.overflowing_add(2), (7, false));
852 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
855 #[stable(feature = "wrapping", since = "1.7.0")]
856 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
858 let (a, b) = $add_with_overflow(self as $ActualT,
864 /// Calculates `self` - `rhs`
866 /// Returns a tuple of the subtraction along with a boolean indicating
867 /// whether an arithmetic overflow would occur. If an overflow would
868 /// have occurred then the wrapped value is returned.
877 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
878 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
881 #[stable(feature = "wrapping", since = "1.7.0")]
882 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
884 let (a, b) = $sub_with_overflow(self as $ActualT,
890 /// Calculates the multiplication of `self` and `rhs`.
892 /// Returns a tuple of the multiplication along with a boolean
893 /// indicating whether an arithmetic overflow would occur. If an
894 /// overflow would have occurred then the wrapped value is returned.
901 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
902 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
905 #[stable(feature = "wrapping", since = "1.7.0")]
906 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
908 let (a, b) = $mul_with_overflow(self as $ActualT,
914 /// Calculates the divisor when `self` is divided by `rhs`.
916 /// Returns a tuple of the divisor along with a boolean indicating
917 /// whether an arithmetic overflow would occur. If an overflow would
918 /// occur then self is returned.
922 /// This function will panic if `rhs` is 0.
931 /// assert_eq!(5i32.overflowing_div(2), (2, false));
932 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
935 #[stable(feature = "wrapping", since = "1.7.0")]
936 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
937 if self == Self::min_value() && rhs == -1 {
944 /// Calculates the remainder when `self` is divided by `rhs`.
946 /// Returns a tuple of the remainder after dividing along with a boolean
947 /// indicating whether an arithmetic overflow would occur. If an
948 /// overflow would occur then 0 is returned.
952 /// This function will panic if `rhs` is 0.
961 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
962 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
965 #[stable(feature = "wrapping", since = "1.7.0")]
966 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
967 if self == Self::min_value() && rhs == -1 {
974 /// Negates self, overflowing if this is equal to the minimum value.
976 /// Returns a tuple of the negated version of self along with a boolean
977 /// indicating whether an overflow happened. If `self` is the minimum
978 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
979 /// value will be returned again and `true` will be returned for an
980 /// overflow happening.
989 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
990 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
993 #[stable(feature = "wrapping", since = "1.7.0")]
994 pub fn overflowing_neg(self) -> (Self, bool) {
995 if self == Self::min_value() {
996 (Self::min_value(), true)
1002 /// Shifts self left by `rhs` bits.
1004 /// Returns a tuple of the shifted version of self along with a boolean
1005 /// indicating whether the shift value was larger than or equal to the
1006 /// number of bits. If the shift value is too large, then value is
1007 /// masked (N-1) where N is the number of bits, and this value is then
1008 /// used to perform the shift.
1015 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
1016 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
1019 #[stable(feature = "wrapping", since = "1.7.0")]
1020 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1021 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1024 /// Shifts self right by `rhs` bits.
1026 /// Returns a tuple of the shifted version of self along with a boolean
1027 /// indicating whether the shift value was larger than or equal to the
1028 /// number of bits. If the shift value is too large, then value is
1029 /// masked (N-1) where N is the number of bits, and this value is then
1030 /// used to perform the shift.
1037 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
1038 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1041 #[stable(feature = "wrapping", since = "1.7.0")]
1042 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1043 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1046 /// Computes the absolute value of `self`.
1048 /// Returns a tuple of the absolute version of self along with a
1049 /// boolean indicating whether an overflow happened. If self is the
1050 /// minimum value (e.g. i32::MIN for values of type i32), then the
1051 /// minimum value will be returned again and true will be returned for
1052 /// an overflow happening.
1059 /// assert_eq!(10i8.overflowing_abs(), (10,false));
1060 /// assert_eq!((-10i8).overflowing_abs(), (10,false));
1061 /// assert_eq!((-128i8).overflowing_abs(), (-128,true));
1063 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1065 pub fn overflowing_abs(self) -> (Self, bool) {
1066 if self.is_negative() {
1067 self.overflowing_neg()
1073 /// Raises self to the power of `exp`, using exponentiation by squaring.
1080 /// let x: i32 = 2; // or any other integer type
1082 /// assert_eq!(x.pow(4), 16);
1084 #[stable(feature = "rust1", since = "1.0.0")]
1086 #[rustc_inherit_overflow_checks]
1087 pub fn pow(self, mut exp: u32) -> Self {
1088 let mut base = self;
1099 // Deal with the final bit of the exponent separately, since
1100 // squaring the base afterwards is not necessary and may cause a
1101 // needless overflow.
1109 /// Computes the absolute value of `self`.
1111 /// # Overflow behavior
1113 /// The absolute value of `i32::min_value()` cannot be represented as an
1114 /// `i32`, and attempting to calculate it will cause an overflow. This
1115 /// means that code in debug mode will trigger a panic on this case and
1116 /// optimized code will return `i32::min_value()` without a panic.
1123 /// assert_eq!(10i8.abs(), 10);
1124 /// assert_eq!((-10i8).abs(), 10);
1126 #[stable(feature = "rust1", since = "1.0.0")]
1128 #[rustc_inherit_overflow_checks]
1129 pub fn abs(self) -> Self {
1130 if self.is_negative() {
1131 // Note that the #[inline] above means that the overflow
1132 // semantics of this negation depend on the crate we're being
1140 /// Returns a number representing sign of `self`.
1142 /// - `0` if the number is zero
1143 /// - `1` if the number is positive
1144 /// - `-1` if the number is negative
1151 /// assert_eq!(10i8.signum(), 1);
1152 /// assert_eq!(0i8.signum(), 0);
1153 /// assert_eq!((-10i8).signum(), -1);
1155 #[stable(feature = "rust1", since = "1.0.0")]
1157 pub fn signum(self) -> Self {
1165 /// Returns `true` if `self` is positive and `false` if the number
1166 /// is zero or negative.
1173 /// assert!(10i8.is_positive());
1174 /// assert!(!(-10i8).is_positive());
1176 #[stable(feature = "rust1", since = "1.0.0")]
1178 pub fn is_positive(self) -> bool { self > 0 }
1180 /// Returns `true` if `self` is negative and `false` if the number
1181 /// is zero or positive.
1188 /// assert!((-10i8).is_negative());
1189 /// assert!(!10i8.is_negative());
1191 #[stable(feature = "rust1", since = "1.0.0")]
1193 pub fn is_negative(self) -> bool { self < 0 }
1199 int_impl! { i8, i8, u8, 8,
1200 intrinsics::add_with_overflow,
1201 intrinsics::sub_with_overflow,
1202 intrinsics::mul_with_overflow }
1207 int_impl! { i16, i16, u16, 16,
1208 intrinsics::add_with_overflow,
1209 intrinsics::sub_with_overflow,
1210 intrinsics::mul_with_overflow }
1215 int_impl! { i32, i32, u32, 32,
1216 intrinsics::add_with_overflow,
1217 intrinsics::sub_with_overflow,
1218 intrinsics::mul_with_overflow }
1223 int_impl! { i64, i64, u64, 64,
1224 intrinsics::add_with_overflow,
1225 intrinsics::sub_with_overflow,
1226 intrinsics::mul_with_overflow }
1231 int_impl! { i128, i128, u128, 128,
1232 intrinsics::add_with_overflow,
1233 intrinsics::sub_with_overflow,
1234 intrinsics::mul_with_overflow }
1237 #[cfg(target_pointer_width = "16")]
1240 int_impl! { isize, i16, u16, 16,
1241 intrinsics::add_with_overflow,
1242 intrinsics::sub_with_overflow,
1243 intrinsics::mul_with_overflow }
1246 #[cfg(target_pointer_width = "32")]
1249 int_impl! { isize, i32, u32, 32,
1250 intrinsics::add_with_overflow,
1251 intrinsics::sub_with_overflow,
1252 intrinsics::mul_with_overflow }
1255 #[cfg(target_pointer_width = "64")]
1258 int_impl! { isize, i64, u64, 64,
1259 intrinsics::add_with_overflow,
1260 intrinsics::sub_with_overflow,
1261 intrinsics::mul_with_overflow }
1264 // `Int` + `UnsignedInt` implemented for unsigned integers
1265 macro_rules! uint_impl {
1266 ($SelfT:ty, $ActualT:ty, $BITS:expr,
1272 $add_with_overflow:path,
1273 $sub_with_overflow:path,
1274 $mul_with_overflow:path) => {
1275 /// Returns the smallest value that can be represented by this integer type.
1280 /// assert_eq!(u8::min_value(), 0);
1282 #[stable(feature = "rust1", since = "1.0.0")]
1284 pub const fn min_value() -> Self { 0 }
1286 /// Returns the largest value that can be represented by this integer type.
1291 /// assert_eq!(u8::max_value(), 255);
1293 #[stable(feature = "rust1", since = "1.0.0")]
1295 pub const fn max_value() -> Self { !0 }
1297 /// Converts a string slice in a given base to an integer.
1299 /// Leading and trailing whitespace represent an error.
1306 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
1308 #[stable(feature = "rust1", since = "1.0.0")]
1309 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1310 from_str_radix(src, radix)
1313 /// Returns the number of ones in the binary representation of `self`.
1320 /// let n = 0b01001100u8;
1322 /// assert_eq!(n.count_ones(), 3);
1324 #[stable(feature = "rust1", since = "1.0.0")]
1326 pub fn count_ones(self) -> u32 {
1327 unsafe { $ctpop(self as $ActualT) as u32 }
1330 /// Returns the number of zeros in the binary representation of `self`.
1337 /// let n = 0b01001100u8;
1339 /// assert_eq!(n.count_zeros(), 5);
1341 #[stable(feature = "rust1", since = "1.0.0")]
1343 pub fn count_zeros(self) -> u32 {
1344 (!self).count_ones()
1347 /// Returns the number of leading zeros in the binary representation
1355 /// let n = 0b0101000u16;
1357 /// assert_eq!(n.leading_zeros(), 10);
1359 #[stable(feature = "rust1", since = "1.0.0")]
1361 pub fn leading_zeros(self) -> u32 {
1362 unsafe { $ctlz(self as $ActualT) as u32 }
1365 /// Returns the number of trailing zeros in the binary representation
1373 /// let n = 0b0101000u16;
1375 /// assert_eq!(n.trailing_zeros(), 3);
1377 #[stable(feature = "rust1", since = "1.0.0")]
1379 pub fn trailing_zeros(self) -> u32 {
1380 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1381 // emits two conditional moves on x86_64. By promoting the value to
1382 // u16 and setting bit 8, we get better code without any conditional
1384 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1385 // pending, remove this workaround once LLVM generates better code
1389 intrinsics::cttz(self as u16 | 0x100) as u32
1391 intrinsics::cttz(self) as u32
1396 /// Shifts the bits to the left by a specified amount, `n`,
1397 /// wrapping the truncated bits to the end of the resulting integer.
1399 /// Please note this isn't the same operation as `<<`!
1406 /// let n = 0x0123456789ABCDEFu64;
1407 /// let m = 0x3456789ABCDEF012u64;
1409 /// assert_eq!(n.rotate_left(12), m);
1411 #[stable(feature = "rust1", since = "1.0.0")]
1413 pub fn rotate_left(self, n: u32) -> Self {
1414 // Protect against undefined behaviour for over-long bit shifts
1416 (self << n) | (self >> (($BITS - n) % $BITS))
1419 /// Shifts the bits to the right by a specified amount, `n`,
1420 /// wrapping the truncated bits to the beginning of the resulting
1423 /// Please note this isn't the same operation as `>>`!
1430 /// let n = 0x0123456789ABCDEFu64;
1431 /// let m = 0xDEF0123456789ABCu64;
1433 /// assert_eq!(n.rotate_right(12), m);
1435 #[stable(feature = "rust1", since = "1.0.0")]
1437 pub fn rotate_right(self, n: u32) -> Self {
1438 // Protect against undefined behaviour for over-long bit shifts
1440 (self >> n) | (self << (($BITS - n) % $BITS))
1443 /// Reverses the byte order of the integer.
1450 /// let n = 0x0123456789ABCDEFu64;
1451 /// let m = 0xEFCDAB8967452301u64;
1453 /// assert_eq!(n.swap_bytes(), m);
1455 #[stable(feature = "rust1", since = "1.0.0")]
1457 pub fn swap_bytes(self) -> Self {
1458 unsafe { $bswap(self as $ActualT) as Self }
1461 /// Converts an integer from big endian to the target's endianness.
1463 /// On big endian this is a no-op. On little endian the bytes are
1471 /// let n = 0x0123456789ABCDEFu64;
1473 /// if cfg!(target_endian = "big") {
1474 /// assert_eq!(u64::from_be(n), n)
1476 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1479 #[stable(feature = "rust1", since = "1.0.0")]
1481 pub fn from_be(x: Self) -> Self {
1482 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1485 /// Converts an integer from little endian to the target's endianness.
1487 /// On little endian this is a no-op. On big endian the bytes are
1495 /// let n = 0x0123456789ABCDEFu64;
1497 /// if cfg!(target_endian = "little") {
1498 /// assert_eq!(u64::from_le(n), n)
1500 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1503 #[stable(feature = "rust1", since = "1.0.0")]
1505 pub fn from_le(x: Self) -> Self {
1506 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1509 /// Converts `self` to big endian from the target's endianness.
1511 /// On big endian this is a no-op. On little endian the bytes are
1519 /// let n = 0x0123456789ABCDEFu64;
1521 /// if cfg!(target_endian = "big") {
1522 /// assert_eq!(n.to_be(), n)
1524 /// assert_eq!(n.to_be(), n.swap_bytes())
1527 #[stable(feature = "rust1", since = "1.0.0")]
1529 pub fn to_be(self) -> Self { // or not to be?
1530 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1533 /// Converts `self` to little endian from the target's endianness.
1535 /// On little endian this is a no-op. On big endian the bytes are
1543 /// let n = 0x0123456789ABCDEFu64;
1545 /// if cfg!(target_endian = "little") {
1546 /// assert_eq!(n.to_le(), n)
1548 /// assert_eq!(n.to_le(), n.swap_bytes())
1551 #[stable(feature = "rust1", since = "1.0.0")]
1553 pub fn to_le(self) -> Self {
1554 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1557 /// Checked integer addition. Computes `self + other`, returning `None`
1558 /// if overflow occurred.
1565 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1566 /// assert_eq!(6u16.checked_add(65530), None);
1568 #[stable(feature = "rust1", since = "1.0.0")]
1570 pub fn checked_add(self, other: Self) -> Option<Self> {
1571 let (a, b) = self.overflowing_add(other);
1572 if b {None} else {Some(a)}
1575 /// Checked integer subtraction. Computes `self - other`, returning
1576 /// `None` if underflow occurred.
1583 /// assert_eq!(1u8.checked_sub(1), Some(0));
1584 /// assert_eq!(0u8.checked_sub(1), None);
1586 #[stable(feature = "rust1", since = "1.0.0")]
1588 pub fn checked_sub(self, other: Self) -> Option<Self> {
1589 let (a, b) = self.overflowing_sub(other);
1590 if b {None} else {Some(a)}
1593 /// Checked integer multiplication. Computes `self * other`, returning
1594 /// `None` if underflow or overflow occurred.
1601 /// assert_eq!(5u8.checked_mul(51), Some(255));
1602 /// assert_eq!(5u8.checked_mul(52), None);
1604 #[stable(feature = "rust1", since = "1.0.0")]
1606 pub fn checked_mul(self, other: Self) -> Option<Self> {
1607 let (a, b) = self.overflowing_mul(other);
1608 if b {None} else {Some(a)}
1611 /// Checked integer division. Computes `self / other`, returning `None`
1612 /// if `other == 0` or the operation results in underflow or overflow.
1619 /// assert_eq!(128u8.checked_div(2), Some(64));
1620 /// assert_eq!(1u8.checked_div(0), None);
1622 #[stable(feature = "rust1", since = "1.0.0")]
1624 pub fn checked_div(self, other: Self) -> Option<Self> {
1627 other => Some(unsafe { intrinsics::unchecked_div(self, other) }),
1631 /// Checked integer remainder. Computes `self % other`, returning `None`
1632 /// if `other == 0` or the operation results in underflow or overflow.
1639 /// assert_eq!(5u32.checked_rem(2), Some(1));
1640 /// assert_eq!(5u32.checked_rem(0), None);
1642 #[stable(feature = "wrapping", since = "1.7.0")]
1644 pub fn checked_rem(self, other: Self) -> Option<Self> {
1648 Some(unsafe { intrinsics::unchecked_rem(self, other) })
1652 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1655 /// Note that negating any positive integer will overflow.
1662 /// assert_eq!(0u32.checked_neg(), Some(0));
1663 /// assert_eq!(1u32.checked_neg(), None);
1665 #[stable(feature = "wrapping", since = "1.7.0")]
1667 pub fn checked_neg(self) -> Option<Self> {
1668 let (a, b) = self.overflowing_neg();
1669 if b {None} else {Some(a)}
1672 /// Checked shift left. Computes `self << rhs`, returning `None`
1673 /// if `rhs` is larger than or equal to the number of bits in `self`.
1680 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1681 /// assert_eq!(0x10u32.checked_shl(33), None);
1683 #[stable(feature = "wrapping", since = "1.7.0")]
1685 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1686 let (a, b) = self.overflowing_shl(rhs);
1687 if b {None} else {Some(a)}
1690 /// Checked shift right. Computes `self >> rhs`, returning `None`
1691 /// if `rhs` is larger than or equal to the number of bits in `self`.
1698 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1699 /// assert_eq!(0x10u32.checked_shr(33), None);
1701 #[stable(feature = "wrapping", since = "1.7.0")]
1703 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1704 let (a, b) = self.overflowing_shr(rhs);
1705 if b {None} else {Some(a)}
1708 /// Saturating integer addition. Computes `self + other`, saturating at
1709 /// the numeric bounds instead of overflowing.
1716 /// assert_eq!(100u8.saturating_add(1), 101);
1717 /// assert_eq!(200u8.saturating_add(127), 255);
1719 #[stable(feature = "rust1", since = "1.0.0")]
1721 pub fn saturating_add(self, other: Self) -> Self {
1722 match self.checked_add(other) {
1724 None => Self::max_value(),
1728 /// Saturating integer subtraction. Computes `self - other`, saturating
1729 /// at the numeric bounds instead of overflowing.
1736 /// assert_eq!(100u8.saturating_sub(27), 73);
1737 /// assert_eq!(13u8.saturating_sub(127), 0);
1739 #[stable(feature = "rust1", since = "1.0.0")]
1741 pub fn saturating_sub(self, other: Self) -> Self {
1742 match self.checked_sub(other) {
1744 None => Self::min_value(),
1748 /// Saturating integer multiplication. Computes `self * other`,
1749 /// saturating at the numeric bounds instead of overflowing.
1758 /// assert_eq!(100u32.saturating_mul(127), 12700);
1759 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1761 #[stable(feature = "wrapping", since = "1.7.0")]
1763 pub fn saturating_mul(self, other: Self) -> Self {
1764 self.checked_mul(other).unwrap_or(Self::max_value())
1767 /// Wrapping (modular) addition. Computes `self + other`,
1768 /// wrapping around at the boundary of the type.
1775 /// assert_eq!(200u8.wrapping_add(55), 255);
1776 /// assert_eq!(200u8.wrapping_add(155), 99);
1778 #[stable(feature = "rust1", since = "1.0.0")]
1780 pub fn wrapping_add(self, rhs: Self) -> Self {
1782 intrinsics::overflowing_add(self, rhs)
1786 /// Wrapping (modular) subtraction. Computes `self - other`,
1787 /// wrapping around at the boundary of the type.
1794 /// assert_eq!(100u8.wrapping_sub(100), 0);
1795 /// assert_eq!(100u8.wrapping_sub(155), 201);
1797 #[stable(feature = "rust1", since = "1.0.0")]
1799 pub fn wrapping_sub(self, rhs: Self) -> Self {
1801 intrinsics::overflowing_sub(self, rhs)
1805 /// Wrapping (modular) multiplication. Computes `self *
1806 /// other`, wrapping around at the boundary of the type.
1813 /// assert_eq!(10u8.wrapping_mul(12), 120);
1814 /// assert_eq!(25u8.wrapping_mul(12), 44);
1816 #[stable(feature = "rust1", since = "1.0.0")]
1818 pub fn wrapping_mul(self, rhs: Self) -> Self {
1820 intrinsics::overflowing_mul(self, rhs)
1824 /// Wrapping (modular) division. Computes `self / other`.
1825 /// Wrapped division on unsigned types is just normal division.
1826 /// There's no way wrapping could ever happen.
1827 /// This function exists, so that all operations
1828 /// are accounted for in the wrapping operations.
1835 /// assert_eq!(100u8.wrapping_div(10), 10);
1837 #[stable(feature = "num_wrapping", since = "1.2.0")]
1839 pub fn wrapping_div(self, rhs: Self) -> Self {
1843 /// Wrapping (modular) remainder. Computes `self % other`.
1844 /// Wrapped remainder calculation on unsigned types is
1845 /// just the regular remainder calculation.
1846 /// There's no way wrapping could ever happen.
1847 /// This function exists, so that all operations
1848 /// are accounted for in the wrapping operations.
1855 /// assert_eq!(100u8.wrapping_rem(10), 0);
1857 #[stable(feature = "num_wrapping", since = "1.2.0")]
1859 pub fn wrapping_rem(self, rhs: Self) -> Self {
1863 /// Wrapping (modular) negation. Computes `-self`,
1864 /// wrapping around at the boundary of the type.
1866 /// Since unsigned types do not have negative equivalents
1867 /// all applications of this function will wrap (except for `-0`).
1868 /// For values smaller than the corresponding signed type's maximum
1869 /// the result is the same as casting the corresponding signed value.
1870 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1871 /// `MAX` is the corresponding signed type's maximum.
1878 /// assert_eq!(100u8.wrapping_neg(), 156);
1879 /// assert_eq!(0u8.wrapping_neg(), 0);
1880 /// assert_eq!(180u8.wrapping_neg(), 76);
1881 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1883 #[stable(feature = "num_wrapping", since = "1.2.0")]
1885 pub fn wrapping_neg(self) -> Self {
1886 self.overflowing_neg().0
1889 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1890 /// where `mask` removes any high-order bits of `rhs` that
1891 /// would cause the shift to exceed the bitwidth of the type.
1893 /// Note that this is *not* the same as a rotate-left; the
1894 /// RHS of a wrapping shift-left is restricted to the range
1895 /// of the type, rather than the bits shifted out of the LHS
1896 /// being returned to the other end. The primitive integer
1897 /// types all implement a `rotate_left` function, which may
1898 /// be what you want instead.
1905 /// assert_eq!(1u8.wrapping_shl(7), 128);
1906 /// assert_eq!(1u8.wrapping_shl(8), 1);
1908 #[stable(feature = "num_wrapping", since = "1.2.0")]
1910 pub fn wrapping_shl(self, rhs: u32) -> Self {
1912 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1916 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1917 /// where `mask` removes any high-order bits of `rhs` that
1918 /// would cause the shift to exceed the bitwidth of the type.
1920 /// Note that this is *not* the same as a rotate-right; the
1921 /// RHS of a wrapping shift-right is restricted to the range
1922 /// of the type, rather than the bits shifted out of the LHS
1923 /// being returned to the other end. The primitive integer
1924 /// types all implement a `rotate_right` function, which may
1925 /// be what you want instead.
1932 /// assert_eq!(128u8.wrapping_shr(7), 1);
1933 /// assert_eq!(128u8.wrapping_shr(8), 128);
1935 #[stable(feature = "num_wrapping", since = "1.2.0")]
1937 pub fn wrapping_shr(self, rhs: u32) -> Self {
1939 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1943 /// Calculates `self` + `rhs`
1945 /// Returns a tuple of the addition along with a boolean indicating
1946 /// whether an arithmetic overflow would occur. If an overflow would
1947 /// have occurred then the wrapped value is returned.
1956 /// assert_eq!(5u32.overflowing_add(2), (7, false));
1957 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
1960 #[stable(feature = "wrapping", since = "1.7.0")]
1961 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1963 let (a, b) = $add_with_overflow(self as $ActualT,
1969 /// Calculates `self` - `rhs`
1971 /// Returns a tuple of the subtraction along with a boolean indicating
1972 /// whether an arithmetic overflow would occur. If an overflow would
1973 /// have occurred then the wrapped value is returned.
1982 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
1983 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
1986 #[stable(feature = "wrapping", since = "1.7.0")]
1987 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1989 let (a, b) = $sub_with_overflow(self as $ActualT,
1995 /// Calculates the multiplication of `self` and `rhs`.
1997 /// Returns a tuple of the multiplication along with a boolean
1998 /// indicating whether an arithmetic overflow would occur. If an
1999 /// overflow would have occurred then the wrapped value is returned.
2006 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2007 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2010 #[stable(feature = "wrapping", since = "1.7.0")]
2011 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2013 let (a, b) = $mul_with_overflow(self as $ActualT,
2019 /// Calculates the divisor when `self` is divided by `rhs`.
2021 /// Returns a tuple of the divisor along with a boolean indicating
2022 /// whether an arithmetic overflow would occur. Note that for unsigned
2023 /// integers overflow never occurs, so the second value is always
2028 /// This function will panic if `rhs` is 0.
2035 /// assert_eq!(5u32.overflowing_div(2), (2, false));
2038 #[stable(feature = "wrapping", since = "1.7.0")]
2039 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2043 /// Calculates the remainder when `self` is divided by `rhs`.
2045 /// Returns a tuple of the remainder after dividing along with a boolean
2046 /// indicating whether an arithmetic overflow would occur. Note that for
2047 /// unsigned integers overflow never occurs, so the second value is
2052 /// This function will panic if `rhs` is 0.
2059 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
2062 #[stable(feature = "wrapping", since = "1.7.0")]
2063 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2067 /// Negates self in an overflowing fashion.
2069 /// Returns `!self + 1` using wrapping operations to return the value
2070 /// that represents the negation of this unsigned value. Note that for
2071 /// positive unsigned values overflow always occurs, but negating 0 does
2079 /// assert_eq!(0u32.overflowing_neg(), (0, false));
2080 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
2083 #[stable(feature = "wrapping", since = "1.7.0")]
2084 pub fn overflowing_neg(self) -> (Self, bool) {
2085 ((!self).wrapping_add(1), self != 0)
2088 /// Shifts self left by `rhs` bits.
2090 /// Returns a tuple of the shifted version of self along with a boolean
2091 /// indicating whether the shift value was larger than or equal to the
2092 /// number of bits. If the shift value is too large, then value is
2093 /// masked (N-1) where N is the number of bits, and this value is then
2094 /// used to perform the shift.
2101 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
2102 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
2105 #[stable(feature = "wrapping", since = "1.7.0")]
2106 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2107 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
2110 /// Shifts self right by `rhs` bits.
2112 /// Returns a tuple of the shifted version of self along with a boolean
2113 /// indicating whether the shift value was larger than or equal to the
2114 /// number of bits. If the shift value is too large, then value is
2115 /// masked (N-1) where N is the number of bits, and this value is then
2116 /// used to perform the shift.
2123 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
2124 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2127 #[stable(feature = "wrapping", since = "1.7.0")]
2128 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2129 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
2133 /// Raises self to the power of `exp`, using exponentiation by squaring.
2140 /// assert_eq!(2u32.pow(4), 16);
2142 #[stable(feature = "rust1", since = "1.0.0")]
2144 #[rustc_inherit_overflow_checks]
2145 pub fn pow(self, mut exp: u32) -> Self {
2146 let mut base = self;
2157 // Deal with the final bit of the exponent separately, since
2158 // squaring the base afterwards is not necessary and may cause a
2159 // needless overflow.
2167 /// Returns `true` if and only if `self == 2^k` for some `k`.
2174 /// assert!(16u8.is_power_of_two());
2175 /// assert!(!10u8.is_power_of_two());
2177 #[stable(feature = "rust1", since = "1.0.0")]
2179 pub fn is_power_of_two(self) -> bool {
2180 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2183 // Returns one less than next power of two.
2184 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2186 // 8u8.one_less_than_next_power_of_two() == 7
2187 // 6u8.one_less_than_next_power_of_two() == 7
2189 // This method cannot overflow, as in the `next_power_of_two`
2190 // overflow cases it instead ends up returning the maximum value
2191 // of the type, and can return 0 for 0.
2193 fn one_less_than_next_power_of_two(self) -> Self {
2194 if self <= 1 { return 0; }
2196 // Because `p > 0`, it cannot consist entirely of leading zeros.
2197 // That means the shift is always in-bounds, and some processors
2198 // (such as intel pre-haswell) have more efficient ctlz
2199 // intrinsics when the argument is non-zero.
2201 let z = unsafe { $ctlz_nonzero(p) };
2202 <$SelfT>::max_value() >> z
2205 /// Returns the smallest power of two greater than or equal to `self`.
2207 /// When return value overflows (i.e. `self > (1 << (N-1))` for type
2208 /// `uN`), it panics in debug mode and return value is wrapped to 0 in
2209 /// release mode (the only situation in which method can return 0).
2216 /// assert_eq!(2u8.next_power_of_two(), 2);
2217 /// assert_eq!(3u8.next_power_of_two(), 4);
2219 #[stable(feature = "rust1", since = "1.0.0")]
2221 pub fn next_power_of_two(self) -> Self {
2222 self.one_less_than_next_power_of_two() + 1
2225 /// Returns the smallest power of two greater than or equal to `n`. If
2226 /// the next power of two is greater than the type's maximum value,
2227 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2234 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2235 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2236 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2238 #[stable(feature = "rust1", since = "1.0.0")]
2239 pub fn checked_next_power_of_two(self) -> Option<Self> {
2240 self.one_less_than_next_power_of_two().checked_add(1)
2247 uint_impl! { u8, u8, 8,
2250 intrinsics::ctlz_nonzero,
2253 intrinsics::add_with_overflow,
2254 intrinsics::sub_with_overflow,
2255 intrinsics::mul_with_overflow }
2260 uint_impl! { u16, u16, 16,
2263 intrinsics::ctlz_nonzero,
2266 intrinsics::add_with_overflow,
2267 intrinsics::sub_with_overflow,
2268 intrinsics::mul_with_overflow }
2273 uint_impl! { u32, u32, 32,
2276 intrinsics::ctlz_nonzero,
2279 intrinsics::add_with_overflow,
2280 intrinsics::sub_with_overflow,
2281 intrinsics::mul_with_overflow }
2286 uint_impl! { u64, u64, 64,
2289 intrinsics::ctlz_nonzero,
2292 intrinsics::add_with_overflow,
2293 intrinsics::sub_with_overflow,
2294 intrinsics::mul_with_overflow }
2299 uint_impl! { u128, u128, 128,
2302 intrinsics::ctlz_nonzero,
2305 intrinsics::add_with_overflow,
2306 intrinsics::sub_with_overflow,
2307 intrinsics::mul_with_overflow }
2310 #[cfg(target_pointer_width = "16")]
2313 uint_impl! { usize, u16, 16,
2316 intrinsics::ctlz_nonzero,
2319 intrinsics::add_with_overflow,
2320 intrinsics::sub_with_overflow,
2321 intrinsics::mul_with_overflow }
2323 #[cfg(target_pointer_width = "32")]
2326 uint_impl! { usize, u32, 32,
2329 intrinsics::ctlz_nonzero,
2332 intrinsics::add_with_overflow,
2333 intrinsics::sub_with_overflow,
2334 intrinsics::mul_with_overflow }
2337 #[cfg(target_pointer_width = "64")]
2340 uint_impl! { usize, u64, 64,
2343 intrinsics::ctlz_nonzero,
2346 intrinsics::add_with_overflow,
2347 intrinsics::sub_with_overflow,
2348 intrinsics::mul_with_overflow }
2351 /// A classification of floating point numbers.
2353 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
2354 /// their documentation for more.
2356 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
2357 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
2362 /// use std::num::FpCategory;
2365 /// let num = 12.4_f32;
2366 /// let inf = f32::INFINITY;
2367 /// let zero = 0f32;
2368 /// let sub: f32 = 1.1754942e-38;
2369 /// let nan = f32::NAN;
2371 /// assert_eq!(num.classify(), FpCategory::Normal);
2372 /// assert_eq!(inf.classify(), FpCategory::Infinite);
2373 /// assert_eq!(zero.classify(), FpCategory::Zero);
2374 /// assert_eq!(nan.classify(), FpCategory::Nan);
2375 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
2377 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2378 #[stable(feature = "rust1", since = "1.0.0")]
2379 pub enum FpCategory {
2380 /// "Not a Number", often obtained by dividing by zero.
2381 #[stable(feature = "rust1", since = "1.0.0")]
2384 /// Positive or negative infinity.
2385 #[stable(feature = "rust1", since = "1.0.0")]
2388 /// Positive or negative zero.
2389 #[stable(feature = "rust1", since = "1.0.0")]
2392 /// De-normalized floating point representation (less precise than `Normal`).
2393 #[stable(feature = "rust1", since = "1.0.0")]
2396 /// A regular floating point number.
2397 #[stable(feature = "rust1", since = "1.0.0")]
2401 /// A built-in floating point number.
2403 #[unstable(feature = "core_float",
2404 reason = "stable interface is via `impl f{32,64}` in later crates",
2406 pub trait Float: Sized {
2407 /// Returns `true` if this value is NaN and false otherwise.
2408 #[stable(feature = "core", since = "1.6.0")]
2409 fn is_nan(self) -> bool;
2410 /// Returns `true` if this value is positive infinity or negative infinity and
2411 /// false otherwise.
2412 #[stable(feature = "core", since = "1.6.0")]
2413 fn is_infinite(self) -> bool;
2414 /// Returns `true` if this number is neither infinite nor NaN.
2415 #[stable(feature = "core", since = "1.6.0")]
2416 fn is_finite(self) -> bool;
2417 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
2418 #[stable(feature = "core", since = "1.6.0")]
2419 fn is_normal(self) -> bool;
2420 /// Returns the category that this number falls into.
2421 #[stable(feature = "core", since = "1.6.0")]
2422 fn classify(self) -> FpCategory;
2424 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2425 /// number is `Float::nan()`.
2426 #[stable(feature = "core", since = "1.6.0")]
2427 fn abs(self) -> Self;
2428 /// Returns a number that represents the sign of `self`.
2430 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2431 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2432 /// - `Float::nan()` if the number is `Float::nan()`
2433 #[stable(feature = "core", since = "1.6.0")]
2434 fn signum(self) -> Self;
2436 /// Returns `true` if `self` is positive, including `+0.0` and
2437 /// `Float::infinity()`.
2438 #[stable(feature = "core", since = "1.6.0")]
2439 fn is_sign_positive(self) -> bool;
2440 /// Returns `true` if `self` is negative, including `-0.0` and
2441 /// `Float::neg_infinity()`.
2442 #[stable(feature = "core", since = "1.6.0")]
2443 fn is_sign_negative(self) -> bool;
2445 /// Take the reciprocal (inverse) of a number, `1/x`.
2446 #[stable(feature = "core", since = "1.6.0")]
2447 fn recip(self) -> Self;
2449 /// Raise a number to an integer power.
2451 /// Using this function is generally faster than using `powf`
2452 #[stable(feature = "core", since = "1.6.0")]
2453 fn powi(self, n: i32) -> Self;
2455 /// Convert radians to degrees.
2456 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2457 fn to_degrees(self) -> Self;
2458 /// Convert degrees to radians.
2459 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2460 fn to_radians(self) -> Self;
2462 /// Returns the maximum of the two numbers.
2463 #[stable(feature = "core_float_min_max", since="1.20.0")]
2464 fn max(self, other: Self) -> Self;
2465 /// Returns the minimum of the two numbers.
2466 #[stable(feature = "core_float_min_max", since="1.20.0")]
2467 fn min(self, other: Self) -> Self;
2470 macro_rules! from_str_radix_int_impl {
2472 #[stable(feature = "rust1", since = "1.0.0")]
2473 impl FromStr for $t {
2474 type Err = ParseIntError;
2475 fn from_str(src: &str) -> Result<Self, ParseIntError> {
2476 from_str_radix(src, 10)
2481 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
2483 /// The error type returned when a checked integral type conversion fails.
2484 #[unstable(feature = "try_from", issue = "33417")]
2485 #[derive(Debug, Copy, Clone)]
2486 pub struct TryFromIntError(());
2488 impl TryFromIntError {
2489 #[unstable(feature = "int_error_internals",
2490 reason = "available through Error trait and this method should \
2491 not be exposed publicly",
2494 pub fn __description(&self) -> &str {
2495 "out of range integral type conversion attempted"
2499 #[unstable(feature = "try_from", issue = "33417")]
2500 impl fmt::Display for TryFromIntError {
2501 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2502 self.__description().fmt(fmt)
2506 // no possible bounds violation
2507 macro_rules! try_from_unbounded {
2508 ($source:ty, $($target:ty),*) => {$(
2509 #[unstable(feature = "try_from", issue = "33417")]
2510 impl TryFrom<$source> for $target {
2511 type Error = TryFromIntError;
2514 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2521 // only negative bounds
2522 macro_rules! try_from_lower_bounded {
2523 ($source:ty, $($target:ty),*) => {$(
2524 #[unstable(feature = "try_from", issue = "33417")]
2525 impl TryFrom<$source> for $target {
2526 type Error = TryFromIntError;
2529 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2533 Err(TryFromIntError(()))
2540 // unsigned to signed (only positive bound)
2541 macro_rules! try_from_upper_bounded {
2542 ($source:ty, $($target:ty),*) => {$(
2543 #[unstable(feature = "try_from", issue = "33417")]
2544 impl TryFrom<$source> for $target {
2545 type Error = TryFromIntError;
2548 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2549 if u > (<$target>::max_value() as $source) {
2550 Err(TryFromIntError(()))
2560 macro_rules! try_from_both_bounded {
2561 ($source:ty, $($target:ty),*) => {$(
2562 #[unstable(feature = "try_from", issue = "33417")]
2563 impl TryFrom<$source> for $target {
2564 type Error = TryFromIntError;
2567 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2568 let min = <$target>::min_value() as $source;
2569 let max = <$target>::max_value() as $source;
2570 if u < min || u > max {
2571 Err(TryFromIntError(()))
2581 ($mac:ident, $source:ty, $($target:ty),*) => {$(
2582 $mac!($target, $source);
2586 /// intra-sign conversions
2587 try_from_unbounded!(u8, u8, u16, u32, u64, u128);
2588 try_from_unbounded!(u16, u16, u32, u64, u128);
2589 try_from_unbounded!(u32, u32, u64, u128);
2590 try_from_unbounded!(u64, u64, u128);
2591 try_from_unbounded!(u128, u128);
2592 try_from_upper_bounded!(u16, u8);
2593 try_from_upper_bounded!(u32, u16, u8);
2594 try_from_upper_bounded!(u64, u32, u16, u8);
2595 try_from_upper_bounded!(u128, u64, u32, u16, u8);
2597 try_from_unbounded!(i8, i8, i16, i32, i64, i128);
2598 try_from_unbounded!(i16, i16, i32, i64, i128);
2599 try_from_unbounded!(i32, i32, i64, i128);
2600 try_from_unbounded!(i64, i64, i128);
2601 try_from_unbounded!(i128, i128);
2602 try_from_both_bounded!(i16, i8);
2603 try_from_both_bounded!(i32, i16, i8);
2604 try_from_both_bounded!(i64, i32, i16, i8);
2605 try_from_both_bounded!(i128, i64, i32, i16, i8);
2607 // unsigned-to-signed
2608 try_from_unbounded!(u8, i16, i32, i64, i128);
2609 try_from_unbounded!(u16, i32, i64, i128);
2610 try_from_unbounded!(u32, i64, i128);
2611 try_from_unbounded!(u64, i128);
2612 try_from_upper_bounded!(u8, i8);
2613 try_from_upper_bounded!(u16, i8, i16);
2614 try_from_upper_bounded!(u32, i8, i16, i32);
2615 try_from_upper_bounded!(u64, i8, i16, i32, i64);
2616 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
2618 // signed-to-unsigned
2619 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
2620 try_from_lower_bounded!(i16, u16, u32, u64, u128);
2621 try_from_lower_bounded!(i32, u32, u64, u128);
2622 try_from_lower_bounded!(i64, u64, u128);
2623 try_from_lower_bounded!(i128, u128);
2624 try_from_both_bounded!(i16, u8);
2625 try_from_both_bounded!(i32, u16, u8);
2626 try_from_both_bounded!(i64, u32, u16, u8);
2627 try_from_both_bounded!(i128, u64, u32, u16, u8);
2630 try_from_unbounded!(usize, usize);
2631 try_from_upper_bounded!(usize, isize);
2632 try_from_lower_bounded!(isize, usize);
2633 try_from_unbounded!(isize, isize);
2635 #[cfg(target_pointer_width = "16")]
2636 mod ptr_try_from_impls {
2637 use super::TryFromIntError;
2638 use convert::TryFrom;
2640 try_from_upper_bounded!(usize, u8);
2641 try_from_unbounded!(usize, u16, u32, u64, u128);
2642 try_from_upper_bounded!(usize, i8, i16);
2643 try_from_unbounded!(usize, i32, i64, i128);
2645 try_from_both_bounded!(isize, u8);
2646 try_from_lower_bounded!(isize, u16, u32, u64, u128);
2647 try_from_both_bounded!(isize, i8);
2648 try_from_unbounded!(isize, i16, i32, i64, i128);
2650 rev!(try_from_unbounded, usize, u8, u16);
2651 rev!(try_from_upper_bounded, usize, u32, u64, u128);
2652 rev!(try_from_lower_bounded, usize, i8, i16);
2653 rev!(try_from_both_bounded, usize, i32, i64, i128);
2655 rev!(try_from_unbounded, isize, u8);
2656 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
2657 rev!(try_from_unbounded, isize, i8, i16);
2658 rev!(try_from_both_bounded, isize, i32, i64, i128);
2661 #[cfg(target_pointer_width = "32")]
2662 mod ptr_try_from_impls {
2663 use super::TryFromIntError;
2664 use convert::TryFrom;
2666 try_from_upper_bounded!(usize, u8, u16);
2667 try_from_unbounded!(usize, u32, u64, u128);
2668 try_from_upper_bounded!(usize, i8, i16, i32);
2669 try_from_unbounded!(usize, i64, i128);
2671 try_from_both_bounded!(isize, u8, u16);
2672 try_from_lower_bounded!(isize, u32, u64, u128);
2673 try_from_both_bounded!(isize, i8, i16);
2674 try_from_unbounded!(isize, i32, i64, i128);
2676 rev!(try_from_unbounded, usize, u8, u16, u32);
2677 rev!(try_from_upper_bounded, usize, u64, u128);
2678 rev!(try_from_lower_bounded, usize, i8, i16, i32);
2679 rev!(try_from_both_bounded, usize, i64, i128);
2681 rev!(try_from_unbounded, isize, u8, u16);
2682 rev!(try_from_upper_bounded, isize, u32, u64, u128);
2683 rev!(try_from_unbounded, isize, i8, i16, i32);
2684 rev!(try_from_both_bounded, isize, i64, i128);
2687 #[cfg(target_pointer_width = "64")]
2688 mod ptr_try_from_impls {
2689 use super::TryFromIntError;
2690 use convert::TryFrom;
2692 try_from_upper_bounded!(usize, u8, u16, u32);
2693 try_from_unbounded!(usize, u64, u128);
2694 try_from_upper_bounded!(usize, i8, i16, i32, i64);
2695 try_from_unbounded!(usize, i128);
2697 try_from_both_bounded!(isize, u8, u16, u32);
2698 try_from_lower_bounded!(isize, u64, u128);
2699 try_from_both_bounded!(isize, i8, i16, i32);
2700 try_from_unbounded!(isize, i64, i128);
2702 rev!(try_from_unbounded, usize, u8, u16, u32, u64);
2703 rev!(try_from_upper_bounded, usize, u128);
2704 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
2705 rev!(try_from_both_bounded, usize, i128);
2707 rev!(try_from_unbounded, isize, u8, u16, u32);
2708 rev!(try_from_upper_bounded, isize, u64, u128);
2709 rev!(try_from_unbounded, isize, i8, i16, i32, i64);
2710 rev!(try_from_both_bounded, isize, i128);
2714 trait FromStrRadixHelper: PartialOrd + Copy {
2715 fn min_value() -> Self;
2716 fn max_value() -> Self;
2717 fn from_u32(u: u32) -> Self;
2718 fn checked_mul(&self, other: u32) -> Option<Self>;
2719 fn checked_sub(&self, other: u32) -> Option<Self>;
2720 fn checked_add(&self, other: u32) -> Option<Self>;
2724 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
2726 fn min_value() -> Self { Self::min_value() }
2728 fn max_value() -> Self { Self::max_value() }
2730 fn from_u32(u: u32) -> Self { u as Self }
2732 fn checked_mul(&self, other: u32) -> Option<Self> {
2733 Self::checked_mul(*self, other as Self)
2736 fn checked_sub(&self, other: u32) -> Option<Self> {
2737 Self::checked_sub(*self, other as Self)
2740 fn checked_add(&self, other: u32) -> Option<Self> {
2741 Self::checked_add(*self, other as Self)
2745 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
2747 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
2748 use self::IntErrorKind::*;
2749 use self::ParseIntError as PIE;
2751 assert!(radix >= 2 && radix <= 36,
2752 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2756 return Err(PIE { kind: Empty });
2759 let is_signed_ty = T::from_u32(0) > T::min_value();
2761 // all valid digits are ascii, so we will just iterate over the utf8 bytes
2762 // and cast them to chars. .to_digit() will safely return None for anything
2763 // other than a valid ascii digit for the given radix, including the first-byte
2764 // of multi-byte sequences
2765 let src = src.as_bytes();
2767 let (is_positive, digits) = match src[0] {
2768 b'+' => (true, &src[1..]),
2769 b'-' if is_signed_ty => (false, &src[1..]),
2773 if digits.is_empty() {
2774 return Err(PIE { kind: Empty });
2777 let mut result = T::from_u32(0);
2779 // The number is positive
2781 let x = match (c as char).to_digit(radix) {
2783 None => return Err(PIE { kind: InvalidDigit }),
2785 result = match result.checked_mul(radix) {
2786 Some(result) => result,
2787 None => return Err(PIE { kind: Overflow }),
2789 result = match result.checked_add(x) {
2790 Some(result) => result,
2791 None => return Err(PIE { kind: Overflow }),
2795 // The number is negative
2797 let x = match (c as char).to_digit(radix) {
2799 None => return Err(PIE { kind: InvalidDigit }),
2801 result = match result.checked_mul(radix) {
2802 Some(result) => result,
2803 None => return Err(PIE { kind: Underflow }),
2805 result = match result.checked_sub(x) {
2806 Some(result) => result,
2807 None => return Err(PIE { kind: Underflow }),
2814 /// An error which can be returned when parsing an integer.
2816 /// This error is used as the error type for the `from_str_radix()` functions
2817 /// on the primitive integer types, such as [`i8::from_str_radix`].
2819 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
2820 #[derive(Debug, Clone, PartialEq, Eq)]
2821 #[stable(feature = "rust1", since = "1.0.0")]
2822 pub struct ParseIntError {
2826 #[derive(Debug, Clone, PartialEq, Eq)]
2834 impl ParseIntError {
2835 #[unstable(feature = "int_error_internals",
2836 reason = "available through Error trait and this method should \
2837 not be exposed publicly",
2840 pub fn __description(&self) -> &str {
2842 IntErrorKind::Empty => "cannot parse integer from empty string",
2843 IntErrorKind::InvalidDigit => "invalid digit found in string",
2844 IntErrorKind::Overflow => "number too large to fit in target type",
2845 IntErrorKind::Underflow => "number too small to fit in target type",
2850 #[stable(feature = "rust1", since = "1.0.0")]
2851 impl fmt::Display for ParseIntError {
2852 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2853 self.__description().fmt(f)
2857 #[stable(feature = "rust1", since = "1.0.0")]
2858 pub use num::dec2flt::ParseFloatError;
2860 // Conversion traits for primitive integer and float types
2861 // Conversions T -> T are covered by a blanket impl and therefore excluded
2862 // Some conversions from and to usize/isize are not implemented due to portability concerns
2863 macro_rules! impl_from {
2864 ($Small: ty, $Large: ty, #[$attr:meta]) => {
2866 impl From<$Small> for $Large {
2868 fn from(small: $Small) -> $Large {
2875 // Unsigned -> Unsigned
2876 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2877 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2878 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2879 impl_from! { u8, u128, #[unstable(feature = "i128", issue = "35118")] }
2880 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2881 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2882 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2883 impl_from! { u16, u128, #[unstable(feature = "i128", issue = "35118")] }
2884 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2885 impl_from! { u32, u128, #[unstable(feature = "i128", issue = "35118")] }
2886 impl_from! { u64, u128, #[unstable(feature = "i128", issue = "35118")] }
2889 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2890 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2891 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2892 impl_from! { i8, i128, #[unstable(feature = "i128", issue = "35118")] }
2893 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2894 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2895 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2896 impl_from! { i16, i128, #[unstable(feature = "i128", issue = "35118")] }
2897 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2898 impl_from! { i32, i128, #[unstable(feature = "i128", issue = "35118")] }
2899 impl_from! { i64, i128, #[unstable(feature = "i128", issue = "35118")] }
2901 // Unsigned -> Signed
2902 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2903 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2904 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2905 impl_from! { u8, i128, #[unstable(feature = "i128", issue = "35118")] }
2906 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2907 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2908 impl_from! { u16, i128, #[unstable(feature = "i128", issue = "35118")] }
2909 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2910 impl_from! { u32, i128, #[unstable(feature = "i128", issue = "35118")] }
2911 impl_from! { u64, i128, #[unstable(feature = "i128", issue = "35118")] }
2913 // Note: integers can only be represented with full precision in a float if
2914 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2915 // Lossy float conversions are not implemented at this time.
2918 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2919 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2920 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2921 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2922 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2924 // Unsigned -> Float
2925 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2926 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2927 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2928 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2929 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2932 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }