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")]
14 #![allow(missing_docs)]
16 use self::wrapping::OverflowingOps;
19 use cmp::{Eq, PartialOrd};
23 use marker::{Copy, Sized};
25 use option::Option::{self, Some, None};
26 use result::Result::{self, Ok, Err};
27 use str::{FromStr, StrExt};
30 /// Provides intentionally-wrapped arithmetic on `T`.
32 /// Operations like `+` on `u32` values is intended to never overflow,
33 /// and in some debug configurations overflow is detected and results
34 /// in a panic. While most arithmetic falls into this category, some
35 /// code explicitly expects and relies upon modular arithmetic (e.g.,
38 /// Wrapping arithmetic can be achieved either through methods like
39 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
40 /// all standard arithmetic operations on the underlying value are
41 /// intended to have wrapping semantics.
42 #[stable(feature = "rust1", since = "1.0.0")]
43 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default)]
44 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
48 // All these modules are technically private and only exposed for libcoretest:
54 /// Types that have a "zero" value.
56 /// This trait is intended for use in conjunction with `Add`, as an identity:
57 /// `x + T::zero() == x`.
58 #[unstable(feature = "zero_one",
59 reason = "unsure of placement, wants to use associated constants",
61 pub trait Zero: Sized {
62 /// The "zero" (usually, additive identity) for this type.
66 /// Types that have a "one" value.
68 /// This trait is intended for use in conjunction with `Mul`, as an identity:
69 /// `x * T::one() == x`.
70 #[unstable(feature = "zero_one",
71 reason = "unsure of placement, wants to use associated constants",
73 pub trait One: Sized {
74 /// The "one" (usually, multiplicative identity) for this type.
78 macro_rules! zero_one_impl {
80 #[unstable(feature = "zero_one",
81 reason = "unsure of placement, wants to use associated constants",
85 fn zero() -> Self { 0 }
87 #[unstable(feature = "zero_one",
88 reason = "unsure of placement, wants to use associated constants",
92 fn one() -> Self { 1 }
96 zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
98 macro_rules! zero_one_impl_float {
100 #[unstable(feature = "zero_one",
101 reason = "unsure of placement, wants to use associated constants",
105 fn zero() -> Self { 0.0 }
107 #[unstable(feature = "zero_one",
108 reason = "unsure of placement, wants to use associated constants",
112 fn one() -> Self { 1.0 }
116 zero_one_impl_float! { f32 f64 }
118 // Just for stage0; a byte swap on a byte is a no-op
119 // Delete this once it becomes unused
121 unsafe fn bswap8(x: u8) -> u8 { x }
123 macro_rules! checked_op {
124 ($U:ty, $op:path, $x:expr, $y:expr) => {{
125 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
126 if overflowed { None } else { Some(result as Self) }
130 // `Int` + `SignedInt` implemented for signed integers
131 macro_rules! int_impl {
132 ($ActualT:ty, $UnsignedT:ty, $BITS:expr,
133 $add_with_overflow:path,
134 $sub_with_overflow:path,
135 $mul_with_overflow:path) => {
136 /// Returns the smallest value that can be represented by this integer type.
137 #[stable(feature = "rust1", since = "1.0.0")]
139 pub const fn min_value() -> Self {
140 (-1 as Self) << ($BITS - 1)
143 /// Returns the largest value that can be represented by this integer type.
144 #[stable(feature = "rust1", since = "1.0.0")]
146 pub const fn max_value() -> Self {
150 /// Converts a string slice in a given base to an integer.
152 /// Leading and trailing whitespace represent an error.
159 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
161 #[stable(feature = "rust1", since = "1.0.0")]
162 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
163 from_str_radix(src, radix)
166 /// Returns the number of ones in the binary representation of `self`.
173 /// let n = 0b01001100u8;
175 /// assert_eq!(n.count_ones(), 3);
177 #[stable(feature = "rust1", since = "1.0.0")]
179 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
181 /// Returns the number of zeros in the binary representation of `self`.
188 /// let n = 0b01001100u8;
190 /// assert_eq!(n.count_zeros(), 5);
192 #[stable(feature = "rust1", since = "1.0.0")]
194 pub fn count_zeros(self) -> u32 {
198 /// Returns the number of leading zeros in the binary representation
206 /// let n = 0b0101000u16;
208 /// assert_eq!(n.leading_zeros(), 10);
210 #[stable(feature = "rust1", since = "1.0.0")]
212 pub fn leading_zeros(self) -> u32 {
213 (self as $UnsignedT).leading_zeros()
216 /// Returns the number of trailing zeros in the binary representation
224 /// let n = 0b0101000u16;
226 /// assert_eq!(n.trailing_zeros(), 3);
228 #[stable(feature = "rust1", since = "1.0.0")]
230 pub fn trailing_zeros(self) -> u32 {
231 (self as $UnsignedT).trailing_zeros()
234 /// Shifts the bits to the left by a specified amount, `n`,
235 /// wrapping the truncated bits to the end of the resulting integer.
242 /// let n = 0x0123456789ABCDEFu64;
243 /// let m = 0x3456789ABCDEF012u64;
245 /// assert_eq!(n.rotate_left(12), m);
247 #[stable(feature = "rust1", since = "1.0.0")]
249 pub fn rotate_left(self, n: u32) -> Self {
250 (self as $UnsignedT).rotate_left(n) as Self
253 /// Shifts the bits to the right by a specified amount, `n`,
254 /// wrapping the truncated bits to the beginning of the resulting
262 /// let n = 0x0123456789ABCDEFu64;
263 /// let m = 0xDEF0123456789ABCu64;
265 /// assert_eq!(n.rotate_right(12), m);
267 #[stable(feature = "rust1", since = "1.0.0")]
269 pub fn rotate_right(self, n: u32) -> Self {
270 (self as $UnsignedT).rotate_right(n) as Self
273 /// Reverses the byte order of the integer.
280 /// let n = 0x0123456789ABCDEFu64;
281 /// let m = 0xEFCDAB8967452301u64;
283 /// assert_eq!(n.swap_bytes(), m);
285 #[stable(feature = "rust1", since = "1.0.0")]
287 pub fn swap_bytes(self) -> Self {
288 (self as $UnsignedT).swap_bytes() as Self
291 /// Converts an integer from big endian to the target's endianness.
293 /// On big endian this is a no-op. On little endian the bytes are
301 /// let n = 0x0123456789ABCDEFu64;
303 /// if cfg!(target_endian = "big") {
304 /// assert_eq!(u64::from_be(n), n)
306 /// assert_eq!(u64::from_be(n), n.swap_bytes())
309 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn from_be(x: Self) -> Self {
312 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
315 /// Converts an integer from little endian to the target's endianness.
317 /// On little endian this is a no-op. On big endian the bytes are
325 /// let n = 0x0123456789ABCDEFu64;
327 /// if cfg!(target_endian = "little") {
328 /// assert_eq!(u64::from_le(n), n)
330 /// assert_eq!(u64::from_le(n), n.swap_bytes())
333 #[stable(feature = "rust1", since = "1.0.0")]
335 pub fn from_le(x: Self) -> Self {
336 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
339 /// Converts `self` to big endian from the target's endianness.
341 /// On big endian this is a no-op. On little endian the bytes are
349 /// let n = 0x0123456789ABCDEFu64;
351 /// if cfg!(target_endian = "big") {
352 /// assert_eq!(n.to_be(), n)
354 /// assert_eq!(n.to_be(), n.swap_bytes())
357 #[stable(feature = "rust1", since = "1.0.0")]
359 pub fn to_be(self) -> Self { // or not to be?
360 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
363 /// Converts `self` to little endian from the target's endianness.
365 /// On little endian this is a no-op. On big endian the bytes are
373 /// let n = 0x0123456789ABCDEFu64;
375 /// if cfg!(target_endian = "little") {
376 /// assert_eq!(n.to_le(), n)
378 /// assert_eq!(n.to_le(), n.swap_bytes())
381 #[stable(feature = "rust1", since = "1.0.0")]
383 pub fn to_le(self) -> Self {
384 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
387 /// Checked integer addition. Computes `self + other`, returning `None`
388 /// if overflow occurred.
395 /// assert_eq!(5u16.checked_add(65530), Some(65535));
396 /// assert_eq!(6u16.checked_add(65530), None);
398 #[stable(feature = "rust1", since = "1.0.0")]
400 pub fn checked_add(self, other: Self) -> Option<Self> {
401 checked_op!($ActualT, $add_with_overflow, self, other)
404 /// Checked integer subtraction. Computes `self - other`, returning
405 /// `None` if underflow occurred.
412 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
413 /// assert_eq!((-128i8).checked_sub(1), None);
415 #[stable(feature = "rust1", since = "1.0.0")]
417 pub fn checked_sub(self, other: Self) -> Option<Self> {
418 checked_op!($ActualT, $sub_with_overflow, self, other)
421 /// Checked integer multiplication. Computes `self * other`, returning
422 /// `None` if underflow or overflow occurred.
429 /// assert_eq!(5u8.checked_mul(51), Some(255));
430 /// assert_eq!(5u8.checked_mul(52), None);
432 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn checked_mul(self, other: Self) -> Option<Self> {
435 checked_op!($ActualT, $mul_with_overflow, self, other)
438 /// Checked integer division. Computes `self / other`, returning `None`
439 /// if `other == 0` or the operation results in underflow or overflow.
446 /// assert_eq!((-127i8).checked_div(-1), Some(127));
447 /// assert_eq!((-128i8).checked_div(-1), None);
448 /// assert_eq!((1i8).checked_div(0), None);
450 #[stable(feature = "rust1", since = "1.0.0")]
452 pub fn checked_div(self, other: Self) -> Option<Self> {
455 -1 if self == Self::min_value()
457 other => Some(self / other),
461 /// Saturating integer addition. Computes `self + other`, saturating at
462 /// the numeric bounds instead of overflowing.
469 /// assert_eq!(100i8.saturating_add(1), 101);
470 /// assert_eq!(100i8.saturating_add(127), 127);
472 #[stable(feature = "rust1", since = "1.0.0")]
474 pub fn saturating_add(self, other: Self) -> Self {
475 match self.checked_add(other) {
477 None if other >= Self::zero() => Self::max_value(),
478 None => Self::min_value(),
482 /// Saturating integer subtraction. Computes `self - other`, saturating
483 /// at the numeric bounds instead of overflowing.
490 /// assert_eq!(100i8.saturating_sub(127), -27);
491 /// assert_eq!((-100i8).saturating_sub(127), -128);
493 #[stable(feature = "rust1", since = "1.0.0")]
495 pub fn saturating_sub(self, other: Self) -> Self {
496 match self.checked_sub(other) {
498 None if other >= Self::zero() => Self::min_value(),
499 None => Self::max_value(),
503 /// Wrapping (modular) addition. Computes `self + other`,
504 /// wrapping around at the boundary of the type.
511 /// assert_eq!(100i8.wrapping_add(27), 127);
512 /// assert_eq!(100i8.wrapping_add(127), -29);
514 #[stable(feature = "rust1", since = "1.0.0")]
516 pub fn wrapping_add(self, rhs: Self) -> Self {
518 intrinsics::overflowing_add(self, rhs)
522 /// Wrapping (modular) subtraction. Computes `self - other`,
523 /// wrapping around at the boundary of the type.
530 /// assert_eq!(0i8.wrapping_sub(127), -127);
531 /// assert_eq!((-2i8).wrapping_sub(127), 127);
533 #[stable(feature = "rust1", since = "1.0.0")]
535 pub fn wrapping_sub(self, rhs: Self) -> Self {
537 intrinsics::overflowing_sub(self, rhs)
541 /// Wrapping (modular) multiplication. Computes `self *
542 /// other`, wrapping around at the boundary of the type.
549 /// assert_eq!(10i8.wrapping_mul(12), 120);
550 /// assert_eq!(11i8.wrapping_mul(12), -124);
552 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn wrapping_mul(self, rhs: Self) -> Self {
556 intrinsics::overflowing_mul(self, rhs)
560 /// Wrapping (modular) division. Computes `self / other`,
561 /// wrapping around at the boundary of the type.
563 /// The only case where such wrapping can occur is when one
564 /// divides `MIN / -1` on a signed type (where `MIN` is the
565 /// negative minimal value for the type); this is equivalent
566 /// to `-MIN`, a positive value that is too large to represent
567 /// in the type. In such a case, this function returns `MIN`
575 /// assert_eq!(100u8.wrapping_div(10), 10);
576 /// assert_eq!((-128i8).wrapping_div(-1), -128);
578 #[stable(feature = "num_wrapping", since = "1.2.0")]
580 pub fn wrapping_div(self, rhs: Self) -> Self {
581 self.overflowing_div(rhs).0
584 /// Wrapping (modular) remainder. Computes `self % other`,
585 /// wrapping around at the boundary of the type.
587 /// Such wrap-around never actually occurs mathematically;
588 /// implementation artifacts make `x % y` invalid for `MIN /
589 /// -1` on a signed type (where `MIN` is the negative
590 /// minimal value). In such a case, this function returns `0`.
597 /// assert_eq!(100i8.wrapping_rem(10), 0);
598 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
600 #[stable(feature = "num_wrapping", since = "1.2.0")]
602 pub fn wrapping_rem(self, rhs: Self) -> Self {
603 self.overflowing_rem(rhs).0
606 /// Wrapping (modular) negation. Computes `-self`,
607 /// wrapping around at the boundary of the type.
609 /// The only case where such wrapping can occur is when one
610 /// negates `MIN` on a signed type (where `MIN` is the
611 /// negative minimal value for the type); this is a positive
612 /// value that is too large to represent in the type. In such
613 /// a case, this function returns `MIN` itself.
620 /// assert_eq!(100i8.wrapping_neg(), -100);
621 /// assert_eq!((-128i8).wrapping_neg(), -128);
623 #[stable(feature = "num_wrapping", since = "1.2.0")]
625 pub fn wrapping_neg(self) -> Self {
626 self.overflowing_neg().0
629 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
630 /// where `mask` removes any high-order bits of `rhs` that
631 /// would cause the shift to exceed the bitwidth of the type.
638 /// assert_eq!(1u8.wrapping_shl(7), 128);
639 /// assert_eq!(1u8.wrapping_shl(8), 1);
641 #[stable(feature = "num_wrapping", since = "1.2.0")]
643 pub fn wrapping_shl(self, rhs: u32) -> Self {
644 self.overflowing_shl(rhs).0
647 /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
648 /// where `mask` removes any high-order bits of `rhs` that
649 /// would cause the shift to exceed the bitwidth of the type.
656 /// assert_eq!(128u8.wrapping_shr(7), 1);
657 /// assert_eq!(128u8.wrapping_shr(8), 128);
659 #[stable(feature = "num_wrapping", since = "1.2.0")]
661 pub fn wrapping_shr(self, rhs: u32) -> Self {
662 self.overflowing_shr(rhs).0
665 /// Raises self to the power of `exp`, using exponentiation by squaring.
672 /// let x: i32 = 2; // or any other integer type
674 /// assert_eq!(x.pow(4), 16);
676 #[stable(feature = "rust1", since = "1.0.0")]
678 pub fn pow(self, mut exp: u32) -> Self {
680 let mut acc = Self::one();
690 // Deal with the final bit of the exponent separately, since
691 // squaring the base afterwards is not necessary and may cause a
692 // needless overflow.
700 /// Computes the absolute value of `self`.
702 /// # Overflow behavior
704 /// The absolute value of `i32::min_value()` cannot be represented as an
705 /// `i32`, and attempting to calculate it will cause an overflow. This
706 /// means that code in debug mode will trigger a panic on this case and
707 /// optimized code will return `i32::min_value()` without a panic.
714 /// assert_eq!(10i8.abs(), 10);
715 /// assert_eq!((-10i8).abs(), 10);
717 #[stable(feature = "rust1", since = "1.0.0")]
719 pub fn abs(self) -> Self {
720 if self.is_negative() {
721 // Note that the #[inline] above means that the overflow
722 // semantics of this negation depend on the crate we're being
730 /// Returns a number representing sign of `self`.
732 /// - `0` if the number is zero
733 /// - `1` if the number is positive
734 /// - `-1` if the number is negative
741 /// assert_eq!(10i8.signum(), 1);
742 /// assert_eq!(0i8.signum(), 0);
743 /// assert_eq!((-10i8).signum(), -1);
745 #[stable(feature = "rust1", since = "1.0.0")]
747 pub fn signum(self) -> Self {
755 /// Returns `true` if `self` is positive and `false` if the number
756 /// is zero or negative.
763 /// assert!(10i8.is_positive());
764 /// assert!(!(-10i8).is_positive());
766 #[stable(feature = "rust1", since = "1.0.0")]
768 pub fn is_positive(self) -> bool { self > 0 }
770 /// Returns `true` if `self` is negative and `false` if the number
771 /// is zero or positive.
778 /// assert!((-10i8).is_negative());
779 /// assert!(!10i8.is_negative());
781 #[stable(feature = "rust1", since = "1.0.0")]
783 pub fn is_negative(self) -> bool { self < 0 }
790 int_impl! { i8, u8, 8,
791 intrinsics::i8_add_with_overflow,
792 intrinsics::i8_sub_with_overflow,
793 intrinsics::i8_mul_with_overflow }
798 int_impl! { i8, u8, 8,
799 intrinsics::add_with_overflow,
800 intrinsics::sub_with_overflow,
801 intrinsics::mul_with_overflow }
807 int_impl! { i16, u16, 16,
808 intrinsics::i16_add_with_overflow,
809 intrinsics::i16_sub_with_overflow,
810 intrinsics::i16_mul_with_overflow }
815 int_impl! { i16, u16, 16,
816 intrinsics::add_with_overflow,
817 intrinsics::sub_with_overflow,
818 intrinsics::mul_with_overflow }
824 int_impl! { i32, u32, 32,
825 intrinsics::i32_add_with_overflow,
826 intrinsics::i32_sub_with_overflow,
827 intrinsics::i32_mul_with_overflow }
832 int_impl! { i32, u32, 32,
833 intrinsics::add_with_overflow,
834 intrinsics::sub_with_overflow,
835 intrinsics::mul_with_overflow }
841 int_impl! { i64, u64, 64,
842 intrinsics::i64_add_with_overflow,
843 intrinsics::i64_sub_with_overflow,
844 intrinsics::i64_mul_with_overflow }
849 int_impl! { i64, u64, 64,
850 intrinsics::add_with_overflow,
851 intrinsics::sub_with_overflow,
852 intrinsics::mul_with_overflow }
855 #[cfg(target_pointer_width = "32")]
859 int_impl! { i32, u32, 32,
860 intrinsics::i32_add_with_overflow,
861 intrinsics::i32_sub_with_overflow,
862 intrinsics::i32_mul_with_overflow }
864 #[cfg(target_pointer_width = "32")]
868 int_impl! { i32, u32, 32,
869 intrinsics::add_with_overflow,
870 intrinsics::sub_with_overflow,
871 intrinsics::mul_with_overflow }
874 #[cfg(target_pointer_width = "64")]
878 int_impl! { i64, u64, 64,
879 intrinsics::i64_add_with_overflow,
880 intrinsics::i64_sub_with_overflow,
881 intrinsics::i64_mul_with_overflow }
883 #[cfg(target_pointer_width = "64")]
887 int_impl! { i64, u64, 64,
888 intrinsics::add_with_overflow,
889 intrinsics::sub_with_overflow,
890 intrinsics::mul_with_overflow }
893 // `Int` + `UnsignedInt` implemented for signed integers
894 macro_rules! uint_impl {
895 ($ActualT:ty, $BITS:expr,
900 $add_with_overflow:path,
901 $sub_with_overflow:path,
902 $mul_with_overflow:path) => {
903 /// Returns the smallest value that can be represented by this integer type.
904 #[stable(feature = "rust1", since = "1.0.0")]
906 pub const fn min_value() -> Self { 0 }
908 /// Returns the largest value that can be represented by this integer type.
909 #[stable(feature = "rust1", since = "1.0.0")]
911 pub const fn max_value() -> Self { !0 }
913 /// Converts a string slice in a given base to an integer.
915 /// Leading and trailing whitespace represent an error.
919 /// * src - A string slice
920 /// * radix - The base to use. Must lie in the range [2 .. 36]
924 /// `Err(ParseIntError)` if the string did not represent a valid number.
925 /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
926 #[stable(feature = "rust1", since = "1.0.0")]
927 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
928 from_str_radix(src, radix)
931 /// Returns the number of ones in the binary representation of `self`.
938 /// let n = 0b01001100u8;
940 /// assert_eq!(n.count_ones(), 3);
942 #[stable(feature = "rust1", since = "1.0.0")]
944 pub fn count_ones(self) -> u32 {
945 unsafe { $ctpop(self as $ActualT) as u32 }
948 /// Returns the number of zeros in the binary representation of `self`.
955 /// let n = 0b01001100u8;
957 /// assert_eq!(n.count_zeros(), 5);
959 #[stable(feature = "rust1", since = "1.0.0")]
961 pub fn count_zeros(self) -> u32 {
965 /// Returns the number of leading zeros in the binary representation
973 /// let n = 0b0101000u16;
975 /// assert_eq!(n.leading_zeros(), 10);
977 #[stable(feature = "rust1", since = "1.0.0")]
979 pub fn leading_zeros(self) -> u32 {
980 unsafe { $ctlz(self as $ActualT) as u32 }
983 #[stable(feature = "rust1", since = "1.0.0")]
986 pub fn trailing_zeros(self) -> u32 {
987 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
988 // emits two conditional moves on x86_64. By promoting the value to
989 // u16 and setting bit 8, we get better code without any conditional
991 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
992 // pending, remove this workaround once LLVM generates better code
996 intrinsics::cttz16(self as u16 | 0x100) as u32
998 $cttz(self as $ActualT) as u32
1002 /// Returns the number of trailing zeros in the binary representation
1010 /// let n = 0b0101000u16;
1012 /// assert_eq!(n.trailing_zeros(), 3);
1014 #[stable(feature = "rust1", since = "1.0.0")]
1017 pub fn trailing_zeros(self) -> u32 {
1018 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1019 // emits two conditional moves on x86_64. By promoting the value to
1020 // u16 and setting bit 8, we get better code without any conditional
1022 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1023 // pending, remove this workaround once LLVM generates better code
1027 intrinsics::cttz(self as u16 | 0x100) as u32
1029 intrinsics::cttz(self) as u32
1034 /// Shifts the bits to the left by a specified amount, `n`,
1035 /// wrapping the truncated bits to the end of the resulting integer.
1042 /// let n = 0x0123456789ABCDEFu64;
1043 /// let m = 0x3456789ABCDEF012u64;
1045 /// assert_eq!(n.rotate_left(12), m);
1047 #[stable(feature = "rust1", since = "1.0.0")]
1049 pub fn rotate_left(self, n: u32) -> Self {
1050 // Protect against undefined behaviour for over-long bit shifts
1052 (self << n) | (self >> (($BITS - n) % $BITS))
1055 /// Shifts the bits to the right by a specified amount, `n`,
1056 /// wrapping the truncated bits to the beginning of the resulting
1064 /// let n = 0x0123456789ABCDEFu64;
1065 /// let m = 0xDEF0123456789ABCu64;
1067 /// assert_eq!(n.rotate_right(12), m);
1069 #[stable(feature = "rust1", since = "1.0.0")]
1071 pub fn rotate_right(self, n: u32) -> Self {
1072 // Protect against undefined behaviour for over-long bit shifts
1074 (self >> n) | (self << (($BITS - n) % $BITS))
1077 /// Reverses the byte order of the integer.
1084 /// let n = 0x0123456789ABCDEFu64;
1085 /// let m = 0xEFCDAB8967452301u64;
1087 /// assert_eq!(n.swap_bytes(), m);
1089 #[stable(feature = "rust1", since = "1.0.0")]
1091 pub fn swap_bytes(self) -> Self {
1092 unsafe { $bswap(self as $ActualT) as Self }
1095 /// Converts an integer from big endian to the target's endianness.
1097 /// On big endian this is a no-op. On little endian the bytes are
1105 /// let n = 0x0123456789ABCDEFu64;
1107 /// if cfg!(target_endian = "big") {
1108 /// assert_eq!(u64::from_be(n), n)
1110 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1113 #[stable(feature = "rust1", since = "1.0.0")]
1115 pub fn from_be(x: Self) -> Self {
1116 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1119 /// Converts an integer from little endian to the target's endianness.
1121 /// On little endian this is a no-op. On big endian the bytes are
1129 /// let n = 0x0123456789ABCDEFu64;
1131 /// if cfg!(target_endian = "little") {
1132 /// assert_eq!(u64::from_le(n), n)
1134 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1137 #[stable(feature = "rust1", since = "1.0.0")]
1139 pub fn from_le(x: Self) -> Self {
1140 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1143 /// Converts `self` to big endian from the target's endianness.
1145 /// On big endian this is a no-op. On little endian the bytes are
1153 /// let n = 0x0123456789ABCDEFu64;
1155 /// if cfg!(target_endian = "big") {
1156 /// assert_eq!(n.to_be(), n)
1158 /// assert_eq!(n.to_be(), n.swap_bytes())
1161 #[stable(feature = "rust1", since = "1.0.0")]
1163 pub fn to_be(self) -> Self { // or not to be?
1164 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1167 /// Converts `self` to little endian from the target's endianness.
1169 /// On little endian this is a no-op. On big endian the bytes are
1177 /// let n = 0x0123456789ABCDEFu64;
1179 /// if cfg!(target_endian = "little") {
1180 /// assert_eq!(n.to_le(), n)
1182 /// assert_eq!(n.to_le(), n.swap_bytes())
1185 #[stable(feature = "rust1", since = "1.0.0")]
1187 pub fn to_le(self) -> Self {
1188 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1191 /// Checked integer addition. Computes `self + other`, returning `None`
1192 /// if overflow occurred.
1199 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1200 /// assert_eq!(6u16.checked_add(65530), None);
1202 #[stable(feature = "rust1", since = "1.0.0")]
1204 pub fn checked_add(self, other: Self) -> Option<Self> {
1205 checked_op!($ActualT, $add_with_overflow, self, other)
1208 /// Checked integer subtraction. Computes `self - other`, returning
1209 /// `None` if underflow occurred.
1216 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
1217 /// assert_eq!((-128i8).checked_sub(1), None);
1219 #[stable(feature = "rust1", since = "1.0.0")]
1221 pub fn checked_sub(self, other: Self) -> Option<Self> {
1222 checked_op!($ActualT, $sub_with_overflow, self, other)
1225 /// Checked integer multiplication. Computes `self * other`, returning
1226 /// `None` if underflow or overflow occurred.
1233 /// assert_eq!(5u8.checked_mul(51), Some(255));
1234 /// assert_eq!(5u8.checked_mul(52), None);
1236 #[stable(feature = "rust1", since = "1.0.0")]
1238 pub fn checked_mul(self, other: Self) -> Option<Self> {
1239 checked_op!($ActualT, $mul_with_overflow, self, other)
1242 /// Checked integer division. Computes `self / other`, returning `None`
1243 /// if `other == 0` or the operation results in underflow or overflow.
1250 /// assert_eq!((-127i8).checked_div(-1), Some(127));
1251 /// assert_eq!((-128i8).checked_div(-1), None);
1252 /// assert_eq!((1i8).checked_div(0), None);
1254 #[stable(feature = "rust1", since = "1.0.0")]
1256 pub fn checked_div(self, other: Self) -> Option<Self> {
1259 other => Some(self / other),
1263 /// Saturating integer addition. Computes `self + other`, saturating at
1264 /// the numeric bounds instead of overflowing.
1271 /// assert_eq!(100i8.saturating_add(1), 101);
1272 /// assert_eq!(100i8.saturating_add(127), 127);
1274 #[stable(feature = "rust1", since = "1.0.0")]
1276 pub fn saturating_add(self, other: Self) -> Self {
1277 match self.checked_add(other) {
1279 None if other >= Self::zero() => Self::max_value(),
1280 None => Self::min_value(),
1284 /// Saturating integer subtraction. Computes `self - other`, saturating
1285 /// at the numeric bounds instead of overflowing.
1292 /// assert_eq!(100i8.saturating_sub(127), -27);
1293 /// assert_eq!((-100i8).saturating_sub(127), -128);
1295 #[stable(feature = "rust1", since = "1.0.0")]
1297 pub fn saturating_sub(self, other: Self) -> Self {
1298 match self.checked_sub(other) {
1300 None if other >= Self::zero() => Self::min_value(),
1301 None => Self::max_value(),
1305 /// Wrapping (modular) addition. Computes `self + other`,
1306 /// wrapping around at the boundary of the type.
1313 /// assert_eq!(100i8.wrapping_add(27), 127);
1314 /// assert_eq!(100i8.wrapping_add(127), -29);
1316 #[stable(feature = "rust1", since = "1.0.0")]
1318 pub fn wrapping_add(self, rhs: Self) -> Self {
1320 intrinsics::overflowing_add(self, rhs)
1324 /// Wrapping (modular) subtraction. Computes `self - other`,
1325 /// wrapping around at the boundary of the type.
1332 /// assert_eq!(0i8.wrapping_sub(127), -127);
1333 /// assert_eq!((-2i8).wrapping_sub(127), 127);
1335 #[stable(feature = "rust1", since = "1.0.0")]
1337 pub fn wrapping_sub(self, rhs: Self) -> Self {
1339 intrinsics::overflowing_sub(self, rhs)
1343 /// Wrapping (modular) multiplication. Computes `self *
1344 /// other`, wrapping around at the boundary of the type.
1351 /// assert_eq!(10i8.wrapping_mul(12), 120);
1352 /// assert_eq!(11i8.wrapping_mul(12), -124);
1354 #[stable(feature = "rust1", since = "1.0.0")]
1356 pub fn wrapping_mul(self, rhs: Self) -> Self {
1358 intrinsics::overflowing_mul(self, rhs)
1362 /// Wrapping (modular) division. Computes `self / other`,
1363 /// wrapping around at the boundary of the type.
1365 /// The only case where such wrapping can occur is when one
1366 /// divides `MIN / -1` on a signed type (where `MIN` is the
1367 /// negative minimal value for the type); this is equivalent
1368 /// to `-MIN`, a positive value that is too large to represent
1369 /// in the type. In such a case, this function returns `MIN`
1377 /// assert_eq!(100u8.wrapping_div(10), 10);
1378 /// assert_eq!((-128i8).wrapping_div(-1), -128);
1380 #[stable(feature = "num_wrapping", since = "1.2.0")]
1382 pub fn wrapping_div(self, rhs: Self) -> Self {
1383 self.overflowing_div(rhs).0
1386 /// Wrapping (modular) remainder. Computes `self % other`,
1387 /// wrapping around at the boundary of the type.
1389 /// Such wrap-around never actually occurs mathematically;
1390 /// implementation artifacts make `x % y` invalid for `MIN /
1391 /// -1` on a signed type (where `MIN` is the negative
1392 /// minimal value). In such a case, this function returns `0`.
1399 /// assert_eq!(100i8.wrapping_rem(10), 0);
1400 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
1402 #[stable(feature = "num_wrapping", since = "1.2.0")]
1404 pub fn wrapping_rem(self, rhs: Self) -> Self {
1405 self.overflowing_rem(rhs).0
1408 /// Wrapping (modular) negation. Computes `-self`,
1409 /// wrapping around at the boundary of the type.
1411 /// The only case where such wrapping can occur is when one
1412 /// negates `MIN` on a signed type (where `MIN` is the
1413 /// negative minimal value for the type); this is a positive
1414 /// value that is too large to represent in the type. In such
1415 /// a case, this function returns `MIN` itself.
1422 /// assert_eq!(100i8.wrapping_neg(), -100);
1423 /// assert_eq!((-128i8).wrapping_neg(), -128);
1425 #[stable(feature = "num_wrapping", since = "1.2.0")]
1427 pub fn wrapping_neg(self) -> Self {
1428 self.overflowing_neg().0
1431 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1432 /// where `mask` removes any high-order bits of `rhs` that
1433 /// would cause the shift to exceed the bitwidth of the type.
1440 /// assert_eq!(1u8.wrapping_shl(7), 128);
1441 /// assert_eq!(1u8.wrapping_shl(8), 1);
1443 #[stable(feature = "num_wrapping", since = "1.2.0")]
1445 pub fn wrapping_shl(self, rhs: u32) -> Self {
1446 self.overflowing_shl(rhs).0
1449 /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
1450 /// where `mask` removes any high-order bits of `rhs` that
1451 /// would cause the shift to exceed the bitwidth of the type.
1458 /// assert_eq!(128u8.wrapping_shr(7), 1);
1459 /// assert_eq!(128u8.wrapping_shr(8), 128);
1461 #[stable(feature = "num_wrapping", since = "1.2.0")]
1463 pub fn wrapping_shr(self, rhs: u32) -> Self {
1464 self.overflowing_shr(rhs).0
1467 /// Raises self to the power of `exp`, using exponentiation by squaring.
1474 /// assert_eq!(2i32.pow(4), 16);
1476 #[stable(feature = "rust1", since = "1.0.0")]
1478 pub fn pow(self, mut exp: u32) -> Self {
1479 let mut base = self;
1480 let mut acc = Self::one();
1482 let mut prev_base = self;
1483 let mut base_oflo = false;
1487 // ensure overflow occurs in the same manner it
1488 // would have otherwise (i.e. signal any exception
1489 // it would have otherwise).
1490 acc = acc * (prev_base * prev_base);
1496 let (new_base, new_base_oflo) = base.overflowing_mul(base);
1498 base_oflo = new_base_oflo;
1504 /// Returns `true` if and only if `self == 2^k` for some `k`.
1511 /// assert!(16u8.is_power_of_two());
1512 /// assert!(!10u8.is_power_of_two());
1514 #[stable(feature = "rust1", since = "1.0.0")]
1516 pub fn is_power_of_two(self) -> bool {
1517 (self.wrapping_sub(Self::one())) & self == Self::zero() &&
1518 !(self == Self::zero())
1521 /// Returns the smallest power of two greater than or equal to `self`.
1522 /// Unspecified behavior on overflow.
1529 /// assert_eq!(2u8.next_power_of_two(), 2);
1530 /// assert_eq!(3u8.next_power_of_two(), 4);
1532 #[stable(feature = "rust1", since = "1.0.0")]
1534 pub fn next_power_of_two(self) -> Self {
1535 let bits = size_of::<Self>() * 8;
1536 let one: Self = Self::one();
1537 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
1540 /// Returns the smallest power of two greater than or equal to `n`. If
1541 /// the next power of two is greater than the type's maximum value,
1542 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
1549 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
1550 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
1551 /// assert_eq!(200u8.checked_next_power_of_two(), None);
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 pub fn checked_next_power_of_two(self) -> Option<Self> {
1555 let npot = self.next_power_of_two();
1573 intrinsics::u8_add_with_overflow,
1574 intrinsics::u8_sub_with_overflow,
1575 intrinsics::u8_mul_with_overflow }
1585 intrinsics::add_with_overflow,
1586 intrinsics::sub_with_overflow,
1587 intrinsics::mul_with_overflow }
1593 uint_impl! { u16, 16,
1594 intrinsics::ctpop16,
1597 intrinsics::bswap16,
1598 intrinsics::u16_add_with_overflow,
1599 intrinsics::u16_sub_with_overflow,
1600 intrinsics::u16_mul_with_overflow }
1605 uint_impl! { u16, 16,
1610 intrinsics::add_with_overflow,
1611 intrinsics::sub_with_overflow,
1612 intrinsics::mul_with_overflow }
1618 uint_impl! { u32, 32,
1619 intrinsics::ctpop32,
1622 intrinsics::bswap32,
1623 intrinsics::u32_add_with_overflow,
1624 intrinsics::u32_sub_with_overflow,
1625 intrinsics::u32_mul_with_overflow }
1630 uint_impl! { u32, 32,
1635 intrinsics::add_with_overflow,
1636 intrinsics::sub_with_overflow,
1637 intrinsics::mul_with_overflow }
1643 uint_impl! { u64, 64,
1644 intrinsics::ctpop64,
1647 intrinsics::bswap64,
1648 intrinsics::u64_add_with_overflow,
1649 intrinsics::u64_sub_with_overflow,
1650 intrinsics::u64_mul_with_overflow }
1655 uint_impl! { u64, 64,
1660 intrinsics::add_with_overflow,
1661 intrinsics::sub_with_overflow,
1662 intrinsics::mul_with_overflow }
1665 #[cfg(target_pointer_width = "32")]
1669 uint_impl! { u32, 32,
1670 intrinsics::ctpop32,
1673 intrinsics::bswap32,
1674 intrinsics::u32_add_with_overflow,
1675 intrinsics::u32_sub_with_overflow,
1676 intrinsics::u32_mul_with_overflow }
1678 #[cfg(target_pointer_width = "32")]
1682 uint_impl! { u32, 32,
1687 intrinsics::add_with_overflow,
1688 intrinsics::sub_with_overflow,
1689 intrinsics::mul_with_overflow }
1692 #[cfg(target_pointer_width = "64")]
1696 uint_impl! { u64, 64,
1697 intrinsics::ctpop64,
1700 intrinsics::bswap64,
1701 intrinsics::u64_add_with_overflow,
1702 intrinsics::u64_sub_with_overflow,
1703 intrinsics::u64_mul_with_overflow }
1705 #[cfg(target_pointer_width = "64")]
1709 uint_impl! { u64, 64,
1714 intrinsics::add_with_overflow,
1715 intrinsics::sub_with_overflow,
1716 intrinsics::mul_with_overflow }
1719 /// Used for representing the classification of floating point numbers
1720 #[derive(Copy, Clone, PartialEq, Debug)]
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 pub enum FpCategory {
1723 /// "Not a Number", often obtained by dividing by zero
1724 #[stable(feature = "rust1", since = "1.0.0")]
1727 /// Positive or negative infinity
1728 #[stable(feature = "rust1", since = "1.0.0")]
1731 /// Positive or negative zero
1732 #[stable(feature = "rust1", since = "1.0.0")]
1735 /// De-normalized floating point representation (less precise than `Normal`)
1736 #[stable(feature = "rust1", since = "1.0.0")]
1739 /// A regular floating point number
1740 #[stable(feature = "rust1", since = "1.0.0")]
1744 /// A built-in floating point number.
1746 #[unstable(feature = "core_float",
1747 reason = "stable interface is via `impl f{32,64}` in later crates",
1749 pub trait Float: Sized {
1750 /// Returns the NaN value.
1751 #[unstable(feature = "float_extras", reason = "needs removal",
1754 /// Returns the infinite value.
1755 #[unstable(feature = "float_extras", reason = "needs removal",
1757 fn infinity() -> Self;
1758 /// Returns the negative infinite value.
1759 #[unstable(feature = "float_extras", reason = "needs removal",
1761 fn neg_infinity() -> Self;
1763 #[unstable(feature = "float_extras", reason = "needs removal",
1765 fn neg_zero() -> Self;
1767 #[unstable(feature = "float_extras", reason = "needs removal",
1771 #[unstable(feature = "float_extras", reason = "needs removal",
1774 /// Parses the string `s` with the radix `r` as a float.
1775 #[unstable(feature = "float_from_str_radix", reason = "recently moved API",
1777 #[rustc_deprecated(since = "1.4.0",
1778 reason = "unclear how useful or correct this is")]
1779 fn from_str_radix(s: &str, r: u32) -> Result<Self, ParseFloatError>;
1781 /// Returns true if this value is NaN and false otherwise.
1782 #[stable(feature = "core", since = "1.6.0")]
1783 fn is_nan(self) -> bool;
1784 /// Returns true if this value is positive infinity or negative infinity and
1785 /// false otherwise.
1786 #[stable(feature = "core", since = "1.6.0")]
1787 fn is_infinite(self) -> bool;
1788 /// Returns true if this number is neither infinite nor NaN.
1789 #[stable(feature = "core", since = "1.6.0")]
1790 fn is_finite(self) -> bool;
1791 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1792 #[stable(feature = "core", since = "1.6.0")]
1793 fn is_normal(self) -> bool;
1794 /// Returns the category that this number falls into.
1795 #[stable(feature = "core", since = "1.6.0")]
1796 fn classify(self) -> FpCategory;
1798 /// Returns the mantissa, exponent and sign as integers, respectively.
1799 #[unstable(feature = "float_extras", reason = "signature is undecided",
1801 fn integer_decode(self) -> (u64, i16, i8);
1803 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1804 /// number is `Float::nan()`.
1805 #[stable(feature = "core", since = "1.6.0")]
1806 fn abs(self) -> Self;
1807 /// Returns a number that represents the sign of `self`.
1809 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1810 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1811 /// - `Float::nan()` if the number is `Float::nan()`
1812 #[stable(feature = "core", since = "1.6.0")]
1813 fn signum(self) -> Self;
1815 /// Returns `true` if `self` is positive, including `+0.0` and
1816 /// `Float::infinity()`.
1817 #[stable(feature = "core", since = "1.6.0")]
1818 fn is_sign_positive(self) -> bool;
1819 /// Returns `true` if `self` is negative, including `-0.0` and
1820 /// `Float::neg_infinity()`.
1821 #[stable(feature = "core", since = "1.6.0")]
1822 fn is_sign_negative(self) -> bool;
1824 /// Take the reciprocal (inverse) of a number, `1/x`.
1825 #[stable(feature = "core", since = "1.6.0")]
1826 fn recip(self) -> Self;
1828 /// Raise a number to an integer power.
1830 /// Using this function is generally faster than using `powf`
1831 #[stable(feature = "core", since = "1.6.0")]
1832 fn powi(self, n: i32) -> Self;
1834 /// Convert radians to degrees.
1835 #[unstable(feature = "float_extras", reason = "desirability is unclear",
1837 fn to_degrees(self) -> Self;
1838 /// Convert degrees to radians.
1839 #[unstable(feature = "float_extras", reason = "desirability is unclear",
1841 fn to_radians(self) -> Self;
1844 macro_rules! from_str_radix_int_impl {
1846 #[stable(feature = "rust1", since = "1.0.0")]
1847 impl FromStr for $t {
1848 type Err = ParseIntError;
1849 fn from_str(src: &str) -> Result<Self, ParseIntError> {
1850 from_str_radix(src, 10)
1855 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
1858 trait FromStrRadixHelper: PartialOrd + Copy {
1859 fn min_value() -> Self;
1860 fn from_u32(u: u32) -> Self;
1861 fn checked_mul(&self, other: u32) -> Option<Self>;
1862 fn checked_sub(&self, other: u32) -> Option<Self>;
1863 fn checked_add(&self, other: u32) -> Option<Self>;
1867 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
1868 fn min_value() -> Self { Self::min_value() }
1869 fn from_u32(u: u32) -> Self { u as Self }
1870 fn checked_mul(&self, other: u32) -> Option<Self> {
1871 Self::checked_mul(*self, other as Self)
1873 fn checked_sub(&self, other: u32) -> Option<Self> {
1874 Self::checked_sub(*self, other as Self)
1876 fn checked_add(&self, other: u32) -> Option<Self> {
1877 Self::checked_add(*self, other as Self)
1881 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1883 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
1884 -> Result<T, ParseIntError> {
1885 use self::IntErrorKind::*;
1886 use self::ParseIntError as PIE;
1888 assert!(radix >= 2 && radix <= 36,
1889 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1893 return Err(PIE { kind: Empty });
1896 let is_signed_ty = T::from_u32(0) > T::min_value();
1898 // all valid digits are ascii, so we will just iterate over the utf8 bytes
1899 // and cast them to chars. .to_digit() will safely return None for anything
1900 // other than a valid ascii digit for the given radix, including the first-byte
1901 // of multi-byte sequences
1902 let src = src.as_bytes();
1904 let (is_positive, digits) = match src[0] {
1905 b'+' => (true, &src[1..]),
1906 b'-' if is_signed_ty => (false, &src[1..]),
1910 if digits.is_empty() {
1911 return Err(PIE { kind: Empty });
1914 let mut result = T::from_u32(0);
1916 // The number is positive
1918 let x = match (c as char).to_digit(radix) {
1920 None => return Err(PIE { kind: InvalidDigit }),
1922 result = match result.checked_mul(radix) {
1923 Some(result) => result,
1924 None => return Err(PIE { kind: Overflow }),
1926 result = match result.checked_add(x) {
1927 Some(result) => result,
1928 None => return Err(PIE { kind: Overflow }),
1932 // The number is negative
1934 let x = match (c as char).to_digit(radix) {
1936 None => return Err(PIE { kind: InvalidDigit }),
1938 result = match result.checked_mul(radix) {
1939 Some(result) => result,
1940 None => return Err(PIE { kind: Underflow }),
1942 result = match result.checked_sub(x) {
1943 Some(result) => result,
1944 None => return Err(PIE { kind: Underflow }),
1951 /// An error which can be returned when parsing an integer.
1952 #[derive(Debug, Clone, PartialEq)]
1953 #[stable(feature = "rust1", since = "1.0.0")]
1954 pub struct ParseIntError { kind: IntErrorKind }
1956 #[derive(Debug, Clone, PartialEq)]
1964 impl ParseIntError {
1965 #[unstable(feature = "int_error_internals",
1966 reason = "available through Error trait and this method should \
1967 not be exposed publicly",
1970 pub fn __description(&self) -> &str {
1972 IntErrorKind::Empty => "cannot parse integer from empty string",
1973 IntErrorKind::InvalidDigit => "invalid digit found in string",
1974 IntErrorKind::Overflow => "number too large to fit in target type",
1975 IntErrorKind::Underflow => "number too small to fit in target type",
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 impl fmt::Display for ParseIntError {
1982 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1983 self.__description().fmt(f)
1987 #[stable(feature = "rust1", since = "1.0.0")]
1988 pub use num::dec2flt::ParseFloatError;
1990 // Conversion traits for primitive integer and float types
1991 // Conversions T -> T are covered by a blanket impl and therefore excluded
1992 // Some conversions from and to usize/isize are not implemented due to portability concerns
1993 macro_rules! impl_from {
1994 ($Small: ty, $Large: ty) => {
1995 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
1996 impl From<$Small> for $Large {
1998 fn from(small: $Small) -> $Large {
2005 // Unsigned -> Unsigned
2006 impl_from! { u8, u16 }
2007 impl_from! { u8, u32 }
2008 impl_from! { u8, u64 }
2009 impl_from! { u8, usize }
2010 impl_from! { u16, u32 }
2011 impl_from! { u16, u64 }
2012 impl_from! { u32, u64 }
2015 impl_from! { i8, i16 }
2016 impl_from! { i8, i32 }
2017 impl_from! { i8, i64 }
2018 impl_from! { i8, isize }
2019 impl_from! { i16, i32 }
2020 impl_from! { i16, i64 }
2021 impl_from! { i32, i64 }
2023 // Unsigned -> Signed
2024 impl_from! { u8, i16 }
2025 impl_from! { u8, i32 }
2026 impl_from! { u8, i64 }
2027 impl_from! { u16, i32 }
2028 impl_from! { u16, i64 }
2029 impl_from! { u32, i64 }
2031 // Note: integers can only be represented with full precision in a float if
2032 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2033 // Lossy float conversions are not implemented at this time.
2036 impl_from! { i8, f32 }
2037 impl_from! { i8, f64 }
2038 impl_from! { i16, f32 }
2039 impl_from! { i16, f64 }
2040 impl_from! { i32, f64 }
2042 // Unsigned -> Float
2043 impl_from! { u8, f32 }
2044 impl_from! { u8, f64 }
2045 impl_from! { u16, f32 }
2046 impl_from! { u16, f64 }
2047 impl_from! { u32, f64 }
2050 impl_from! { f32, f64 }