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 {
82 fn zero() -> Self { 0 }
86 fn one() -> Self { 1 }
90 zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
92 macro_rules! zero_one_impl_float {
96 fn zero() -> Self { 0.0 }
100 fn one() -> Self { 1.0 }
104 zero_one_impl_float! { f32 f64 }
106 // Just for stage0; a byte swap on a byte is a no-op
107 // Delete this once it becomes unused
109 unsafe fn bswap8(x: u8) -> u8 { x }
111 macro_rules! checked_op {
112 ($U:ty, $op:path, $x:expr, $y:expr) => {{
113 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
114 if overflowed { None } else { Some(result as Self) }
118 // `Int` + `SignedInt` implemented for signed integers
119 macro_rules! int_impl {
120 ($ActualT:ty, $UnsignedT:ty, $BITS:expr,
121 $add_with_overflow:path,
122 $sub_with_overflow:path,
123 $mul_with_overflow:path) => {
124 /// Returns the smallest value that can be represented by this integer type.
125 #[stable(feature = "rust1", since = "1.0.0")]
127 pub const fn min_value() -> Self {
128 (-1 as Self) << ($BITS - 1)
131 /// Returns the largest value that can be represented by this integer type.
132 #[stable(feature = "rust1", since = "1.0.0")]
134 pub const fn max_value() -> Self {
138 /// Converts a string slice in a given base to an integer.
140 /// Leading and trailing whitespace represent an error.
147 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
149 #[stable(feature = "rust1", since = "1.0.0")]
150 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
151 from_str_radix(src, radix)
154 /// Returns the number of ones in the binary representation of `self`.
161 /// let n = 0b01001100u8;
163 /// assert_eq!(n.count_ones(), 3);
165 #[stable(feature = "rust1", since = "1.0.0")]
167 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
169 /// Returns the number of zeros in the binary representation of `self`.
176 /// let n = 0b01001100u8;
178 /// assert_eq!(n.count_zeros(), 5);
180 #[stable(feature = "rust1", since = "1.0.0")]
182 pub fn count_zeros(self) -> u32 {
186 /// Returns the number of leading zeros in the binary representation
194 /// let n = 0b0101000u16;
196 /// assert_eq!(n.leading_zeros(), 10);
198 #[stable(feature = "rust1", since = "1.0.0")]
200 pub fn leading_zeros(self) -> u32 {
201 (self as $UnsignedT).leading_zeros()
204 /// Returns the number of trailing zeros in the binary representation
212 /// let n = 0b0101000u16;
214 /// assert_eq!(n.trailing_zeros(), 3);
216 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn trailing_zeros(self) -> u32 {
219 (self as $UnsignedT).trailing_zeros()
222 /// Shifts the bits to the left by a specified amount, `n`,
223 /// wrapping the truncated bits to the end of the resulting integer.
230 /// let n = 0x0123456789ABCDEFu64;
231 /// let m = 0x3456789ABCDEF012u64;
233 /// assert_eq!(n.rotate_left(12), m);
235 #[stable(feature = "rust1", since = "1.0.0")]
237 pub fn rotate_left(self, n: u32) -> Self {
238 (self as $UnsignedT).rotate_left(n) as Self
241 /// Shifts the bits to the right by a specified amount, `n`,
242 /// wrapping the truncated bits to the beginning of the resulting
250 /// let n = 0x0123456789ABCDEFu64;
251 /// let m = 0xDEF0123456789ABCu64;
253 /// assert_eq!(n.rotate_right(12), m);
255 #[stable(feature = "rust1", since = "1.0.0")]
257 pub fn rotate_right(self, n: u32) -> Self {
258 (self as $UnsignedT).rotate_right(n) as Self
261 /// Reverses the byte order of the integer.
268 /// let n = 0x0123456789ABCDEFu64;
269 /// let m = 0xEFCDAB8967452301u64;
271 /// assert_eq!(n.swap_bytes(), m);
273 #[stable(feature = "rust1", since = "1.0.0")]
275 pub fn swap_bytes(self) -> Self {
276 (self as $UnsignedT).swap_bytes() as Self
279 /// Converts an integer from big endian to the target's endianness.
281 /// On big endian this is a no-op. On little endian the bytes are
289 /// let n = 0x0123456789ABCDEFu64;
291 /// if cfg!(target_endian = "big") {
292 /// assert_eq!(u64::from_be(n), n)
294 /// assert_eq!(u64::from_be(n), n.swap_bytes())
297 #[stable(feature = "rust1", since = "1.0.0")]
299 pub fn from_be(x: Self) -> Self {
300 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
303 /// Converts an integer from little endian to the target's endianness.
305 /// On little endian this is a no-op. On big endian the bytes are
313 /// let n = 0x0123456789ABCDEFu64;
315 /// if cfg!(target_endian = "little") {
316 /// assert_eq!(u64::from_le(n), n)
318 /// assert_eq!(u64::from_le(n), n.swap_bytes())
321 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn from_le(x: Self) -> Self {
324 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
327 /// Converts `self` to big endian from the target's endianness.
329 /// On big endian this is a no-op. On little endian the bytes are
337 /// let n = 0x0123456789ABCDEFu64;
339 /// if cfg!(target_endian = "big") {
340 /// assert_eq!(n.to_be(), n)
342 /// assert_eq!(n.to_be(), n.swap_bytes())
345 #[stable(feature = "rust1", since = "1.0.0")]
347 pub fn to_be(self) -> Self { // or not to be?
348 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
351 /// Converts `self` to little endian from the target's endianness.
353 /// On little endian this is a no-op. On big endian the bytes are
361 /// let n = 0x0123456789ABCDEFu64;
363 /// if cfg!(target_endian = "little") {
364 /// assert_eq!(n.to_le(), n)
366 /// assert_eq!(n.to_le(), n.swap_bytes())
369 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn to_le(self) -> Self {
372 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
375 /// Checked integer addition. Computes `self + other`, returning `None`
376 /// if overflow occurred.
383 /// assert_eq!(5u16.checked_add(65530), Some(65535));
384 /// assert_eq!(6u16.checked_add(65530), None);
386 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn checked_add(self, other: Self) -> Option<Self> {
389 checked_op!($ActualT, $add_with_overflow, self, other)
392 /// Checked integer subtraction. Computes `self - other`, returning
393 /// `None` if underflow occurred.
400 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
401 /// assert_eq!((-128i8).checked_sub(1), None);
403 #[stable(feature = "rust1", since = "1.0.0")]
405 pub fn checked_sub(self, other: Self) -> Option<Self> {
406 checked_op!($ActualT, $sub_with_overflow, self, other)
409 /// Checked integer multiplication. Computes `self * other`, returning
410 /// `None` if underflow or overflow occurred.
417 /// assert_eq!(5u8.checked_mul(51), Some(255));
418 /// assert_eq!(5u8.checked_mul(52), None);
420 #[stable(feature = "rust1", since = "1.0.0")]
422 pub fn checked_mul(self, other: Self) -> Option<Self> {
423 checked_op!($ActualT, $mul_with_overflow, self, other)
426 /// Checked integer division. Computes `self / other`, returning `None`
427 /// if `other == 0` or the operation results in underflow or overflow.
434 /// assert_eq!((-127i8).checked_div(-1), Some(127));
435 /// assert_eq!((-128i8).checked_div(-1), None);
436 /// assert_eq!((1i8).checked_div(0), None);
438 #[stable(feature = "rust1", since = "1.0.0")]
440 pub fn checked_div(self, other: Self) -> Option<Self> {
443 -1 if self == Self::min_value()
445 other => Some(self / other),
449 /// Saturating integer addition. Computes `self + other`, saturating at
450 /// the numeric bounds instead of overflowing.
457 /// assert_eq!(100i8.saturating_add(1), 101);
458 /// assert_eq!(100i8.saturating_add(127), 127);
460 #[stable(feature = "rust1", since = "1.0.0")]
462 pub fn saturating_add(self, other: Self) -> Self {
463 match self.checked_add(other) {
465 None if other >= Self::zero() => Self::max_value(),
466 None => Self::min_value(),
470 /// Saturating integer subtraction. Computes `self - other`, saturating
471 /// at the numeric bounds instead of overflowing.
478 /// assert_eq!(100i8.saturating_sub(127), -27);
479 /// assert_eq!((-100i8).saturating_sub(127), -128);
481 #[stable(feature = "rust1", since = "1.0.0")]
483 pub fn saturating_sub(self, other: Self) -> Self {
484 match self.checked_sub(other) {
486 None if other >= Self::zero() => Self::min_value(),
487 None => Self::max_value(),
491 /// Wrapping (modular) addition. Computes `self + other`,
492 /// wrapping around at the boundary of the type.
499 /// assert_eq!(100i8.wrapping_add(27), 127);
500 /// assert_eq!(100i8.wrapping_add(127), -29);
502 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn wrapping_add(self, rhs: Self) -> Self {
506 intrinsics::overflowing_add(self, rhs)
510 /// Wrapping (modular) subtraction. Computes `self - other`,
511 /// wrapping around at the boundary of the type.
518 /// assert_eq!(0i8.wrapping_sub(127), -127);
519 /// assert_eq!((-2i8).wrapping_sub(127), 127);
521 #[stable(feature = "rust1", since = "1.0.0")]
523 pub fn wrapping_sub(self, rhs: Self) -> Self {
525 intrinsics::overflowing_sub(self, rhs)
529 /// Wrapping (modular) multiplication. Computes `self *
530 /// other`, wrapping around at the boundary of the type.
537 /// assert_eq!(10i8.wrapping_mul(12), 120);
538 /// assert_eq!(11i8.wrapping_mul(12), -124);
540 #[stable(feature = "rust1", since = "1.0.0")]
542 pub fn wrapping_mul(self, rhs: Self) -> Self {
544 intrinsics::overflowing_mul(self, rhs)
548 /// Wrapping (modular) division. Computes `self / other`,
549 /// wrapping around at the boundary of the type.
551 /// The only case where such wrapping can occur is when one
552 /// divides `MIN / -1` on a signed type (where `MIN` is the
553 /// negative minimal value for the type); this is equivalent
554 /// to `-MIN`, a positive value that is too large to represent
555 /// in the type. In such a case, this function returns `MIN`
563 /// assert_eq!(100u8.wrapping_div(10), 10);
564 /// assert_eq!((-128i8).wrapping_div(-1), -128);
566 #[stable(feature = "num_wrapping", since = "1.2.0")]
568 pub fn wrapping_div(self, rhs: Self) -> Self {
569 self.overflowing_div(rhs).0
572 /// Wrapping (modular) remainder. Computes `self % other`,
573 /// wrapping around at the boundary of the type.
575 /// Such wrap-around never actually occurs mathematically;
576 /// implementation artifacts make `x % y` invalid for `MIN /
577 /// -1` on a signed type (where `MIN` is the negative
578 /// minimal value). In such a case, this function returns `0`.
585 /// assert_eq!(100i8.wrapping_rem(10), 0);
586 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
588 #[stable(feature = "num_wrapping", since = "1.2.0")]
590 pub fn wrapping_rem(self, rhs: Self) -> Self {
591 self.overflowing_rem(rhs).0
594 /// Wrapping (modular) negation. Computes `-self`,
595 /// wrapping around at the boundary of the type.
597 /// The only case where such wrapping can occur is when one
598 /// negates `MIN` on a signed type (where `MIN` is the
599 /// negative minimal value for the type); this is a positive
600 /// value that is too large to represent in the type. In such
601 /// a case, this function returns `MIN` itself.
608 /// assert_eq!(100i8.wrapping_neg(), -100);
609 /// assert_eq!((-128i8).wrapping_neg(), -128);
611 #[stable(feature = "num_wrapping", since = "1.2.0")]
613 pub fn wrapping_neg(self) -> Self {
614 self.overflowing_neg().0
617 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
618 /// where `mask` removes any high-order bits of `rhs` that
619 /// would cause the shift to exceed the bitwidth of the type.
626 /// assert_eq!(1u8.wrapping_shl(7), 128);
627 /// assert_eq!(1u8.wrapping_shl(8), 1);
629 #[stable(feature = "num_wrapping", since = "1.2.0")]
631 pub fn wrapping_shl(self, rhs: u32) -> Self {
632 self.overflowing_shl(rhs).0
635 /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
636 /// where `mask` removes any high-order bits of `rhs` that
637 /// would cause the shift to exceed the bitwidth of the type.
644 /// assert_eq!(128u8.wrapping_shr(7), 1);
645 /// assert_eq!(128u8.wrapping_shr(8), 128);
647 #[stable(feature = "num_wrapping", since = "1.2.0")]
649 pub fn wrapping_shr(self, rhs: u32) -> Self {
650 self.overflowing_shr(rhs).0
653 /// Raises self to the power of `exp`, using exponentiation by squaring.
660 /// let x: i32 = 2; // or any other integer type
662 /// assert_eq!(x.pow(4), 16);
664 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn pow(self, mut exp: u32) -> Self {
668 let mut acc = Self::one();
678 // Deal with the final bit of the exponent separately, since
679 // squaring the base afterwards is not necessary and may cause a
680 // needless overflow.
688 /// Computes the absolute value of `self`.
690 /// # Overflow behavior
692 /// The absolute value of `i32::min_value()` cannot be represented as an
693 /// `i32`, and attempting to calculate it will cause an overflow. This
694 /// means that code in debug mode will trigger a panic on this case and
695 /// optimized code will return `i32::min_value()` without a panic.
702 /// assert_eq!(10i8.abs(), 10);
703 /// assert_eq!((-10i8).abs(), 10);
705 #[stable(feature = "rust1", since = "1.0.0")]
707 pub fn abs(self) -> Self {
708 if self.is_negative() {
709 // Note that the #[inline] above means that the overflow
710 // semantics of this negation depend on the crate we're being
718 /// Returns a number representing sign of `self`.
720 /// - `0` if the number is zero
721 /// - `1` if the number is positive
722 /// - `-1` if the number is negative
729 /// assert_eq!(10i8.signum(), 1);
730 /// assert_eq!(0i8.signum(), 0);
731 /// assert_eq!((-10i8).signum(), -1);
733 #[stable(feature = "rust1", since = "1.0.0")]
735 pub fn signum(self) -> Self {
743 /// Returns `true` if `self` is positive and `false` if the number
744 /// is zero or negative.
751 /// assert!(10i8.is_positive());
752 /// assert!(!(-10i8).is_positive());
754 #[stable(feature = "rust1", since = "1.0.0")]
756 pub fn is_positive(self) -> bool { self > 0 }
758 /// Returns `true` if `self` is negative and `false` if the number
759 /// is zero or positive.
766 /// assert!((-10i8).is_negative());
767 /// assert!(!10i8.is_negative());
769 #[stable(feature = "rust1", since = "1.0.0")]
771 pub fn is_negative(self) -> bool { self < 0 }
778 int_impl! { i8, u8, 8,
779 intrinsics::i8_add_with_overflow,
780 intrinsics::i8_sub_with_overflow,
781 intrinsics::i8_mul_with_overflow }
786 int_impl! { i8, u8, 8,
787 intrinsics::add_with_overflow,
788 intrinsics::sub_with_overflow,
789 intrinsics::mul_with_overflow }
795 int_impl! { i16, u16, 16,
796 intrinsics::i16_add_with_overflow,
797 intrinsics::i16_sub_with_overflow,
798 intrinsics::i16_mul_with_overflow }
803 int_impl! { i16, u16, 16,
804 intrinsics::add_with_overflow,
805 intrinsics::sub_with_overflow,
806 intrinsics::mul_with_overflow }
812 int_impl! { i32, u32, 32,
813 intrinsics::i32_add_with_overflow,
814 intrinsics::i32_sub_with_overflow,
815 intrinsics::i32_mul_with_overflow }
820 int_impl! { i32, u32, 32,
821 intrinsics::add_with_overflow,
822 intrinsics::sub_with_overflow,
823 intrinsics::mul_with_overflow }
829 int_impl! { i64, u64, 64,
830 intrinsics::i64_add_with_overflow,
831 intrinsics::i64_sub_with_overflow,
832 intrinsics::i64_mul_with_overflow }
837 int_impl! { i64, u64, 64,
838 intrinsics::add_with_overflow,
839 intrinsics::sub_with_overflow,
840 intrinsics::mul_with_overflow }
843 #[cfg(target_pointer_width = "32")]
847 int_impl! { i32, u32, 32,
848 intrinsics::i32_add_with_overflow,
849 intrinsics::i32_sub_with_overflow,
850 intrinsics::i32_mul_with_overflow }
852 #[cfg(target_pointer_width = "32")]
856 int_impl! { i32, u32, 32,
857 intrinsics::add_with_overflow,
858 intrinsics::sub_with_overflow,
859 intrinsics::mul_with_overflow }
862 #[cfg(target_pointer_width = "64")]
866 int_impl! { i64, u64, 64,
867 intrinsics::i64_add_with_overflow,
868 intrinsics::i64_sub_with_overflow,
869 intrinsics::i64_mul_with_overflow }
871 #[cfg(target_pointer_width = "64")]
875 int_impl! { i64, u64, 64,
876 intrinsics::add_with_overflow,
877 intrinsics::sub_with_overflow,
878 intrinsics::mul_with_overflow }
881 // `Int` + `UnsignedInt` implemented for signed integers
882 macro_rules! uint_impl {
883 ($ActualT:ty, $BITS:expr,
888 $add_with_overflow:path,
889 $sub_with_overflow:path,
890 $mul_with_overflow:path) => {
891 /// Returns the smallest value that can be represented by this integer type.
892 #[stable(feature = "rust1", since = "1.0.0")]
894 pub const fn min_value() -> Self { 0 }
896 /// Returns the largest value that can be represented by this integer type.
897 #[stable(feature = "rust1", since = "1.0.0")]
899 pub const fn max_value() -> Self { !0 }
901 /// Converts a string slice in a given base to an integer.
903 /// Leading and trailing whitespace represent an error.
907 /// * src - A string slice
908 /// * radix - The base to use. Must lie in the range [2 .. 36]
912 /// `Err(ParseIntError)` if the string did not represent a valid number.
913 /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
914 #[stable(feature = "rust1", since = "1.0.0")]
915 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
916 from_str_radix(src, radix)
919 /// Returns the number of ones in the binary representation of `self`.
926 /// let n = 0b01001100u8;
928 /// assert_eq!(n.count_ones(), 3);
930 #[stable(feature = "rust1", since = "1.0.0")]
932 pub fn count_ones(self) -> u32 {
933 unsafe { $ctpop(self as $ActualT) as u32 }
936 /// Returns the number of zeros in the binary representation of `self`.
943 /// let n = 0b01001100u8;
945 /// assert_eq!(n.count_zeros(), 5);
947 #[stable(feature = "rust1", since = "1.0.0")]
949 pub fn count_zeros(self) -> u32 {
953 /// Returns the number of leading zeros in the binary representation
961 /// let n = 0b0101000u16;
963 /// assert_eq!(n.leading_zeros(), 10);
965 #[stable(feature = "rust1", since = "1.0.0")]
967 pub fn leading_zeros(self) -> u32 {
968 unsafe { $ctlz(self as $ActualT) as u32 }
971 #[stable(feature = "rust1", since = "1.0.0")]
974 pub fn trailing_zeros(self) -> u32 {
975 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
976 // emits two conditional moves on x86_64. By promoting the value to
977 // u16 and setting bit 8, we get better code without any conditional
979 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
980 // pending, remove this workaround once LLVM generates better code
984 intrinsics::cttz16(self as u16 | 0x100) as u32
986 $cttz(self as $ActualT) as u32
990 /// Returns the number of trailing zeros in the binary representation
998 /// let n = 0b0101000u16;
1000 /// assert_eq!(n.trailing_zeros(), 3);
1002 #[stable(feature = "rust1", since = "1.0.0")]
1005 pub fn trailing_zeros(self) -> u32 {
1006 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1007 // emits two conditional moves on x86_64. By promoting the value to
1008 // u16 and setting bit 8, we get better code without any conditional
1010 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1011 // pending, remove this workaround once LLVM generates better code
1015 intrinsics::cttz(self as u16 | 0x100) as u32
1017 intrinsics::cttz(self) as u32
1022 /// Shifts the bits to the left by a specified amount, `n`,
1023 /// wrapping the truncated bits to the end of the resulting integer.
1030 /// let n = 0x0123456789ABCDEFu64;
1031 /// let m = 0x3456789ABCDEF012u64;
1033 /// assert_eq!(n.rotate_left(12), m);
1035 #[stable(feature = "rust1", since = "1.0.0")]
1037 pub fn rotate_left(self, n: u32) -> Self {
1038 // Protect against undefined behaviour for over-long bit shifts
1040 (self << n) | (self >> (($BITS - n) % $BITS))
1043 /// Shifts the bits to the right by a specified amount, `n`,
1044 /// wrapping the truncated bits to the beginning of the resulting
1052 /// let n = 0x0123456789ABCDEFu64;
1053 /// let m = 0xDEF0123456789ABCu64;
1055 /// assert_eq!(n.rotate_right(12), m);
1057 #[stable(feature = "rust1", since = "1.0.0")]
1059 pub fn rotate_right(self, n: u32) -> Self {
1060 // Protect against undefined behaviour for over-long bit shifts
1062 (self >> n) | (self << (($BITS - n) % $BITS))
1065 /// Reverses the byte order of the integer.
1072 /// let n = 0x0123456789ABCDEFu64;
1073 /// let m = 0xEFCDAB8967452301u64;
1075 /// assert_eq!(n.swap_bytes(), m);
1077 #[stable(feature = "rust1", since = "1.0.0")]
1079 pub fn swap_bytes(self) -> Self {
1080 unsafe { $bswap(self as $ActualT) as Self }
1083 /// Converts an integer from big endian to the target's endianness.
1085 /// On big endian this is a no-op. On little endian the bytes are
1093 /// let n = 0x0123456789ABCDEFu64;
1095 /// if cfg!(target_endian = "big") {
1096 /// assert_eq!(u64::from_be(n), n)
1098 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1101 #[stable(feature = "rust1", since = "1.0.0")]
1103 pub fn from_be(x: Self) -> Self {
1104 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1107 /// Converts an integer from little endian to the target's endianness.
1109 /// On little endian this is a no-op. On big endian the bytes are
1117 /// let n = 0x0123456789ABCDEFu64;
1119 /// if cfg!(target_endian = "little") {
1120 /// assert_eq!(u64::from_le(n), n)
1122 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1125 #[stable(feature = "rust1", since = "1.0.0")]
1127 pub fn from_le(x: Self) -> Self {
1128 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1131 /// Converts `self` to big endian from the target's endianness.
1133 /// On big endian this is a no-op. On little endian the bytes are
1141 /// let n = 0x0123456789ABCDEFu64;
1143 /// if cfg!(target_endian = "big") {
1144 /// assert_eq!(n.to_be(), n)
1146 /// assert_eq!(n.to_be(), n.swap_bytes())
1149 #[stable(feature = "rust1", since = "1.0.0")]
1151 pub fn to_be(self) -> Self { // or not to be?
1152 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1155 /// Converts `self` to little endian from the target's endianness.
1157 /// On little endian this is a no-op. On big endian the bytes are
1165 /// let n = 0x0123456789ABCDEFu64;
1167 /// if cfg!(target_endian = "little") {
1168 /// assert_eq!(n.to_le(), n)
1170 /// assert_eq!(n.to_le(), n.swap_bytes())
1173 #[stable(feature = "rust1", since = "1.0.0")]
1175 pub fn to_le(self) -> Self {
1176 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1179 /// Checked integer addition. Computes `self + other`, returning `None`
1180 /// if overflow occurred.
1187 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1188 /// assert_eq!(6u16.checked_add(65530), None);
1190 #[stable(feature = "rust1", since = "1.0.0")]
1192 pub fn checked_add(self, other: Self) -> Option<Self> {
1193 checked_op!($ActualT, $add_with_overflow, self, other)
1196 /// Checked integer subtraction. Computes `self - other`, returning
1197 /// `None` if underflow occurred.
1204 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
1205 /// assert_eq!((-128i8).checked_sub(1), None);
1207 #[stable(feature = "rust1", since = "1.0.0")]
1209 pub fn checked_sub(self, other: Self) -> Option<Self> {
1210 checked_op!($ActualT, $sub_with_overflow, self, other)
1213 /// Checked integer multiplication. Computes `self * other`, returning
1214 /// `None` if underflow or overflow occurred.
1221 /// assert_eq!(5u8.checked_mul(51), Some(255));
1222 /// assert_eq!(5u8.checked_mul(52), None);
1224 #[stable(feature = "rust1", since = "1.0.0")]
1226 pub fn checked_mul(self, other: Self) -> Option<Self> {
1227 checked_op!($ActualT, $mul_with_overflow, self, other)
1230 /// Checked integer division. Computes `self / other`, returning `None`
1231 /// if `other == 0` or the operation results in underflow or overflow.
1238 /// assert_eq!((-127i8).checked_div(-1), Some(127));
1239 /// assert_eq!((-128i8).checked_div(-1), None);
1240 /// assert_eq!((1i8).checked_div(0), None);
1242 #[stable(feature = "rust1", since = "1.0.0")]
1244 pub fn checked_div(self, other: Self) -> Option<Self> {
1247 other => Some(self / other),
1251 /// Saturating integer addition. Computes `self + other`, saturating at
1252 /// the numeric bounds instead of overflowing.
1259 /// assert_eq!(100i8.saturating_add(1), 101);
1260 /// assert_eq!(100i8.saturating_add(127), 127);
1262 #[stable(feature = "rust1", since = "1.0.0")]
1264 pub fn saturating_add(self, other: Self) -> Self {
1265 match self.checked_add(other) {
1267 None if other >= Self::zero() => Self::max_value(),
1268 None => Self::min_value(),
1272 /// Saturating integer subtraction. Computes `self - other`, saturating
1273 /// at the numeric bounds instead of overflowing.
1280 /// assert_eq!(100i8.saturating_sub(127), -27);
1281 /// assert_eq!((-100i8).saturating_sub(127), -128);
1283 #[stable(feature = "rust1", since = "1.0.0")]
1285 pub fn saturating_sub(self, other: Self) -> Self {
1286 match self.checked_sub(other) {
1288 None if other >= Self::zero() => Self::min_value(),
1289 None => Self::max_value(),
1293 /// Wrapping (modular) addition. Computes `self + other`,
1294 /// wrapping around at the boundary of the type.
1301 /// assert_eq!(100i8.wrapping_add(27), 127);
1302 /// assert_eq!(100i8.wrapping_add(127), -29);
1304 #[stable(feature = "rust1", since = "1.0.0")]
1306 pub fn wrapping_add(self, rhs: Self) -> Self {
1308 intrinsics::overflowing_add(self, rhs)
1312 /// Wrapping (modular) subtraction. Computes `self - other`,
1313 /// wrapping around at the boundary of the type.
1320 /// assert_eq!(0i8.wrapping_sub(127), -127);
1321 /// assert_eq!((-2i8).wrapping_sub(127), 127);
1323 #[stable(feature = "rust1", since = "1.0.0")]
1325 pub fn wrapping_sub(self, rhs: Self) -> Self {
1327 intrinsics::overflowing_sub(self, rhs)
1331 /// Wrapping (modular) multiplication. Computes `self *
1332 /// other`, wrapping around at the boundary of the type.
1339 /// assert_eq!(10i8.wrapping_mul(12), 120);
1340 /// assert_eq!(11i8.wrapping_mul(12), -124);
1342 #[stable(feature = "rust1", since = "1.0.0")]
1344 pub fn wrapping_mul(self, rhs: Self) -> Self {
1346 intrinsics::overflowing_mul(self, rhs)
1350 /// Wrapping (modular) division. Computes `self / other`,
1351 /// wrapping around at the boundary of the type.
1353 /// The only case where such wrapping can occur is when one
1354 /// divides `MIN / -1` on a signed type (where `MIN` is the
1355 /// negative minimal value for the type); this is equivalent
1356 /// to `-MIN`, a positive value that is too large to represent
1357 /// in the type. In such a case, this function returns `MIN`
1365 /// assert_eq!(100u8.wrapping_div(10), 10);
1366 /// assert_eq!((-128i8).wrapping_div(-1), -128);
1368 #[stable(feature = "num_wrapping", since = "1.2.0")]
1370 pub fn wrapping_div(self, rhs: Self) -> Self {
1371 self.overflowing_div(rhs).0
1374 /// Wrapping (modular) remainder. Computes `self % other`,
1375 /// wrapping around at the boundary of the type.
1377 /// Such wrap-around never actually occurs mathematically;
1378 /// implementation artifacts make `x % y` invalid for `MIN /
1379 /// -1` on a signed type (where `MIN` is the negative
1380 /// minimal value). In such a case, this function returns `0`.
1387 /// assert_eq!(100i8.wrapping_rem(10), 0);
1388 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
1390 #[stable(feature = "num_wrapping", since = "1.2.0")]
1392 pub fn wrapping_rem(self, rhs: Self) -> Self {
1393 self.overflowing_rem(rhs).0
1396 /// Wrapping (modular) negation. Computes `-self`,
1397 /// wrapping around at the boundary of the type.
1399 /// The only case where such wrapping can occur is when one
1400 /// negates `MIN` on a signed type (where `MIN` is the
1401 /// negative minimal value for the type); this is a positive
1402 /// value that is too large to represent in the type. In such
1403 /// a case, this function returns `MIN` itself.
1410 /// assert_eq!(100i8.wrapping_neg(), -100);
1411 /// assert_eq!((-128i8).wrapping_neg(), -128);
1413 #[stable(feature = "num_wrapping", since = "1.2.0")]
1415 pub fn wrapping_neg(self) -> Self {
1416 self.overflowing_neg().0
1419 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1420 /// where `mask` removes any high-order bits of `rhs` that
1421 /// would cause the shift to exceed the bitwidth of the type.
1428 /// assert_eq!(1u8.wrapping_shl(7), 128);
1429 /// assert_eq!(1u8.wrapping_shl(8), 1);
1431 #[stable(feature = "num_wrapping", since = "1.2.0")]
1433 pub fn wrapping_shl(self, rhs: u32) -> Self {
1434 self.overflowing_shl(rhs).0
1437 /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
1438 /// where `mask` removes any high-order bits of `rhs` that
1439 /// would cause the shift to exceed the bitwidth of the type.
1446 /// assert_eq!(128u8.wrapping_shr(7), 1);
1447 /// assert_eq!(128u8.wrapping_shr(8), 128);
1449 #[stable(feature = "num_wrapping", since = "1.2.0")]
1451 pub fn wrapping_shr(self, rhs: u32) -> Self {
1452 self.overflowing_shr(rhs).0
1455 /// Raises self to the power of `exp`, using exponentiation by squaring.
1462 /// assert_eq!(2i32.pow(4), 16);
1464 #[stable(feature = "rust1", since = "1.0.0")]
1466 pub fn pow(self, mut exp: u32) -> Self {
1467 let mut base = self;
1468 let mut acc = Self::one();
1470 let mut prev_base = self;
1471 let mut base_oflo = false;
1475 // ensure overflow occurs in the same manner it
1476 // would have otherwise (i.e. signal any exception
1477 // it would have otherwise).
1478 acc = acc * (prev_base * prev_base);
1484 let (new_base, new_base_oflo) = base.overflowing_mul(base);
1486 base_oflo = new_base_oflo;
1492 /// Returns `true` if and only if `self == 2^k` for some `k`.
1499 /// assert!(16u8.is_power_of_two());
1500 /// assert!(!10u8.is_power_of_two());
1502 #[stable(feature = "rust1", since = "1.0.0")]
1504 pub fn is_power_of_two(self) -> bool {
1505 (self.wrapping_sub(Self::one())) & self == Self::zero() &&
1506 !(self == Self::zero())
1509 /// Returns the smallest power of two greater than or equal to `self`.
1510 /// Unspecified behavior on overflow.
1517 /// assert_eq!(2u8.next_power_of_two(), 2);
1518 /// assert_eq!(3u8.next_power_of_two(), 4);
1520 #[stable(feature = "rust1", since = "1.0.0")]
1522 pub fn next_power_of_two(self) -> Self {
1523 let bits = size_of::<Self>() * 8;
1524 let one: Self = Self::one();
1525 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
1528 /// Returns the smallest power of two greater than or equal to `n`. If
1529 /// the next power of two is greater than the type's maximum value,
1530 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
1537 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
1538 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
1539 /// assert_eq!(200u8.checked_next_power_of_two(), None);
1541 #[stable(feature = "rust1", since = "1.0.0")]
1542 pub fn checked_next_power_of_two(self) -> Option<Self> {
1543 let npot = self.next_power_of_two();
1561 intrinsics::u8_add_with_overflow,
1562 intrinsics::u8_sub_with_overflow,
1563 intrinsics::u8_mul_with_overflow }
1573 intrinsics::add_with_overflow,
1574 intrinsics::sub_with_overflow,
1575 intrinsics::mul_with_overflow }
1581 uint_impl! { u16, 16,
1582 intrinsics::ctpop16,
1585 intrinsics::bswap16,
1586 intrinsics::u16_add_with_overflow,
1587 intrinsics::u16_sub_with_overflow,
1588 intrinsics::u16_mul_with_overflow }
1593 uint_impl! { u16, 16,
1598 intrinsics::add_with_overflow,
1599 intrinsics::sub_with_overflow,
1600 intrinsics::mul_with_overflow }
1606 uint_impl! { u32, 32,
1607 intrinsics::ctpop32,
1610 intrinsics::bswap32,
1611 intrinsics::u32_add_with_overflow,
1612 intrinsics::u32_sub_with_overflow,
1613 intrinsics::u32_mul_with_overflow }
1618 uint_impl! { u32, 32,
1623 intrinsics::add_with_overflow,
1624 intrinsics::sub_with_overflow,
1625 intrinsics::mul_with_overflow }
1631 uint_impl! { u64, 64,
1632 intrinsics::ctpop64,
1635 intrinsics::bswap64,
1636 intrinsics::u64_add_with_overflow,
1637 intrinsics::u64_sub_with_overflow,
1638 intrinsics::u64_mul_with_overflow }
1643 uint_impl! { u64, 64,
1648 intrinsics::add_with_overflow,
1649 intrinsics::sub_with_overflow,
1650 intrinsics::mul_with_overflow }
1653 #[cfg(target_pointer_width = "32")]
1657 uint_impl! { u32, 32,
1658 intrinsics::ctpop32,
1661 intrinsics::bswap32,
1662 intrinsics::u32_add_with_overflow,
1663 intrinsics::u32_sub_with_overflow,
1664 intrinsics::u32_mul_with_overflow }
1666 #[cfg(target_pointer_width = "32")]
1670 uint_impl! { u32, 32,
1675 intrinsics::add_with_overflow,
1676 intrinsics::sub_with_overflow,
1677 intrinsics::mul_with_overflow }
1680 #[cfg(target_pointer_width = "64")]
1684 uint_impl! { u64, 64,
1685 intrinsics::ctpop64,
1688 intrinsics::bswap64,
1689 intrinsics::u64_add_with_overflow,
1690 intrinsics::u64_sub_with_overflow,
1691 intrinsics::u64_mul_with_overflow }
1693 #[cfg(target_pointer_width = "64")]
1697 uint_impl! { u64, 64,
1702 intrinsics::add_with_overflow,
1703 intrinsics::sub_with_overflow,
1704 intrinsics::mul_with_overflow }
1707 /// Used for representing the classification of floating point numbers
1708 #[derive(Copy, Clone, PartialEq, Debug)]
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 pub enum FpCategory {
1711 /// "Not a Number", often obtained by dividing by zero
1712 #[stable(feature = "rust1", since = "1.0.0")]
1715 /// Positive or negative infinity
1716 #[stable(feature = "rust1", since = "1.0.0")]
1719 /// Positive or negative zero
1720 #[stable(feature = "rust1", since = "1.0.0")]
1723 /// De-normalized floating point representation (less precise than `Normal`)
1724 #[stable(feature = "rust1", since = "1.0.0")]
1727 /// A regular floating point number
1728 #[stable(feature = "rust1", since = "1.0.0")]
1732 /// A built-in floating point number.
1734 #[unstable(feature = "core_float",
1735 reason = "stable interface is via `impl f{32,64}` in later crates",
1737 pub trait Float: Sized {
1738 /// Returns the NaN value.
1740 /// Returns the infinite value.
1741 fn infinity() -> Self;
1742 /// Returns the negative infinite value.
1743 fn neg_infinity() -> Self;
1745 fn neg_zero() -> Self;
1750 /// Parses the string `s` with the radix `r` as a float.
1751 fn from_str_radix(s: &str, r: u32) -> Result<Self, ParseFloatError>;
1753 /// Returns true if this value is NaN and false otherwise.
1754 fn is_nan(self) -> bool;
1755 /// Returns true if this value is positive infinity or negative infinity and
1756 /// false otherwise.
1757 fn is_infinite(self) -> bool;
1758 /// Returns true if this number is neither infinite nor NaN.
1759 fn is_finite(self) -> bool;
1760 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1761 fn is_normal(self) -> bool;
1762 /// Returns the category that this number falls into.
1763 fn classify(self) -> FpCategory;
1765 /// Returns the mantissa, exponent and sign as integers, respectively.
1766 fn integer_decode(self) -> (u64, i16, i8);
1768 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1769 /// number is `Float::nan()`.
1770 fn abs(self) -> Self;
1771 /// Returns a number that represents the sign of `self`.
1773 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1774 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1775 /// - `Float::nan()` if the number is `Float::nan()`
1776 fn signum(self) -> Self;
1777 /// Returns `true` if `self` is positive, including `+0.0` and
1778 /// `Float::infinity()`.
1779 fn is_positive(self) -> bool;
1780 /// Returns `true` if `self` is negative, including `-0.0` and
1781 /// `Float::neg_infinity()`.
1782 fn is_negative(self) -> bool;
1784 /// Take the reciprocal (inverse) of a number, `1/x`.
1785 fn recip(self) -> Self;
1787 /// Raise a number to an integer power.
1789 /// Using this function is generally faster than using `powf`
1790 fn powi(self, n: i32) -> Self;
1792 /// Convert radians to degrees.
1793 fn to_degrees(self) -> Self;
1794 /// Convert degrees to radians.
1795 fn to_radians(self) -> Self;
1798 macro_rules! from_str_radix_int_impl {
1800 #[stable(feature = "rust1", since = "1.0.0")]
1801 impl FromStr for $t {
1802 type Err = ParseIntError;
1803 fn from_str(src: &str) -> Result<Self, ParseIntError> {
1804 from_str_radix(src, 10)
1809 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
1812 trait FromStrRadixHelper: PartialOrd + Copy {
1813 fn min_value() -> Self;
1814 fn from_u32(u: u32) -> Self;
1815 fn checked_mul(&self, other: u32) -> Option<Self>;
1816 fn checked_sub(&self, other: u32) -> Option<Self>;
1817 fn checked_add(&self, other: u32) -> Option<Self>;
1821 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
1822 fn min_value() -> Self { Self::min_value() }
1823 fn from_u32(u: u32) -> Self { u as Self }
1824 fn checked_mul(&self, other: u32) -> Option<Self> {
1825 Self::checked_mul(*self, other as Self)
1827 fn checked_sub(&self, other: u32) -> Option<Self> {
1828 Self::checked_sub(*self, other as Self)
1830 fn checked_add(&self, other: u32) -> Option<Self> {
1831 Self::checked_add(*self, other as Self)
1835 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1837 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
1838 -> Result<T, ParseIntError> {
1839 use self::IntErrorKind::*;
1840 use self::ParseIntError as PIE;
1842 assert!(radix >= 2 && radix <= 36,
1843 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1847 return Err(PIE { kind: Empty });
1850 let is_signed_ty = T::from_u32(0) > T::min_value();
1852 // all valid digits are ascii, so we will just iterate over the utf8 bytes
1853 // and cast them to chars. .to_digit() will safely return None for anything
1854 // other than a valid ascii digit for the given radix, including the first-byte
1855 // of multi-byte sequences
1856 let src = src.as_bytes();
1858 let (is_positive, digits) = match src[0] {
1859 b'+' => (true, &src[1..]),
1860 b'-' if is_signed_ty => (false, &src[1..]),
1864 if digits.is_empty() {
1865 return Err(PIE { kind: Empty });
1868 let mut result = T::from_u32(0);
1870 // The number is positive
1872 let x = match (c as char).to_digit(radix) {
1874 None => return Err(PIE { kind: InvalidDigit }),
1876 result = match result.checked_mul(radix) {
1877 Some(result) => result,
1878 None => return Err(PIE { kind: Overflow }),
1880 result = match result.checked_add(x) {
1881 Some(result) => result,
1882 None => return Err(PIE { kind: Overflow }),
1886 // The number is negative
1888 let x = match (c as char).to_digit(radix) {
1890 None => return Err(PIE { kind: InvalidDigit }),
1892 result = match result.checked_mul(radix) {
1893 Some(result) => result,
1894 None => return Err(PIE { kind: Underflow }),
1896 result = match result.checked_sub(x) {
1897 Some(result) => result,
1898 None => return Err(PIE { kind: Underflow }),
1905 /// An error which can be returned when parsing an integer.
1906 #[derive(Debug, Clone, PartialEq)]
1907 #[stable(feature = "rust1", since = "1.0.0")]
1908 pub struct ParseIntError { kind: IntErrorKind }
1910 #[derive(Debug, Clone, PartialEq)]
1918 impl ParseIntError {
1919 #[unstable(feature = "int_error_internals",
1920 reason = "available through Error trait and this method should \
1921 not be exposed publicly",
1924 pub fn __description(&self) -> &str {
1926 IntErrorKind::Empty => "cannot parse integer from empty string",
1927 IntErrorKind::InvalidDigit => "invalid digit found in string",
1928 IntErrorKind::Overflow => "number too large to fit in target type",
1929 IntErrorKind::Underflow => "number too small to fit in target type",
1934 #[stable(feature = "rust1", since = "1.0.0")]
1935 impl fmt::Display for ParseIntError {
1936 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1937 self.__description().fmt(f)
1941 pub use num::dec2flt::ParseFloatError;
1943 // Conversion traits for primitive integer and float types
1944 // Conversions T -> T are covered by a blanket impl and therefore excluded
1945 // Some conversions from and to usize/isize are not implemented due to portability concerns
1946 macro_rules! impl_from {
1947 ($Small: ty, $Large: ty) => {
1948 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
1949 impl From<$Small> for $Large {
1951 fn from(small: $Small) -> $Large {
1958 // Unsigned -> Unsigned
1959 impl_from! { u8, u16 }
1960 impl_from! { u8, u32 }
1961 impl_from! { u8, u64 }
1962 impl_from! { u8, usize }
1963 impl_from! { u16, u32 }
1964 impl_from! { u16, u64 }
1965 impl_from! { u32, u64 }
1968 impl_from! { i8, i16 }
1969 impl_from! { i8, i32 }
1970 impl_from! { i8, i64 }
1971 impl_from! { i8, isize }
1972 impl_from! { i16, i32 }
1973 impl_from! { i16, i64 }
1974 impl_from! { i32, i64 }
1976 // Unsigned -> Signed
1977 impl_from! { u8, i16 }
1978 impl_from! { u8, i32 }
1979 impl_from! { u8, i64 }
1980 impl_from! { u16, i32 }
1981 impl_from! { u16, i64 }
1982 impl_from! { u32, i64 }
1984 // Note: integers can only be represented with full precision in a float if
1985 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
1986 // Lossy float conversions are not implemented at this time.
1989 impl_from! { i8, f32 }
1990 impl_from! { i8, f64 }
1991 impl_from! { i16, f32 }
1992 impl_from! { i16, f64 }
1993 impl_from! { i32, f64 }
1995 // Unsigned -> Float
1996 impl_from! { u8, f32 }
1997 impl_from! { u8, f64 }
1998 impl_from! { u16, f32 }
1999 impl_from! { u16, f64 }
2000 impl_from! { u32, f64 }
2003 impl_from! { f32, f64 }