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")]
17 use convert
::{From, TryFrom}
;
20 use marker
::{Copy, Sized}
;
22 use option
::Option
::{self, Some, None}
;
23 use result
::Result
::{self, Ok, Err}
;
24 use str::{FromStr, StrExt}
;
27 /// Provides intentionally-wrapped arithmetic on `T`.
29 /// Operations like `+` on `u32` values is intended to never overflow,
30 /// and in some debug configurations overflow is detected and results
31 /// in a panic. While most arithmetic falls into this category, some
32 /// code explicitly expects and relies upon modular arithmetic (e.g.,
35 /// Wrapping arithmetic can be achieved either through methods like
36 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
37 /// all standard arithmetic operations on the underlying value are
38 /// intended to have wrapping semantics.
43 /// use std::num::Wrapping;
45 /// let zero = Wrapping(0u32);
46 /// let one = Wrapping(1u32);
48 /// assert_eq!(std::u32::MAX, (zero - one).0);
50 #[stable(feature = "rust1", since = "1.0.0")]
51 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
52 pub struct Wrapping
<T
>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
54 #[stable(feature = "rust1", since = "1.0.0")]
55 impl<T
: fmt
::Debug
> fmt
::Debug
for Wrapping
<T
> {
56 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
61 #[stable(feature = "wrapping_display", since = "1.10.0")]
62 impl<T
: fmt
::Display
> fmt
::Display
for Wrapping
<T
> {
63 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
68 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
69 impl<T
: fmt
::Binary
> fmt
::Binary
for Wrapping
<T
> {
70 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
75 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
76 impl<T
: fmt
::Octal
> fmt
::Octal
for Wrapping
<T
> {
77 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
82 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
83 impl<T
: fmt
::LowerHex
> fmt
::LowerHex
for Wrapping
<T
> {
84 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
89 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
90 impl<T
: fmt
::UpperHex
> fmt
::UpperHex
for Wrapping
<T
> {
91 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
98 // All these modules are technically private and only exposed for libcoretest:
104 /// Types that have a "zero" value.
106 /// This trait is intended for use in conjunction with `Add`, as an identity:
107 /// `x + T::zero() == x`.
108 #[unstable(feature = "zero_one",
109 reason
= "unsure of placement, wants to use associated constants",
111 #[rustc_deprecated(since = "1.11.0", reason = "no longer used for \
113 pub trait Zero
: Sized
{
114 /// The "zero" (usually, additive identity) for this type.
118 /// Types that have a "one" value.
120 /// This trait is intended for use in conjunction with `Mul`, as an identity:
121 /// `x * T::one() == x`.
122 #[unstable(feature = "zero_one",
123 reason
= "unsure of placement, wants to use associated constants",
125 #[rustc_deprecated(since = "1.11.0", reason = "no longer used for \
127 pub trait One
: Sized
{
128 /// The "one" (usually, multiplicative identity) for this type.
132 macro_rules
! zero_one_impl
{
134 #[unstable(feature = "zero_one",
135 reason
= "unsure of placement, wants to use associated constants",
140 fn zero() -> Self { 0 }
142 #[unstable(feature = "zero_one",
143 reason
= "unsure of placement, wants to use associated constants",
148 fn one() -> Self { 1 }
152 zero_one_impl
! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
154 macro_rules
! zero_one_impl_float
{
156 #[unstable(feature = "zero_one",
157 reason
= "unsure of placement, wants to use associated constants",
162 fn zero() -> Self { 0.0 }
164 #[unstable(feature = "zero_one",
165 reason
= "unsure of placement, wants to use associated constants",
170 fn one() -> Self { 1.0 }
174 zero_one_impl_float
! { f32 f64 }
176 macro_rules
! checked_op
{
177 ($U
:ty
, $op
:path
, $x
:expr
, $y
:expr
) => {{
178 let (result
, overflowed
) = unsafe { $op($x as $U, $y as $U) }
;
179 if overflowed { None }
else { Some(result as Self) }
183 // `Int` + `SignedInt` implemented for signed integers
184 macro_rules
! int_impl
{
185 ($ActualT
:ident
, $UnsignedT
:ty
, $BITS
:expr
,
186 $add_with_overflow
:path
,
187 $sub_with_overflow
:path
,
188 $mul_with_overflow
:path
) => {
189 /// Returns the smallest value that can be represented by this integer type.
194 /// assert_eq!(i8::min_value(), -128);
196 #[stable(feature = "rust1", since = "1.0.0")]
198 pub const fn min_value() -> Self {
199 (-1 as Self) << ($BITS
- 1)
202 /// Returns the largest value that can be represented by this integer type.
207 /// assert_eq!(i8::max_value(), 127);
209 #[stable(feature = "rust1", since = "1.0.0")]
211 pub const fn max_value() -> Self {
215 /// Converts a string slice in a given base to an integer.
217 /// Leading and trailing whitespace represent an error.
224 /// assert_eq!(i32::from_str_radix("A", 16), Ok(10));
226 #[stable(feature = "rust1", since = "1.0.0")]
227 pub fn from_str_radix(src
: &str, radix
: u32) -> Result
<Self, ParseIntError
> {
228 from_str_radix(src
, radix
)
231 /// Returns the number of ones in the binary representation of `self`.
238 /// let n = -0b1000_0000i8;
240 /// assert_eq!(n.count_ones(), 1);
242 #[stable(feature = "rust1", since = "1.0.0")]
244 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
246 /// Returns the number of zeros in the binary representation of `self`.
253 /// let n = -0b1000_0000i8;
255 /// assert_eq!(n.count_zeros(), 7);
257 #[stable(feature = "rust1", since = "1.0.0")]
259 pub fn count_zeros(self) -> u32 {
263 /// Returns the number of leading zeros in the binary representation
273 /// assert_eq!(n.leading_zeros(), 0);
275 #[stable(feature = "rust1", since = "1.0.0")]
277 pub fn leading_zeros(self) -> u32 {
278 (self as $UnsignedT
).leading_zeros()
281 /// Returns the number of trailing zeros in the binary representation
291 /// assert_eq!(n.trailing_zeros(), 2);
293 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn trailing_zeros(self) -> u32 {
296 (self as $UnsignedT
).trailing_zeros()
299 /// Shifts the bits to the left by a specified amount, `n`,
300 /// wrapping the truncated bits to the end of the resulting integer.
302 /// Please note this isn't the same operation as `<<`!
309 /// let n = 0x0123456789ABCDEFi64;
310 /// let m = -0x76543210FEDCBA99i64;
312 /// assert_eq!(n.rotate_left(32), m);
314 #[stable(feature = "rust1", since = "1.0.0")]
316 pub fn rotate_left(self, n
: u32) -> Self {
317 (self as $UnsignedT
).rotate_left(n
) as Self
320 /// Shifts the bits to the right by a specified amount, `n`,
321 /// wrapping the truncated bits to the beginning of the resulting
324 /// Please note this isn't the same operation as `>>`!
331 /// let n = 0x0123456789ABCDEFi64;
332 /// let m = -0xFEDCBA987654322i64;
334 /// assert_eq!(n.rotate_right(4), m);
336 #[stable(feature = "rust1", since = "1.0.0")]
338 pub fn rotate_right(self, n
: u32) -> Self {
339 (self as $UnsignedT
).rotate_right(n
) as Self
342 /// Reverses the byte order of the integer.
349 /// let n = 0x0123456789ABCDEFi64;
350 /// let m = -0x1032547698BADCFFi64;
352 /// assert_eq!(n.swap_bytes(), m);
354 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn swap_bytes(self) -> Self {
357 (self as $UnsignedT
).swap_bytes() as Self
360 /// Converts an integer from big endian to the target's endianness.
362 /// On big endian this is a no-op. On little endian the bytes are
370 /// let n = 0x0123456789ABCDEFi64;
372 /// if cfg!(target_endian = "big") {
373 /// assert_eq!(i64::from_be(n), n)
375 /// assert_eq!(i64::from_be(n), n.swap_bytes())
378 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn from_be(x
: Self) -> Self {
381 if cfg
!(target_endian
= "big") { x }
else { x.swap_bytes() }
384 /// Converts an integer from little endian to the target's endianness.
386 /// On little endian this is a no-op. On big endian the bytes are
394 /// let n = 0x0123456789ABCDEFi64;
396 /// if cfg!(target_endian = "little") {
397 /// assert_eq!(i64::from_le(n), n)
399 /// assert_eq!(i64::from_le(n), n.swap_bytes())
402 #[stable(feature = "rust1", since = "1.0.0")]
404 pub fn from_le(x
: Self) -> Self {
405 if cfg
!(target_endian
= "little") { x }
else { x.swap_bytes() }
408 /// Converts `self` to big endian from the target's endianness.
410 /// On big endian this is a no-op. On little endian the bytes are
418 /// let n = 0x0123456789ABCDEFi64;
420 /// if cfg!(target_endian = "big") {
421 /// assert_eq!(n.to_be(), n)
423 /// assert_eq!(n.to_be(), n.swap_bytes())
426 #[stable(feature = "rust1", since = "1.0.0")]
428 pub fn to_be(self) -> Self { // or not to be?
429 if cfg
!(target_endian
= "big") { self }
else { self.swap_bytes() }
432 /// Converts `self` to little endian from the target's endianness.
434 /// On little endian this is a no-op. On big endian the bytes are
442 /// let n = 0x0123456789ABCDEFi64;
444 /// if cfg!(target_endian = "little") {
445 /// assert_eq!(n.to_le(), n)
447 /// assert_eq!(n.to_le(), n.swap_bytes())
450 #[stable(feature = "rust1", since = "1.0.0")]
452 pub fn to_le(self) -> Self {
453 if cfg
!(target_endian
= "little") { self }
else { self.swap_bytes() }
456 /// Checked integer addition. Computes `self + other`, returning `None`
457 /// if overflow occurred.
464 /// assert_eq!(7i16.checked_add(32760), Some(32767));
465 /// assert_eq!(8i16.checked_add(32760), None);
467 #[stable(feature = "rust1", since = "1.0.0")]
469 pub fn checked_add(self, other
: Self) -> Option
<Self> {
470 let (a
, b
) = self.overflowing_add(other
);
471 if b {None}
else {Some(a)}
474 /// Checked integer subtraction. Computes `self - other`, returning
475 /// `None` if underflow occurred.
482 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
483 /// assert_eq!((-128i8).checked_sub(1), None);
485 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn checked_sub(self, other
: Self) -> Option
<Self> {
488 let (a
, b
) = self.overflowing_sub(other
);
489 if b {None}
else {Some(a)}
492 /// Checked integer multiplication. Computes `self * other`, returning
493 /// `None` if underflow or overflow occurred.
500 /// assert_eq!(6i8.checked_mul(21), Some(126));
501 /// assert_eq!(6i8.checked_mul(22), None);
503 #[stable(feature = "rust1", since = "1.0.0")]
505 pub fn checked_mul(self, other
: Self) -> Option
<Self> {
506 let (a
, b
) = self.overflowing_mul(other
);
507 if b {None}
else {Some(a)}
510 /// Checked integer division. Computes `self / other`, returning `None`
511 /// if `other == 0` or the operation results in underflow or overflow.
518 /// assert_eq!((-127i8).checked_div(-1), Some(127));
519 /// assert_eq!((-128i8).checked_div(-1), None);
520 /// assert_eq!((1i8).checked_div(0), None);
522 #[stable(feature = "rust1", since = "1.0.0")]
524 pub fn checked_div(self, other
: Self) -> Option
<Self> {
528 let (a
, b
) = self.overflowing_div(other
);
529 if b {None}
else {Some(a)}
533 /// Checked integer remainder. Computes `self % other`, returning `None`
534 /// if `other == 0` or the operation results in underflow or overflow.
543 /// assert_eq!(5i32.checked_rem(2), Some(1));
544 /// assert_eq!(5i32.checked_rem(0), None);
545 /// assert_eq!(i32::MIN.checked_rem(-1), None);
547 #[stable(feature = "wrapping", since = "1.7.0")]
549 pub fn checked_rem(self, other
: Self) -> Option
<Self> {
553 let (a
, b
) = self.overflowing_rem(other
);
554 if b {None}
else {Some(a)}
558 /// Checked negation. Computes `-self`, returning `None` if `self ==
568 /// assert_eq!(5i32.checked_neg(), Some(-5));
569 /// assert_eq!(i32::MIN.checked_neg(), None);
571 #[stable(feature = "wrapping", since = "1.7.0")]
573 pub fn checked_neg(self) -> Option
<Self> {
574 let (a
, b
) = self.overflowing_neg();
575 if b {None}
else {Some(a)}
578 /// Checked shift left. Computes `self << rhs`, returning `None`
579 /// if `rhs` is larger than or equal to the number of bits in `self`.
586 /// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
587 /// assert_eq!(0x10i32.checked_shl(33), None);
589 #[stable(feature = "wrapping", since = "1.7.0")]
591 pub fn checked_shl(self, rhs
: u32) -> Option
<Self> {
592 let (a
, b
) = self.overflowing_shl(rhs
);
593 if b {None}
else {Some(a)}
596 /// Checked shift right. Computes `self >> rhs`, returning `None`
597 /// if `rhs` is larger than or equal to the number of bits in `self`.
604 /// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
605 /// assert_eq!(0x10i32.checked_shr(33), None);
607 #[stable(feature = "wrapping", since = "1.7.0")]
609 pub fn checked_shr(self, rhs
: u32) -> Option
<Self> {
610 let (a
, b
) = self.overflowing_shr(rhs
);
611 if b {None}
else {Some(a)}
614 /// Checked absolute value. Computes `self.abs()`, returning `None` if
622 /// # #![feature(no_panic_abs)]
626 /// assert_eq!((-5i32).checked_abs(), Some(5));
627 /// assert_eq!(i32::MIN.checked_abs(), None);
629 #[unstable(feature = "no_panic_abs", issue = "35057")]
631 pub fn checked_abs(self) -> Option
<Self> {
632 if self.is_negative() {
639 /// Saturating integer addition. Computes `self + other`, saturating at
640 /// the numeric bounds instead of overflowing.
647 /// assert_eq!(100i8.saturating_add(1), 101);
648 /// assert_eq!(100i8.saturating_add(127), 127);
650 #[stable(feature = "rust1", since = "1.0.0")]
652 pub fn saturating_add(self, other
: Self) -> Self {
653 match self.checked_add(other
) {
655 None
if other
>= 0 => Self::max_value(),
656 None
=> Self::min_value(),
660 /// Saturating integer subtraction. Computes `self - other`, saturating
661 /// at the numeric bounds instead of overflowing.
668 /// assert_eq!(100i8.saturating_sub(127), -27);
669 /// assert_eq!((-100i8).saturating_sub(127), -128);
671 #[stable(feature = "rust1", since = "1.0.0")]
673 pub fn saturating_sub(self, other
: Self) -> Self {
674 match self.checked_sub(other
) {
676 None
if other
>= 0 => Self::min_value(),
677 None
=> Self::max_value(),
681 /// Saturating integer multiplication. Computes `self * other`,
682 /// saturating at the numeric bounds instead of overflowing.
691 /// assert_eq!(100i32.saturating_mul(127), 12700);
692 /// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
693 /// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
695 #[stable(feature = "wrapping", since = "1.7.0")]
697 pub fn saturating_mul(self, other
: Self) -> Self {
698 self.checked_mul(other
).unwrap_or_else(|| {
699 if (self < 0 && other
< 0) || (self > 0 && other
> 0) {
707 /// Wrapping (modular) addition. Computes `self + other`,
708 /// wrapping around at the boundary of the type.
715 /// assert_eq!(100i8.wrapping_add(27), 127);
716 /// assert_eq!(100i8.wrapping_add(127), -29);
718 #[stable(feature = "rust1", since = "1.0.0")]
720 pub fn wrapping_add(self, rhs
: Self) -> Self {
722 intrinsics
::overflowing_add(self, rhs
)
726 /// Wrapping (modular) subtraction. Computes `self - other`,
727 /// wrapping around at the boundary of the type.
734 /// assert_eq!(0i8.wrapping_sub(127), -127);
735 /// assert_eq!((-2i8).wrapping_sub(127), 127);
737 #[stable(feature = "rust1", since = "1.0.0")]
739 pub fn wrapping_sub(self, rhs
: Self) -> Self {
741 intrinsics
::overflowing_sub(self, rhs
)
745 /// Wrapping (modular) multiplication. Computes `self *
746 /// other`, wrapping around at the boundary of the type.
753 /// assert_eq!(10i8.wrapping_mul(12), 120);
754 /// assert_eq!(11i8.wrapping_mul(12), -124);
756 #[stable(feature = "rust1", since = "1.0.0")]
758 pub fn wrapping_mul(self, rhs
: Self) -> Self {
760 intrinsics
::overflowing_mul(self, rhs
)
764 /// Wrapping (modular) division. Computes `self / other`,
765 /// wrapping around at the boundary of the type.
767 /// The only case where such wrapping can occur is when one
768 /// divides `MIN / -1` on a signed type (where `MIN` is the
769 /// negative minimal value for the type); this is equivalent
770 /// to `-MIN`, a positive value that is too large to represent
771 /// in the type. In such a case, this function returns `MIN`
776 /// This function will panic if `rhs` is 0.
783 /// assert_eq!(100u8.wrapping_div(10), 10);
784 /// assert_eq!((-128i8).wrapping_div(-1), -128);
786 #[stable(feature = "num_wrapping", since = "1.2.0")]
788 pub fn wrapping_div(self, rhs
: Self) -> Self {
789 self.overflowing_div(rhs
).0
792 /// Wrapping (modular) remainder. Computes `self % other`,
793 /// wrapping around at the boundary of the type.
795 /// Such wrap-around never actually occurs mathematically;
796 /// implementation artifacts make `x % y` invalid for `MIN /
797 /// -1` on a signed type (where `MIN` is the negative
798 /// minimal value). In such a case, this function returns `0`.
802 /// This function will panic if `rhs` is 0.
809 /// assert_eq!(100i8.wrapping_rem(10), 0);
810 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
812 #[stable(feature = "num_wrapping", since = "1.2.0")]
814 pub fn wrapping_rem(self, rhs
: Self) -> Self {
815 self.overflowing_rem(rhs
).0
818 /// Wrapping (modular) negation. Computes `-self`,
819 /// wrapping around at the boundary of the type.
821 /// The only case where such wrapping can occur is when one
822 /// negates `MIN` on a signed type (where `MIN` is the
823 /// negative minimal value for the type); this is a positive
824 /// value that is too large to represent in the type. In such
825 /// a case, this function returns `MIN` itself.
832 /// assert_eq!(100i8.wrapping_neg(), -100);
833 /// assert_eq!((-128i8).wrapping_neg(), -128);
835 #[stable(feature = "num_wrapping", since = "1.2.0")]
837 pub fn wrapping_neg(self) -> Self {
838 self.overflowing_neg().0
841 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
842 /// where `mask` removes any high-order bits of `rhs` that
843 /// would cause the shift to exceed the bitwidth of the type.
845 /// Note that this is *not* the same as a rotate-left; the
846 /// RHS of a wrapping shift-left is restricted to the range
847 /// of the type, rather than the bits shifted out of the LHS
848 /// being returned to the other end. The primitive integer
849 /// types all implement a `rotate_left` function, which may
850 /// be what you want instead.
857 /// assert_eq!((-1i8).wrapping_shl(7), -128);
858 /// assert_eq!((-1i8).wrapping_shl(8), -1);
860 #[stable(feature = "num_wrapping", since = "1.2.0")]
862 pub fn wrapping_shl(self, rhs
: u32) -> Self {
863 self.overflowing_shl(rhs
).0
866 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
867 /// where `mask` removes any high-order bits of `rhs` that
868 /// would cause the shift to exceed the bitwidth of the type.
870 /// Note that this is *not* the same as a rotate-right; the
871 /// RHS of a wrapping shift-right is restricted to the range
872 /// of the type, rather than the bits shifted out of the LHS
873 /// being returned to the other end. The primitive integer
874 /// types all implement a `rotate_right` function, which may
875 /// be what you want instead.
882 /// assert_eq!((-128i8).wrapping_shr(7), -1);
883 /// assert_eq!((-128i8).wrapping_shr(8), -128);
885 #[stable(feature = "num_wrapping", since = "1.2.0")]
887 pub fn wrapping_shr(self, rhs
: u32) -> Self {
888 self.overflowing_shr(rhs
).0
891 /// Wrapping (modular) absolute value. Computes `self.abs()`,
892 /// wrapping around at the boundary of the type.
894 /// The only case where such wrapping can occur is when one takes
895 /// the absolute value of the negative minimal value for the type
896 /// this is a positive value that is too large to represent in the
897 /// type. In such a case, this function returns `MIN` itself.
904 /// # #![feature(no_panic_abs)]
906 /// assert_eq!(100i8.wrapping_abs(), 100);
907 /// assert_eq!((-100i8).wrapping_abs(), 100);
908 /// assert_eq!((-128i8).wrapping_abs(), -128);
909 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
911 #[unstable(feature = "no_panic_abs", issue = "35057")]
913 pub fn wrapping_abs(self) -> Self {
914 if self.is_negative() {
921 /// Calculates `self` + `rhs`
923 /// Returns a tuple of the addition along with a boolean indicating
924 /// whether an arithmetic overflow would occur. If an overflow would
925 /// have occurred then the wrapped value is returned.
934 /// assert_eq!(5i32.overflowing_add(2), (7, false));
935 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
938 #[stable(feature = "wrapping", since = "1.7.0")]
939 pub fn overflowing_add(self, rhs
: Self) -> (Self, bool
) {
941 let (a
, b
) = $
add_with_overflow(self as $ActualT
,
947 /// Calculates `self` - `rhs`
949 /// Returns a tuple of the subtraction along with a boolean indicating
950 /// whether an arithmetic overflow would occur. If an overflow would
951 /// have occurred then the wrapped value is returned.
960 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
961 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
964 #[stable(feature = "wrapping", since = "1.7.0")]
965 pub fn overflowing_sub(self, rhs
: Self) -> (Self, bool
) {
967 let (a
, b
) = $
sub_with_overflow(self as $ActualT
,
973 /// Calculates the multiplication of `self` and `rhs`.
975 /// Returns a tuple of the multiplication along with a boolean
976 /// indicating whether an arithmetic overflow would occur. If an
977 /// overflow would have occurred then the wrapped value is returned.
984 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
985 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
988 #[stable(feature = "wrapping", since = "1.7.0")]
989 pub fn overflowing_mul(self, rhs
: Self) -> (Self, bool
) {
991 let (a
, b
) = $
mul_with_overflow(self as $ActualT
,
997 /// Calculates the divisor when `self` is divided by `rhs`.
999 /// Returns a tuple of the divisor along with a boolean indicating
1000 /// whether an arithmetic overflow would occur. If an overflow would
1001 /// occur then self is returned.
1005 /// This function will panic if `rhs` is 0.
1014 /// assert_eq!(5i32.overflowing_div(2), (2, false));
1015 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
1018 #[stable(feature = "wrapping", since = "1.7.0")]
1019 pub fn overflowing_div(self, rhs
: Self) -> (Self, bool
) {
1020 if self == Self::min_value() && rhs
== -1 {
1027 /// Calculates the remainder when `self` is divided by `rhs`.
1029 /// Returns a tuple of the remainder after dividing along with a boolean
1030 /// indicating whether an arithmetic overflow would occur. If an
1031 /// overflow would occur then 0 is returned.
1035 /// This function will panic if `rhs` is 0.
1044 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
1045 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
1048 #[stable(feature = "wrapping", since = "1.7.0")]
1049 pub fn overflowing_rem(self, rhs
: Self) -> (Self, bool
) {
1050 if self == Self::min_value() && rhs
== -1 {
1057 /// Negates self, overflowing if this is equal to the minimum value.
1059 /// Returns a tuple of the negated version of self along with a boolean
1060 /// indicating whether an overflow happened. If `self` is the minimum
1061 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
1062 /// value will be returned again and `true` will be returned for an
1063 /// overflow happening.
1072 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
1073 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
1076 #[stable(feature = "wrapping", since = "1.7.0")]
1077 pub fn overflowing_neg(self) -> (Self, bool
) {
1078 if self == Self::min_value() {
1079 (Self::min_value(), true)
1085 /// Shifts self left by `rhs` bits.
1087 /// Returns a tuple of the shifted version of self along with a boolean
1088 /// indicating whether the shift value was larger than or equal to the
1089 /// number of bits. If the shift value is too large, then value is
1090 /// masked (N-1) where N is the number of bits, and this value is then
1091 /// used to perform the shift.
1098 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
1099 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
1102 #[stable(feature = "wrapping", since = "1.7.0")]
1103 pub fn overflowing_shl(self, rhs
: u32) -> (Self, bool
) {
1104 (self << (rhs
& ($BITS
- 1)), (rhs
> ($BITS
- 1)))
1107 /// Shifts self right by `rhs` bits.
1109 /// Returns a tuple of the shifted version of self along with a boolean
1110 /// indicating whether the shift value was larger than or equal to the
1111 /// number of bits. If the shift value is too large, then value is
1112 /// masked (N-1) where N is the number of bits, and this value is then
1113 /// used to perform the shift.
1120 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
1121 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1124 #[stable(feature = "wrapping", since = "1.7.0")]
1125 pub fn overflowing_shr(self, rhs
: u32) -> (Self, bool
) {
1126 (self >> (rhs
& ($BITS
- 1)), (rhs
> ($BITS
- 1)))
1129 /// Computes the absolute value of `self`.
1131 /// Returns a tuple of the absolute version of self along with a
1132 /// boolean indicating whether an overflow happened. If self is the
1133 /// minimum value (e.g. i32::MIN for values of type i32), then the
1134 /// minimum value will be returned again and true will be returned for
1135 /// an overflow happening.
1142 /// # #![feature(no_panic_abs)]
1144 /// assert_eq!(10i8.overflowing_abs(), (10,false));
1145 /// assert_eq!((-10i8).overflowing_abs(), (10,false));
1146 /// assert_eq!((-128i8).overflowing_abs(), (-128,true));
1148 #[unstable(feature = "no_panic_abs", issue = "35057")]
1150 pub fn overflowing_abs(self) -> (Self, bool
) {
1151 if self.is_negative() {
1152 self.overflowing_neg()
1158 /// Raises self to the power of `exp`, using exponentiation by squaring.
1165 /// let x: i32 = 2; // or any other integer type
1167 /// assert_eq!(x.pow(4), 16);
1169 #[stable(feature = "rust1", since = "1.0.0")]
1171 #[rustc_inherit_overflow_checks]
1172 pub fn pow(self, mut exp
: u32) -> Self {
1173 let mut base
= self;
1184 // Deal with the final bit of the exponent separately, since
1185 // squaring the base afterwards is not necessary and may cause a
1186 // needless overflow.
1194 /// Computes the absolute value of `self`.
1196 /// # Overflow behavior
1198 /// The absolute value of `i32::min_value()` cannot be represented as an
1199 /// `i32`, and attempting to calculate it will cause an overflow. This
1200 /// means that code in debug mode will trigger a panic on this case and
1201 /// optimized code will return `i32::min_value()` without a panic.
1208 /// assert_eq!(10i8.abs(), 10);
1209 /// assert_eq!((-10i8).abs(), 10);
1211 #[stable(feature = "rust1", since = "1.0.0")]
1213 #[rustc_inherit_overflow_checks]
1214 pub fn abs(self) -> Self {
1215 if self.is_negative() {
1216 // Note that the #[inline] above means that the overflow
1217 // semantics of this negation depend on the crate we're being
1225 /// Returns a number representing sign of `self`.
1227 /// - `0` if the number is zero
1228 /// - `1` if the number is positive
1229 /// - `-1` if the number is negative
1236 /// assert_eq!(10i8.signum(), 1);
1237 /// assert_eq!(0i8.signum(), 0);
1238 /// assert_eq!((-10i8).signum(), -1);
1240 #[stable(feature = "rust1", since = "1.0.0")]
1242 pub fn signum(self) -> Self {
1250 /// Returns `true` if `self` is positive and `false` if the number
1251 /// is zero or negative.
1258 /// assert!(10i8.is_positive());
1259 /// assert!(!(-10i8).is_positive());
1261 #[stable(feature = "rust1", since = "1.0.0")]
1263 pub fn is_positive(self) -> bool { self > 0 }
1265 /// Returns `true` if `self` is negative and `false` if the number
1266 /// is zero or positive.
1273 /// assert!((-10i8).is_negative());
1274 /// assert!(!10i8.is_negative());
1276 #[stable(feature = "rust1", since = "1.0.0")]
1278 pub fn is_negative(self) -> bool { self < 0 }
1284 int_impl
! { i8, u8, 8,
1285 intrinsics
::add_with_overflow
,
1286 intrinsics
::sub_with_overflow
,
1287 intrinsics
::mul_with_overflow
}
1292 int_impl
! { i16, u16, 16,
1293 intrinsics
::add_with_overflow
,
1294 intrinsics
::sub_with_overflow
,
1295 intrinsics
::mul_with_overflow
}
1300 int_impl
! { i32, u32, 32,
1301 intrinsics
::add_with_overflow
,
1302 intrinsics
::sub_with_overflow
,
1303 intrinsics
::mul_with_overflow
}
1308 int_impl
! { i64, u64, 64,
1309 intrinsics
::add_with_overflow
,
1310 intrinsics
::sub_with_overflow
,
1311 intrinsics
::mul_with_overflow
}
1314 #[cfg(target_pointer_width = "16")]
1317 int_impl
! { i16, u16, 16,
1318 intrinsics
::add_with_overflow
,
1319 intrinsics
::sub_with_overflow
,
1320 intrinsics
::mul_with_overflow
}
1323 #[cfg(target_pointer_width = "32")]
1326 int_impl
! { i32, u32, 32,
1327 intrinsics
::add_with_overflow
,
1328 intrinsics
::sub_with_overflow
,
1329 intrinsics
::mul_with_overflow
}
1332 #[cfg(target_pointer_width = "64")]
1335 int_impl
! { i64, u64, 64,
1336 intrinsics
::add_with_overflow
,
1337 intrinsics
::sub_with_overflow
,
1338 intrinsics
::mul_with_overflow
}
1341 // `Int` + `UnsignedInt` implemented for unsigned integers
1342 macro_rules
! uint_impl
{
1343 ($ActualT
:ty
, $BITS
:expr
,
1348 $add_with_overflow
:path
,
1349 $sub_with_overflow
:path
,
1350 $mul_with_overflow
:path
) => {
1351 /// Returns the smallest value that can be represented by this integer type.
1356 /// assert_eq!(u8::min_value(), 0);
1358 #[stable(feature = "rust1", since = "1.0.0")]
1360 pub const fn min_value() -> Self { 0 }
1362 /// Returns the largest value that can be represented by this integer type.
1367 /// assert_eq!(u8::max_value(), 255);
1369 #[stable(feature = "rust1", since = "1.0.0")]
1371 pub const fn max_value() -> Self { !0 }
1373 /// Converts a string slice in a given base to an integer.
1375 /// Leading and trailing whitespace represent an error.
1382 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 pub fn from_str_radix(src
: &str, radix
: u32) -> Result
<Self, ParseIntError
> {
1386 from_str_radix(src
, radix
)
1389 /// Returns the number of ones in the binary representation of `self`.
1396 /// let n = 0b01001100u8;
1398 /// assert_eq!(n.count_ones(), 3);
1400 #[stable(feature = "rust1", since = "1.0.0")]
1402 pub fn count_ones(self) -> u32 {
1403 unsafe { $ctpop(self as $ActualT) as u32 }
1406 /// Returns the number of zeros in the binary representation of `self`.
1413 /// let n = 0b01001100u8;
1415 /// assert_eq!(n.count_zeros(), 5);
1417 #[stable(feature = "rust1", since = "1.0.0")]
1419 pub fn count_zeros(self) -> u32 {
1420 (!self).count_ones()
1423 /// Returns the number of leading zeros in the binary representation
1431 /// let n = 0b0101000u16;
1433 /// assert_eq!(n.leading_zeros(), 10);
1435 #[stable(feature = "rust1", since = "1.0.0")]
1437 pub fn leading_zeros(self) -> u32 {
1438 unsafe { $ctlz(self as $ActualT) as u32 }
1441 /// Returns the number of trailing zeros in the binary representation
1449 /// let n = 0b0101000u16;
1451 /// assert_eq!(n.trailing_zeros(), 3);
1453 #[stable(feature = "rust1", since = "1.0.0")]
1455 pub fn trailing_zeros(self) -> u32 {
1456 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1457 // emits two conditional moves on x86_64. By promoting the value to
1458 // u16 and setting bit 8, we get better code without any conditional
1460 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1461 // pending, remove this workaround once LLVM generates better code
1465 intrinsics
::cttz(self as u16 | 0x100) as u32
1467 intrinsics
::cttz(self) as u32
1472 /// Shifts the bits to the left by a specified amount, `n`,
1473 /// wrapping the truncated bits to the end of the resulting integer.
1475 /// Please note this isn't the same operation as `<<`!
1482 /// let n = 0x0123456789ABCDEFu64;
1483 /// let m = 0x3456789ABCDEF012u64;
1485 /// assert_eq!(n.rotate_left(12), m);
1487 #[stable(feature = "rust1", since = "1.0.0")]
1489 pub fn rotate_left(self, n
: u32) -> Self {
1490 // Protect against undefined behaviour for over-long bit shifts
1492 (self << n
) | (self >> (($BITS
- n
) % $BITS
))
1495 /// Shifts the bits to the right by a specified amount, `n`,
1496 /// wrapping the truncated bits to the beginning of the resulting
1499 /// Please note this isn't the same operation as `>>`!
1506 /// let n = 0x0123456789ABCDEFu64;
1507 /// let m = 0xDEF0123456789ABCu64;
1509 /// assert_eq!(n.rotate_right(12), m);
1511 #[stable(feature = "rust1", since = "1.0.0")]
1513 pub fn rotate_right(self, n
: u32) -> Self {
1514 // Protect against undefined behaviour for over-long bit shifts
1516 (self >> n
) | (self << (($BITS
- n
) % $BITS
))
1519 /// Reverses the byte order of the integer.
1526 /// let n = 0x0123456789ABCDEFu64;
1527 /// let m = 0xEFCDAB8967452301u64;
1529 /// assert_eq!(n.swap_bytes(), m);
1531 #[stable(feature = "rust1", since = "1.0.0")]
1533 pub fn swap_bytes(self) -> Self {
1534 unsafe { $bswap(self as $ActualT) as Self }
1537 /// Converts an integer from big endian to the target's endianness.
1539 /// On big endian this is a no-op. On little endian the bytes are
1547 /// let n = 0x0123456789ABCDEFu64;
1549 /// if cfg!(target_endian = "big") {
1550 /// assert_eq!(u64::from_be(n), n)
1552 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1555 #[stable(feature = "rust1", since = "1.0.0")]
1557 pub fn from_be(x
: Self) -> Self {
1558 if cfg
!(target_endian
= "big") { x }
else { x.swap_bytes() }
1561 /// Converts an integer from little endian to the target's endianness.
1563 /// On little endian this is a no-op. On big endian the bytes are
1571 /// let n = 0x0123456789ABCDEFu64;
1573 /// if cfg!(target_endian = "little") {
1574 /// assert_eq!(u64::from_le(n), n)
1576 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1579 #[stable(feature = "rust1", since = "1.0.0")]
1581 pub fn from_le(x
: Self) -> Self {
1582 if cfg
!(target_endian
= "little") { x }
else { x.swap_bytes() }
1585 /// Converts `self` to big endian from the target's endianness.
1587 /// On big endian this is a no-op. On little endian the bytes are
1595 /// let n = 0x0123456789ABCDEFu64;
1597 /// if cfg!(target_endian = "big") {
1598 /// assert_eq!(n.to_be(), n)
1600 /// assert_eq!(n.to_be(), n.swap_bytes())
1603 #[stable(feature = "rust1", since = "1.0.0")]
1605 pub fn to_be(self) -> Self { // or not to be?
1606 if cfg
!(target_endian
= "big") { self }
else { self.swap_bytes() }
1609 /// Converts `self` to little endian from the target's endianness.
1611 /// On little endian this is a no-op. On big endian the bytes are
1619 /// let n = 0x0123456789ABCDEFu64;
1621 /// if cfg!(target_endian = "little") {
1622 /// assert_eq!(n.to_le(), n)
1624 /// assert_eq!(n.to_le(), n.swap_bytes())
1627 #[stable(feature = "rust1", since = "1.0.0")]
1629 pub fn to_le(self) -> Self {
1630 if cfg
!(target_endian
= "little") { self }
else { self.swap_bytes() }
1633 /// Checked integer addition. Computes `self + other`, returning `None`
1634 /// if overflow occurred.
1641 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1642 /// assert_eq!(6u16.checked_add(65530), None);
1644 #[stable(feature = "rust1", since = "1.0.0")]
1646 pub fn checked_add(self, other
: Self) -> Option
<Self> {
1647 let (a
, b
) = self.overflowing_add(other
);
1648 if b {None}
else {Some(a)}
1651 /// Checked integer subtraction. Computes `self - other`, returning
1652 /// `None` if underflow occurred.
1659 /// assert_eq!(1u8.checked_sub(1), Some(0));
1660 /// assert_eq!(0u8.checked_sub(1), None);
1662 #[stable(feature = "rust1", since = "1.0.0")]
1664 pub fn checked_sub(self, other
: Self) -> Option
<Self> {
1665 let (a
, b
) = self.overflowing_sub(other
);
1666 if b {None}
else {Some(a)}
1669 /// Checked integer multiplication. Computes `self * other`, returning
1670 /// `None` if underflow or overflow occurred.
1677 /// assert_eq!(5u8.checked_mul(51), Some(255));
1678 /// assert_eq!(5u8.checked_mul(52), None);
1680 #[stable(feature = "rust1", since = "1.0.0")]
1682 pub fn checked_mul(self, other
: Self) -> Option
<Self> {
1683 let (a
, b
) = self.overflowing_mul(other
);
1684 if b {None}
else {Some(a)}
1687 /// Checked integer division. Computes `self / other`, returning `None`
1688 /// if `other == 0` or the operation results in underflow or overflow.
1695 /// assert_eq!(128u8.checked_div(2), Some(64));
1696 /// assert_eq!(1u8.checked_div(0), None);
1698 #[stable(feature = "rust1", since = "1.0.0")]
1700 pub fn checked_div(self, other
: Self) -> Option
<Self> {
1703 other
=> Some(self / other
),
1707 /// Checked integer remainder. Computes `self % other`, returning `None`
1708 /// if `other == 0` or the operation results in underflow or overflow.
1715 /// assert_eq!(5u32.checked_rem(2), Some(1));
1716 /// assert_eq!(5u32.checked_rem(0), None);
1718 #[stable(feature = "wrapping", since = "1.7.0")]
1720 pub fn checked_rem(self, other
: Self) -> Option
<Self> {
1728 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1731 /// Note that negating any positive integer will overflow.
1738 /// assert_eq!(0u32.checked_neg(), Some(0));
1739 /// assert_eq!(1u32.checked_neg(), None);
1741 #[stable(feature = "wrapping", since = "1.7.0")]
1743 pub fn checked_neg(self) -> Option
<Self> {
1744 let (a
, b
) = self.overflowing_neg();
1745 if b {None}
else {Some(a)}
1748 /// Checked shift left. Computes `self << rhs`, returning `None`
1749 /// if `rhs` is larger than or equal to the number of bits in `self`.
1756 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1757 /// assert_eq!(0x10u32.checked_shl(33), None);
1759 #[stable(feature = "wrapping", since = "1.7.0")]
1761 pub fn checked_shl(self, rhs
: u32) -> Option
<Self> {
1762 let (a
, b
) = self.overflowing_shl(rhs
);
1763 if b {None}
else {Some(a)}
1766 /// Checked shift right. Computes `self >> rhs`, returning `None`
1767 /// if `rhs` is larger than or equal to the number of bits in `self`.
1774 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1775 /// assert_eq!(0x10u32.checked_shr(33), None);
1777 #[stable(feature = "wrapping", since = "1.7.0")]
1779 pub fn checked_shr(self, rhs
: u32) -> Option
<Self> {
1780 let (a
, b
) = self.overflowing_shr(rhs
);
1781 if b {None}
else {Some(a)}
1784 /// Saturating integer addition. Computes `self + other`, saturating at
1785 /// the numeric bounds instead of overflowing.
1792 /// assert_eq!(100u8.saturating_add(1), 101);
1793 /// assert_eq!(200u8.saturating_add(127), 255);
1795 #[stable(feature = "rust1", since = "1.0.0")]
1797 pub fn saturating_add(self, other
: Self) -> Self {
1798 match self.checked_add(other
) {
1800 None
=> Self::max_value(),
1804 /// Saturating integer subtraction. Computes `self - other`, saturating
1805 /// at the numeric bounds instead of overflowing.
1812 /// assert_eq!(100u8.saturating_sub(27), 73);
1813 /// assert_eq!(13u8.saturating_sub(127), 0);
1815 #[stable(feature = "rust1", since = "1.0.0")]
1817 pub fn saturating_sub(self, other
: Self) -> Self {
1818 match self.checked_sub(other
) {
1820 None
=> Self::min_value(),
1824 /// Saturating integer multiplication. Computes `self * other`,
1825 /// saturating at the numeric bounds instead of overflowing.
1834 /// assert_eq!(100u32.saturating_mul(127), 12700);
1835 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1837 #[stable(feature = "wrapping", since = "1.7.0")]
1839 pub fn saturating_mul(self, other
: Self) -> Self {
1840 self.checked_mul(other
).unwrap_or(Self::max_value())
1843 /// Wrapping (modular) addition. Computes `self + other`,
1844 /// wrapping around at the boundary of the type.
1851 /// assert_eq!(200u8.wrapping_add(55), 255);
1852 /// assert_eq!(200u8.wrapping_add(155), 99);
1854 #[stable(feature = "rust1", since = "1.0.0")]
1856 pub fn wrapping_add(self, rhs
: Self) -> Self {
1858 intrinsics
::overflowing_add(self, rhs
)
1862 /// Wrapping (modular) subtraction. Computes `self - other`,
1863 /// wrapping around at the boundary of the type.
1870 /// assert_eq!(100u8.wrapping_sub(100), 0);
1871 /// assert_eq!(100u8.wrapping_sub(155), 201);
1873 #[stable(feature = "rust1", since = "1.0.0")]
1875 pub fn wrapping_sub(self, rhs
: Self) -> Self {
1877 intrinsics
::overflowing_sub(self, rhs
)
1881 /// Wrapping (modular) multiplication. Computes `self *
1882 /// other`, wrapping around at the boundary of the type.
1889 /// assert_eq!(10u8.wrapping_mul(12), 120);
1890 /// assert_eq!(25u8.wrapping_mul(12), 44);
1892 #[stable(feature = "rust1", since = "1.0.0")]
1894 pub fn wrapping_mul(self, rhs
: Self) -> Self {
1896 intrinsics
::overflowing_mul(self, rhs
)
1900 /// Wrapping (modular) division. Computes `self / other`.
1901 /// Wrapped division on unsigned types is just normal division.
1902 /// There's no way wrapping could ever happen.
1903 /// This function exists, so that all operations
1904 /// are accounted for in the wrapping operations.
1911 /// assert_eq!(100u8.wrapping_div(10), 10);
1913 #[stable(feature = "num_wrapping", since = "1.2.0")]
1915 pub fn wrapping_div(self, rhs
: Self) -> Self {
1919 /// Wrapping (modular) remainder. Computes `self % other`.
1920 /// Wrapped remainder calculation on unsigned types is
1921 /// just the regular remainder calculation.
1922 /// There's no way wrapping could ever happen.
1923 /// This function exists, so that all operations
1924 /// are accounted for in the wrapping operations.
1931 /// assert_eq!(100u8.wrapping_rem(10), 0);
1933 #[stable(feature = "num_wrapping", since = "1.2.0")]
1935 pub fn wrapping_rem(self, rhs
: Self) -> Self {
1939 /// Wrapping (modular) negation. Computes `-self`,
1940 /// wrapping around at the boundary of the type.
1942 /// Since unsigned types do not have negative equivalents
1943 /// all applications of this function will wrap (except for `-0`).
1944 /// For values smaller than the corresponding signed type's maximum
1945 /// the result is the same as casting the corresponding signed value.
1946 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1947 /// `MAX` is the corresponding signed type's maximum.
1954 /// assert_eq!(100u8.wrapping_neg(), 156);
1955 /// assert_eq!(0u8.wrapping_neg(), 0);
1956 /// assert_eq!(180u8.wrapping_neg(), 76);
1957 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1959 #[stable(feature = "num_wrapping", since = "1.2.0")]
1961 pub fn wrapping_neg(self) -> Self {
1962 self.overflowing_neg().0
1965 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1966 /// where `mask` removes any high-order bits of `rhs` that
1967 /// would cause the shift to exceed the bitwidth of the type.
1969 /// Note that this is *not* the same as a rotate-left; the
1970 /// RHS of a wrapping shift-left is restricted to the range
1971 /// of the type, rather than the bits shifted out of the LHS
1972 /// being returned to the other end. The primitive integer
1973 /// types all implement a `rotate_left` function, which may
1974 /// be what you want instead.
1981 /// assert_eq!(1u8.wrapping_shl(7), 128);
1982 /// assert_eq!(1u8.wrapping_shl(8), 1);
1984 #[stable(feature = "num_wrapping", since = "1.2.0")]
1986 pub fn wrapping_shl(self, rhs
: u32) -> Self {
1987 self.overflowing_shl(rhs
).0
1990 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1991 /// where `mask` removes any high-order bits of `rhs` that
1992 /// would cause the shift to exceed the bitwidth of the type.
1994 /// Note that this is *not* the same as a rotate-right; the
1995 /// RHS of a wrapping shift-right is restricted to the range
1996 /// of the type, rather than the bits shifted out of the LHS
1997 /// being returned to the other end. The primitive integer
1998 /// types all implement a `rotate_right` function, which may
1999 /// be what you want instead.
2006 /// assert_eq!(128u8.wrapping_shr(7), 1);
2007 /// assert_eq!(128u8.wrapping_shr(8), 128);
2009 #[stable(feature = "num_wrapping", since = "1.2.0")]
2011 pub fn wrapping_shr(self, rhs
: u32) -> Self {
2012 self.overflowing_shr(rhs
).0
2015 /// Calculates `self` + `rhs`
2017 /// Returns a tuple of the addition along with a boolean indicating
2018 /// whether an arithmetic overflow would occur. If an overflow would
2019 /// have occurred then the wrapped value is returned.
2028 /// assert_eq!(5u32.overflowing_add(2), (7, false));
2029 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
2032 #[stable(feature = "wrapping", since = "1.7.0")]
2033 pub fn overflowing_add(self, rhs
: Self) -> (Self, bool
) {
2035 let (a
, b
) = $
add_with_overflow(self as $ActualT
,
2041 /// Calculates `self` - `rhs`
2043 /// Returns a tuple of the subtraction along with a boolean indicating
2044 /// whether an arithmetic overflow would occur. If an overflow would
2045 /// have occurred then the wrapped value is returned.
2054 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
2055 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
2058 #[stable(feature = "wrapping", since = "1.7.0")]
2059 pub fn overflowing_sub(self, rhs
: Self) -> (Self, bool
) {
2061 let (a
, b
) = $
sub_with_overflow(self as $ActualT
,
2067 /// Calculates the multiplication of `self` and `rhs`.
2069 /// Returns a tuple of the multiplication along with a boolean
2070 /// indicating whether an arithmetic overflow would occur. If an
2071 /// overflow would have occurred then the wrapped value is returned.
2078 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2079 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2082 #[stable(feature = "wrapping", since = "1.7.0")]
2083 pub fn overflowing_mul(self, rhs
: Self) -> (Self, bool
) {
2085 let (a
, b
) = $
mul_with_overflow(self as $ActualT
,
2091 /// Calculates the divisor when `self` is divided by `rhs`.
2093 /// Returns a tuple of the divisor along with a boolean indicating
2094 /// whether an arithmetic overflow would occur. Note that for unsigned
2095 /// integers overflow never occurs, so the second value is always
2100 /// This function will panic if `rhs` is 0.
2107 /// assert_eq!(5u32.overflowing_div(2), (2, false));
2110 #[stable(feature = "wrapping", since = "1.7.0")]
2111 pub fn overflowing_div(self, rhs
: Self) -> (Self, bool
) {
2115 /// Calculates the remainder when `self` is divided by `rhs`.
2117 /// Returns a tuple of the remainder after dividing along with a boolean
2118 /// indicating whether an arithmetic overflow would occur. Note that for
2119 /// unsigned integers overflow never occurs, so the second value is
2124 /// This function will panic if `rhs` is 0.
2131 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
2134 #[stable(feature = "wrapping", since = "1.7.0")]
2135 pub fn overflowing_rem(self, rhs
: Self) -> (Self, bool
) {
2139 /// Negates self in an overflowing fashion.
2141 /// Returns `!self + 1` using wrapping operations to return the value
2142 /// that represents the negation of this unsigned value. Note that for
2143 /// positive unsigned values overflow always occurs, but negating 0 does
2151 /// assert_eq!(0u32.overflowing_neg(), (0, false));
2152 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
2155 #[stable(feature = "wrapping", since = "1.7.0")]
2156 pub fn overflowing_neg(self) -> (Self, bool
) {
2157 ((!self).wrapping_add(1), self != 0)
2160 /// Shifts self left by `rhs` bits.
2162 /// Returns a tuple of the shifted version of self along with a boolean
2163 /// indicating whether the shift value was larger than or equal to the
2164 /// number of bits. If the shift value is too large, then value is
2165 /// masked (N-1) where N is the number of bits, and this value is then
2166 /// used to perform the shift.
2173 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
2174 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
2177 #[stable(feature = "wrapping", since = "1.7.0")]
2178 pub fn overflowing_shl(self, rhs
: u32) -> (Self, bool
) {
2179 (self << (rhs
& ($BITS
- 1)), (rhs
> ($BITS
- 1)))
2182 /// Shifts self right by `rhs` bits.
2184 /// Returns a tuple of the shifted version of self along with a boolean
2185 /// indicating whether the shift value was larger than or equal to the
2186 /// number of bits. If the shift value is too large, then value is
2187 /// masked (N-1) where N is the number of bits, and this value is then
2188 /// used to perform the shift.
2195 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
2196 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2199 #[stable(feature = "wrapping", since = "1.7.0")]
2200 pub fn overflowing_shr(self, rhs
: u32) -> (Self, bool
) {
2201 (self >> (rhs
& ($BITS
- 1)), (rhs
> ($BITS
- 1)))
2204 /// Raises self to the power of `exp`, using exponentiation by squaring.
2211 /// assert_eq!(2u32.pow(4), 16);
2213 #[stable(feature = "rust1", since = "1.0.0")]
2215 #[rustc_inherit_overflow_checks]
2216 pub fn pow(self, mut exp
: u32) -> Self {
2217 let mut base
= self;
2220 let mut prev_base
= self;
2221 let mut base_oflo
= false;
2225 // ensure overflow occurs in the same manner it
2226 // would have otherwise (i.e. signal any exception
2227 // it would have otherwise).
2228 acc
= acc
* (prev_base
* prev_base
);
2234 let (new_base
, new_base_oflo
) = base
.overflowing_mul(base
);
2236 base_oflo
= new_base_oflo
;
2242 /// Returns `true` if and only if `self == 2^k` for some `k`.
2249 /// assert!(16u8.is_power_of_two());
2250 /// assert!(!10u8.is_power_of_two());
2252 #[stable(feature = "rust1", since = "1.0.0")]
2254 pub fn is_power_of_two(self) -> bool
{
2255 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2258 /// Returns the smallest power of two greater than or equal to `self`.
2259 /// Unspecified behavior on overflow.
2266 /// assert_eq!(2u8.next_power_of_two(), 2);
2267 /// assert_eq!(3u8.next_power_of_two(), 4);
2269 #[stable(feature = "rust1", since = "1.0.0")]
2271 pub fn next_power_of_two(self) -> Self {
2272 let bits
= size_of
::<Self>() * 8;
2274 one
<< ((bits
- self.wrapping_sub(one
).leading_zeros() as usize) % bits
)
2277 /// Returns the smallest power of two greater than or equal to `n`. If
2278 /// the next power of two is greater than the type's maximum value,
2279 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2286 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2287 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2288 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2290 #[stable(feature = "rust1", since = "1.0.0")]
2291 pub fn checked_next_power_of_two(self) -> Option
<Self> {
2292 let npot
= self.next_power_of_two();
2309 intrinsics
::add_with_overflow
,
2310 intrinsics
::sub_with_overflow
,
2311 intrinsics
::mul_with_overflow
}
2316 uint_impl
! { u16, 16,
2321 intrinsics
::add_with_overflow
,
2322 intrinsics
::sub_with_overflow
,
2323 intrinsics
::mul_with_overflow
}
2328 uint_impl
! { u32, 32,
2333 intrinsics
::add_with_overflow
,
2334 intrinsics
::sub_with_overflow
,
2335 intrinsics
::mul_with_overflow
}
2340 uint_impl
! { u64, 64,
2345 intrinsics
::add_with_overflow
,
2346 intrinsics
::sub_with_overflow
,
2347 intrinsics
::mul_with_overflow
}
2350 #[cfg(target_pointer_width = "16")]
2353 uint_impl
! { u16, 16,
2358 intrinsics
::add_with_overflow
,
2359 intrinsics
::sub_with_overflow
,
2360 intrinsics
::mul_with_overflow
}
2362 #[cfg(target_pointer_width = "32")]
2365 uint_impl
! { u32, 32,
2370 intrinsics
::add_with_overflow
,
2371 intrinsics
::sub_with_overflow
,
2372 intrinsics
::mul_with_overflow
}
2375 #[cfg(target_pointer_width = "64")]
2378 uint_impl
! { u64, 64,
2383 intrinsics
::add_with_overflow
,
2384 intrinsics
::sub_with_overflow
,
2385 intrinsics
::mul_with_overflow
}
2388 /// A classification of floating point numbers.
2390 /// This `enum` is used as the return type for [`f32::classify()`] and [`f64::classify()`]. See
2391 /// their documentation for more.
2393 /// [`f32::classify()`]: ../../std/primitive.f32.html#method.classify
2394 /// [`f64::classify()`]: ../../std/primitive.f64.html#method.classify
2399 /// use std::num::FpCategory;
2402 /// let num = 12.4_f32;
2403 /// let inf = f32::INFINITY;
2404 /// let zero = 0f32;
2405 /// let sub: f32 = 1.1754942e-38;
2406 /// let nan = f32::NAN;
2408 /// assert_eq!(num.classify(), FpCategory::Normal);
2409 /// assert_eq!(inf.classify(), FpCategory::Infinite);
2410 /// assert_eq!(zero.classify(), FpCategory::Zero);
2411 /// assert_eq!(nan.classify(), FpCategory::Nan);
2412 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
2414 #[derive(Copy, Clone, PartialEq, Debug)]
2415 #[stable(feature = "rust1", since = "1.0.0")]
2416 pub enum FpCategory
{
2417 /// "Not a Number", often obtained by dividing by zero.
2418 #[stable(feature = "rust1", since = "1.0.0")]
2421 /// Positive or negative infinity.
2422 #[stable(feature = "rust1", since = "1.0.0")]
2425 /// Positive or negative zero.
2426 #[stable(feature = "rust1", since = "1.0.0")]
2429 /// De-normalized floating point representation (less precise than `Normal`).
2430 #[stable(feature = "rust1", since = "1.0.0")]
2433 /// A regular floating point number.
2434 #[stable(feature = "rust1", since = "1.0.0")]
2438 /// A built-in floating point number.
2440 #[unstable(feature = "core_float",
2441 reason
= "stable interface is via `impl f{32,64}` in later crates",
2443 pub trait Float
: Sized
{
2444 /// Returns the NaN value.
2445 #[unstable(feature = "float_extras", reason = "needs removal",
2447 #[rustc_deprecated(since = "1.11.0",
2448 reason
= "never really came to fruition and easily \
2449 implementable outside the standard library")]
2451 /// Returns the infinite value.
2452 #[unstable(feature = "float_extras", reason = "needs removal",
2454 #[rustc_deprecated(since = "1.11.0",
2455 reason
= "never really came to fruition and easily \
2456 implementable outside the standard library")]
2457 fn infinity() -> Self;
2458 /// Returns the negative infinite value.
2459 #[unstable(feature = "float_extras", reason = "needs removal",
2461 #[rustc_deprecated(since = "1.11.0",
2462 reason
= "never really came to fruition and easily \
2463 implementable outside the standard library")]
2464 fn neg_infinity() -> Self;
2466 #[unstable(feature = "float_extras", reason = "needs removal",
2468 #[rustc_deprecated(since = "1.11.0",
2469 reason
= "never really came to fruition and easily \
2470 implementable outside the standard library")]
2471 fn neg_zero() -> Self;
2473 #[unstable(feature = "float_extras", reason = "needs removal",
2475 #[rustc_deprecated(since = "1.11.0",
2476 reason
= "never really came to fruition and easily \
2477 implementable outside the standard library")]
2480 #[unstable(feature = "float_extras", reason = "needs removal",
2482 #[rustc_deprecated(since = "1.11.0",
2483 reason
= "never really came to fruition and easily \
2484 implementable outside the standard library")]
2487 /// Returns true if this value is NaN and false otherwise.
2488 #[stable(feature = "core", since = "1.6.0")]
2489 fn is_nan(self) -> bool
;
2490 /// Returns true if this value is positive infinity or negative infinity and
2491 /// false otherwise.
2492 #[stable(feature = "core", since = "1.6.0")]
2493 fn is_infinite(self) -> bool
;
2494 /// Returns true if this number is neither infinite nor NaN.
2495 #[stable(feature = "core", since = "1.6.0")]
2496 fn is_finite(self) -> bool
;
2497 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
2498 #[stable(feature = "core", since = "1.6.0")]
2499 fn is_normal(self) -> bool
;
2500 /// Returns the category that this number falls into.
2501 #[stable(feature = "core", since = "1.6.0")]
2502 fn classify(self) -> FpCategory
;
2504 /// Returns the mantissa, exponent and sign as integers, respectively.
2505 #[unstable(feature = "float_extras", reason = "signature is undecided",
2507 #[rustc_deprecated(since = "1.11.0",
2508 reason
= "never really came to fruition and easily \
2509 implementable outside the standard library")]
2510 fn integer_decode(self) -> (u64, i16, i8);
2512 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2513 /// number is `Float::nan()`.
2514 #[stable(feature = "core", since = "1.6.0")]
2515 fn abs(self) -> Self;
2516 /// Returns a number that represents the sign of `self`.
2518 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2519 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2520 /// - `Float::nan()` if the number is `Float::nan()`
2521 #[stable(feature = "core", since = "1.6.0")]
2522 fn signum(self) -> Self;
2524 /// Returns `true` if `self` is positive, including `+0.0` and
2525 /// `Float::infinity()`.
2526 #[stable(feature = "core", since = "1.6.0")]
2527 fn is_sign_positive(self) -> bool
;
2528 /// Returns `true` if `self` is negative, including `-0.0` and
2529 /// `Float::neg_infinity()`.
2530 #[stable(feature = "core", since = "1.6.0")]
2531 fn is_sign_negative(self) -> bool
;
2533 /// Take the reciprocal (inverse) of a number, `1/x`.
2534 #[stable(feature = "core", since = "1.6.0")]
2535 fn recip(self) -> Self;
2537 /// Raise a number to an integer power.
2539 /// Using this function is generally faster than using `powf`
2540 #[stable(feature = "core", since = "1.6.0")]
2541 fn powi(self, n
: i32) -> Self;
2543 /// Convert radians to degrees.
2544 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2545 fn to_degrees(self) -> Self;
2546 /// Convert degrees to radians.
2547 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2548 fn to_radians(self) -> Self;
2551 macro_rules
! from_str_radix_int_impl
{
2553 #[stable(feature = "rust1", since = "1.0.0")]
2554 impl FromStr
for $t
{
2555 type Err
= ParseIntError
;
2556 fn from_str(src
: &str) -> Result
<Self, ParseIntError
> {
2557 from_str_radix(src
, 10)
2562 from_str_radix_int_impl
! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
2564 /// The error type returned when a checked integral type conversion fails.
2565 #[unstable(feature = "try_from", issue = "33417")]
2566 #[derive(Debug, Copy, Clone)]
2567 pub struct TryFromIntError(());
2569 impl TryFromIntError
{
2570 #[unstable(feature = "int_error_internals",
2571 reason
= "available through Error trait and this method should \
2572 not be exposed publicly",
2575 pub fn __description(&self) -> &str {
2576 "out of range integral type conversion attempted"
2580 #[unstable(feature = "try_from", issue = "33417")]
2581 impl fmt
::Display
for TryFromIntError
{
2582 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
2583 self.__description().fmt(fmt
)
2587 macro_rules
! same_sign_from_int_impl
{
2588 ($storage
:ty
, $target
:ty
, $
($source
:ty
),*) => {$
(
2589 #[stable(feature = "rust1", since = "1.0.0")]
2590 impl TryFrom
<$source
> for $target
{
2591 type Err
= TryFromIntError
;
2593 fn try_from(u
: $source
) -> Result
<$target
, TryFromIntError
> {
2594 let min
= <$target
as FromStrRadixHelper
>::min_value() as $storage
;
2595 let max
= <$target
as FromStrRadixHelper
>::max_value() as $storage
;
2596 if u
as $storage
< min
|| u
as $storage
> max
{
2597 Err(TryFromIntError(()))
2606 same_sign_from_int_impl
!(u64, u8, u8, u16, u32, u64, usize);
2607 same_sign_from_int_impl
!(i64, i8, i8, i16, i32, i64, isize);
2608 same_sign_from_int_impl
!(u64, u16, u8, u16, u32, u64, usize);
2609 same_sign_from_int_impl
!(i64, i16, i8, i16, i32, i64, isize);
2610 same_sign_from_int_impl
!(u64, u32, u8, u16, u32, u64, usize);
2611 same_sign_from_int_impl
!(i64, i32, i8, i16, i32, i64, isize);
2612 same_sign_from_int_impl
!(u64, u64, u8, u16, u32, u64, usize);
2613 same_sign_from_int_impl
!(i64, i64, i8, i16, i32, i64, isize);
2614 same_sign_from_int_impl
!(u64, usize, u8, u16, u32, u64, usize);
2615 same_sign_from_int_impl
!(i64, isize, i8, i16, i32, i64, isize);
2617 macro_rules
! cross_sign_from_int_impl
{
2618 ($unsigned
:ty
, $
($signed
:ty
),*) => {$
(
2619 #[stable(feature = "rust1", since = "1.0.0")]
2620 impl TryFrom
<$unsigned
> for $signed
{
2621 type Err
= TryFromIntError
;
2623 fn try_from(u
: $unsigned
) -> Result
<$signed
, TryFromIntError
> {
2624 let max
= <$signed
as FromStrRadixHelper
>::max_value() as u64;
2626 Err(TryFromIntError(()))
2633 #[stable(feature = "rust1", since = "1.0.0")]
2634 impl TryFrom
<$signed
> for $unsigned
{
2635 type Err
= TryFromIntError
;
2637 fn try_from(u
: $signed
) -> Result
<$unsigned
, TryFromIntError
> {
2638 let max
= <$unsigned
as FromStrRadixHelper
>::max_value() as u64;
2639 if u
< 0 || u
as u64 > max
{
2640 Err(TryFromIntError(()))
2649 cross_sign_from_int_impl
!(u8, i8, i16, i32, i64, isize);
2650 cross_sign_from_int_impl
!(u16, i8, i16, i32, i64, isize);
2651 cross_sign_from_int_impl
!(u32, i8, i16, i32, i64, isize);
2652 cross_sign_from_int_impl
!(u64, i8, i16, i32, i64, isize);
2653 cross_sign_from_int_impl
!(usize, i8, i16, i32, i64, isize);
2656 trait FromStrRadixHelper
: PartialOrd
+ Copy
{
2657 fn min_value() -> Self;
2658 fn max_value() -> Self;
2659 fn from_u32(u
: u32) -> Self;
2660 fn checked_mul(&self, other
: u32) -> Option
<Self>;
2661 fn checked_sub(&self, other
: u32) -> Option
<Self>;
2662 fn checked_add(&self, other
: u32) -> Option
<Self>;
2666 ($
($t
:ty
)*) => ($
(impl FromStrRadixHelper
for $t
{
2667 fn min_value() -> Self { Self::min_value() }
2668 fn max_value() -> Self { Self::max_value() }
2669 fn from_u32(u
: u32) -> Self { u as Self }
2670 fn checked_mul(&self, other
: u32) -> Option
<Self> {
2671 Self::checked_mul(*self, other
as Self)
2673 fn checked_sub(&self, other
: u32) -> Option
<Self> {
2674 Self::checked_sub(*self, other
as Self)
2676 fn checked_add(&self, other
: u32) -> Option
<Self> {
2677 Self::checked_add(*self, other
as Self)
2681 doit
! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
2683 fn from_str_radix
<T
: FromStrRadixHelper
>(src
: &str, radix
: u32)
2684 -> Result
<T
, ParseIntError
> {
2685 use self::IntErrorKind
::*;
2686 use self::ParseIntError
as PIE
;
2688 assert
!(radix
>= 2 && radix
<= 36,
2689 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2693 return Err(PIE { kind: Empty }
);
2696 let is_signed_ty
= T
::from_u32(0) > T
::min_value();
2698 // all valid digits are ascii, so we will just iterate over the utf8 bytes
2699 // and cast them to chars. .to_digit() will safely return None for anything
2700 // other than a valid ascii digit for the given radix, including the first-byte
2701 // of multi-byte sequences
2702 let src
= src
.as_bytes();
2704 let (is_positive
, digits
) = match src
[0] {
2705 b'
+'
=> (true, &src
[1..]),
2706 b'
-'
if is_signed_ty
=> (false, &src
[1..]),
2710 if digits
.is_empty() {
2711 return Err(PIE { kind: Empty }
);
2714 let mut result
= T
::from_u32(0);
2716 // The number is positive
2718 let x
= match (c
as char).to_digit(radix
) {
2720 None
=> return Err(PIE { kind: InvalidDigit }
),
2722 result
= match result
.checked_mul(radix
) {
2723 Some(result
) => result
,
2724 None
=> return Err(PIE { kind: Overflow }
),
2726 result
= match result
.checked_add(x
) {
2727 Some(result
) => result
,
2728 None
=> return Err(PIE { kind: Overflow }
),
2732 // The number is negative
2734 let x
= match (c
as char).to_digit(radix
) {
2736 None
=> return Err(PIE { kind: InvalidDigit }
),
2738 result
= match result
.checked_mul(radix
) {
2739 Some(result
) => result
,
2740 None
=> return Err(PIE { kind: Underflow }
),
2742 result
= match result
.checked_sub(x
) {
2743 Some(result
) => result
,
2744 None
=> return Err(PIE { kind: Underflow }
),
2751 /// An error which can be returned when parsing an integer.
2753 /// This error is used as the error type for the `from_str_radix()` functions
2754 /// on the primitive integer types, such as [`i8::from_str_radix()`].
2756 /// [`i8::from_str_radix()`]: ../../std/primitive.i8.html#method.from_str_radix
2757 #[derive(Debug, Clone, PartialEq)]
2758 #[stable(feature = "rust1", since = "1.0.0")]
2759 pub struct ParseIntError { kind: IntErrorKind }
2761 #[derive(Debug, Clone, PartialEq)]
2769 impl ParseIntError
{
2770 #[unstable(feature = "int_error_internals",
2771 reason
= "available through Error trait and this method should \
2772 not be exposed publicly",
2775 pub fn __description(&self) -> &str {
2777 IntErrorKind
::Empty
=> "cannot parse integer from empty string",
2778 IntErrorKind
::InvalidDigit
=> "invalid digit found in string",
2779 IntErrorKind
::Overflow
=> "number too large to fit in target type",
2780 IntErrorKind
::Underflow
=> "number too small to fit in target type",
2785 #[stable(feature = "rust1", since = "1.0.0")]
2786 impl fmt
::Display
for ParseIntError
{
2787 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2788 self.__description().fmt(f
)
2792 #[stable(feature = "rust1", since = "1.0.0")]
2793 pub use num
::dec2flt
::ParseFloatError
;
2795 // Conversion traits for primitive integer and float types
2796 // Conversions T -> T are covered by a blanket impl and therefore excluded
2797 // Some conversions from and to usize/isize are not implemented due to portability concerns
2798 macro_rules
! impl_from
{
2799 ($Small
: ty
, $Large
: ty
) => {
2800 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
2801 impl From
<$Small
> for $Large
{
2803 fn from(small
: $Small
) -> $Large
{
2810 // Unsigned -> Unsigned
2811 impl_from
! { u8, u16 }
2812 impl_from
! { u8, u32 }
2813 impl_from
! { u8, u64 }
2814 impl_from
! { u8, usize }
2815 impl_from
! { u16, u32 }
2816 impl_from
! { u16, u64 }
2817 impl_from
! { u32, u64 }
2820 impl_from
! { i8, i16 }
2821 impl_from
! { i8, i32 }
2822 impl_from
! { i8, i64 }
2823 impl_from
! { i8, isize }
2824 impl_from
! { i16, i32 }
2825 impl_from
! { i16, i64 }
2826 impl_from
! { i32, i64 }
2828 // Unsigned -> Signed
2829 impl_from
! { u8, i16 }
2830 impl_from
! { u8, i32 }
2831 impl_from
! { u8, i64 }
2832 impl_from
! { u16, i32 }
2833 impl_from
! { u16, i64 }
2834 impl_from
! { u32, i64 }
2836 // Note: integers can only be represented with full precision in a float if
2837 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2838 // Lossy float conversions are not implemented at this time.
2841 impl_from
! { i8, f32 }
2842 impl_from
! { i8, f64 }
2843 impl_from
! { i16, f32 }
2844 impl_from
! { i16, f64 }
2845 impl_from
! { i32, f64 }
2847 // Unsigned -> Float
2848 impl_from
! { u8, f32 }
2849 impl_from
! { u8, f64 }
2850 impl_from
! { u16, f32 }
2851 impl_from
! { u16, f64 }
2852 impl_from
! { u32, f64 }
2855 impl_from
! { f32, f64 }