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")]
21 /// Provides intentionally-wrapped arithmetic on `T`.
23 /// Operations like `+` on `u32` values is intended to never overflow,
24 /// and in some debug configurations overflow is detected and results
25 /// in a panic. While most arithmetic falls into this category, some
26 /// code explicitly expects and relies upon modular arithmetic (e.g.,
29 /// Wrapping arithmetic can be achieved either through methods like
30 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
31 /// all standard arithmetic operations on the underlying value are
32 /// intended to have wrapping semantics.
37 /// use std::num::Wrapping;
39 /// let zero = Wrapping(0u32);
40 /// let one = Wrapping(1u32);
42 /// assert_eq!(std::u32::MAX, (zero - one).0);
44 #[stable(feature = "rust1", since = "1.0.0")]
45 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
46 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
49 #[stable(feature = "rust1", since = "1.0.0")]
50 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56 #[stable(feature = "wrapping_display", since = "1.10.0")]
57 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
58 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
64 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
65 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
71 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
72 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
77 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
78 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
79 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
85 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
86 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93 // All these modules are technically private and only exposed for libcoretest:
99 /// Types that have a "zero" value.
101 /// This trait is intended for use in conjunction with `Add`, as an identity:
102 /// `x + T::zero() == x`.
103 #[unstable(feature = "zero_one",
104 reason = "unsure of placement, wants to use associated constants",
106 #[rustc_deprecated(since = "1.11.0", reason = "no longer used for \
108 pub trait Zero: Sized {
109 /// The "zero" (usually, additive identity) for this type.
113 /// Types that have a "one" value.
115 /// This trait is intended for use in conjunction with `Mul`, as an identity:
116 /// `x * T::one() == x`.
117 #[unstable(feature = "zero_one",
118 reason = "unsure of placement, wants to use associated constants",
120 #[rustc_deprecated(since = "1.11.0", reason = "no longer used for \
122 pub trait One: Sized {
123 /// The "one" (usually, multiplicative identity) for this type.
127 macro_rules! zero_one_impl {
129 #[unstable(feature = "zero_one",
130 reason = "unsure of placement, wants to use associated constants",
135 fn zero() -> Self { 0 }
137 #[unstable(feature = "zero_one",
138 reason = "unsure of placement, wants to use associated constants",
143 fn one() -> Self { 1 }
147 zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
149 macro_rules! zero_one_impl_float {
151 #[unstable(feature = "zero_one",
152 reason = "unsure of placement, wants to use associated constants",
157 fn zero() -> Self { 0.0 }
159 #[unstable(feature = "zero_one",
160 reason = "unsure of placement, wants to use associated constants",
165 fn one() -> Self { 1.0 }
169 zero_one_impl_float! { f32 f64 }
171 macro_rules! checked_op {
172 ($U:ty, $op:path, $x:expr, $y:expr) => {{
173 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
174 if overflowed { None } else { Some(result as Self) }
178 // `Int` + `SignedInt` implemented for signed integers
179 macro_rules! int_impl {
180 ($ActualT:ident, $UnsignedT:ty, $BITS:expr,
181 $add_with_overflow:path,
182 $sub_with_overflow:path,
183 $mul_with_overflow:path) => {
184 /// Returns the smallest value that can be represented by this integer type.
189 /// assert_eq!(i8::min_value(), -128);
191 #[stable(feature = "rust1", since = "1.0.0")]
193 pub const fn min_value() -> Self {
194 (-1 as Self) << ($BITS - 1)
197 /// Returns the largest value that can be represented by this integer type.
202 /// assert_eq!(i8::max_value(), 127);
204 #[stable(feature = "rust1", since = "1.0.0")]
206 pub const fn max_value() -> Self {
210 /// Converts a string slice in a given base to an integer.
212 /// Leading and trailing whitespace represent an error.
219 /// assert_eq!(i32::from_str_radix("A", 16), Ok(10));
221 #[stable(feature = "rust1", since = "1.0.0")]
222 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
223 from_str_radix(src, radix)
226 /// Returns the number of ones in the binary representation of `self`.
233 /// let n = -0b1000_0000i8;
235 /// assert_eq!(n.count_ones(), 1);
237 #[stable(feature = "rust1", since = "1.0.0")]
239 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
241 /// Returns the number of zeros in the binary representation of `self`.
248 /// let n = -0b1000_0000i8;
250 /// assert_eq!(n.count_zeros(), 7);
252 #[stable(feature = "rust1", since = "1.0.0")]
254 pub fn count_zeros(self) -> u32 {
258 /// Returns the number of leading zeros in the binary representation
268 /// assert_eq!(n.leading_zeros(), 0);
270 #[stable(feature = "rust1", since = "1.0.0")]
272 pub fn leading_zeros(self) -> u32 {
273 (self as $UnsignedT).leading_zeros()
276 /// Returns the number of trailing zeros in the binary representation
286 /// assert_eq!(n.trailing_zeros(), 2);
288 #[stable(feature = "rust1", since = "1.0.0")]
290 pub fn trailing_zeros(self) -> u32 {
291 (self as $UnsignedT).trailing_zeros()
294 /// Shifts the bits to the left by a specified amount, `n`,
295 /// wrapping the truncated bits to the end of the resulting integer.
297 /// Please note this isn't the same operation as `<<`!
304 /// let n = 0x0123456789ABCDEFi64;
305 /// let m = -0x76543210FEDCBA99i64;
307 /// assert_eq!(n.rotate_left(32), m);
309 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn rotate_left(self, n: u32) -> Self {
312 (self as $UnsignedT).rotate_left(n) as Self
315 /// Shifts the bits to the right by a specified amount, `n`,
316 /// wrapping the truncated bits to the beginning of the resulting
319 /// Please note this isn't the same operation as `>>`!
326 /// let n = 0x0123456789ABCDEFi64;
327 /// let m = -0xFEDCBA987654322i64;
329 /// assert_eq!(n.rotate_right(4), m);
331 #[stable(feature = "rust1", since = "1.0.0")]
333 pub fn rotate_right(self, n: u32) -> Self {
334 (self as $UnsignedT).rotate_right(n) as Self
337 /// Reverses the byte order of the integer.
344 /// let n = 0x0123456789ABCDEFi64;
345 /// let m = -0x1032547698BADCFFi64;
347 /// assert_eq!(n.swap_bytes(), m);
349 #[stable(feature = "rust1", since = "1.0.0")]
351 pub fn swap_bytes(self) -> Self {
352 (self as $UnsignedT).swap_bytes() as Self
355 /// Converts an integer from big endian to the target's endianness.
357 /// On big endian this is a no-op. On little endian the bytes are
365 /// let n = 0x0123456789ABCDEFi64;
367 /// if cfg!(target_endian = "big") {
368 /// assert_eq!(i64::from_be(n), n)
370 /// assert_eq!(i64::from_be(n), n.swap_bytes())
373 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn from_be(x: Self) -> Self {
376 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
379 /// Converts an integer from little endian to the target's endianness.
381 /// On little endian this is a no-op. On big endian the bytes are
389 /// let n = 0x0123456789ABCDEFi64;
391 /// if cfg!(target_endian = "little") {
392 /// assert_eq!(i64::from_le(n), n)
394 /// assert_eq!(i64::from_le(n), n.swap_bytes())
397 #[stable(feature = "rust1", since = "1.0.0")]
399 pub fn from_le(x: Self) -> Self {
400 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
403 /// Converts `self` to big endian from the target's endianness.
405 /// On big endian this is a no-op. On little endian the bytes are
413 /// let n = 0x0123456789ABCDEFi64;
415 /// if cfg!(target_endian = "big") {
416 /// assert_eq!(n.to_be(), n)
418 /// assert_eq!(n.to_be(), n.swap_bytes())
421 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn to_be(self) -> Self { // or not to be?
424 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
427 /// Converts `self` to little endian from the target's endianness.
429 /// On little endian this is a no-op. On big endian the bytes are
437 /// let n = 0x0123456789ABCDEFi64;
439 /// if cfg!(target_endian = "little") {
440 /// assert_eq!(n.to_le(), n)
442 /// assert_eq!(n.to_le(), n.swap_bytes())
445 #[stable(feature = "rust1", since = "1.0.0")]
447 pub fn to_le(self) -> Self {
448 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
451 /// Checked integer addition. Computes `self + other`, returning `None`
452 /// if overflow occurred.
459 /// assert_eq!(7i16.checked_add(32760), Some(32767));
460 /// assert_eq!(8i16.checked_add(32760), None);
462 #[stable(feature = "rust1", since = "1.0.0")]
464 pub fn checked_add(self, other: Self) -> Option<Self> {
465 let (a, b) = self.overflowing_add(other);
466 if b {None} else {Some(a)}
469 /// Checked integer subtraction. Computes `self - other`, returning
470 /// `None` if underflow occurred.
477 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
478 /// assert_eq!((-128i8).checked_sub(1), None);
480 #[stable(feature = "rust1", since = "1.0.0")]
482 pub fn checked_sub(self, other: Self) -> Option<Self> {
483 let (a, b) = self.overflowing_sub(other);
484 if b {None} else {Some(a)}
487 /// Checked integer multiplication. Computes `self * other`, returning
488 /// `None` if underflow or overflow occurred.
495 /// assert_eq!(6i8.checked_mul(21), Some(126));
496 /// assert_eq!(6i8.checked_mul(22), None);
498 #[stable(feature = "rust1", since = "1.0.0")]
500 pub fn checked_mul(self, other: Self) -> Option<Self> {
501 let (a, b) = self.overflowing_mul(other);
502 if b {None} else {Some(a)}
505 /// Checked integer division. Computes `self / other`, returning `None`
506 /// if `other == 0` or the operation results in underflow or overflow.
513 /// assert_eq!((-127i8).checked_div(-1), Some(127));
514 /// assert_eq!((-128i8).checked_div(-1), None);
515 /// assert_eq!((1i8).checked_div(0), None);
517 #[stable(feature = "rust1", since = "1.0.0")]
519 pub fn checked_div(self, other: Self) -> Option<Self> {
520 if other == 0 || (self == Self::min_value() && other == -1) {
523 Some(unsafe { intrinsics::unchecked_div(self, other) })
527 /// Checked integer remainder. Computes `self % other`, returning `None`
528 /// if `other == 0` or the operation results in underflow or overflow.
537 /// assert_eq!(5i32.checked_rem(2), Some(1));
538 /// assert_eq!(5i32.checked_rem(0), None);
539 /// assert_eq!(i32::MIN.checked_rem(-1), None);
541 #[stable(feature = "wrapping", since = "1.7.0")]
543 pub fn checked_rem(self, other: Self) -> Option<Self> {
544 if other == 0 || (self == Self::min_value() && other == -1) {
547 Some(unsafe { intrinsics::unchecked_rem(self, other) })
551 /// Checked negation. Computes `-self`, returning `None` if `self ==
561 /// assert_eq!(5i32.checked_neg(), Some(-5));
562 /// assert_eq!(i32::MIN.checked_neg(), None);
564 #[stable(feature = "wrapping", since = "1.7.0")]
566 pub fn checked_neg(self) -> Option<Self> {
567 let (a, b) = self.overflowing_neg();
568 if b {None} else {Some(a)}
571 /// Checked shift left. Computes `self << rhs`, returning `None`
572 /// if `rhs` is larger than or equal to the number of bits in `self`.
579 /// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
580 /// assert_eq!(0x10i32.checked_shl(33), None);
582 #[stable(feature = "wrapping", since = "1.7.0")]
584 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
585 let (a, b) = self.overflowing_shl(rhs);
586 if b {None} else {Some(a)}
589 /// Checked shift right. Computes `self >> rhs`, returning `None`
590 /// if `rhs` is larger than or equal to the number of bits in `self`.
597 /// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
598 /// assert_eq!(0x10i32.checked_shr(33), None);
600 #[stable(feature = "wrapping", since = "1.7.0")]
602 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
603 let (a, b) = self.overflowing_shr(rhs);
604 if b {None} else {Some(a)}
607 /// Checked absolute value. Computes `self.abs()`, returning `None` if
617 /// assert_eq!((-5i32).checked_abs(), Some(5));
618 /// assert_eq!(i32::MIN.checked_abs(), None);
620 #[stable(feature = "no_panic_abs", since = "1.13.0")]
622 pub fn checked_abs(self) -> Option<Self> {
623 if self.is_negative() {
630 /// Saturating integer addition. Computes `self + other`, saturating at
631 /// the numeric bounds instead of overflowing.
638 /// assert_eq!(100i8.saturating_add(1), 101);
639 /// assert_eq!(100i8.saturating_add(127), 127);
641 #[stable(feature = "rust1", since = "1.0.0")]
643 pub fn saturating_add(self, other: Self) -> Self {
644 match self.checked_add(other) {
646 None if other >= 0 => Self::max_value(),
647 None => Self::min_value(),
651 /// Saturating integer subtraction. Computes `self - other`, saturating
652 /// at the numeric bounds instead of overflowing.
659 /// assert_eq!(100i8.saturating_sub(127), -27);
660 /// assert_eq!((-100i8).saturating_sub(127), -128);
662 #[stable(feature = "rust1", since = "1.0.0")]
664 pub fn saturating_sub(self, other: Self) -> Self {
665 match self.checked_sub(other) {
667 None if other >= 0 => Self::min_value(),
668 None => Self::max_value(),
672 /// Saturating integer multiplication. Computes `self * other`,
673 /// saturating at the numeric bounds instead of overflowing.
682 /// assert_eq!(100i32.saturating_mul(127), 12700);
683 /// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
684 /// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
686 #[stable(feature = "wrapping", since = "1.7.0")]
688 pub fn saturating_mul(self, other: Self) -> Self {
689 self.checked_mul(other).unwrap_or_else(|| {
690 if (self < 0 && other < 0) || (self > 0 && other > 0) {
698 /// Wrapping (modular) addition. Computes `self + other`,
699 /// wrapping around at the boundary of the type.
706 /// assert_eq!(100i8.wrapping_add(27), 127);
707 /// assert_eq!(100i8.wrapping_add(127), -29);
709 #[stable(feature = "rust1", since = "1.0.0")]
711 pub fn wrapping_add(self, rhs: Self) -> Self {
713 intrinsics::overflowing_add(self, rhs)
717 /// Wrapping (modular) subtraction. Computes `self - other`,
718 /// wrapping around at the boundary of the type.
725 /// assert_eq!(0i8.wrapping_sub(127), -127);
726 /// assert_eq!((-2i8).wrapping_sub(127), 127);
728 #[stable(feature = "rust1", since = "1.0.0")]
730 pub fn wrapping_sub(self, rhs: Self) -> Self {
732 intrinsics::overflowing_sub(self, rhs)
736 /// Wrapping (modular) multiplication. Computes `self *
737 /// other`, wrapping around at the boundary of the type.
744 /// assert_eq!(10i8.wrapping_mul(12), 120);
745 /// assert_eq!(11i8.wrapping_mul(12), -124);
747 #[stable(feature = "rust1", since = "1.0.0")]
749 pub fn wrapping_mul(self, rhs: Self) -> Self {
751 intrinsics::overflowing_mul(self, rhs)
755 /// Wrapping (modular) division. Computes `self / other`,
756 /// wrapping around at the boundary of the type.
758 /// The only case where such wrapping can occur is when one
759 /// divides `MIN / -1` on a signed type (where `MIN` is the
760 /// negative minimal value for the type); this is equivalent
761 /// to `-MIN`, a positive value that is too large to represent
762 /// in the type. In such a case, this function returns `MIN`
767 /// This function will panic if `rhs` is 0.
774 /// assert_eq!(100u8.wrapping_div(10), 10);
775 /// assert_eq!((-128i8).wrapping_div(-1), -128);
777 #[stable(feature = "num_wrapping", since = "1.2.0")]
779 pub fn wrapping_div(self, rhs: Self) -> Self {
780 self.overflowing_div(rhs).0
783 /// Wrapping (modular) remainder. Computes `self % other`,
784 /// wrapping around at the boundary of the type.
786 /// Such wrap-around never actually occurs mathematically;
787 /// implementation artifacts make `x % y` invalid for `MIN /
788 /// -1` on a signed type (where `MIN` is the negative
789 /// minimal value). In such a case, this function returns `0`.
793 /// This function will panic if `rhs` is 0.
800 /// assert_eq!(100i8.wrapping_rem(10), 0);
801 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
803 #[stable(feature = "num_wrapping", since = "1.2.0")]
805 pub fn wrapping_rem(self, rhs: Self) -> Self {
806 self.overflowing_rem(rhs).0
809 /// Wrapping (modular) negation. Computes `-self`,
810 /// wrapping around at the boundary of the type.
812 /// The only case where such wrapping can occur is when one
813 /// negates `MIN` on a signed type (where `MIN` is the
814 /// negative minimal value for the type); this is a positive
815 /// value that is too large to represent in the type. In such
816 /// a case, this function returns `MIN` itself.
823 /// assert_eq!(100i8.wrapping_neg(), -100);
824 /// assert_eq!((-128i8).wrapping_neg(), -128);
826 #[stable(feature = "num_wrapping", since = "1.2.0")]
828 pub fn wrapping_neg(self) -> Self {
829 self.overflowing_neg().0
832 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
833 /// where `mask` removes any high-order bits of `rhs` that
834 /// would cause the shift to exceed the bitwidth of the type.
836 /// Note that this is *not* the same as a rotate-left; the
837 /// RHS of a wrapping shift-left is restricted to the range
838 /// of the type, rather than the bits shifted out of the LHS
839 /// being returned to the other end. The primitive integer
840 /// types all implement a `rotate_left` function, which may
841 /// be what you want instead.
848 /// assert_eq!((-1i8).wrapping_shl(7), -128);
849 /// assert_eq!((-1i8).wrapping_shl(8), -1);
851 #[stable(feature = "num_wrapping", since = "1.2.0")]
853 pub fn wrapping_shl(self, rhs: u32) -> Self {
854 self.overflowing_shl(rhs).0
857 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
858 /// where `mask` removes any high-order bits of `rhs` that
859 /// would cause the shift to exceed the bitwidth of the type.
861 /// Note that this is *not* the same as a rotate-right; the
862 /// RHS of a wrapping shift-right is restricted to the range
863 /// of the type, rather than the bits shifted out of the LHS
864 /// being returned to the other end. The primitive integer
865 /// types all implement a `rotate_right` function, which may
866 /// be what you want instead.
873 /// assert_eq!((-128i8).wrapping_shr(7), -1);
874 /// assert_eq!((-128i8).wrapping_shr(8), -128);
876 #[stable(feature = "num_wrapping", since = "1.2.0")]
878 pub fn wrapping_shr(self, rhs: u32) -> Self {
879 self.overflowing_shr(rhs).0
882 /// Wrapping (modular) absolute value. Computes `self.abs()`,
883 /// wrapping around at the boundary of the type.
885 /// The only case where such wrapping can occur is when one takes
886 /// the absolute value of the negative minimal value for the type
887 /// this is a positive value that is too large to represent in the
888 /// type. In such a case, this function returns `MIN` itself.
895 /// assert_eq!(100i8.wrapping_abs(), 100);
896 /// assert_eq!((-100i8).wrapping_abs(), 100);
897 /// assert_eq!((-128i8).wrapping_abs(), -128);
898 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
900 #[stable(feature = "no_panic_abs", since = "1.13.0")]
902 pub fn wrapping_abs(self) -> Self {
903 if self.is_negative() {
910 /// Calculates `self` + `rhs`
912 /// Returns a tuple of the addition along with a boolean indicating
913 /// whether an arithmetic overflow would occur. If an overflow would
914 /// have occurred then the wrapped value is returned.
923 /// assert_eq!(5i32.overflowing_add(2), (7, false));
924 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
927 #[stable(feature = "wrapping", since = "1.7.0")]
928 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
930 let (a, b) = $add_with_overflow(self as $ActualT,
936 /// Calculates `self` - `rhs`
938 /// Returns a tuple of the subtraction along with a boolean indicating
939 /// whether an arithmetic overflow would occur. If an overflow would
940 /// have occurred then the wrapped value is returned.
949 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
950 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
953 #[stable(feature = "wrapping", since = "1.7.0")]
954 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
956 let (a, b) = $sub_with_overflow(self as $ActualT,
962 /// Calculates the multiplication of `self` and `rhs`.
964 /// Returns a tuple of the multiplication along with a boolean
965 /// indicating whether an arithmetic overflow would occur. If an
966 /// overflow would have occurred then the wrapped value is returned.
973 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
974 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
977 #[stable(feature = "wrapping", since = "1.7.0")]
978 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
980 let (a, b) = $mul_with_overflow(self as $ActualT,
986 /// Calculates the divisor when `self` is divided by `rhs`.
988 /// Returns a tuple of the divisor along with a boolean indicating
989 /// whether an arithmetic overflow would occur. If an overflow would
990 /// occur then self is returned.
994 /// This function will panic if `rhs` is 0.
1003 /// assert_eq!(5i32.overflowing_div(2), (2, false));
1004 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
1007 #[stable(feature = "wrapping", since = "1.7.0")]
1008 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1009 if self == Self::min_value() && rhs == -1 {
1016 /// Calculates the remainder when `self` is divided by `rhs`.
1018 /// Returns a tuple of the remainder after dividing along with a boolean
1019 /// indicating whether an arithmetic overflow would occur. If an
1020 /// overflow would occur then 0 is returned.
1024 /// This function will panic if `rhs` is 0.
1033 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
1034 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
1037 #[stable(feature = "wrapping", since = "1.7.0")]
1038 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1039 if self == Self::min_value() && rhs == -1 {
1046 /// Negates self, overflowing if this is equal to the minimum value.
1048 /// Returns a tuple of the negated version of self along with a boolean
1049 /// indicating whether an overflow happened. If `self` is the minimum
1050 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
1051 /// value will be returned again and `true` will be returned for an
1052 /// overflow happening.
1061 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
1062 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
1065 #[stable(feature = "wrapping", since = "1.7.0")]
1066 pub fn overflowing_neg(self) -> (Self, bool) {
1067 if self == Self::min_value() {
1068 (Self::min_value(), true)
1074 /// Shifts self left by `rhs` bits.
1076 /// Returns a tuple of the shifted version of self along with a boolean
1077 /// indicating whether the shift value was larger than or equal to the
1078 /// number of bits. If the shift value is too large, then value is
1079 /// masked (N-1) where N is the number of bits, and this value is then
1080 /// used to perform the shift.
1087 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
1088 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
1091 #[stable(feature = "wrapping", since = "1.7.0")]
1092 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1093 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1096 /// Shifts self right by `rhs` bits.
1098 /// Returns a tuple of the shifted version of self along with a boolean
1099 /// indicating whether the shift value was larger than or equal to the
1100 /// number of bits. If the shift value is too large, then value is
1101 /// masked (N-1) where N is the number of bits, and this value is then
1102 /// used to perform the shift.
1109 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
1110 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1113 #[stable(feature = "wrapping", since = "1.7.0")]
1114 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1115 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1118 /// Computes the absolute value of `self`.
1120 /// Returns a tuple of the absolute version of self along with a
1121 /// boolean indicating whether an overflow happened. If self is the
1122 /// minimum value (e.g. i32::MIN for values of type i32), then the
1123 /// minimum value will be returned again and true will be returned for
1124 /// an overflow happening.
1131 /// assert_eq!(10i8.overflowing_abs(), (10,false));
1132 /// assert_eq!((-10i8).overflowing_abs(), (10,false));
1133 /// assert_eq!((-128i8).overflowing_abs(), (-128,true));
1135 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1137 pub fn overflowing_abs(self) -> (Self, bool) {
1138 if self.is_negative() {
1139 self.overflowing_neg()
1145 /// Raises self to the power of `exp`, using exponentiation by squaring.
1152 /// let x: i32 = 2; // or any other integer type
1154 /// assert_eq!(x.pow(4), 16);
1156 #[stable(feature = "rust1", since = "1.0.0")]
1158 #[rustc_inherit_overflow_checks]
1159 pub fn pow(self, mut exp: u32) -> Self {
1160 let mut base = self;
1171 // Deal with the final bit of the exponent separately, since
1172 // squaring the base afterwards is not necessary and may cause a
1173 // needless overflow.
1181 /// Computes the absolute value of `self`.
1183 /// # Overflow behavior
1185 /// The absolute value of `i32::min_value()` cannot be represented as an
1186 /// `i32`, and attempting to calculate it will cause an overflow. This
1187 /// means that code in debug mode will trigger a panic on this case and
1188 /// optimized code will return `i32::min_value()` without a panic.
1195 /// assert_eq!(10i8.abs(), 10);
1196 /// assert_eq!((-10i8).abs(), 10);
1198 #[stable(feature = "rust1", since = "1.0.0")]
1200 #[rustc_inherit_overflow_checks]
1201 pub fn abs(self) -> Self {
1202 if self.is_negative() {
1203 // Note that the #[inline] above means that the overflow
1204 // semantics of this negation depend on the crate we're being
1212 /// Returns a number representing sign of `self`.
1214 /// - `0` if the number is zero
1215 /// - `1` if the number is positive
1216 /// - `-1` if the number is negative
1223 /// assert_eq!(10i8.signum(), 1);
1224 /// assert_eq!(0i8.signum(), 0);
1225 /// assert_eq!((-10i8).signum(), -1);
1227 #[stable(feature = "rust1", since = "1.0.0")]
1229 pub fn signum(self) -> Self {
1237 /// Returns `true` if `self` is positive and `false` if the number
1238 /// is zero or negative.
1245 /// assert!(10i8.is_positive());
1246 /// assert!(!(-10i8).is_positive());
1248 #[stable(feature = "rust1", since = "1.0.0")]
1250 pub fn is_positive(self) -> bool { self > 0 }
1252 /// Returns `true` if `self` is negative and `false` if the number
1253 /// is zero or positive.
1260 /// assert!((-10i8).is_negative());
1261 /// assert!(!10i8.is_negative());
1263 #[stable(feature = "rust1", since = "1.0.0")]
1265 pub fn is_negative(self) -> bool { self < 0 }
1271 int_impl! { i8, u8, 8,
1272 intrinsics::add_with_overflow,
1273 intrinsics::sub_with_overflow,
1274 intrinsics::mul_with_overflow }
1279 int_impl! { i16, u16, 16,
1280 intrinsics::add_with_overflow,
1281 intrinsics::sub_with_overflow,
1282 intrinsics::mul_with_overflow }
1287 int_impl! { i32, u32, 32,
1288 intrinsics::add_with_overflow,
1289 intrinsics::sub_with_overflow,
1290 intrinsics::mul_with_overflow }
1295 int_impl! { i64, u64, 64,
1296 intrinsics::add_with_overflow,
1297 intrinsics::sub_with_overflow,
1298 intrinsics::mul_with_overflow }
1301 #[cfg(target_pointer_width = "16")]
1304 int_impl! { i16, u16, 16,
1305 intrinsics::add_with_overflow,
1306 intrinsics::sub_with_overflow,
1307 intrinsics::mul_with_overflow }
1310 #[cfg(target_pointer_width = "32")]
1313 int_impl! { i32, u32, 32,
1314 intrinsics::add_with_overflow,
1315 intrinsics::sub_with_overflow,
1316 intrinsics::mul_with_overflow }
1319 #[cfg(target_pointer_width = "64")]
1322 int_impl! { i64, u64, 64,
1323 intrinsics::add_with_overflow,
1324 intrinsics::sub_with_overflow,
1325 intrinsics::mul_with_overflow }
1328 // `Int` + `UnsignedInt` implemented for unsigned integers
1329 macro_rules! uint_impl {
1330 ($ActualT:ty, $BITS:expr,
1335 $add_with_overflow:path,
1336 $sub_with_overflow:path,
1337 $mul_with_overflow:path) => {
1338 /// Returns the smallest value that can be represented by this integer type.
1343 /// assert_eq!(u8::min_value(), 0);
1345 #[stable(feature = "rust1", since = "1.0.0")]
1347 pub const fn min_value() -> Self { 0 }
1349 /// Returns the largest value that can be represented by this integer type.
1354 /// assert_eq!(u8::max_value(), 255);
1356 #[stable(feature = "rust1", since = "1.0.0")]
1358 pub const fn max_value() -> Self { !0 }
1360 /// Converts a string slice in a given base to an integer.
1362 /// Leading and trailing whitespace represent an error.
1369 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1373 from_str_radix(src, radix)
1376 /// Returns the number of ones in the binary representation of `self`.
1383 /// let n = 0b01001100u8;
1385 /// assert_eq!(n.count_ones(), 3);
1387 #[stable(feature = "rust1", since = "1.0.0")]
1389 pub fn count_ones(self) -> u32 {
1390 unsafe { $ctpop(self as $ActualT) as u32 }
1393 /// Returns the number of zeros in the binary representation of `self`.
1400 /// let n = 0b01001100u8;
1402 /// assert_eq!(n.count_zeros(), 5);
1404 #[stable(feature = "rust1", since = "1.0.0")]
1406 pub fn count_zeros(self) -> u32 {
1407 (!self).count_ones()
1410 /// Returns the number of leading zeros in the binary representation
1418 /// let n = 0b0101000u16;
1420 /// assert_eq!(n.leading_zeros(), 10);
1422 #[stable(feature = "rust1", since = "1.0.0")]
1424 pub fn leading_zeros(self) -> u32 {
1425 unsafe { $ctlz(self as $ActualT) as u32 }
1428 /// Returns the number of trailing zeros in the binary representation
1436 /// let n = 0b0101000u16;
1438 /// assert_eq!(n.trailing_zeros(), 3);
1440 #[stable(feature = "rust1", since = "1.0.0")]
1442 pub fn trailing_zeros(self) -> u32 {
1443 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1444 // emits two conditional moves on x86_64. By promoting the value to
1445 // u16 and setting bit 8, we get better code without any conditional
1447 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1448 // pending, remove this workaround once LLVM generates better code
1452 intrinsics::cttz(self as u16 | 0x100) as u32
1454 intrinsics::cttz(self) as u32
1459 /// Shifts the bits to the left by a specified amount, `n`,
1460 /// wrapping the truncated bits to the end of the resulting integer.
1462 /// Please note this isn't the same operation as `<<`!
1469 /// let n = 0x0123456789ABCDEFu64;
1470 /// let m = 0x3456789ABCDEF012u64;
1472 /// assert_eq!(n.rotate_left(12), m);
1474 #[stable(feature = "rust1", since = "1.0.0")]
1476 pub fn rotate_left(self, n: u32) -> Self {
1477 // Protect against undefined behaviour for over-long bit shifts
1479 (self << n) | (self >> (($BITS - n) % $BITS))
1482 /// Shifts the bits to the right by a specified amount, `n`,
1483 /// wrapping the truncated bits to the beginning of the resulting
1486 /// Please note this isn't the same operation as `>>`!
1493 /// let n = 0x0123456789ABCDEFu64;
1494 /// let m = 0xDEF0123456789ABCu64;
1496 /// assert_eq!(n.rotate_right(12), m);
1498 #[stable(feature = "rust1", since = "1.0.0")]
1500 pub fn rotate_right(self, n: u32) -> Self {
1501 // Protect against undefined behaviour for over-long bit shifts
1503 (self >> n) | (self << (($BITS - n) % $BITS))
1506 /// Reverses the byte order of the integer.
1513 /// let n = 0x0123456789ABCDEFu64;
1514 /// let m = 0xEFCDAB8967452301u64;
1516 /// assert_eq!(n.swap_bytes(), m);
1518 #[stable(feature = "rust1", since = "1.0.0")]
1520 pub fn swap_bytes(self) -> Self {
1521 unsafe { $bswap(self as $ActualT) as Self }
1524 /// Converts an integer from big endian to the target's endianness.
1526 /// On big endian this is a no-op. On little endian the bytes are
1534 /// let n = 0x0123456789ABCDEFu64;
1536 /// if cfg!(target_endian = "big") {
1537 /// assert_eq!(u64::from_be(n), n)
1539 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1542 #[stable(feature = "rust1", since = "1.0.0")]
1544 pub fn from_be(x: Self) -> Self {
1545 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1548 /// Converts an integer from little endian to the target's endianness.
1550 /// On little endian this is a no-op. On big endian the bytes are
1558 /// let n = 0x0123456789ABCDEFu64;
1560 /// if cfg!(target_endian = "little") {
1561 /// assert_eq!(u64::from_le(n), n)
1563 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1566 #[stable(feature = "rust1", since = "1.0.0")]
1568 pub fn from_le(x: Self) -> Self {
1569 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1572 /// Converts `self` to big endian from the target's endianness.
1574 /// On big endian this is a no-op. On little endian the bytes are
1582 /// let n = 0x0123456789ABCDEFu64;
1584 /// if cfg!(target_endian = "big") {
1585 /// assert_eq!(n.to_be(), n)
1587 /// assert_eq!(n.to_be(), n.swap_bytes())
1590 #[stable(feature = "rust1", since = "1.0.0")]
1592 pub fn to_be(self) -> Self { // or not to be?
1593 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1596 /// Converts `self` to little endian from the target's endianness.
1598 /// On little endian this is a no-op. On big endian the bytes are
1606 /// let n = 0x0123456789ABCDEFu64;
1608 /// if cfg!(target_endian = "little") {
1609 /// assert_eq!(n.to_le(), n)
1611 /// assert_eq!(n.to_le(), n.swap_bytes())
1614 #[stable(feature = "rust1", since = "1.0.0")]
1616 pub fn to_le(self) -> Self {
1617 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1620 /// Checked integer addition. Computes `self + other`, returning `None`
1621 /// if overflow occurred.
1628 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1629 /// assert_eq!(6u16.checked_add(65530), None);
1631 #[stable(feature = "rust1", since = "1.0.0")]
1633 pub fn checked_add(self, other: Self) -> Option<Self> {
1634 let (a, b) = self.overflowing_add(other);
1635 if b {None} else {Some(a)}
1638 /// Checked integer subtraction. Computes `self - other`, returning
1639 /// `None` if underflow occurred.
1646 /// assert_eq!(1u8.checked_sub(1), Some(0));
1647 /// assert_eq!(0u8.checked_sub(1), None);
1649 #[stable(feature = "rust1", since = "1.0.0")]
1651 pub fn checked_sub(self, other: Self) -> Option<Self> {
1652 let (a, b) = self.overflowing_sub(other);
1653 if b {None} else {Some(a)}
1656 /// Checked integer multiplication. Computes `self * other`, returning
1657 /// `None` if underflow or overflow occurred.
1664 /// assert_eq!(5u8.checked_mul(51), Some(255));
1665 /// assert_eq!(5u8.checked_mul(52), None);
1667 #[stable(feature = "rust1", since = "1.0.0")]
1669 pub fn checked_mul(self, other: Self) -> Option<Self> {
1670 let (a, b) = self.overflowing_mul(other);
1671 if b {None} else {Some(a)}
1674 /// Checked integer division. Computes `self / other`, returning `None`
1675 /// if `other == 0` or the operation results in underflow or overflow.
1682 /// assert_eq!(128u8.checked_div(2), Some(64));
1683 /// assert_eq!(1u8.checked_div(0), None);
1685 #[stable(feature = "rust1", since = "1.0.0")]
1687 pub fn checked_div(self, other: Self) -> Option<Self> {
1690 other => Some(unsafe { intrinsics::unchecked_div(self, other) }),
1694 /// Checked integer remainder. Computes `self % other`, returning `None`
1695 /// if `other == 0` or the operation results in underflow or overflow.
1702 /// assert_eq!(5u32.checked_rem(2), Some(1));
1703 /// assert_eq!(5u32.checked_rem(0), None);
1705 #[stable(feature = "wrapping", since = "1.7.0")]
1707 pub fn checked_rem(self, other: Self) -> Option<Self> {
1711 Some(unsafe { intrinsics::unchecked_rem(self, other) })
1715 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1718 /// Note that negating any positive integer will overflow.
1725 /// assert_eq!(0u32.checked_neg(), Some(0));
1726 /// assert_eq!(1u32.checked_neg(), None);
1728 #[stable(feature = "wrapping", since = "1.7.0")]
1730 pub fn checked_neg(self) -> Option<Self> {
1731 let (a, b) = self.overflowing_neg();
1732 if b {None} else {Some(a)}
1735 /// Checked shift left. Computes `self << rhs`, returning `None`
1736 /// if `rhs` is larger than or equal to the number of bits in `self`.
1743 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1744 /// assert_eq!(0x10u32.checked_shl(33), None);
1746 #[stable(feature = "wrapping", since = "1.7.0")]
1748 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1749 let (a, b) = self.overflowing_shl(rhs);
1750 if b {None} else {Some(a)}
1753 /// Checked shift right. Computes `self >> rhs`, returning `None`
1754 /// if `rhs` is larger than or equal to the number of bits in `self`.
1761 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1762 /// assert_eq!(0x10u32.checked_shr(33), None);
1764 #[stable(feature = "wrapping", since = "1.7.0")]
1766 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1767 let (a, b) = self.overflowing_shr(rhs);
1768 if b {None} else {Some(a)}
1771 /// Saturating integer addition. Computes `self + other`, saturating at
1772 /// the numeric bounds instead of overflowing.
1779 /// assert_eq!(100u8.saturating_add(1), 101);
1780 /// assert_eq!(200u8.saturating_add(127), 255);
1782 #[stable(feature = "rust1", since = "1.0.0")]
1784 pub fn saturating_add(self, other: Self) -> Self {
1785 match self.checked_add(other) {
1787 None => Self::max_value(),
1791 /// Saturating integer subtraction. Computes `self - other`, saturating
1792 /// at the numeric bounds instead of overflowing.
1799 /// assert_eq!(100u8.saturating_sub(27), 73);
1800 /// assert_eq!(13u8.saturating_sub(127), 0);
1802 #[stable(feature = "rust1", since = "1.0.0")]
1804 pub fn saturating_sub(self, other: Self) -> Self {
1805 match self.checked_sub(other) {
1807 None => Self::min_value(),
1811 /// Saturating integer multiplication. Computes `self * other`,
1812 /// saturating at the numeric bounds instead of overflowing.
1821 /// assert_eq!(100u32.saturating_mul(127), 12700);
1822 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1824 #[stable(feature = "wrapping", since = "1.7.0")]
1826 pub fn saturating_mul(self, other: Self) -> Self {
1827 self.checked_mul(other).unwrap_or(Self::max_value())
1830 /// Wrapping (modular) addition. Computes `self + other`,
1831 /// wrapping around at the boundary of the type.
1838 /// assert_eq!(200u8.wrapping_add(55), 255);
1839 /// assert_eq!(200u8.wrapping_add(155), 99);
1841 #[stable(feature = "rust1", since = "1.0.0")]
1843 pub fn wrapping_add(self, rhs: Self) -> Self {
1845 intrinsics::overflowing_add(self, rhs)
1849 /// Wrapping (modular) subtraction. Computes `self - other`,
1850 /// wrapping around at the boundary of the type.
1857 /// assert_eq!(100u8.wrapping_sub(100), 0);
1858 /// assert_eq!(100u8.wrapping_sub(155), 201);
1860 #[stable(feature = "rust1", since = "1.0.0")]
1862 pub fn wrapping_sub(self, rhs: Self) -> Self {
1864 intrinsics::overflowing_sub(self, rhs)
1868 /// Wrapping (modular) multiplication. Computes `self *
1869 /// other`, wrapping around at the boundary of the type.
1876 /// assert_eq!(10u8.wrapping_mul(12), 120);
1877 /// assert_eq!(25u8.wrapping_mul(12), 44);
1879 #[stable(feature = "rust1", since = "1.0.0")]
1881 pub fn wrapping_mul(self, rhs: Self) -> Self {
1883 intrinsics::overflowing_mul(self, rhs)
1887 /// Wrapping (modular) division. Computes `self / other`.
1888 /// Wrapped division on unsigned types is just normal division.
1889 /// There's no way wrapping could ever happen.
1890 /// This function exists, so that all operations
1891 /// are accounted for in the wrapping operations.
1898 /// assert_eq!(100u8.wrapping_div(10), 10);
1900 #[stable(feature = "num_wrapping", since = "1.2.0")]
1902 pub fn wrapping_div(self, rhs: Self) -> Self {
1906 /// Wrapping (modular) remainder. Computes `self % other`.
1907 /// Wrapped remainder calculation on unsigned types is
1908 /// just the regular remainder calculation.
1909 /// There's no way wrapping could ever happen.
1910 /// This function exists, so that all operations
1911 /// are accounted for in the wrapping operations.
1918 /// assert_eq!(100u8.wrapping_rem(10), 0);
1920 #[stable(feature = "num_wrapping", since = "1.2.0")]
1922 pub fn wrapping_rem(self, rhs: Self) -> Self {
1926 /// Wrapping (modular) negation. Computes `-self`,
1927 /// wrapping around at the boundary of the type.
1929 /// Since unsigned types do not have negative equivalents
1930 /// all applications of this function will wrap (except for `-0`).
1931 /// For values smaller than the corresponding signed type's maximum
1932 /// the result is the same as casting the corresponding signed value.
1933 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1934 /// `MAX` is the corresponding signed type's maximum.
1941 /// assert_eq!(100u8.wrapping_neg(), 156);
1942 /// assert_eq!(0u8.wrapping_neg(), 0);
1943 /// assert_eq!(180u8.wrapping_neg(), 76);
1944 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1946 #[stable(feature = "num_wrapping", since = "1.2.0")]
1948 pub fn wrapping_neg(self) -> Self {
1949 self.overflowing_neg().0
1952 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1953 /// where `mask` removes any high-order bits of `rhs` that
1954 /// would cause the shift to exceed the bitwidth of the type.
1956 /// Note that this is *not* the same as a rotate-left; the
1957 /// RHS of a wrapping shift-left is restricted to the range
1958 /// of the type, rather than the bits shifted out of the LHS
1959 /// being returned to the other end. The primitive integer
1960 /// types all implement a `rotate_left` function, which may
1961 /// be what you want instead.
1968 /// assert_eq!(1u8.wrapping_shl(7), 128);
1969 /// assert_eq!(1u8.wrapping_shl(8), 1);
1971 #[stable(feature = "num_wrapping", since = "1.2.0")]
1973 pub fn wrapping_shl(self, rhs: u32) -> Self {
1974 self.overflowing_shl(rhs).0
1977 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1978 /// where `mask` removes any high-order bits of `rhs` that
1979 /// would cause the shift to exceed the bitwidth of the type.
1981 /// Note that this is *not* the same as a rotate-right; the
1982 /// RHS of a wrapping shift-right is restricted to the range
1983 /// of the type, rather than the bits shifted out of the LHS
1984 /// being returned to the other end. The primitive integer
1985 /// types all implement a `rotate_right` function, which may
1986 /// be what you want instead.
1993 /// assert_eq!(128u8.wrapping_shr(7), 1);
1994 /// assert_eq!(128u8.wrapping_shr(8), 128);
1996 #[stable(feature = "num_wrapping", since = "1.2.0")]
1998 pub fn wrapping_shr(self, rhs: u32) -> Self {
1999 self.overflowing_shr(rhs).0
2002 /// Calculates `self` + `rhs`
2004 /// Returns a tuple of the addition along with a boolean indicating
2005 /// whether an arithmetic overflow would occur. If an overflow would
2006 /// have occurred then the wrapped value is returned.
2015 /// assert_eq!(5u32.overflowing_add(2), (7, false));
2016 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
2019 #[stable(feature = "wrapping", since = "1.7.0")]
2020 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2022 let (a, b) = $add_with_overflow(self as $ActualT,
2028 /// Calculates `self` - `rhs`
2030 /// Returns a tuple of the subtraction along with a boolean indicating
2031 /// whether an arithmetic overflow would occur. If an overflow would
2032 /// have occurred then the wrapped value is returned.
2041 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
2042 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
2045 #[stable(feature = "wrapping", since = "1.7.0")]
2046 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2048 let (a, b) = $sub_with_overflow(self as $ActualT,
2054 /// Calculates the multiplication of `self` and `rhs`.
2056 /// Returns a tuple of the multiplication along with a boolean
2057 /// indicating whether an arithmetic overflow would occur. If an
2058 /// overflow would have occurred then the wrapped value is returned.
2065 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2066 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2069 #[stable(feature = "wrapping", since = "1.7.0")]
2070 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2072 let (a, b) = $mul_with_overflow(self as $ActualT,
2078 /// Calculates the divisor when `self` is divided by `rhs`.
2080 /// Returns a tuple of the divisor along with a boolean indicating
2081 /// whether an arithmetic overflow would occur. Note that for unsigned
2082 /// integers overflow never occurs, so the second value is always
2087 /// This function will panic if `rhs` is 0.
2094 /// assert_eq!(5u32.overflowing_div(2), (2, false));
2097 #[stable(feature = "wrapping", since = "1.7.0")]
2098 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2102 /// Calculates the remainder when `self` is divided by `rhs`.
2104 /// Returns a tuple of the remainder after dividing along with a boolean
2105 /// indicating whether an arithmetic overflow would occur. Note that for
2106 /// unsigned integers overflow never occurs, so the second value is
2111 /// This function will panic if `rhs` is 0.
2118 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
2121 #[stable(feature = "wrapping", since = "1.7.0")]
2122 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2126 /// Negates self in an overflowing fashion.
2128 /// Returns `!self + 1` using wrapping operations to return the value
2129 /// that represents the negation of this unsigned value. Note that for
2130 /// positive unsigned values overflow always occurs, but negating 0 does
2138 /// assert_eq!(0u32.overflowing_neg(), (0, false));
2139 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
2142 #[stable(feature = "wrapping", since = "1.7.0")]
2143 pub fn overflowing_neg(self) -> (Self, bool) {
2144 ((!self).wrapping_add(1), self != 0)
2147 /// Shifts self left by `rhs` bits.
2149 /// Returns a tuple of the shifted version of self along with a boolean
2150 /// indicating whether the shift value was larger than or equal to the
2151 /// number of bits. If the shift value is too large, then value is
2152 /// masked (N-1) where N is the number of bits, and this value is then
2153 /// used to perform the shift.
2160 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
2161 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
2164 #[stable(feature = "wrapping", since = "1.7.0")]
2165 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2166 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
2169 /// Shifts self right by `rhs` bits.
2171 /// Returns a tuple of the shifted version of self along with a boolean
2172 /// indicating whether the shift value was larger than or equal to the
2173 /// number of bits. If the shift value is too large, then value is
2174 /// masked (N-1) where N is the number of bits, and this value is then
2175 /// used to perform the shift.
2182 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
2183 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2186 #[stable(feature = "wrapping", since = "1.7.0")]
2187 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2188 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
2191 /// Raises self to the power of `exp`, using exponentiation by squaring.
2198 /// assert_eq!(2u32.pow(4), 16);
2200 #[stable(feature = "rust1", since = "1.0.0")]
2202 #[rustc_inherit_overflow_checks]
2203 pub fn pow(self, mut exp: u32) -> Self {
2204 let mut base = self;
2215 // Deal with the final bit of the exponent separately, since
2216 // squaring the base afterwards is not necessary and may cause a
2217 // needless overflow.
2225 /// Returns `true` if and only if `self == 2^k` for some `k`.
2232 /// assert!(16u8.is_power_of_two());
2233 /// assert!(!10u8.is_power_of_two());
2235 #[stable(feature = "rust1", since = "1.0.0")]
2237 pub fn is_power_of_two(self) -> bool {
2238 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2241 /// Returns the smallest power of two greater than or equal to `self`.
2242 /// Unspecified behavior on overflow.
2249 /// assert_eq!(2u8.next_power_of_two(), 2);
2250 /// assert_eq!(3u8.next_power_of_two(), 4);
2252 #[stable(feature = "rust1", since = "1.0.0")]
2254 pub fn next_power_of_two(self) -> Self {
2255 let bits = size_of::<Self>() * 8;
2257 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
2260 /// Returns the smallest power of two greater than or equal to `n`. If
2261 /// the next power of two is greater than the type's maximum value,
2262 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2269 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2270 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2271 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2273 #[stable(feature = "rust1", since = "1.0.0")]
2274 pub fn checked_next_power_of_two(self) -> Option<Self> {
2275 let npot = self.next_power_of_two();
2292 intrinsics::add_with_overflow,
2293 intrinsics::sub_with_overflow,
2294 intrinsics::mul_with_overflow }
2299 uint_impl! { u16, 16,
2304 intrinsics::add_with_overflow,
2305 intrinsics::sub_with_overflow,
2306 intrinsics::mul_with_overflow }
2311 uint_impl! { u32, 32,
2316 intrinsics::add_with_overflow,
2317 intrinsics::sub_with_overflow,
2318 intrinsics::mul_with_overflow }
2323 uint_impl! { u64, 64,
2328 intrinsics::add_with_overflow,
2329 intrinsics::sub_with_overflow,
2330 intrinsics::mul_with_overflow }
2333 #[cfg(target_pointer_width = "16")]
2336 uint_impl! { u16, 16,
2341 intrinsics::add_with_overflow,
2342 intrinsics::sub_with_overflow,
2343 intrinsics::mul_with_overflow }
2345 #[cfg(target_pointer_width = "32")]
2348 uint_impl! { u32, 32,
2353 intrinsics::add_with_overflow,
2354 intrinsics::sub_with_overflow,
2355 intrinsics::mul_with_overflow }
2358 #[cfg(target_pointer_width = "64")]
2361 uint_impl! { u64, 64,
2366 intrinsics::add_with_overflow,
2367 intrinsics::sub_with_overflow,
2368 intrinsics::mul_with_overflow }
2371 /// A classification of floating point numbers.
2373 /// This `enum` is used as the return type for [`f32::classify()`] and [`f64::classify()`]. See
2374 /// their documentation for more.
2376 /// [`f32::classify()`]: ../../std/primitive.f32.html#method.classify
2377 /// [`f64::classify()`]: ../../std/primitive.f64.html#method.classify
2382 /// use std::num::FpCategory;
2385 /// let num = 12.4_f32;
2386 /// let inf = f32::INFINITY;
2387 /// let zero = 0f32;
2388 /// let sub: f32 = 1.1754942e-38;
2389 /// let nan = f32::NAN;
2391 /// assert_eq!(num.classify(), FpCategory::Normal);
2392 /// assert_eq!(inf.classify(), FpCategory::Infinite);
2393 /// assert_eq!(zero.classify(), FpCategory::Zero);
2394 /// assert_eq!(nan.classify(), FpCategory::Nan);
2395 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
2397 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2398 #[stable(feature = "rust1", since = "1.0.0")]
2399 pub enum FpCategory {
2400 /// "Not a Number", often obtained by dividing by zero.
2401 #[stable(feature = "rust1", since = "1.0.0")]
2404 /// Positive or negative infinity.
2405 #[stable(feature = "rust1", since = "1.0.0")]
2408 /// Positive or negative zero.
2409 #[stable(feature = "rust1", since = "1.0.0")]
2412 /// De-normalized floating point representation (less precise than `Normal`).
2413 #[stable(feature = "rust1", since = "1.0.0")]
2416 /// A regular floating point number.
2417 #[stable(feature = "rust1", since = "1.0.0")]
2421 /// A built-in floating point number.
2423 #[unstable(feature = "core_float",
2424 reason = "stable interface is via `impl f{32,64}` in later crates",
2426 pub trait Float: Sized {
2427 /// Returns the NaN value.
2428 #[unstable(feature = "float_extras", reason = "needs removal",
2430 #[rustc_deprecated(since = "1.11.0",
2431 reason = "never really came to fruition and easily \
2432 implementable outside the standard library")]
2434 /// Returns the infinite value.
2435 #[unstable(feature = "float_extras", reason = "needs removal",
2437 #[rustc_deprecated(since = "1.11.0",
2438 reason = "never really came to fruition and easily \
2439 implementable outside the standard library")]
2440 fn infinity() -> Self;
2441 /// Returns the negative infinite value.
2442 #[unstable(feature = "float_extras", reason = "needs removal",
2444 #[rustc_deprecated(since = "1.11.0",
2445 reason = "never really came to fruition and easily \
2446 implementable outside the standard library")]
2447 fn neg_infinity() -> Self;
2449 #[unstable(feature = "float_extras", reason = "needs removal",
2451 #[rustc_deprecated(since = "1.11.0",
2452 reason = "never really came to fruition and easily \
2453 implementable outside the standard library")]
2454 fn neg_zero() -> Self;
2456 #[unstable(feature = "float_extras", reason = "needs removal",
2458 #[rustc_deprecated(since = "1.11.0",
2459 reason = "never really came to fruition and easily \
2460 implementable outside the standard library")]
2463 #[unstable(feature = "float_extras", reason = "needs removal",
2465 #[rustc_deprecated(since = "1.11.0",
2466 reason = "never really came to fruition and easily \
2467 implementable outside the standard library")]
2470 /// Returns true if this value is NaN and false otherwise.
2471 #[stable(feature = "core", since = "1.6.0")]
2472 fn is_nan(self) -> bool;
2473 /// Returns true if this value is positive infinity or negative infinity and
2474 /// false otherwise.
2475 #[stable(feature = "core", since = "1.6.0")]
2476 fn is_infinite(self) -> bool;
2477 /// Returns true if this number is neither infinite nor NaN.
2478 #[stable(feature = "core", since = "1.6.0")]
2479 fn is_finite(self) -> bool;
2480 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
2481 #[stable(feature = "core", since = "1.6.0")]
2482 fn is_normal(self) -> bool;
2483 /// Returns the category that this number falls into.
2484 #[stable(feature = "core", since = "1.6.0")]
2485 fn classify(self) -> FpCategory;
2487 /// Returns the mantissa, exponent and sign as integers, respectively.
2488 #[unstable(feature = "float_extras", reason = "signature is undecided",
2490 #[rustc_deprecated(since = "1.11.0",
2491 reason = "never really came to fruition and easily \
2492 implementable outside the standard library")]
2493 fn integer_decode(self) -> (u64, i16, i8);
2495 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2496 /// number is `Float::nan()`.
2497 #[stable(feature = "core", since = "1.6.0")]
2498 fn abs(self) -> Self;
2499 /// Returns a number that represents the sign of `self`.
2501 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2502 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2503 /// - `Float::nan()` if the number is `Float::nan()`
2504 #[stable(feature = "core", since = "1.6.0")]
2505 fn signum(self) -> Self;
2507 /// Returns `true` if `self` is positive, including `+0.0` and
2508 /// `Float::infinity()`.
2509 #[stable(feature = "core", since = "1.6.0")]
2510 fn is_sign_positive(self) -> bool;
2511 /// Returns `true` if `self` is negative, including `-0.0` and
2512 /// `Float::neg_infinity()`.
2513 #[stable(feature = "core", since = "1.6.0")]
2514 fn is_sign_negative(self) -> bool;
2516 /// Take the reciprocal (inverse) of a number, `1/x`.
2517 #[stable(feature = "core", since = "1.6.0")]
2518 fn recip(self) -> Self;
2520 /// Raise a number to an integer power.
2522 /// Using this function is generally faster than using `powf`
2523 #[stable(feature = "core", since = "1.6.0")]
2524 fn powi(self, n: i32) -> Self;
2526 /// Convert radians to degrees.
2527 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2528 fn to_degrees(self) -> Self;
2529 /// Convert degrees to radians.
2530 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2531 fn to_radians(self) -> Self;
2534 macro_rules! from_str_radix_int_impl {
2536 #[stable(feature = "rust1", since = "1.0.0")]
2537 impl FromStr for $t {
2538 type Err = ParseIntError;
2539 fn from_str(src: &str) -> Result<Self, ParseIntError> {
2540 from_str_radix(src, 10)
2545 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
2547 /// The error type returned when a checked integral type conversion fails.
2548 #[unstable(feature = "try_from", issue = "33417")]
2549 #[derive(Debug, Copy, Clone)]
2550 pub struct TryFromIntError(());
2552 impl TryFromIntError {
2553 #[unstable(feature = "int_error_internals",
2554 reason = "available through Error trait and this method should \
2555 not be exposed publicly",
2558 pub fn __description(&self) -> &str {
2559 "out of range integral type conversion attempted"
2563 #[unstable(feature = "try_from", issue = "33417")]
2564 impl fmt::Display for TryFromIntError {
2565 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2566 self.__description().fmt(fmt)
2570 macro_rules! same_sign_from_int_impl {
2571 ($storage:ty, $target:ty, $($source:ty),*) => {$(
2572 #[unstable(feature = "try_from", issue = "33417")]
2573 impl TryFrom<$source> for $target {
2574 type Err = TryFromIntError;
2576 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2577 let min = <$target as FromStrRadixHelper>::min_value() as $storage;
2578 let max = <$target as FromStrRadixHelper>::max_value() as $storage;
2579 if u as $storage < min || u as $storage > max {
2580 Err(TryFromIntError(()))
2589 same_sign_from_int_impl!(u64, u8, u8, u16, u32, u64, usize);
2590 same_sign_from_int_impl!(i64, i8, i8, i16, i32, i64, isize);
2591 same_sign_from_int_impl!(u64, u16, u8, u16, u32, u64, usize);
2592 same_sign_from_int_impl!(i64, i16, i8, i16, i32, i64, isize);
2593 same_sign_from_int_impl!(u64, u32, u8, u16, u32, u64, usize);
2594 same_sign_from_int_impl!(i64, i32, i8, i16, i32, i64, isize);
2595 same_sign_from_int_impl!(u64, u64, u8, u16, u32, u64, usize);
2596 same_sign_from_int_impl!(i64, i64, i8, i16, i32, i64, isize);
2597 same_sign_from_int_impl!(u64, usize, u8, u16, u32, u64, usize);
2598 same_sign_from_int_impl!(i64, isize, i8, i16, i32, i64, isize);
2600 macro_rules! cross_sign_from_int_impl {
2601 ($unsigned:ty, $($signed:ty),*) => {$(
2602 #[unstable(feature = "try_from", issue = "33417")]
2603 impl TryFrom<$unsigned> for $signed {
2604 type Err = TryFromIntError;
2606 fn try_from(u: $unsigned) -> Result<$signed, TryFromIntError> {
2607 let max = <$signed as FromStrRadixHelper>::max_value() as u64;
2609 Err(TryFromIntError(()))
2616 #[unstable(feature = "try_from", issue = "33417")]
2617 impl TryFrom<$signed> for $unsigned {
2618 type Err = TryFromIntError;
2620 fn try_from(u: $signed) -> Result<$unsigned, TryFromIntError> {
2621 let max = <$unsigned as FromStrRadixHelper>::max_value() as u64;
2622 if u < 0 || u as u64 > max {
2623 Err(TryFromIntError(()))
2632 cross_sign_from_int_impl!(u8, i8, i16, i32, i64, isize);
2633 cross_sign_from_int_impl!(u16, i8, i16, i32, i64, isize);
2634 cross_sign_from_int_impl!(u32, i8, i16, i32, i64, isize);
2635 cross_sign_from_int_impl!(u64, i8, i16, i32, i64, isize);
2636 cross_sign_from_int_impl!(usize, i8, i16, i32, i64, isize);
2639 trait FromStrRadixHelper: PartialOrd + Copy {
2640 fn min_value() -> Self;
2641 fn max_value() -> Self;
2642 fn from_u32(u: u32) -> Self;
2643 fn checked_mul(&self, other: u32) -> Option<Self>;
2644 fn checked_sub(&self, other: u32) -> Option<Self>;
2645 fn checked_add(&self, other: u32) -> Option<Self>;
2649 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
2650 fn min_value() -> Self { Self::min_value() }
2651 fn max_value() -> Self { Self::max_value() }
2652 fn from_u32(u: u32) -> Self { u as Self }
2653 fn checked_mul(&self, other: u32) -> Option<Self> {
2654 Self::checked_mul(*self, other as Self)
2656 fn checked_sub(&self, other: u32) -> Option<Self> {
2657 Self::checked_sub(*self, other as Self)
2659 fn checked_add(&self, other: u32) -> Option<Self> {
2660 Self::checked_add(*self, other as Self)
2664 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
2666 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
2667 use self::IntErrorKind::*;
2668 use self::ParseIntError as PIE;
2670 assert!(radix >= 2 && radix <= 36,
2671 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2675 return Err(PIE { kind: Empty });
2678 let is_signed_ty = T::from_u32(0) > T::min_value();
2680 // all valid digits are ascii, so we will just iterate over the utf8 bytes
2681 // and cast them to chars. .to_digit() will safely return None for anything
2682 // other than a valid ascii digit for the given radix, including the first-byte
2683 // of multi-byte sequences
2684 let src = src.as_bytes();
2686 let (is_positive, digits) = match src[0] {
2687 b'+' => (true, &src[1..]),
2688 b'-' if is_signed_ty => (false, &src[1..]),
2692 if digits.is_empty() {
2693 return Err(PIE { kind: Empty });
2696 let mut result = T::from_u32(0);
2698 // The number is positive
2700 let x = match (c as char).to_digit(radix) {
2702 None => return Err(PIE { kind: InvalidDigit }),
2704 result = match result.checked_mul(radix) {
2705 Some(result) => result,
2706 None => return Err(PIE { kind: Overflow }),
2708 result = match result.checked_add(x) {
2709 Some(result) => result,
2710 None => return Err(PIE { kind: Overflow }),
2714 // The number is negative
2716 let x = match (c as char).to_digit(radix) {
2718 None => return Err(PIE { kind: InvalidDigit }),
2720 result = match result.checked_mul(radix) {
2721 Some(result) => result,
2722 None => return Err(PIE { kind: Underflow }),
2724 result = match result.checked_sub(x) {
2725 Some(result) => result,
2726 None => return Err(PIE { kind: Underflow }),
2733 /// An error which can be returned when parsing an integer.
2735 /// This error is used as the error type for the `from_str_radix()` functions
2736 /// on the primitive integer types, such as [`i8::from_str_radix()`].
2738 /// [`i8::from_str_radix()`]: ../../std/primitive.i8.html#method.from_str_radix
2739 #[derive(Debug, Clone, PartialEq, Eq)]
2740 #[stable(feature = "rust1", since = "1.0.0")]
2741 pub struct ParseIntError {
2745 #[derive(Debug, Clone, PartialEq, Eq)]
2753 impl ParseIntError {
2754 #[unstable(feature = "int_error_internals",
2755 reason = "available through Error trait and this method should \
2756 not be exposed publicly",
2759 pub fn __description(&self) -> &str {
2761 IntErrorKind::Empty => "cannot parse integer from empty string",
2762 IntErrorKind::InvalidDigit => "invalid digit found in string",
2763 IntErrorKind::Overflow => "number too large to fit in target type",
2764 IntErrorKind::Underflow => "number too small to fit in target type",
2769 #[stable(feature = "rust1", since = "1.0.0")]
2770 impl fmt::Display for ParseIntError {
2771 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2772 self.__description().fmt(f)
2776 #[stable(feature = "rust1", since = "1.0.0")]
2777 pub use num::dec2flt::ParseFloatError;
2779 // Conversion traits for primitive integer and float types
2780 // Conversions T -> T are covered by a blanket impl and therefore excluded
2781 // Some conversions from and to usize/isize are not implemented due to portability concerns
2782 macro_rules! impl_from {
2783 ($Small: ty, $Large: ty) => {
2784 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
2785 impl From<$Small> for $Large {
2787 fn from(small: $Small) -> $Large {
2794 // Unsigned -> Unsigned
2795 impl_from! { u8, u16 }
2796 impl_from! { u8, u32 }
2797 impl_from! { u8, u64 }
2798 impl_from! { u8, usize }
2799 impl_from! { u16, u32 }
2800 impl_from! { u16, u64 }
2801 impl_from! { u32, u64 }
2804 impl_from! { i8, i16 }
2805 impl_from! { i8, i32 }
2806 impl_from! { i8, i64 }
2807 impl_from! { i8, isize }
2808 impl_from! { i16, i32 }
2809 impl_from! { i16, i64 }
2810 impl_from! { i32, i64 }
2812 // Unsigned -> Signed
2813 impl_from! { u8, i16 }
2814 impl_from! { u8, i32 }
2815 impl_from! { u8, i64 }
2816 impl_from! { u16, i32 }
2817 impl_from! { u16, i64 }
2818 impl_from! { u32, i64 }
2820 // Note: integers can only be represented with full precision in a float if
2821 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2822 // Lossy float conversions are not implemented at this time.
2825 impl_from! { i8, f32 }
2826 impl_from! { i8, f64 }
2827 impl_from! { i16, f32 }
2828 impl_from! { i16, f64 }
2829 impl_from! { i32, f64 }
2831 // Unsigned -> Float
2832 impl_from! { u8, f32 }
2833 impl_from! { u8, f64 }
2834 impl_from! { u16, f32 }
2835 impl_from! { u16, f64 }
2836 impl_from! { u32, f64 }
2839 impl_from! { f32, f64 }