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")]
112 #[cfg_attr(not(stage0), rustc_const_unstable(feature = "const_min_value"))]
114 pub const fn min_value() -> Self {
115 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
118 /// Returns the largest value that can be represented by this integer type.
123 /// assert_eq!(i8::max_value(), 127);
125 #[stable(feature = "rust1", since = "1.0.0")]
126 #[cfg_attr(not(stage0), rustc_const_unstable(feature = "const_max_value"))]
128 pub const fn max_value() -> Self {
132 /// Converts a string slice in a given base to an integer.
134 /// Leading and trailing whitespace represent an error.
138 /// This function panics if `radix` is not in the range from 2 to 36.
145 /// assert_eq!(i32::from_str_radix("A", 16), Ok(10));
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
149 from_str_radix(src, radix)
152 /// Returns the number of ones in the binary representation of `self`.
159 /// let n = -0b1000_0000i8;
161 /// assert_eq!(n.count_ones(), 1);
163 #[stable(feature = "rust1", since = "1.0.0")]
165 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
167 /// Returns the number of zeros in the binary representation of `self`.
174 /// let n = -0b1000_0000i8;
176 /// assert_eq!(n.count_zeros(), 7);
178 #[stable(feature = "rust1", since = "1.0.0")]
180 pub fn count_zeros(self) -> u32 {
184 /// Returns the number of leading zeros in the binary representation
194 /// assert_eq!(n.leading_zeros(), 0);
196 #[stable(feature = "rust1", since = "1.0.0")]
198 pub fn leading_zeros(self) -> u32 {
199 (self as $UnsignedT).leading_zeros()
202 /// Returns the number of trailing zeros in the binary representation
212 /// assert_eq!(n.trailing_zeros(), 2);
214 #[stable(feature = "rust1", since = "1.0.0")]
216 pub fn trailing_zeros(self) -> u32 {
217 (self as $UnsignedT).trailing_zeros()
220 /// Shifts the bits to the left by a specified amount, `n`,
221 /// wrapping the truncated bits to the end of the resulting integer.
223 /// Please note this isn't the same operation as `<<`!
230 /// let n = 0x0123456789ABCDEFi64;
231 /// let m = -0x76543210FEDCBA99i64;
233 /// assert_eq!(n.rotate_left(32), m);
235 #[stable(feature = "rust1", since = "1.0.0")]
237 pub fn rotate_left(self, n: u32) -> Self {
238 (self as $UnsignedT).rotate_left(n) as Self
241 /// Shifts the bits to the right by a specified amount, `n`,
242 /// wrapping the truncated bits to the beginning of the resulting
245 /// Please note this isn't the same operation as `>>`!
252 /// let n = 0x0123456789ABCDEFi64;
253 /// let m = -0xFEDCBA987654322i64;
255 /// assert_eq!(n.rotate_right(4), m);
257 #[stable(feature = "rust1", since = "1.0.0")]
259 pub fn rotate_right(self, n: u32) -> Self {
260 (self as $UnsignedT).rotate_right(n) as Self
263 /// Reverses the byte order of the integer.
270 /// let n = 0x0123456789ABCDEFi64;
271 /// let m = -0x1032547698BADCFFi64;
273 /// assert_eq!(n.swap_bytes(), m);
275 #[stable(feature = "rust1", since = "1.0.0")]
277 pub fn swap_bytes(self) -> Self {
278 (self as $UnsignedT).swap_bytes() as Self
281 /// Converts an integer from big endian to the target's endianness.
283 /// On big endian this is a no-op. On little endian the bytes are
291 /// let n = 0x0123456789ABCDEFi64;
293 /// if cfg!(target_endian = "big") {
294 /// assert_eq!(i64::from_be(n), n)
296 /// assert_eq!(i64::from_be(n), n.swap_bytes())
299 #[stable(feature = "rust1", since = "1.0.0")]
301 pub fn from_be(x: Self) -> Self {
302 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
305 /// Converts an integer from little endian to the target's endianness.
307 /// On little endian this is a no-op. On big endian the bytes are
315 /// let n = 0x0123456789ABCDEFi64;
317 /// if cfg!(target_endian = "little") {
318 /// assert_eq!(i64::from_le(n), n)
320 /// assert_eq!(i64::from_le(n), n.swap_bytes())
323 #[stable(feature = "rust1", since = "1.0.0")]
325 pub fn from_le(x: Self) -> Self {
326 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
329 /// Converts `self` to big endian from the target's endianness.
331 /// On big endian this is a no-op. On little endian the bytes are
339 /// let n = 0x0123456789ABCDEFi64;
341 /// if cfg!(target_endian = "big") {
342 /// assert_eq!(n.to_be(), n)
344 /// assert_eq!(n.to_be(), n.swap_bytes())
347 #[stable(feature = "rust1", since = "1.0.0")]
349 pub fn to_be(self) -> Self { // or not to be?
350 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
353 /// Converts `self` to little endian from the target's endianness.
355 /// On little endian this is a no-op. On big endian the bytes are
363 /// let n = 0x0123456789ABCDEFi64;
365 /// if cfg!(target_endian = "little") {
366 /// assert_eq!(n.to_le(), n)
368 /// assert_eq!(n.to_le(), n.swap_bytes())
371 #[stable(feature = "rust1", since = "1.0.0")]
373 pub fn to_le(self) -> Self {
374 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
377 /// Checked integer addition. Computes `self + other`, returning `None`
378 /// if overflow occurred.
385 /// assert_eq!(7i16.checked_add(32760), Some(32767));
386 /// assert_eq!(8i16.checked_add(32760), None);
388 #[stable(feature = "rust1", since = "1.0.0")]
390 pub fn checked_add(self, other: Self) -> Option<Self> {
391 let (a, b) = self.overflowing_add(other);
392 if b {None} else {Some(a)}
395 /// Checked integer subtraction. Computes `self - other`, returning
396 /// `None` if underflow occurred.
403 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
404 /// assert_eq!((-128i8).checked_sub(1), None);
406 #[stable(feature = "rust1", since = "1.0.0")]
408 pub fn checked_sub(self, other: Self) -> Option<Self> {
409 let (a, b) = self.overflowing_sub(other);
410 if b {None} else {Some(a)}
413 /// Checked integer multiplication. Computes `self * other`, returning
414 /// `None` if underflow or overflow occurred.
421 /// assert_eq!(6i8.checked_mul(21), Some(126));
422 /// assert_eq!(6i8.checked_mul(22), None);
424 #[stable(feature = "rust1", since = "1.0.0")]
426 pub fn checked_mul(self, other: Self) -> Option<Self> {
427 let (a, b) = self.overflowing_mul(other);
428 if b {None} else {Some(a)}
431 /// Checked integer division. Computes `self / other`, returning `None`
432 /// if `other == 0` or the operation results in underflow or overflow.
439 /// assert_eq!((-127i8).checked_div(-1), Some(127));
440 /// assert_eq!((-128i8).checked_div(-1), None);
441 /// assert_eq!((1i8).checked_div(0), None);
443 #[stable(feature = "rust1", since = "1.0.0")]
445 pub fn checked_div(self, other: Self) -> Option<Self> {
446 if other == 0 || (self == Self::min_value() && other == -1) {
449 Some(unsafe { intrinsics::unchecked_div(self, other) })
453 /// Checked integer remainder. Computes `self % other`, returning `None`
454 /// if `other == 0` or the operation results in underflow or overflow.
463 /// assert_eq!(5i32.checked_rem(2), Some(1));
464 /// assert_eq!(5i32.checked_rem(0), None);
465 /// assert_eq!(i32::MIN.checked_rem(-1), None);
467 #[stable(feature = "wrapping", since = "1.7.0")]
469 pub fn checked_rem(self, other: Self) -> Option<Self> {
470 if other == 0 || (self == Self::min_value() && other == -1) {
473 Some(unsafe { intrinsics::unchecked_rem(self, other) })
477 /// Checked negation. Computes `-self`, returning `None` if `self ==
487 /// assert_eq!(5i32.checked_neg(), Some(-5));
488 /// assert_eq!(i32::MIN.checked_neg(), None);
490 #[stable(feature = "wrapping", since = "1.7.0")]
492 pub fn checked_neg(self) -> Option<Self> {
493 let (a, b) = self.overflowing_neg();
494 if b {None} else {Some(a)}
497 /// Checked shift left. Computes `self << rhs`, returning `None`
498 /// if `rhs` is larger than or equal to the number of bits in `self`.
505 /// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
506 /// assert_eq!(0x10i32.checked_shl(33), None);
508 #[stable(feature = "wrapping", since = "1.7.0")]
510 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
511 let (a, b) = self.overflowing_shl(rhs);
512 if b {None} else {Some(a)}
515 /// Checked shift right. Computes `self >> rhs`, returning `None`
516 /// if `rhs` is larger than or equal to the number of bits in `self`.
523 /// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
524 /// assert_eq!(0x10i32.checked_shr(33), None);
526 #[stable(feature = "wrapping", since = "1.7.0")]
528 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
529 let (a, b) = self.overflowing_shr(rhs);
530 if b {None} else {Some(a)}
533 /// Checked absolute value. Computes `self.abs()`, returning `None` if
543 /// assert_eq!((-5i32).checked_abs(), Some(5));
544 /// assert_eq!(i32::MIN.checked_abs(), None);
546 #[stable(feature = "no_panic_abs", since = "1.13.0")]
548 pub fn checked_abs(self) -> Option<Self> {
549 if self.is_negative() {
556 /// Saturating integer addition. Computes `self + other`, saturating at
557 /// the numeric bounds instead of overflowing.
564 /// assert_eq!(100i8.saturating_add(1), 101);
565 /// assert_eq!(100i8.saturating_add(127), 127);
567 #[stable(feature = "rust1", since = "1.0.0")]
569 pub fn saturating_add(self, other: Self) -> Self {
570 match self.checked_add(other) {
572 None if other >= 0 => Self::max_value(),
573 None => Self::min_value(),
577 /// Saturating integer subtraction. Computes `self - other`, saturating
578 /// at the numeric bounds instead of overflowing.
585 /// assert_eq!(100i8.saturating_sub(127), -27);
586 /// assert_eq!((-100i8).saturating_sub(127), -128);
588 #[stable(feature = "rust1", since = "1.0.0")]
590 pub fn saturating_sub(self, other: Self) -> Self {
591 match self.checked_sub(other) {
593 None if other >= 0 => Self::min_value(),
594 None => Self::max_value(),
598 /// Saturating integer multiplication. Computes `self * other`,
599 /// saturating at the numeric bounds instead of overflowing.
608 /// assert_eq!(100i32.saturating_mul(127), 12700);
609 /// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
610 /// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
612 #[stable(feature = "wrapping", since = "1.7.0")]
614 pub fn saturating_mul(self, other: Self) -> Self {
615 self.checked_mul(other).unwrap_or_else(|| {
616 if (self < 0 && other < 0) || (self > 0 && other > 0) {
624 /// Wrapping (modular) addition. Computes `self + other`,
625 /// wrapping around at the boundary of the type.
632 /// assert_eq!(100i8.wrapping_add(27), 127);
633 /// assert_eq!(100i8.wrapping_add(127), -29);
635 #[stable(feature = "rust1", since = "1.0.0")]
637 pub fn wrapping_add(self, rhs: Self) -> Self {
639 intrinsics::overflowing_add(self, rhs)
643 /// Wrapping (modular) subtraction. Computes `self - other`,
644 /// wrapping around at the boundary of the type.
651 /// assert_eq!(0i8.wrapping_sub(127), -127);
652 /// assert_eq!((-2i8).wrapping_sub(127), 127);
654 #[stable(feature = "rust1", since = "1.0.0")]
656 pub fn wrapping_sub(self, rhs: Self) -> Self {
658 intrinsics::overflowing_sub(self, rhs)
662 /// Wrapping (modular) multiplication. Computes `self *
663 /// other`, wrapping around at the boundary of the type.
670 /// assert_eq!(10i8.wrapping_mul(12), 120);
671 /// assert_eq!(11i8.wrapping_mul(12), -124);
673 #[stable(feature = "rust1", since = "1.0.0")]
675 pub fn wrapping_mul(self, rhs: Self) -> Self {
677 intrinsics::overflowing_mul(self, rhs)
681 /// Wrapping (modular) division. Computes `self / other`,
682 /// wrapping around at the boundary of the type.
684 /// The only case where such wrapping can occur is when one
685 /// divides `MIN / -1` on a signed type (where `MIN` is the
686 /// negative minimal value for the type); this is equivalent
687 /// to `-MIN`, a positive value that is too large to represent
688 /// in the type. In such a case, this function returns `MIN`
693 /// This function will panic if `rhs` is 0.
700 /// assert_eq!(100u8.wrapping_div(10), 10);
701 /// assert_eq!((-128i8).wrapping_div(-1), -128);
703 #[stable(feature = "num_wrapping", since = "1.2.0")]
705 pub fn wrapping_div(self, rhs: Self) -> Self {
706 self.overflowing_div(rhs).0
709 /// Wrapping (modular) remainder. Computes `self % other`,
710 /// wrapping around at the boundary of the type.
712 /// Such wrap-around never actually occurs mathematically;
713 /// implementation artifacts make `x % y` invalid for `MIN /
714 /// -1` on a signed type (where `MIN` is the negative
715 /// minimal value). In such a case, this function returns `0`.
719 /// This function will panic if `rhs` is 0.
726 /// assert_eq!(100i8.wrapping_rem(10), 0);
727 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
729 #[stable(feature = "num_wrapping", since = "1.2.0")]
731 pub fn wrapping_rem(self, rhs: Self) -> Self {
732 self.overflowing_rem(rhs).0
735 /// Wrapping (modular) negation. Computes `-self`,
736 /// wrapping around at the boundary of the type.
738 /// The only case where such wrapping can occur is when one
739 /// negates `MIN` on a signed type (where `MIN` is the
740 /// negative minimal value for the type); this is a positive
741 /// value that is too large to represent in the type. In such
742 /// a case, this function returns `MIN` itself.
749 /// assert_eq!(100i8.wrapping_neg(), -100);
750 /// assert_eq!((-128i8).wrapping_neg(), -128);
752 #[stable(feature = "num_wrapping", since = "1.2.0")]
754 pub fn wrapping_neg(self) -> Self {
755 self.overflowing_neg().0
758 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
759 /// where `mask` removes any high-order bits of `rhs` that
760 /// would cause the shift to exceed the bitwidth of the type.
762 /// Note that this is *not* the same as a rotate-left; the
763 /// RHS of a wrapping shift-left is restricted to the range
764 /// of the type, rather than the bits shifted out of the LHS
765 /// being returned to the other end. The primitive integer
766 /// types all implement a `rotate_left` function, which may
767 /// be what you want instead.
774 /// assert_eq!((-1i8).wrapping_shl(7), -128);
775 /// assert_eq!((-1i8).wrapping_shl(8), -1);
777 #[stable(feature = "num_wrapping", since = "1.2.0")]
779 pub fn wrapping_shl(self, rhs: u32) -> Self {
781 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
785 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
786 /// where `mask` removes any high-order bits of `rhs` that
787 /// would cause the shift to exceed the bitwidth of the type.
789 /// Note that this is *not* the same as a rotate-right; the
790 /// RHS of a wrapping shift-right is restricted to the range
791 /// of the type, rather than the bits shifted out of the LHS
792 /// being returned to the other end. The primitive integer
793 /// types all implement a `rotate_right` function, which may
794 /// be what you want instead.
801 /// assert_eq!((-128i8).wrapping_shr(7), -1);
802 /// assert_eq!((-128i8).wrapping_shr(8), -128);
804 #[stable(feature = "num_wrapping", since = "1.2.0")]
806 pub fn wrapping_shr(self, rhs: u32) -> Self {
808 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
812 /// Wrapping (modular) absolute value. Computes `self.abs()`,
813 /// wrapping around at the boundary of the type.
815 /// The only case where such wrapping can occur is when one takes
816 /// the absolute value of the negative minimal value for the type
817 /// this is a positive value that is too large to represent in the
818 /// type. In such a case, this function returns `MIN` itself.
825 /// assert_eq!(100i8.wrapping_abs(), 100);
826 /// assert_eq!((-100i8).wrapping_abs(), 100);
827 /// assert_eq!((-128i8).wrapping_abs(), -128);
828 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
830 #[stable(feature = "no_panic_abs", since = "1.13.0")]
832 pub fn wrapping_abs(self) -> Self {
833 if self.is_negative() {
840 /// Calculates `self` + `rhs`
842 /// Returns a tuple of the addition along with a boolean indicating
843 /// whether an arithmetic overflow would occur. If an overflow would
844 /// have occurred then the wrapped value is returned.
853 /// assert_eq!(5i32.overflowing_add(2), (7, false));
854 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
857 #[stable(feature = "wrapping", since = "1.7.0")]
858 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
860 let (a, b) = $add_with_overflow(self as $ActualT,
866 /// Calculates `self` - `rhs`
868 /// Returns a tuple of the subtraction along with a boolean indicating
869 /// whether an arithmetic overflow would occur. If an overflow would
870 /// have occurred then the wrapped value is returned.
879 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
880 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
883 #[stable(feature = "wrapping", since = "1.7.0")]
884 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
886 let (a, b) = $sub_with_overflow(self as $ActualT,
892 /// Calculates the multiplication of `self` and `rhs`.
894 /// Returns a tuple of the multiplication along with a boolean
895 /// indicating whether an arithmetic overflow would occur. If an
896 /// overflow would have occurred then the wrapped value is returned.
903 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
904 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
907 #[stable(feature = "wrapping", since = "1.7.0")]
908 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
910 let (a, b) = $mul_with_overflow(self as $ActualT,
916 /// Calculates the divisor when `self` is divided by `rhs`.
918 /// Returns a tuple of the divisor along with a boolean indicating
919 /// whether an arithmetic overflow would occur. If an overflow would
920 /// occur then self is returned.
924 /// This function will panic if `rhs` is 0.
933 /// assert_eq!(5i32.overflowing_div(2), (2, false));
934 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
937 #[stable(feature = "wrapping", since = "1.7.0")]
938 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
939 if self == Self::min_value() && rhs == -1 {
946 /// Calculates the remainder when `self` is divided by `rhs`.
948 /// Returns a tuple of the remainder after dividing along with a boolean
949 /// indicating whether an arithmetic overflow would occur. If an
950 /// overflow would occur then 0 is returned.
954 /// This function will panic if `rhs` is 0.
963 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
964 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
967 #[stable(feature = "wrapping", since = "1.7.0")]
968 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
969 if self == Self::min_value() && rhs == -1 {
976 /// Negates self, overflowing if this is equal to the minimum value.
978 /// Returns a tuple of the negated version of self along with a boolean
979 /// indicating whether an overflow happened. If `self` is the minimum
980 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
981 /// value will be returned again and `true` will be returned for an
982 /// overflow happening.
991 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
992 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
995 #[stable(feature = "wrapping", since = "1.7.0")]
996 pub fn overflowing_neg(self) -> (Self, bool) {
997 if self == Self::min_value() {
998 (Self::min_value(), true)
1004 /// Shifts self left by `rhs` bits.
1006 /// Returns a tuple of the shifted version of self along with a boolean
1007 /// indicating whether the shift value was larger than or equal to the
1008 /// number of bits. If the shift value is too large, then value is
1009 /// masked (N-1) where N is the number of bits, and this value is then
1010 /// used to perform the shift.
1017 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
1018 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
1021 #[stable(feature = "wrapping", since = "1.7.0")]
1022 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1023 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1026 /// Shifts self right by `rhs` bits.
1028 /// Returns a tuple of the shifted version of self along with a boolean
1029 /// indicating whether the shift value was larger than or equal to the
1030 /// number of bits. If the shift value is too large, then value is
1031 /// masked (N-1) where N is the number of bits, and this value is then
1032 /// used to perform the shift.
1039 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
1040 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1043 #[stable(feature = "wrapping", since = "1.7.0")]
1044 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1045 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1048 /// Computes the absolute value of `self`.
1050 /// Returns a tuple of the absolute version of self along with a
1051 /// boolean indicating whether an overflow happened. If self is the
1052 /// minimum value (e.g. i32::MIN for values of type i32), then the
1053 /// minimum value will be returned again and true will be returned for
1054 /// an overflow happening.
1061 /// assert_eq!(10i8.overflowing_abs(), (10,false));
1062 /// assert_eq!((-10i8).overflowing_abs(), (10,false));
1063 /// assert_eq!((-128i8).overflowing_abs(), (-128,true));
1065 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1067 pub fn overflowing_abs(self) -> (Self, bool) {
1068 if self.is_negative() {
1069 self.overflowing_neg()
1075 /// Raises self to the power of `exp`, using exponentiation by squaring.
1082 /// let x: i32 = 2; // or any other integer type
1084 /// assert_eq!(x.pow(4), 16);
1086 #[stable(feature = "rust1", since = "1.0.0")]
1088 #[rustc_inherit_overflow_checks]
1089 pub fn pow(self, mut exp: u32) -> Self {
1090 let mut base = self;
1101 // Deal with the final bit of the exponent separately, since
1102 // squaring the base afterwards is not necessary and may cause a
1103 // needless overflow.
1111 /// Computes the absolute value of `self`.
1113 /// # Overflow behavior
1115 /// The absolute value of `i32::min_value()` cannot be represented as an
1116 /// `i32`, and attempting to calculate it will cause an overflow. This
1117 /// means that code in debug mode will trigger a panic on this case and
1118 /// optimized code will return `i32::min_value()` without a panic.
1125 /// assert_eq!(10i8.abs(), 10);
1126 /// assert_eq!((-10i8).abs(), 10);
1128 #[stable(feature = "rust1", since = "1.0.0")]
1130 #[rustc_inherit_overflow_checks]
1131 pub fn abs(self) -> Self {
1132 if self.is_negative() {
1133 // Note that the #[inline] above means that the overflow
1134 // semantics of this negation depend on the crate we're being
1142 /// Returns a number representing sign of `self`.
1144 /// - `0` if the number is zero
1145 /// - `1` if the number is positive
1146 /// - `-1` if the number is negative
1153 /// assert_eq!(10i8.signum(), 1);
1154 /// assert_eq!(0i8.signum(), 0);
1155 /// assert_eq!((-10i8).signum(), -1);
1157 #[stable(feature = "rust1", since = "1.0.0")]
1159 pub fn signum(self) -> Self {
1167 /// Returns `true` if `self` is positive and `false` if the number
1168 /// is zero or negative.
1175 /// assert!(10i8.is_positive());
1176 /// assert!(!(-10i8).is_positive());
1178 #[stable(feature = "rust1", since = "1.0.0")]
1180 pub fn is_positive(self) -> bool { self > 0 }
1182 /// Returns `true` if `self` is negative and `false` if the number
1183 /// is zero or positive.
1190 /// assert!((-10i8).is_negative());
1191 /// assert!(!10i8.is_negative());
1193 #[stable(feature = "rust1", since = "1.0.0")]
1195 pub fn is_negative(self) -> bool { self < 0 }
1201 int_impl! { i8, i8, u8, 8,
1202 intrinsics::add_with_overflow,
1203 intrinsics::sub_with_overflow,
1204 intrinsics::mul_with_overflow }
1209 int_impl! { i16, i16, u16, 16,
1210 intrinsics::add_with_overflow,
1211 intrinsics::sub_with_overflow,
1212 intrinsics::mul_with_overflow }
1217 int_impl! { i32, i32, u32, 32,
1218 intrinsics::add_with_overflow,
1219 intrinsics::sub_with_overflow,
1220 intrinsics::mul_with_overflow }
1225 int_impl! { i64, i64, u64, 64,
1226 intrinsics::add_with_overflow,
1227 intrinsics::sub_with_overflow,
1228 intrinsics::mul_with_overflow }
1233 int_impl! { i128, i128, u128, 128,
1234 intrinsics::add_with_overflow,
1235 intrinsics::sub_with_overflow,
1236 intrinsics::mul_with_overflow }
1239 #[cfg(target_pointer_width = "16")]
1242 int_impl! { isize, i16, u16, 16,
1243 intrinsics::add_with_overflow,
1244 intrinsics::sub_with_overflow,
1245 intrinsics::mul_with_overflow }
1248 #[cfg(target_pointer_width = "32")]
1251 int_impl! { isize, i32, u32, 32,
1252 intrinsics::add_with_overflow,
1253 intrinsics::sub_with_overflow,
1254 intrinsics::mul_with_overflow }
1257 #[cfg(target_pointer_width = "64")]
1260 int_impl! { isize, i64, u64, 64,
1261 intrinsics::add_with_overflow,
1262 intrinsics::sub_with_overflow,
1263 intrinsics::mul_with_overflow }
1266 // `Int` + `UnsignedInt` implemented for unsigned integers
1267 macro_rules! uint_impl {
1268 ($SelfT:ty, $ActualT:ty, $BITS:expr,
1274 $add_with_overflow:path,
1275 $sub_with_overflow:path,
1276 $mul_with_overflow:path) => {
1277 /// Returns the smallest value that can be represented by this integer type.
1282 /// assert_eq!(u8::min_value(), 0);
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 #[cfg_attr(not(stage0), rustc_const_unstable(feature = "const_min_value"))]
1287 pub const fn min_value() -> Self { 0 }
1289 /// Returns the largest value that can be represented by this integer type.
1294 /// assert_eq!(u8::max_value(), 255);
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 #[cfg_attr(not(stage0), rustc_const_unstable(feature = "const_max_value"))]
1299 pub const fn max_value() -> Self { !0 }
1301 /// Converts a string slice in a given base to an integer.
1303 /// Leading and trailing whitespace represent an error.
1310 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1314 from_str_radix(src, radix)
1317 /// Returns the number of ones in the binary representation of `self`.
1324 /// let n = 0b01001100u8;
1326 /// assert_eq!(n.count_ones(), 3);
1328 #[stable(feature = "rust1", since = "1.0.0")]
1330 pub fn count_ones(self) -> u32 {
1331 unsafe { $ctpop(self as $ActualT) as u32 }
1334 /// Returns the number of zeros in the binary representation of `self`.
1341 /// let n = 0b01001100u8;
1343 /// assert_eq!(n.count_zeros(), 5);
1345 #[stable(feature = "rust1", since = "1.0.0")]
1347 pub fn count_zeros(self) -> u32 {
1348 (!self).count_ones()
1351 /// Returns the number of leading zeros in the binary representation
1359 /// let n = 0b0101000u16;
1361 /// assert_eq!(n.leading_zeros(), 10);
1363 #[stable(feature = "rust1", since = "1.0.0")]
1365 pub fn leading_zeros(self) -> u32 {
1366 unsafe { $ctlz(self as $ActualT) as u32 }
1369 /// Returns the number of trailing zeros in the binary representation
1377 /// let n = 0b0101000u16;
1379 /// assert_eq!(n.trailing_zeros(), 3);
1381 #[stable(feature = "rust1", since = "1.0.0")]
1383 pub fn trailing_zeros(self) -> u32 {
1384 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1385 // emits two conditional moves on x86_64. By promoting the value to
1386 // u16 and setting bit 8, we get better code without any conditional
1388 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1389 // pending, remove this workaround once LLVM generates better code
1393 intrinsics::cttz(self as u16 | 0x100) as u32
1395 intrinsics::cttz(self) as u32
1400 /// Shifts the bits to the left by a specified amount, `n`,
1401 /// wrapping the truncated bits to the end of the resulting integer.
1403 /// Please note this isn't the same operation as `<<`!
1410 /// let n = 0x0123456789ABCDEFu64;
1411 /// let m = 0x3456789ABCDEF012u64;
1413 /// assert_eq!(n.rotate_left(12), m);
1415 #[stable(feature = "rust1", since = "1.0.0")]
1417 pub fn rotate_left(self, n: u32) -> Self {
1418 // Protect against undefined behaviour for over-long bit shifts
1420 (self << n) | (self >> (($BITS - n) % $BITS))
1423 /// Shifts the bits to the right by a specified amount, `n`,
1424 /// wrapping the truncated bits to the beginning of the resulting
1427 /// Please note this isn't the same operation as `>>`!
1434 /// let n = 0x0123456789ABCDEFu64;
1435 /// let m = 0xDEF0123456789ABCu64;
1437 /// assert_eq!(n.rotate_right(12), m);
1439 #[stable(feature = "rust1", since = "1.0.0")]
1441 pub fn rotate_right(self, n: u32) -> Self {
1442 // Protect against undefined behaviour for over-long bit shifts
1444 (self >> n) | (self << (($BITS - n) % $BITS))
1447 /// Reverses the byte order of the integer.
1454 /// let n = 0x0123456789ABCDEFu64;
1455 /// let m = 0xEFCDAB8967452301u64;
1457 /// assert_eq!(n.swap_bytes(), m);
1459 #[stable(feature = "rust1", since = "1.0.0")]
1461 pub fn swap_bytes(self) -> Self {
1462 unsafe { $bswap(self as $ActualT) as Self }
1465 /// Converts an integer from big endian to the target's endianness.
1467 /// On big endian this is a no-op. On little endian the bytes are
1475 /// let n = 0x0123456789ABCDEFu64;
1477 /// if cfg!(target_endian = "big") {
1478 /// assert_eq!(u64::from_be(n), n)
1480 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1483 #[stable(feature = "rust1", since = "1.0.0")]
1485 pub fn from_be(x: Self) -> Self {
1486 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1489 /// Converts an integer from little endian to the target's endianness.
1491 /// On little endian this is a no-op. On big endian the bytes are
1499 /// let n = 0x0123456789ABCDEFu64;
1501 /// if cfg!(target_endian = "little") {
1502 /// assert_eq!(u64::from_le(n), n)
1504 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1507 #[stable(feature = "rust1", since = "1.0.0")]
1509 pub fn from_le(x: Self) -> Self {
1510 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1513 /// Converts `self` to big endian from the target's endianness.
1515 /// On big endian this is a no-op. On little endian the bytes are
1523 /// let n = 0x0123456789ABCDEFu64;
1525 /// if cfg!(target_endian = "big") {
1526 /// assert_eq!(n.to_be(), n)
1528 /// assert_eq!(n.to_be(), n.swap_bytes())
1531 #[stable(feature = "rust1", since = "1.0.0")]
1533 pub fn to_be(self) -> Self { // or not to be?
1534 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1537 /// Converts `self` to little endian from the target's endianness.
1539 /// On little endian this is a no-op. On big endian the bytes are
1547 /// let n = 0x0123456789ABCDEFu64;
1549 /// if cfg!(target_endian = "little") {
1550 /// assert_eq!(n.to_le(), n)
1552 /// assert_eq!(n.to_le(), n.swap_bytes())
1555 #[stable(feature = "rust1", since = "1.0.0")]
1557 pub fn to_le(self) -> Self {
1558 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1561 /// Checked integer addition. Computes `self + other`, returning `None`
1562 /// if overflow occurred.
1569 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1570 /// assert_eq!(6u16.checked_add(65530), None);
1572 #[stable(feature = "rust1", since = "1.0.0")]
1574 pub fn checked_add(self, other: Self) -> Option<Self> {
1575 let (a, b) = self.overflowing_add(other);
1576 if b {None} else {Some(a)}
1579 /// Checked integer subtraction. Computes `self - other`, returning
1580 /// `None` if underflow occurred.
1587 /// assert_eq!(1u8.checked_sub(1), Some(0));
1588 /// assert_eq!(0u8.checked_sub(1), None);
1590 #[stable(feature = "rust1", since = "1.0.0")]
1592 pub fn checked_sub(self, other: Self) -> Option<Self> {
1593 let (a, b) = self.overflowing_sub(other);
1594 if b {None} else {Some(a)}
1597 /// Checked integer multiplication. Computes `self * other`, returning
1598 /// `None` if underflow or overflow occurred.
1605 /// assert_eq!(5u8.checked_mul(51), Some(255));
1606 /// assert_eq!(5u8.checked_mul(52), None);
1608 #[stable(feature = "rust1", since = "1.0.0")]
1610 pub fn checked_mul(self, other: Self) -> Option<Self> {
1611 let (a, b) = self.overflowing_mul(other);
1612 if b {None} else {Some(a)}
1615 /// Checked integer division. Computes `self / other`, returning `None`
1616 /// if `other == 0` or the operation results in underflow or overflow.
1623 /// assert_eq!(128u8.checked_div(2), Some(64));
1624 /// assert_eq!(1u8.checked_div(0), None);
1626 #[stable(feature = "rust1", since = "1.0.0")]
1628 pub fn checked_div(self, other: Self) -> Option<Self> {
1631 other => Some(unsafe { intrinsics::unchecked_div(self, other) }),
1635 /// Checked integer remainder. Computes `self % other`, returning `None`
1636 /// if `other == 0` or the operation results in underflow or overflow.
1643 /// assert_eq!(5u32.checked_rem(2), Some(1));
1644 /// assert_eq!(5u32.checked_rem(0), None);
1646 #[stable(feature = "wrapping", since = "1.7.0")]
1648 pub fn checked_rem(self, other: Self) -> Option<Self> {
1652 Some(unsafe { intrinsics::unchecked_rem(self, other) })
1656 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1659 /// Note that negating any positive integer will overflow.
1666 /// assert_eq!(0u32.checked_neg(), Some(0));
1667 /// assert_eq!(1u32.checked_neg(), None);
1669 #[stable(feature = "wrapping", since = "1.7.0")]
1671 pub fn checked_neg(self) -> Option<Self> {
1672 let (a, b) = self.overflowing_neg();
1673 if b {None} else {Some(a)}
1676 /// Checked shift left. Computes `self << rhs`, returning `None`
1677 /// if `rhs` is larger than or equal to the number of bits in `self`.
1684 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1685 /// assert_eq!(0x10u32.checked_shl(33), None);
1687 #[stable(feature = "wrapping", since = "1.7.0")]
1689 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1690 let (a, b) = self.overflowing_shl(rhs);
1691 if b {None} else {Some(a)}
1694 /// Checked shift right. Computes `self >> rhs`, returning `None`
1695 /// if `rhs` is larger than or equal to the number of bits in `self`.
1702 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1703 /// assert_eq!(0x10u32.checked_shr(33), None);
1705 #[stable(feature = "wrapping", since = "1.7.0")]
1707 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1708 let (a, b) = self.overflowing_shr(rhs);
1709 if b {None} else {Some(a)}
1712 /// Saturating integer addition. Computes `self + other`, saturating at
1713 /// the numeric bounds instead of overflowing.
1720 /// assert_eq!(100u8.saturating_add(1), 101);
1721 /// assert_eq!(200u8.saturating_add(127), 255);
1723 #[stable(feature = "rust1", since = "1.0.0")]
1725 pub fn saturating_add(self, other: Self) -> Self {
1726 match self.checked_add(other) {
1728 None => Self::max_value(),
1732 /// Saturating integer subtraction. Computes `self - other`, saturating
1733 /// at the numeric bounds instead of overflowing.
1740 /// assert_eq!(100u8.saturating_sub(27), 73);
1741 /// assert_eq!(13u8.saturating_sub(127), 0);
1743 #[stable(feature = "rust1", since = "1.0.0")]
1745 pub fn saturating_sub(self, other: Self) -> Self {
1746 match self.checked_sub(other) {
1748 None => Self::min_value(),
1752 /// Saturating integer multiplication. Computes `self * other`,
1753 /// saturating at the numeric bounds instead of overflowing.
1762 /// assert_eq!(100u32.saturating_mul(127), 12700);
1763 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1765 #[stable(feature = "wrapping", since = "1.7.0")]
1767 pub fn saturating_mul(self, other: Self) -> Self {
1768 self.checked_mul(other).unwrap_or(Self::max_value())
1771 /// Wrapping (modular) addition. Computes `self + other`,
1772 /// wrapping around at the boundary of the type.
1779 /// assert_eq!(200u8.wrapping_add(55), 255);
1780 /// assert_eq!(200u8.wrapping_add(155), 99);
1782 #[stable(feature = "rust1", since = "1.0.0")]
1784 pub fn wrapping_add(self, rhs: Self) -> Self {
1786 intrinsics::overflowing_add(self, rhs)
1790 /// Wrapping (modular) subtraction. Computes `self - other`,
1791 /// wrapping around at the boundary of the type.
1798 /// assert_eq!(100u8.wrapping_sub(100), 0);
1799 /// assert_eq!(100u8.wrapping_sub(155), 201);
1801 #[stable(feature = "rust1", since = "1.0.0")]
1803 pub fn wrapping_sub(self, rhs: Self) -> Self {
1805 intrinsics::overflowing_sub(self, rhs)
1809 /// Wrapping (modular) multiplication. Computes `self *
1810 /// other`, wrapping around at the boundary of the type.
1817 /// assert_eq!(10u8.wrapping_mul(12), 120);
1818 /// assert_eq!(25u8.wrapping_mul(12), 44);
1820 #[stable(feature = "rust1", since = "1.0.0")]
1822 pub fn wrapping_mul(self, rhs: Self) -> Self {
1824 intrinsics::overflowing_mul(self, rhs)
1828 /// Wrapping (modular) division. Computes `self / other`.
1829 /// Wrapped division on unsigned types is just normal division.
1830 /// There's no way wrapping could ever happen.
1831 /// This function exists, so that all operations
1832 /// are accounted for in the wrapping operations.
1839 /// assert_eq!(100u8.wrapping_div(10), 10);
1841 #[stable(feature = "num_wrapping", since = "1.2.0")]
1843 pub fn wrapping_div(self, rhs: Self) -> Self {
1847 /// Wrapping (modular) remainder. Computes `self % other`.
1848 /// Wrapped remainder calculation on unsigned types is
1849 /// just the regular remainder calculation.
1850 /// There's no way wrapping could ever happen.
1851 /// This function exists, so that all operations
1852 /// are accounted for in the wrapping operations.
1859 /// assert_eq!(100u8.wrapping_rem(10), 0);
1861 #[stable(feature = "num_wrapping", since = "1.2.0")]
1863 pub fn wrapping_rem(self, rhs: Self) -> Self {
1867 /// Wrapping (modular) negation. Computes `-self`,
1868 /// wrapping around at the boundary of the type.
1870 /// Since unsigned types do not have negative equivalents
1871 /// all applications of this function will wrap (except for `-0`).
1872 /// For values smaller than the corresponding signed type's maximum
1873 /// the result is the same as casting the corresponding signed value.
1874 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1875 /// `MAX` is the corresponding signed type's maximum.
1882 /// assert_eq!(100u8.wrapping_neg(), 156);
1883 /// assert_eq!(0u8.wrapping_neg(), 0);
1884 /// assert_eq!(180u8.wrapping_neg(), 76);
1885 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1887 #[stable(feature = "num_wrapping", since = "1.2.0")]
1889 pub fn wrapping_neg(self) -> Self {
1890 self.overflowing_neg().0
1893 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1894 /// where `mask` removes any high-order bits of `rhs` that
1895 /// would cause the shift to exceed the bitwidth of the type.
1897 /// Note that this is *not* the same as a rotate-left; the
1898 /// RHS of a wrapping shift-left is restricted to the range
1899 /// of the type, rather than the bits shifted out of the LHS
1900 /// being returned to the other end. The primitive integer
1901 /// types all implement a `rotate_left` function, which may
1902 /// be what you want instead.
1909 /// assert_eq!(1u8.wrapping_shl(7), 128);
1910 /// assert_eq!(1u8.wrapping_shl(8), 1);
1912 #[stable(feature = "num_wrapping", since = "1.2.0")]
1914 pub fn wrapping_shl(self, rhs: u32) -> Self {
1916 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1920 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1921 /// where `mask` removes any high-order bits of `rhs` that
1922 /// would cause the shift to exceed the bitwidth of the type.
1924 /// Note that this is *not* the same as a rotate-right; the
1925 /// RHS of a wrapping shift-right is restricted to the range
1926 /// of the type, rather than the bits shifted out of the LHS
1927 /// being returned to the other end. The primitive integer
1928 /// types all implement a `rotate_right` function, which may
1929 /// be what you want instead.
1936 /// assert_eq!(128u8.wrapping_shr(7), 1);
1937 /// assert_eq!(128u8.wrapping_shr(8), 128);
1939 #[stable(feature = "num_wrapping", since = "1.2.0")]
1941 pub fn wrapping_shr(self, rhs: u32) -> Self {
1943 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1947 /// Calculates `self` + `rhs`
1949 /// Returns a tuple of the addition along with a boolean indicating
1950 /// whether an arithmetic overflow would occur. If an overflow would
1951 /// have occurred then the wrapped value is returned.
1960 /// assert_eq!(5u32.overflowing_add(2), (7, false));
1961 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
1964 #[stable(feature = "wrapping", since = "1.7.0")]
1965 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1967 let (a, b) = $add_with_overflow(self as $ActualT,
1973 /// Calculates `self` - `rhs`
1975 /// Returns a tuple of the subtraction along with a boolean indicating
1976 /// whether an arithmetic overflow would occur. If an overflow would
1977 /// have occurred then the wrapped value is returned.
1986 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
1987 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
1990 #[stable(feature = "wrapping", since = "1.7.0")]
1991 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1993 let (a, b) = $sub_with_overflow(self as $ActualT,
1999 /// Calculates the multiplication of `self` and `rhs`.
2001 /// Returns a tuple of the multiplication along with a boolean
2002 /// indicating whether an arithmetic overflow would occur. If an
2003 /// overflow would have occurred then the wrapped value is returned.
2010 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2011 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2014 #[stable(feature = "wrapping", since = "1.7.0")]
2015 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2017 let (a, b) = $mul_with_overflow(self as $ActualT,
2023 /// Calculates the divisor when `self` is divided by `rhs`.
2025 /// Returns a tuple of the divisor along with a boolean indicating
2026 /// whether an arithmetic overflow would occur. Note that for unsigned
2027 /// integers overflow never occurs, so the second value is always
2032 /// This function will panic if `rhs` is 0.
2039 /// assert_eq!(5u32.overflowing_div(2), (2, false));
2042 #[stable(feature = "wrapping", since = "1.7.0")]
2043 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2047 /// Calculates the remainder when `self` is divided by `rhs`.
2049 /// Returns a tuple of the remainder after dividing along with a boolean
2050 /// indicating whether an arithmetic overflow would occur. Note that for
2051 /// unsigned integers overflow never occurs, so the second value is
2056 /// This function will panic if `rhs` is 0.
2063 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
2066 #[stable(feature = "wrapping", since = "1.7.0")]
2067 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2071 /// Negates self in an overflowing fashion.
2073 /// Returns `!self + 1` using wrapping operations to return the value
2074 /// that represents the negation of this unsigned value. Note that for
2075 /// positive unsigned values overflow always occurs, but negating 0 does
2083 /// assert_eq!(0u32.overflowing_neg(), (0, false));
2084 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
2087 #[stable(feature = "wrapping", since = "1.7.0")]
2088 pub fn overflowing_neg(self) -> (Self, bool) {
2089 ((!self).wrapping_add(1), self != 0)
2092 /// Shifts self left by `rhs` bits.
2094 /// Returns a tuple of the shifted version of self along with a boolean
2095 /// indicating whether the shift value was larger than or equal to the
2096 /// number of bits. If the shift value is too large, then value is
2097 /// masked (N-1) where N is the number of bits, and this value is then
2098 /// used to perform the shift.
2105 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
2106 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
2109 #[stable(feature = "wrapping", since = "1.7.0")]
2110 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2111 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
2114 /// Shifts self right by `rhs` bits.
2116 /// Returns a tuple of the shifted version of self along with a boolean
2117 /// indicating whether the shift value was larger than or equal to the
2118 /// number of bits. If the shift value is too large, then value is
2119 /// masked (N-1) where N is the number of bits, and this value is then
2120 /// used to perform the shift.
2127 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
2128 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2131 #[stable(feature = "wrapping", since = "1.7.0")]
2132 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2133 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
2137 /// Raises self to the power of `exp`, using exponentiation by squaring.
2144 /// assert_eq!(2u32.pow(4), 16);
2146 #[stable(feature = "rust1", since = "1.0.0")]
2148 #[rustc_inherit_overflow_checks]
2149 pub fn pow(self, mut exp: u32) -> Self {
2150 let mut base = self;
2161 // Deal with the final bit of the exponent separately, since
2162 // squaring the base afterwards is not necessary and may cause a
2163 // needless overflow.
2171 /// Returns `true` if and only if `self == 2^k` for some `k`.
2178 /// assert!(16u8.is_power_of_two());
2179 /// assert!(!10u8.is_power_of_two());
2181 #[stable(feature = "rust1", since = "1.0.0")]
2183 pub fn is_power_of_two(self) -> bool {
2184 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2187 // Returns one less than next power of two.
2188 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2190 // 8u8.one_less_than_next_power_of_two() == 7
2191 // 6u8.one_less_than_next_power_of_two() == 7
2193 // This method cannot overflow, as in the `next_power_of_two`
2194 // overflow cases it instead ends up returning the maximum value
2195 // of the type, and can return 0 for 0.
2197 fn one_less_than_next_power_of_two(self) -> Self {
2198 if self <= 1 { return 0; }
2200 // Because `p > 0`, it cannot consist entirely of leading zeros.
2201 // That means the shift is always in-bounds, and some processors
2202 // (such as intel pre-haswell) have more efficient ctlz
2203 // intrinsics when the argument is non-zero.
2205 let z = unsafe { $ctlz_nonzero(p) };
2206 <$SelfT>::max_value() >> z
2209 /// Returns the smallest power of two greater than or equal to `self`.
2211 /// When return value overflows (i.e. `self > (1 << (N-1))` for type
2212 /// `uN`), it panics in debug mode and return value is wrapped to 0 in
2213 /// release mode (the only situation in which method can return 0).
2220 /// assert_eq!(2u8.next_power_of_two(), 2);
2221 /// assert_eq!(3u8.next_power_of_two(), 4);
2223 #[stable(feature = "rust1", since = "1.0.0")]
2225 pub fn next_power_of_two(self) -> Self {
2226 self.one_less_than_next_power_of_two() + 1
2229 /// Returns the smallest power of two greater than or equal to `n`. If
2230 /// the next power of two is greater than the type's maximum value,
2231 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2238 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2239 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2240 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2242 #[stable(feature = "rust1", since = "1.0.0")]
2243 pub fn checked_next_power_of_two(self) -> Option<Self> {
2244 self.one_less_than_next_power_of_two().checked_add(1)
2251 uint_impl! { u8, u8, 8,
2254 intrinsics::ctlz_nonzero,
2257 intrinsics::add_with_overflow,
2258 intrinsics::sub_with_overflow,
2259 intrinsics::mul_with_overflow }
2264 uint_impl! { u16, u16, 16,
2267 intrinsics::ctlz_nonzero,
2270 intrinsics::add_with_overflow,
2271 intrinsics::sub_with_overflow,
2272 intrinsics::mul_with_overflow }
2277 uint_impl! { u32, u32, 32,
2280 intrinsics::ctlz_nonzero,
2283 intrinsics::add_with_overflow,
2284 intrinsics::sub_with_overflow,
2285 intrinsics::mul_with_overflow }
2290 uint_impl! { u64, u64, 64,
2293 intrinsics::ctlz_nonzero,
2296 intrinsics::add_with_overflow,
2297 intrinsics::sub_with_overflow,
2298 intrinsics::mul_with_overflow }
2303 uint_impl! { u128, u128, 128,
2306 intrinsics::ctlz_nonzero,
2309 intrinsics::add_with_overflow,
2310 intrinsics::sub_with_overflow,
2311 intrinsics::mul_with_overflow }
2314 #[cfg(target_pointer_width = "16")]
2317 uint_impl! { usize, u16, 16,
2320 intrinsics::ctlz_nonzero,
2323 intrinsics::add_with_overflow,
2324 intrinsics::sub_with_overflow,
2325 intrinsics::mul_with_overflow }
2327 #[cfg(target_pointer_width = "32")]
2330 uint_impl! { usize, u32, 32,
2333 intrinsics::ctlz_nonzero,
2336 intrinsics::add_with_overflow,
2337 intrinsics::sub_with_overflow,
2338 intrinsics::mul_with_overflow }
2341 #[cfg(target_pointer_width = "64")]
2344 uint_impl! { usize, u64, 64,
2347 intrinsics::ctlz_nonzero,
2350 intrinsics::add_with_overflow,
2351 intrinsics::sub_with_overflow,
2352 intrinsics::mul_with_overflow }
2355 /// A classification of floating point numbers.
2357 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
2358 /// their documentation for more.
2360 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
2361 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
2366 /// use std::num::FpCategory;
2369 /// let num = 12.4_f32;
2370 /// let inf = f32::INFINITY;
2371 /// let zero = 0f32;
2372 /// let sub: f32 = 1.1754942e-38;
2373 /// let nan = f32::NAN;
2375 /// assert_eq!(num.classify(), FpCategory::Normal);
2376 /// assert_eq!(inf.classify(), FpCategory::Infinite);
2377 /// assert_eq!(zero.classify(), FpCategory::Zero);
2378 /// assert_eq!(nan.classify(), FpCategory::Nan);
2379 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
2381 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2382 #[stable(feature = "rust1", since = "1.0.0")]
2383 pub enum FpCategory {
2384 /// "Not a Number", often obtained by dividing by zero.
2385 #[stable(feature = "rust1", since = "1.0.0")]
2388 /// Positive or negative infinity.
2389 #[stable(feature = "rust1", since = "1.0.0")]
2392 /// Positive or negative zero.
2393 #[stable(feature = "rust1", since = "1.0.0")]
2396 /// De-normalized floating point representation (less precise than `Normal`).
2397 #[stable(feature = "rust1", since = "1.0.0")]
2400 /// A regular floating point number.
2401 #[stable(feature = "rust1", since = "1.0.0")]
2405 /// A built-in floating point number.
2407 #[unstable(feature = "core_float",
2408 reason = "stable interface is via `impl f{32,64}` in later crates",
2410 pub trait Float: Sized {
2411 /// Returns `true` if this value is NaN and false otherwise.
2412 #[stable(feature = "core", since = "1.6.0")]
2413 fn is_nan(self) -> bool;
2414 /// Returns `true` if this value is positive infinity or negative infinity and
2415 /// false otherwise.
2416 #[stable(feature = "core", since = "1.6.0")]
2417 fn is_infinite(self) -> bool;
2418 /// Returns `true` if this number is neither infinite nor NaN.
2419 #[stable(feature = "core", since = "1.6.0")]
2420 fn is_finite(self) -> bool;
2421 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
2422 #[stable(feature = "core", since = "1.6.0")]
2423 fn is_normal(self) -> bool;
2424 /// Returns the category that this number falls into.
2425 #[stable(feature = "core", since = "1.6.0")]
2426 fn classify(self) -> FpCategory;
2428 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2429 /// number is `Float::nan()`.
2430 #[stable(feature = "core", since = "1.6.0")]
2431 fn abs(self) -> Self;
2432 /// Returns a number that represents the sign of `self`.
2434 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2435 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2436 /// - `Float::nan()` if the number is `Float::nan()`
2437 #[stable(feature = "core", since = "1.6.0")]
2438 fn signum(self) -> Self;
2440 /// Returns `true` if `self` is positive, including `+0.0` and
2441 /// `Float::infinity()`.
2442 #[stable(feature = "core", since = "1.6.0")]
2443 fn is_sign_positive(self) -> bool;
2444 /// Returns `true` if `self` is negative, including `-0.0` and
2445 /// `Float::neg_infinity()`.
2446 #[stable(feature = "core", since = "1.6.0")]
2447 fn is_sign_negative(self) -> bool;
2449 /// Take the reciprocal (inverse) of a number, `1/x`.
2450 #[stable(feature = "core", since = "1.6.0")]
2451 fn recip(self) -> Self;
2453 /// Raise a number to an integer power.
2455 /// Using this function is generally faster than using `powf`
2456 #[stable(feature = "core", since = "1.6.0")]
2457 fn powi(self, n: i32) -> Self;
2459 /// Convert radians to degrees.
2460 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2461 fn to_degrees(self) -> Self;
2462 /// Convert degrees to radians.
2463 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2464 fn to_radians(self) -> Self;
2466 /// Returns the maximum of the two numbers.
2467 #[stable(feature = "core_float_min_max", since="1.20.0")]
2468 fn max(self, other: Self) -> Self;
2469 /// Returns the minimum of the two numbers.
2470 #[stable(feature = "core_float_min_max", since="1.20.0")]
2471 fn min(self, other: Self) -> Self;
2474 macro_rules! from_str_radix_int_impl {
2476 #[stable(feature = "rust1", since = "1.0.0")]
2477 impl FromStr for $t {
2478 type Err = ParseIntError;
2479 fn from_str(src: &str) -> Result<Self, ParseIntError> {
2480 from_str_radix(src, 10)
2485 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
2487 /// The error type returned when a checked integral type conversion fails.
2488 #[unstable(feature = "try_from", issue = "33417")]
2489 #[derive(Debug, Copy, Clone)]
2490 pub struct TryFromIntError(());
2492 impl TryFromIntError {
2493 #[unstable(feature = "int_error_internals",
2494 reason = "available through Error trait and this method should \
2495 not be exposed publicly",
2498 pub fn __description(&self) -> &str {
2499 "out of range integral type conversion attempted"
2503 #[unstable(feature = "try_from", issue = "33417")]
2504 impl fmt::Display for TryFromIntError {
2505 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2506 self.__description().fmt(fmt)
2510 // no possible bounds violation
2511 macro_rules! try_from_unbounded {
2512 ($source:ty, $($target:ty),*) => {$(
2513 #[unstable(feature = "try_from", issue = "33417")]
2514 impl TryFrom<$source> for $target {
2515 type Error = TryFromIntError;
2518 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2525 // only negative bounds
2526 macro_rules! try_from_lower_bounded {
2527 ($source:ty, $($target:ty),*) => {$(
2528 #[unstable(feature = "try_from", issue = "33417")]
2529 impl TryFrom<$source> for $target {
2530 type Error = TryFromIntError;
2533 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2537 Err(TryFromIntError(()))
2544 // unsigned to signed (only positive bound)
2545 macro_rules! try_from_upper_bounded {
2546 ($source:ty, $($target:ty),*) => {$(
2547 #[unstable(feature = "try_from", issue = "33417")]
2548 impl TryFrom<$source> for $target {
2549 type Error = TryFromIntError;
2552 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2553 if u > (<$target>::max_value() as $source) {
2554 Err(TryFromIntError(()))
2564 macro_rules! try_from_both_bounded {
2565 ($source:ty, $($target:ty),*) => {$(
2566 #[unstable(feature = "try_from", issue = "33417")]
2567 impl TryFrom<$source> for $target {
2568 type Error = TryFromIntError;
2571 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2572 let min = <$target>::min_value() as $source;
2573 let max = <$target>::max_value() as $source;
2574 if u < min || u > max {
2575 Err(TryFromIntError(()))
2585 ($mac:ident, $source:ty, $($target:ty),*) => {$(
2586 $mac!($target, $source);
2590 /// intra-sign conversions
2591 try_from_unbounded!(u8, u8, u16, u32, u64, u128);
2592 try_from_unbounded!(u16, u16, u32, u64, u128);
2593 try_from_unbounded!(u32, u32, u64, u128);
2594 try_from_unbounded!(u64, u64, u128);
2595 try_from_unbounded!(u128, u128);
2596 try_from_upper_bounded!(u16, u8);
2597 try_from_upper_bounded!(u32, u16, u8);
2598 try_from_upper_bounded!(u64, u32, u16, u8);
2599 try_from_upper_bounded!(u128, u64, u32, u16, u8);
2601 try_from_unbounded!(i8, i8, i16, i32, i64, i128);
2602 try_from_unbounded!(i16, i16, i32, i64, i128);
2603 try_from_unbounded!(i32, i32, i64, i128);
2604 try_from_unbounded!(i64, i64, i128);
2605 try_from_unbounded!(i128, i128);
2606 try_from_both_bounded!(i16, i8);
2607 try_from_both_bounded!(i32, i16, i8);
2608 try_from_both_bounded!(i64, i32, i16, i8);
2609 try_from_both_bounded!(i128, i64, i32, i16, i8);
2611 // unsigned-to-signed
2612 try_from_unbounded!(u8, i16, i32, i64, i128);
2613 try_from_unbounded!(u16, i32, i64, i128);
2614 try_from_unbounded!(u32, i64, i128);
2615 try_from_unbounded!(u64, i128);
2616 try_from_upper_bounded!(u8, i8);
2617 try_from_upper_bounded!(u16, i8, i16);
2618 try_from_upper_bounded!(u32, i8, i16, i32);
2619 try_from_upper_bounded!(u64, i8, i16, i32, i64);
2620 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
2622 // signed-to-unsigned
2623 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
2624 try_from_lower_bounded!(i16, u16, u32, u64, u128);
2625 try_from_lower_bounded!(i32, u32, u64, u128);
2626 try_from_lower_bounded!(i64, u64, u128);
2627 try_from_lower_bounded!(i128, u128);
2628 try_from_both_bounded!(i16, u8);
2629 try_from_both_bounded!(i32, u16, u8);
2630 try_from_both_bounded!(i64, u32, u16, u8);
2631 try_from_both_bounded!(i128, u64, u32, u16, u8);
2634 try_from_unbounded!(usize, usize);
2635 try_from_upper_bounded!(usize, isize);
2636 try_from_lower_bounded!(isize, usize);
2637 try_from_unbounded!(isize, isize);
2639 #[cfg(target_pointer_width = "16")]
2640 mod ptr_try_from_impls {
2641 use super::TryFromIntError;
2642 use convert::TryFrom;
2644 try_from_upper_bounded!(usize, u8);
2645 try_from_unbounded!(usize, u16, u32, u64, u128);
2646 try_from_upper_bounded!(usize, i8, i16);
2647 try_from_unbounded!(usize, i32, i64, i128);
2649 try_from_both_bounded!(isize, u8);
2650 try_from_lower_bounded!(isize, u16, u32, u64, u128);
2651 try_from_both_bounded!(isize, i8);
2652 try_from_unbounded!(isize, i16, i32, i64, i128);
2654 rev!(try_from_unbounded, usize, u8, u16);
2655 rev!(try_from_upper_bounded, usize, u32, u64, u128);
2656 rev!(try_from_lower_bounded, usize, i8, i16);
2657 rev!(try_from_both_bounded, usize, i32, i64, i128);
2659 rev!(try_from_unbounded, isize, u8);
2660 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
2661 rev!(try_from_unbounded, isize, i8, i16);
2662 rev!(try_from_both_bounded, isize, i32, i64, i128);
2665 #[cfg(target_pointer_width = "32")]
2666 mod ptr_try_from_impls {
2667 use super::TryFromIntError;
2668 use convert::TryFrom;
2670 try_from_upper_bounded!(usize, u8, u16);
2671 try_from_unbounded!(usize, u32, u64, u128);
2672 try_from_upper_bounded!(usize, i8, i16, i32);
2673 try_from_unbounded!(usize, i64, i128);
2675 try_from_both_bounded!(isize, u8, u16);
2676 try_from_lower_bounded!(isize, u32, u64, u128);
2677 try_from_both_bounded!(isize, i8, i16);
2678 try_from_unbounded!(isize, i32, i64, i128);
2680 rev!(try_from_unbounded, usize, u8, u16, u32);
2681 rev!(try_from_upper_bounded, usize, u64, u128);
2682 rev!(try_from_lower_bounded, usize, i8, i16, i32);
2683 rev!(try_from_both_bounded, usize, i64, i128);
2685 rev!(try_from_unbounded, isize, u8, u16);
2686 rev!(try_from_upper_bounded, isize, u32, u64, u128);
2687 rev!(try_from_unbounded, isize, i8, i16, i32);
2688 rev!(try_from_both_bounded, isize, i64, i128);
2691 #[cfg(target_pointer_width = "64")]
2692 mod ptr_try_from_impls {
2693 use super::TryFromIntError;
2694 use convert::TryFrom;
2696 try_from_upper_bounded!(usize, u8, u16, u32);
2697 try_from_unbounded!(usize, u64, u128);
2698 try_from_upper_bounded!(usize, i8, i16, i32, i64);
2699 try_from_unbounded!(usize, i128);
2701 try_from_both_bounded!(isize, u8, u16, u32);
2702 try_from_lower_bounded!(isize, u64, u128);
2703 try_from_both_bounded!(isize, i8, i16, i32);
2704 try_from_unbounded!(isize, i64, i128);
2706 rev!(try_from_unbounded, usize, u8, u16, u32, u64);
2707 rev!(try_from_upper_bounded, usize, u128);
2708 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
2709 rev!(try_from_both_bounded, usize, i128);
2711 rev!(try_from_unbounded, isize, u8, u16, u32);
2712 rev!(try_from_upper_bounded, isize, u64, u128);
2713 rev!(try_from_unbounded, isize, i8, i16, i32, i64);
2714 rev!(try_from_both_bounded, isize, i128);
2718 trait FromStrRadixHelper: PartialOrd + Copy {
2719 fn min_value() -> Self;
2720 fn max_value() -> Self;
2721 fn from_u32(u: u32) -> Self;
2722 fn checked_mul(&self, other: u32) -> Option<Self>;
2723 fn checked_sub(&self, other: u32) -> Option<Self>;
2724 fn checked_add(&self, other: u32) -> Option<Self>;
2728 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
2730 fn min_value() -> Self { Self::min_value() }
2732 fn max_value() -> Self { Self::max_value() }
2734 fn from_u32(u: u32) -> Self { u as Self }
2736 fn checked_mul(&self, other: u32) -> Option<Self> {
2737 Self::checked_mul(*self, other as Self)
2740 fn checked_sub(&self, other: u32) -> Option<Self> {
2741 Self::checked_sub(*self, other as Self)
2744 fn checked_add(&self, other: u32) -> Option<Self> {
2745 Self::checked_add(*self, other as Self)
2749 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
2751 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
2752 use self::IntErrorKind::*;
2753 use self::ParseIntError as PIE;
2755 assert!(radix >= 2 && radix <= 36,
2756 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2760 return Err(PIE { kind: Empty });
2763 let is_signed_ty = T::from_u32(0) > T::min_value();
2765 // all valid digits are ascii, so we will just iterate over the utf8 bytes
2766 // and cast them to chars. .to_digit() will safely return None for anything
2767 // other than a valid ascii digit for the given radix, including the first-byte
2768 // of multi-byte sequences
2769 let src = src.as_bytes();
2771 let (is_positive, digits) = match src[0] {
2772 b'+' => (true, &src[1..]),
2773 b'-' if is_signed_ty => (false, &src[1..]),
2777 if digits.is_empty() {
2778 return Err(PIE { kind: Empty });
2781 let mut result = T::from_u32(0);
2783 // The number is positive
2785 let x = match (c as char).to_digit(radix) {
2787 None => return Err(PIE { kind: InvalidDigit }),
2789 result = match result.checked_mul(radix) {
2790 Some(result) => result,
2791 None => return Err(PIE { kind: Overflow }),
2793 result = match result.checked_add(x) {
2794 Some(result) => result,
2795 None => return Err(PIE { kind: Overflow }),
2799 // The number is negative
2801 let x = match (c as char).to_digit(radix) {
2803 None => return Err(PIE { kind: InvalidDigit }),
2805 result = match result.checked_mul(radix) {
2806 Some(result) => result,
2807 None => return Err(PIE { kind: Underflow }),
2809 result = match result.checked_sub(x) {
2810 Some(result) => result,
2811 None => return Err(PIE { kind: Underflow }),
2818 /// An error which can be returned when parsing an integer.
2820 /// This error is used as the error type for the `from_str_radix()` functions
2821 /// on the primitive integer types, such as [`i8::from_str_radix`].
2823 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
2824 #[derive(Debug, Clone, PartialEq, Eq)]
2825 #[stable(feature = "rust1", since = "1.0.0")]
2826 pub struct ParseIntError {
2830 #[derive(Debug, Clone, PartialEq, Eq)]
2838 impl ParseIntError {
2839 #[unstable(feature = "int_error_internals",
2840 reason = "available through Error trait and this method should \
2841 not be exposed publicly",
2844 pub fn __description(&self) -> &str {
2846 IntErrorKind::Empty => "cannot parse integer from empty string",
2847 IntErrorKind::InvalidDigit => "invalid digit found in string",
2848 IntErrorKind::Overflow => "number too large to fit in target type",
2849 IntErrorKind::Underflow => "number too small to fit in target type",
2854 #[stable(feature = "rust1", since = "1.0.0")]
2855 impl fmt::Display for ParseIntError {
2856 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2857 self.__description().fmt(f)
2861 #[stable(feature = "rust1", since = "1.0.0")]
2862 pub use num::dec2flt::ParseFloatError;
2864 // Conversion traits for primitive integer and float types
2865 // Conversions T -> T are covered by a blanket impl and therefore excluded
2866 // Some conversions from and to usize/isize are not implemented due to portability concerns
2867 macro_rules! impl_from {
2868 ($Small: ty, $Large: ty, #[$attr:meta]) => {
2870 impl From<$Small> for $Large {
2872 fn from(small: $Small) -> $Large {
2879 // Unsigned -> Unsigned
2880 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2881 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2882 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2883 impl_from! { u8, u128, #[unstable(feature = "i128", issue = "35118")] }
2884 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2885 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2886 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2887 impl_from! { u16, u128, #[unstable(feature = "i128", issue = "35118")] }
2888 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2889 impl_from! { u32, u128, #[unstable(feature = "i128", issue = "35118")] }
2890 impl_from! { u64, u128, #[unstable(feature = "i128", issue = "35118")] }
2893 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2894 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2895 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2896 impl_from! { i8, i128, #[unstable(feature = "i128", issue = "35118")] }
2897 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2898 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2899 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2900 impl_from! { i16, i128, #[unstable(feature = "i128", issue = "35118")] }
2901 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2902 impl_from! { i32, i128, #[unstable(feature = "i128", issue = "35118")] }
2903 impl_from! { i64, i128, #[unstable(feature = "i128", issue = "35118")] }
2905 // Unsigned -> Signed
2906 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2907 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2908 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2909 impl_from! { u8, i128, #[unstable(feature = "i128", issue = "35118")] }
2910 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2911 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2912 impl_from! { u16, i128, #[unstable(feature = "i128", issue = "35118")] }
2913 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
2914 impl_from! { u32, i128, #[unstable(feature = "i128", issue = "35118")] }
2915 impl_from! { u64, i128, #[unstable(feature = "i128", issue = "35118")] }
2917 // Note: integers can only be represented with full precision in a float if
2918 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2919 // Lossy float conversions are not implemented at this time.
2922 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2923 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2924 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2925 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2926 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2928 // Unsigned -> Float
2929 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2930 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2931 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2932 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2933 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
2936 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }