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 coretests:
99 macro_rules! checked_op {
100 ($U:ty, $op:path, $x:expr, $y:expr) => {{
101 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
102 if overflowed { None } else { Some(result as Self) }
106 // `Int` + `SignedInt` implemented for signed integers
107 macro_rules! int_impl {
108 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr,
109 $add_with_overflow:path,
110 $sub_with_overflow:path,
111 $mul_with_overflow:path) => {
112 /// Returns the smallest value that can be represented by this integer type.
117 /// assert_eq!(i8::min_value(), -128);
119 #[stable(feature = "rust1", since = "1.0.0")]
121 pub const fn min_value() -> Self {
122 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
125 /// Returns the largest value that can be represented by this integer type.
130 /// assert_eq!(i8::max_value(), 127);
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!(i32::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 = -0b1000_0000i8;
163 /// assert_eq!(n.count_ones(), 1);
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 = -0b1000_0000i8;
178 /// assert_eq!(n.count_zeros(), 7);
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
196 /// assert_eq!(n.leading_zeros(), 0);
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
214 /// assert_eq!(n.trailing_zeros(), 2);
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.
225 /// Please note this isn't the same operation as `<<`!
232 /// let n = 0x0123456789ABCDEFi64;
233 /// let m = -0x76543210FEDCBA99i64;
235 /// assert_eq!(n.rotate_left(32), m);
237 #[stable(feature = "rust1", since = "1.0.0")]
239 pub fn rotate_left(self, n: u32) -> Self {
240 (self as $UnsignedT).rotate_left(n) as Self
243 /// Shifts the bits to the right by a specified amount, `n`,
244 /// wrapping the truncated bits to the beginning of the resulting
247 /// Please note this isn't the same operation as `>>`!
254 /// let n = 0x0123456789ABCDEFi64;
255 /// let m = -0xFEDCBA987654322i64;
257 /// assert_eq!(n.rotate_right(4), m);
259 #[stable(feature = "rust1", since = "1.0.0")]
261 pub fn rotate_right(self, n: u32) -> Self {
262 (self as $UnsignedT).rotate_right(n) as Self
265 /// Reverses the byte order of the integer.
272 /// let n = 0x0123456789ABCDEFi64;
273 /// let m = -0x1032547698BADCFFi64;
275 /// assert_eq!(n.swap_bytes(), m);
277 #[stable(feature = "rust1", since = "1.0.0")]
279 pub fn swap_bytes(self) -> Self {
280 (self as $UnsignedT).swap_bytes() as Self
283 /// Converts an integer from big endian to the target's endianness.
285 /// On big endian this is a no-op. On little endian the bytes are
293 /// let n = 0x0123456789ABCDEFi64;
295 /// if cfg!(target_endian = "big") {
296 /// assert_eq!(i64::from_be(n), n)
298 /// assert_eq!(i64::from_be(n), n.swap_bytes())
301 #[stable(feature = "rust1", since = "1.0.0")]
303 pub fn from_be(x: Self) -> Self {
304 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
307 /// Converts an integer from little endian to the target's endianness.
309 /// On little endian this is a no-op. On big endian the bytes are
317 /// let n = 0x0123456789ABCDEFi64;
319 /// if cfg!(target_endian = "little") {
320 /// assert_eq!(i64::from_le(n), n)
322 /// assert_eq!(i64::from_le(n), n.swap_bytes())
325 #[stable(feature = "rust1", since = "1.0.0")]
327 pub fn from_le(x: Self) -> Self {
328 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
331 /// Converts `self` to big endian from the target's endianness.
333 /// On big endian this is a no-op. On little endian the bytes are
341 /// let n = 0x0123456789ABCDEFi64;
343 /// if cfg!(target_endian = "big") {
344 /// assert_eq!(n.to_be(), n)
346 /// assert_eq!(n.to_be(), n.swap_bytes())
349 #[stable(feature = "rust1", since = "1.0.0")]
351 pub fn to_be(self) -> Self { // or not to be?
352 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
355 /// Converts `self` to little endian from the target's endianness.
357 /// On little endian this is a no-op. On big endian the bytes are
365 /// let n = 0x0123456789ABCDEFi64;
367 /// if cfg!(target_endian = "little") {
368 /// assert_eq!(n.to_le(), n)
370 /// assert_eq!(n.to_le(), n.swap_bytes())
373 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn to_le(self) -> Self {
376 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
379 /// Checked integer addition. Computes `self + other`, returning `None`
380 /// if overflow occurred.
387 /// assert_eq!(7i16.checked_add(32760), Some(32767));
388 /// assert_eq!(8i16.checked_add(32760), None);
390 #[stable(feature = "rust1", since = "1.0.0")]
392 pub fn checked_add(self, other: Self) -> Option<Self> {
393 let (a, b) = self.overflowing_add(other);
394 if b {None} else {Some(a)}
397 /// Checked integer subtraction. Computes `self - other`, returning
398 /// `None` if underflow occurred.
405 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
406 /// assert_eq!((-128i8).checked_sub(1), None);
408 #[stable(feature = "rust1", since = "1.0.0")]
410 pub fn checked_sub(self, other: Self) -> Option<Self> {
411 let (a, b) = self.overflowing_sub(other);
412 if b {None} else {Some(a)}
415 /// Checked integer multiplication. Computes `self * other`, returning
416 /// `None` if underflow or overflow occurred.
423 /// assert_eq!(6i8.checked_mul(21), Some(126));
424 /// assert_eq!(6i8.checked_mul(22), None);
426 #[stable(feature = "rust1", since = "1.0.0")]
428 pub fn checked_mul(self, other: Self) -> Option<Self> {
429 let (a, b) = self.overflowing_mul(other);
430 if b {None} else {Some(a)}
433 /// Checked integer division. Computes `self / other`, returning `None`
434 /// if `other == 0` or the operation results in underflow or overflow.
441 /// assert_eq!((-127i8).checked_div(-1), Some(127));
442 /// assert_eq!((-128i8).checked_div(-1), None);
443 /// assert_eq!((1i8).checked_div(0), None);
445 #[stable(feature = "rust1", since = "1.0.0")]
447 pub fn checked_div(self, other: Self) -> Option<Self> {
448 if other == 0 || (self == Self::min_value() && other == -1) {
451 Some(unsafe { intrinsics::unchecked_div(self, other) })
455 /// Checked integer remainder. Computes `self % other`, returning `None`
456 /// if `other == 0` or the operation results in underflow or overflow.
465 /// assert_eq!(5i32.checked_rem(2), Some(1));
466 /// assert_eq!(5i32.checked_rem(0), None);
467 /// assert_eq!(i32::MIN.checked_rem(-1), None);
469 #[stable(feature = "wrapping", since = "1.7.0")]
471 pub fn checked_rem(self, other: Self) -> Option<Self> {
472 if other == 0 || (self == Self::min_value() && other == -1) {
475 Some(unsafe { intrinsics::unchecked_rem(self, other) })
479 /// Checked negation. Computes `-self`, returning `None` if `self ==
489 /// assert_eq!(5i32.checked_neg(), Some(-5));
490 /// assert_eq!(i32::MIN.checked_neg(), None);
492 #[stable(feature = "wrapping", since = "1.7.0")]
494 pub fn checked_neg(self) -> Option<Self> {
495 let (a, b) = self.overflowing_neg();
496 if b {None} else {Some(a)}
499 /// Checked shift left. Computes `self << rhs`, returning `None`
500 /// if `rhs` is larger than or equal to the number of bits in `self`.
507 /// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
508 /// assert_eq!(0x10i32.checked_shl(33), None);
510 #[stable(feature = "wrapping", since = "1.7.0")]
512 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
513 let (a, b) = self.overflowing_shl(rhs);
514 if b {None} else {Some(a)}
517 /// Checked shift right. Computes `self >> rhs`, returning `None`
518 /// if `rhs` is larger than or equal to the number of bits in `self`.
525 /// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
526 /// assert_eq!(0x10i32.checked_shr(33), None);
528 #[stable(feature = "wrapping", since = "1.7.0")]
530 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
531 let (a, b) = self.overflowing_shr(rhs);
532 if b {None} else {Some(a)}
535 /// Checked absolute value. Computes `self.abs()`, returning `None` if
545 /// assert_eq!((-5i32).checked_abs(), Some(5));
546 /// assert_eq!(i32::MIN.checked_abs(), None);
548 #[stable(feature = "no_panic_abs", since = "1.13.0")]
550 pub fn checked_abs(self) -> Option<Self> {
551 if self.is_negative() {
558 /// Saturating integer addition. Computes `self + other`, saturating at
559 /// the numeric bounds instead of overflowing.
566 /// assert_eq!(100i8.saturating_add(1), 101);
567 /// assert_eq!(100i8.saturating_add(127), 127);
569 #[stable(feature = "rust1", since = "1.0.0")]
571 pub fn saturating_add(self, other: Self) -> Self {
572 match self.checked_add(other) {
574 None if other >= 0 => Self::max_value(),
575 None => Self::min_value(),
579 /// Saturating integer subtraction. Computes `self - other`, saturating
580 /// at the numeric bounds instead of overflowing.
587 /// assert_eq!(100i8.saturating_sub(127), -27);
588 /// assert_eq!((-100i8).saturating_sub(127), -128);
590 #[stable(feature = "rust1", since = "1.0.0")]
592 pub fn saturating_sub(self, other: Self) -> Self {
593 match self.checked_sub(other) {
595 None if other >= 0 => Self::min_value(),
596 None => Self::max_value(),
600 /// Saturating integer multiplication. Computes `self * other`,
601 /// saturating at the numeric bounds instead of overflowing.
610 /// assert_eq!(100i32.saturating_mul(127), 12700);
611 /// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
612 /// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
614 #[stable(feature = "wrapping", since = "1.7.0")]
616 pub fn saturating_mul(self, other: Self) -> Self {
617 self.checked_mul(other).unwrap_or_else(|| {
618 if (self < 0 && other < 0) || (self > 0 && other > 0) {
626 /// Wrapping (modular) addition. Computes `self + other`,
627 /// wrapping around at the boundary of the type.
634 /// assert_eq!(100i8.wrapping_add(27), 127);
635 /// assert_eq!(100i8.wrapping_add(127), -29);
637 #[stable(feature = "rust1", since = "1.0.0")]
639 pub fn wrapping_add(self, rhs: Self) -> Self {
641 intrinsics::overflowing_add(self, rhs)
645 /// Wrapping (modular) subtraction. Computes `self - other`,
646 /// wrapping around at the boundary of the type.
653 /// assert_eq!(0i8.wrapping_sub(127), -127);
654 /// assert_eq!((-2i8).wrapping_sub(127), 127);
656 #[stable(feature = "rust1", since = "1.0.0")]
658 pub fn wrapping_sub(self, rhs: Self) -> Self {
660 intrinsics::overflowing_sub(self, rhs)
664 /// Wrapping (modular) multiplication. Computes `self *
665 /// other`, wrapping around at the boundary of the type.
672 /// assert_eq!(10i8.wrapping_mul(12), 120);
673 /// assert_eq!(11i8.wrapping_mul(12), -124);
675 #[stable(feature = "rust1", since = "1.0.0")]
677 pub fn wrapping_mul(self, rhs: Self) -> Self {
679 intrinsics::overflowing_mul(self, rhs)
683 /// Wrapping (modular) division. Computes `self / other`,
684 /// wrapping around at the boundary of the type.
686 /// The only case where such wrapping can occur is when one
687 /// divides `MIN / -1` on a signed type (where `MIN` is the
688 /// negative minimal value for the type); this is equivalent
689 /// to `-MIN`, a positive value that is too large to represent
690 /// in the type. In such a case, this function returns `MIN`
695 /// This function will panic if `rhs` is 0.
702 /// assert_eq!(100u8.wrapping_div(10), 10);
703 /// assert_eq!((-128i8).wrapping_div(-1), -128);
705 #[stable(feature = "num_wrapping", since = "1.2.0")]
707 pub fn wrapping_div(self, rhs: Self) -> Self {
708 self.overflowing_div(rhs).0
711 /// Wrapping (modular) remainder. Computes `self % other`,
712 /// wrapping around at the boundary of the type.
714 /// Such wrap-around never actually occurs mathematically;
715 /// implementation artifacts make `x % y` invalid for `MIN /
716 /// -1` on a signed type (where `MIN` is the negative
717 /// minimal value). In such a case, this function returns `0`.
721 /// This function will panic if `rhs` is 0.
728 /// assert_eq!(100i8.wrapping_rem(10), 0);
729 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
731 #[stable(feature = "num_wrapping", since = "1.2.0")]
733 pub fn wrapping_rem(self, rhs: Self) -> Self {
734 self.overflowing_rem(rhs).0
737 /// Wrapping (modular) negation. Computes `-self`,
738 /// wrapping around at the boundary of the type.
740 /// The only case where such wrapping can occur is when one
741 /// negates `MIN` on a signed type (where `MIN` is the
742 /// negative minimal value for the type); this is a positive
743 /// value that is too large to represent in the type. In such
744 /// a case, this function returns `MIN` itself.
751 /// assert_eq!(100i8.wrapping_neg(), -100);
752 /// assert_eq!((-128i8).wrapping_neg(), -128);
754 #[stable(feature = "num_wrapping", since = "1.2.0")]
756 pub fn wrapping_neg(self) -> Self {
757 self.overflowing_neg().0
760 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
761 /// where `mask` removes any high-order bits of `rhs` that
762 /// would cause the shift to exceed the bitwidth of the type.
764 /// Note that this is *not* the same as a rotate-left; the
765 /// RHS of a wrapping shift-left is restricted to the range
766 /// of the type, rather than the bits shifted out of the LHS
767 /// being returned to the other end. The primitive integer
768 /// types all implement a `rotate_left` function, which may
769 /// be what you want instead.
776 /// assert_eq!((-1i8).wrapping_shl(7), -128);
777 /// assert_eq!((-1i8).wrapping_shl(8), -1);
779 #[stable(feature = "num_wrapping", since = "1.2.0")]
782 pub fn wrapping_shl(self, rhs: u32) -> Self {
784 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
789 #[stable(feature = "num_wrapping", since = "1.2.0")]
792 pub fn wrapping_shl(self, rhs: u32) -> Self {
793 self.overflowing_shl(rhs).0
796 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
797 /// where `mask` removes any high-order bits of `rhs` that
798 /// would cause the shift to exceed the bitwidth of the type.
800 /// Note that this is *not* the same as a rotate-right; the
801 /// RHS of a wrapping shift-right is restricted to the range
802 /// of the type, rather than the bits shifted out of the LHS
803 /// being returned to the other end. The primitive integer
804 /// types all implement a `rotate_right` function, which may
805 /// be what you want instead.
812 /// assert_eq!((-128i8).wrapping_shr(7), -1);
813 /// assert_eq!((-128i8).wrapping_shr(8), -128);
815 #[stable(feature = "num_wrapping", since = "1.2.0")]
818 pub fn wrapping_shr(self, rhs: u32) -> Self {
820 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
825 #[stable(feature = "num_wrapping", since = "1.2.0")]
828 pub fn wrapping_shr(self, rhs: u32) -> Self {
829 self.overflowing_shr(rhs).0
832 /// Wrapping (modular) absolute value. Computes `self.abs()`,
833 /// wrapping around at the boundary of the type.
835 /// The only case where such wrapping can occur is when one takes
836 /// the absolute value of the negative minimal value for the type
837 /// this is a positive value that is too large to represent in the
838 /// type. In such a case, this function returns `MIN` itself.
845 /// assert_eq!(100i8.wrapping_abs(), 100);
846 /// assert_eq!((-100i8).wrapping_abs(), 100);
847 /// assert_eq!((-128i8).wrapping_abs(), -128);
848 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
850 #[stable(feature = "no_panic_abs", since = "1.13.0")]
852 pub fn wrapping_abs(self) -> Self {
853 if self.is_negative() {
860 /// Calculates `self` + `rhs`
862 /// Returns a tuple of the addition along with a boolean indicating
863 /// whether an arithmetic overflow would occur. If an overflow would
864 /// have occurred then the wrapped value is returned.
873 /// assert_eq!(5i32.overflowing_add(2), (7, false));
874 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
877 #[stable(feature = "wrapping", since = "1.7.0")]
878 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
880 let (a, b) = $add_with_overflow(self as $ActualT,
886 /// Calculates `self` - `rhs`
888 /// Returns a tuple of the subtraction along with a boolean indicating
889 /// whether an arithmetic overflow would occur. If an overflow would
890 /// have occurred then the wrapped value is returned.
899 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
900 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
903 #[stable(feature = "wrapping", since = "1.7.0")]
904 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
906 let (a, b) = $sub_with_overflow(self as $ActualT,
912 /// Calculates the multiplication of `self` and `rhs`.
914 /// Returns a tuple of the multiplication along with a boolean
915 /// indicating whether an arithmetic overflow would occur. If an
916 /// overflow would have occurred then the wrapped value is returned.
923 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
924 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
927 #[stable(feature = "wrapping", since = "1.7.0")]
928 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
930 let (a, b) = $mul_with_overflow(self as $ActualT,
936 /// Calculates the divisor when `self` is divided by `rhs`.
938 /// Returns a tuple of the divisor along with a boolean indicating
939 /// whether an arithmetic overflow would occur. If an overflow would
940 /// occur then self is returned.
944 /// This function will panic if `rhs` is 0.
953 /// assert_eq!(5i32.overflowing_div(2), (2, false));
954 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
957 #[stable(feature = "wrapping", since = "1.7.0")]
958 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
959 if self == Self::min_value() && rhs == -1 {
966 /// Calculates the remainder when `self` is divided by `rhs`.
968 /// Returns a tuple of the remainder after dividing along with a boolean
969 /// indicating whether an arithmetic overflow would occur. If an
970 /// overflow would occur then 0 is returned.
974 /// This function will panic if `rhs` is 0.
983 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
984 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
987 #[stable(feature = "wrapping", since = "1.7.0")]
988 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
989 if self == Self::min_value() && rhs == -1 {
996 /// Negates self, overflowing if this is equal to the minimum value.
998 /// Returns a tuple of the negated version of self along with a boolean
999 /// indicating whether an overflow happened. If `self` is the minimum
1000 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
1001 /// value will be returned again and `true` will be returned for an
1002 /// overflow happening.
1011 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
1012 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
1015 #[stable(feature = "wrapping", since = "1.7.0")]
1016 pub fn overflowing_neg(self) -> (Self, bool) {
1017 if self == Self::min_value() {
1018 (Self::min_value(), true)
1024 /// Shifts self left by `rhs` bits.
1026 /// Returns a tuple of the shifted version of self along with a boolean
1027 /// indicating whether the shift value was larger than or equal to the
1028 /// number of bits. If the shift value is too large, then value is
1029 /// masked (N-1) where N is the number of bits, and this value is then
1030 /// used to perform the shift.
1037 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
1038 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
1041 #[stable(feature = "wrapping", since = "1.7.0")]
1043 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1044 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1049 #[stable(feature = "wrapping", since = "1.7.0")]
1051 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1052 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1055 /// Shifts self right by `rhs` bits.
1057 /// Returns a tuple of the shifted version of self along with a boolean
1058 /// indicating whether the shift value was larger than or equal to the
1059 /// number of bits. If the shift value is too large, then value is
1060 /// masked (N-1) where N is the number of bits, and this value is then
1061 /// used to perform the shift.
1068 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
1069 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1072 #[stable(feature = "wrapping", since = "1.7.0")]
1074 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1075 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1080 #[stable(feature = "wrapping", since = "1.7.0")]
1082 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1083 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1086 /// Computes the absolute value of `self`.
1088 /// Returns a tuple of the absolute version of self along with a
1089 /// boolean indicating whether an overflow happened. If self is the
1090 /// minimum value (e.g. i32::MIN for values of type i32), then the
1091 /// minimum value will be returned again and true will be returned for
1092 /// an overflow happening.
1099 /// assert_eq!(10i8.overflowing_abs(), (10,false));
1100 /// assert_eq!((-10i8).overflowing_abs(), (10,false));
1101 /// assert_eq!((-128i8).overflowing_abs(), (-128,true));
1103 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1105 pub fn overflowing_abs(self) -> (Self, bool) {
1106 if self.is_negative() {
1107 self.overflowing_neg()
1113 /// Raises self to the power of `exp`, using exponentiation by squaring.
1120 /// let x: i32 = 2; // or any other integer type
1122 /// assert_eq!(x.pow(4), 16);
1124 #[stable(feature = "rust1", since = "1.0.0")]
1126 #[rustc_inherit_overflow_checks]
1127 pub fn pow(self, mut exp: u32) -> Self {
1128 let mut base = self;
1139 // Deal with the final bit of the exponent separately, since
1140 // squaring the base afterwards is not necessary and may cause a
1141 // needless overflow.
1149 /// Computes the absolute value of `self`.
1151 /// # Overflow behavior
1153 /// The absolute value of `i32::min_value()` cannot be represented as an
1154 /// `i32`, and attempting to calculate it will cause an overflow. This
1155 /// means that code in debug mode will trigger a panic on this case and
1156 /// optimized code will return `i32::min_value()` without a panic.
1163 /// assert_eq!(10i8.abs(), 10);
1164 /// assert_eq!((-10i8).abs(), 10);
1166 #[stable(feature = "rust1", since = "1.0.0")]
1168 #[rustc_inherit_overflow_checks]
1169 pub fn abs(self) -> Self {
1170 if self.is_negative() {
1171 // Note that the #[inline] above means that the overflow
1172 // semantics of this negation depend on the crate we're being
1180 /// Returns a number representing sign of `self`.
1182 /// - `0` if the number is zero
1183 /// - `1` if the number is positive
1184 /// - `-1` if the number is negative
1191 /// assert_eq!(10i8.signum(), 1);
1192 /// assert_eq!(0i8.signum(), 0);
1193 /// assert_eq!((-10i8).signum(), -1);
1195 #[stable(feature = "rust1", since = "1.0.0")]
1197 pub fn signum(self) -> Self {
1205 /// Returns `true` if `self` is positive and `false` if the number
1206 /// is zero or negative.
1213 /// assert!(10i8.is_positive());
1214 /// assert!(!(-10i8).is_positive());
1216 #[stable(feature = "rust1", since = "1.0.0")]
1218 pub fn is_positive(self) -> bool { self > 0 }
1220 /// Returns `true` if `self` is negative and `false` if the number
1221 /// is zero or positive.
1228 /// assert!((-10i8).is_negative());
1229 /// assert!(!10i8.is_negative());
1231 #[stable(feature = "rust1", since = "1.0.0")]
1233 pub fn is_negative(self) -> bool { self < 0 }
1239 int_impl! { i8, i8, u8, 8,
1240 intrinsics::add_with_overflow,
1241 intrinsics::sub_with_overflow,
1242 intrinsics::mul_with_overflow }
1247 int_impl! { i16, i16, u16, 16,
1248 intrinsics::add_with_overflow,
1249 intrinsics::sub_with_overflow,
1250 intrinsics::mul_with_overflow }
1255 int_impl! { i32, i32, u32, 32,
1256 intrinsics::add_with_overflow,
1257 intrinsics::sub_with_overflow,
1258 intrinsics::mul_with_overflow }
1263 int_impl! { i64, i64, u64, 64,
1264 intrinsics::add_with_overflow,
1265 intrinsics::sub_with_overflow,
1266 intrinsics::mul_with_overflow }
1271 int_impl! { i128, i128, u128, 128,
1272 intrinsics::add_with_overflow,
1273 intrinsics::sub_with_overflow,
1274 intrinsics::mul_with_overflow }
1277 #[cfg(target_pointer_width = "16")]
1280 int_impl! { isize, i16, u16, 16,
1281 intrinsics::add_with_overflow,
1282 intrinsics::sub_with_overflow,
1283 intrinsics::mul_with_overflow }
1286 #[cfg(target_pointer_width = "32")]
1289 int_impl! { isize, i32, u32, 32,
1290 intrinsics::add_with_overflow,
1291 intrinsics::sub_with_overflow,
1292 intrinsics::mul_with_overflow }
1295 #[cfg(target_pointer_width = "64")]
1298 int_impl! { isize, i64, u64, 64,
1299 intrinsics::add_with_overflow,
1300 intrinsics::sub_with_overflow,
1301 intrinsics::mul_with_overflow }
1304 // `Int` + `UnsignedInt` implemented for unsigned integers
1305 macro_rules! uint_impl {
1306 ($SelfT:ty, $ActualT:ty, $BITS:expr,
1311 $add_with_overflow:path,
1312 $sub_with_overflow:path,
1313 $mul_with_overflow:path) => {
1314 /// Returns the smallest value that can be represented by this integer type.
1319 /// assert_eq!(u8::min_value(), 0);
1321 #[stable(feature = "rust1", since = "1.0.0")]
1323 pub const fn min_value() -> Self { 0 }
1325 /// Returns the largest value that can be represented by this integer type.
1330 /// assert_eq!(u8::max_value(), 255);
1332 #[stable(feature = "rust1", since = "1.0.0")]
1334 pub const fn max_value() -> Self { !0 }
1336 /// Converts a string slice in a given base to an integer.
1338 /// Leading and trailing whitespace represent an error.
1345 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1349 from_str_radix(src, radix)
1352 /// Returns the number of ones in the binary representation of `self`.
1359 /// let n = 0b01001100u8;
1361 /// assert_eq!(n.count_ones(), 3);
1363 #[stable(feature = "rust1", since = "1.0.0")]
1365 pub fn count_ones(self) -> u32 {
1366 unsafe { $ctpop(self as $ActualT) as u32 }
1369 /// Returns the number of zeros in the binary representation of `self`.
1376 /// let n = 0b01001100u8;
1378 /// assert_eq!(n.count_zeros(), 5);
1380 #[stable(feature = "rust1", since = "1.0.0")]
1382 pub fn count_zeros(self) -> u32 {
1383 (!self).count_ones()
1386 /// Returns the number of leading zeros in the binary representation
1394 /// let n = 0b0101000u16;
1396 /// assert_eq!(n.leading_zeros(), 10);
1398 #[stable(feature = "rust1", since = "1.0.0")]
1400 pub fn leading_zeros(self) -> u32 {
1401 unsafe { $ctlz(self as $ActualT) as u32 }
1404 /// Returns the number of trailing zeros in the binary representation
1412 /// let n = 0b0101000u16;
1414 /// assert_eq!(n.trailing_zeros(), 3);
1416 #[stable(feature = "rust1", since = "1.0.0")]
1418 pub fn trailing_zeros(self) -> u32 {
1419 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1420 // emits two conditional moves on x86_64. By promoting the value to
1421 // u16 and setting bit 8, we get better code without any conditional
1423 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1424 // pending, remove this workaround once LLVM generates better code
1428 intrinsics::cttz(self as u16 | 0x100) as u32
1430 intrinsics::cttz(self) as u32
1435 /// Shifts the bits to the left by a specified amount, `n`,
1436 /// wrapping the truncated bits to the end of the resulting integer.
1438 /// Please note this isn't the same operation as `<<`!
1445 /// let n = 0x0123456789ABCDEFu64;
1446 /// let m = 0x3456789ABCDEF012u64;
1448 /// assert_eq!(n.rotate_left(12), m);
1450 #[stable(feature = "rust1", since = "1.0.0")]
1452 pub fn rotate_left(self, n: u32) -> Self {
1453 // Protect against undefined behaviour for over-long bit shifts
1455 (self << n) | (self >> (($BITS - n) % $BITS))
1458 /// Shifts the bits to the right by a specified amount, `n`,
1459 /// wrapping the truncated bits to the beginning of the resulting
1462 /// Please note this isn't the same operation as `>>`!
1469 /// let n = 0x0123456789ABCDEFu64;
1470 /// let m = 0xDEF0123456789ABCu64;
1472 /// assert_eq!(n.rotate_right(12), m);
1474 #[stable(feature = "rust1", since = "1.0.0")]
1476 pub fn rotate_right(self, n: u32) -> Self {
1477 // Protect against undefined behaviour for over-long bit shifts
1479 (self >> n) | (self << (($BITS - n) % $BITS))
1482 /// Reverses the byte order of the integer.
1489 /// let n = 0x0123456789ABCDEFu64;
1490 /// let m = 0xEFCDAB8967452301u64;
1492 /// assert_eq!(n.swap_bytes(), m);
1494 #[stable(feature = "rust1", since = "1.0.0")]
1496 pub fn swap_bytes(self) -> Self {
1497 unsafe { $bswap(self as $ActualT) as Self }
1500 /// Converts an integer from big endian to the target's endianness.
1502 /// On big endian this is a no-op. On little endian the bytes are
1510 /// let n = 0x0123456789ABCDEFu64;
1512 /// if cfg!(target_endian = "big") {
1513 /// assert_eq!(u64::from_be(n), n)
1515 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1518 #[stable(feature = "rust1", since = "1.0.0")]
1520 pub fn from_be(x: Self) -> Self {
1521 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1524 /// Converts an integer from little endian to the target's endianness.
1526 /// On little endian this is a no-op. On big endian the bytes are
1534 /// let n = 0x0123456789ABCDEFu64;
1536 /// if cfg!(target_endian = "little") {
1537 /// assert_eq!(u64::from_le(n), n)
1539 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1542 #[stable(feature = "rust1", since = "1.0.0")]
1544 pub fn from_le(x: Self) -> Self {
1545 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1548 /// Converts `self` to big endian from the target's endianness.
1550 /// On big endian this is a no-op. On little endian the bytes are
1558 /// let n = 0x0123456789ABCDEFu64;
1560 /// if cfg!(target_endian = "big") {
1561 /// assert_eq!(n.to_be(), n)
1563 /// assert_eq!(n.to_be(), n.swap_bytes())
1566 #[stable(feature = "rust1", since = "1.0.0")]
1568 pub fn to_be(self) -> Self { // or not to be?
1569 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1572 /// Converts `self` to little endian from the target's endianness.
1574 /// On little endian this is a no-op. On big endian the bytes are
1582 /// let n = 0x0123456789ABCDEFu64;
1584 /// if cfg!(target_endian = "little") {
1585 /// assert_eq!(n.to_le(), n)
1587 /// assert_eq!(n.to_le(), n.swap_bytes())
1590 #[stable(feature = "rust1", since = "1.0.0")]
1592 pub fn to_le(self) -> Self {
1593 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1596 /// Checked integer addition. Computes `self + other`, returning `None`
1597 /// if overflow occurred.
1604 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1605 /// assert_eq!(6u16.checked_add(65530), None);
1607 #[stable(feature = "rust1", since = "1.0.0")]
1609 pub fn checked_add(self, other: Self) -> Option<Self> {
1610 let (a, b) = self.overflowing_add(other);
1611 if b {None} else {Some(a)}
1614 /// Checked integer subtraction. Computes `self - other`, returning
1615 /// `None` if underflow occurred.
1622 /// assert_eq!(1u8.checked_sub(1), Some(0));
1623 /// assert_eq!(0u8.checked_sub(1), None);
1625 #[stable(feature = "rust1", since = "1.0.0")]
1627 pub fn checked_sub(self, other: Self) -> Option<Self> {
1628 let (a, b) = self.overflowing_sub(other);
1629 if b {None} else {Some(a)}
1632 /// Checked integer multiplication. Computes `self * other`, returning
1633 /// `None` if underflow or overflow occurred.
1640 /// assert_eq!(5u8.checked_mul(51), Some(255));
1641 /// assert_eq!(5u8.checked_mul(52), None);
1643 #[stable(feature = "rust1", since = "1.0.0")]
1645 pub fn checked_mul(self, other: Self) -> Option<Self> {
1646 let (a, b) = self.overflowing_mul(other);
1647 if b {None} else {Some(a)}
1650 /// Checked integer division. Computes `self / other`, returning `None`
1651 /// if `other == 0` or the operation results in underflow or overflow.
1658 /// assert_eq!(128u8.checked_div(2), Some(64));
1659 /// assert_eq!(1u8.checked_div(0), None);
1661 #[stable(feature = "rust1", since = "1.0.0")]
1663 pub fn checked_div(self, other: Self) -> Option<Self> {
1666 other => Some(unsafe { intrinsics::unchecked_div(self, other) }),
1670 /// Checked integer remainder. Computes `self % other`, returning `None`
1671 /// if `other == 0` or the operation results in underflow or overflow.
1678 /// assert_eq!(5u32.checked_rem(2), Some(1));
1679 /// assert_eq!(5u32.checked_rem(0), None);
1681 #[stable(feature = "wrapping", since = "1.7.0")]
1683 pub fn checked_rem(self, other: Self) -> Option<Self> {
1687 Some(unsafe { intrinsics::unchecked_rem(self, other) })
1691 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1694 /// Note that negating any positive integer will overflow.
1701 /// assert_eq!(0u32.checked_neg(), Some(0));
1702 /// assert_eq!(1u32.checked_neg(), None);
1704 #[stable(feature = "wrapping", since = "1.7.0")]
1706 pub fn checked_neg(self) -> Option<Self> {
1707 let (a, b) = self.overflowing_neg();
1708 if b {None} else {Some(a)}
1711 /// Checked shift left. Computes `self << rhs`, returning `None`
1712 /// if `rhs` is larger than or equal to the number of bits in `self`.
1719 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1720 /// assert_eq!(0x10u32.checked_shl(33), None);
1722 #[stable(feature = "wrapping", since = "1.7.0")]
1724 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1725 let (a, b) = self.overflowing_shl(rhs);
1726 if b {None} else {Some(a)}
1729 /// Checked shift right. Computes `self >> rhs`, returning `None`
1730 /// if `rhs` is larger than or equal to the number of bits in `self`.
1737 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1738 /// assert_eq!(0x10u32.checked_shr(33), None);
1740 #[stable(feature = "wrapping", since = "1.7.0")]
1742 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1743 let (a, b) = self.overflowing_shr(rhs);
1744 if b {None} else {Some(a)}
1747 /// Saturating integer addition. Computes `self + other`, saturating at
1748 /// the numeric bounds instead of overflowing.
1755 /// assert_eq!(100u8.saturating_add(1), 101);
1756 /// assert_eq!(200u8.saturating_add(127), 255);
1758 #[stable(feature = "rust1", since = "1.0.0")]
1760 pub fn saturating_add(self, other: Self) -> Self {
1761 match self.checked_add(other) {
1763 None => Self::max_value(),
1767 /// Saturating integer subtraction. Computes `self - other`, saturating
1768 /// at the numeric bounds instead of overflowing.
1775 /// assert_eq!(100u8.saturating_sub(27), 73);
1776 /// assert_eq!(13u8.saturating_sub(127), 0);
1778 #[stable(feature = "rust1", since = "1.0.0")]
1780 pub fn saturating_sub(self, other: Self) -> Self {
1781 match self.checked_sub(other) {
1783 None => Self::min_value(),
1787 /// Saturating integer multiplication. Computes `self * other`,
1788 /// saturating at the numeric bounds instead of overflowing.
1797 /// assert_eq!(100u32.saturating_mul(127), 12700);
1798 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1800 #[stable(feature = "wrapping", since = "1.7.0")]
1802 pub fn saturating_mul(self, other: Self) -> Self {
1803 self.checked_mul(other).unwrap_or(Self::max_value())
1806 /// Wrapping (modular) addition. Computes `self + other`,
1807 /// wrapping around at the boundary of the type.
1814 /// assert_eq!(200u8.wrapping_add(55), 255);
1815 /// assert_eq!(200u8.wrapping_add(155), 99);
1817 #[stable(feature = "rust1", since = "1.0.0")]
1819 pub fn wrapping_add(self, rhs: Self) -> Self {
1821 intrinsics::overflowing_add(self, rhs)
1825 /// Wrapping (modular) subtraction. Computes `self - other`,
1826 /// wrapping around at the boundary of the type.
1833 /// assert_eq!(100u8.wrapping_sub(100), 0);
1834 /// assert_eq!(100u8.wrapping_sub(155), 201);
1836 #[stable(feature = "rust1", since = "1.0.0")]
1838 pub fn wrapping_sub(self, rhs: Self) -> Self {
1840 intrinsics::overflowing_sub(self, rhs)
1844 /// Wrapping (modular) multiplication. Computes `self *
1845 /// other`, wrapping around at the boundary of the type.
1852 /// assert_eq!(10u8.wrapping_mul(12), 120);
1853 /// assert_eq!(25u8.wrapping_mul(12), 44);
1855 #[stable(feature = "rust1", since = "1.0.0")]
1857 pub fn wrapping_mul(self, rhs: Self) -> Self {
1859 intrinsics::overflowing_mul(self, rhs)
1863 /// Wrapping (modular) division. Computes `self / other`.
1864 /// Wrapped division on unsigned types is just normal division.
1865 /// There's no way wrapping could ever happen.
1866 /// This function exists, so that all operations
1867 /// are accounted for in the wrapping operations.
1874 /// assert_eq!(100u8.wrapping_div(10), 10);
1876 #[stable(feature = "num_wrapping", since = "1.2.0")]
1878 pub fn wrapping_div(self, rhs: Self) -> Self {
1882 /// Wrapping (modular) remainder. Computes `self % other`.
1883 /// Wrapped remainder calculation on unsigned types is
1884 /// just the regular remainder calculation.
1885 /// There's no way wrapping could ever happen.
1886 /// This function exists, so that all operations
1887 /// are accounted for in the wrapping operations.
1894 /// assert_eq!(100u8.wrapping_rem(10), 0);
1896 #[stable(feature = "num_wrapping", since = "1.2.0")]
1898 pub fn wrapping_rem(self, rhs: Self) -> Self {
1902 /// Wrapping (modular) negation. Computes `-self`,
1903 /// wrapping around at the boundary of the type.
1905 /// Since unsigned types do not have negative equivalents
1906 /// all applications of this function will wrap (except for `-0`).
1907 /// For values smaller than the corresponding signed type's maximum
1908 /// the result is the same as casting the corresponding signed value.
1909 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1910 /// `MAX` is the corresponding signed type's maximum.
1917 /// assert_eq!(100u8.wrapping_neg(), 156);
1918 /// assert_eq!(0u8.wrapping_neg(), 0);
1919 /// assert_eq!(180u8.wrapping_neg(), 76);
1920 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1922 #[stable(feature = "num_wrapping", since = "1.2.0")]
1924 pub fn wrapping_neg(self) -> Self {
1925 self.overflowing_neg().0
1928 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1929 /// where `mask` removes any high-order bits of `rhs` that
1930 /// would cause the shift to exceed the bitwidth of the type.
1932 /// Note that this is *not* the same as a rotate-left; the
1933 /// RHS of a wrapping shift-left is restricted to the range
1934 /// of the type, rather than the bits shifted out of the LHS
1935 /// being returned to the other end. The primitive integer
1936 /// types all implement a `rotate_left` function, which may
1937 /// be what you want instead.
1944 /// assert_eq!(1u8.wrapping_shl(7), 128);
1945 /// assert_eq!(1u8.wrapping_shl(8), 1);
1947 #[stable(feature = "num_wrapping", since = "1.2.0")]
1950 pub fn wrapping_shl(self, rhs: u32) -> Self {
1952 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1957 #[stable(feature = "num_wrapping", since = "1.2.0")]
1960 pub fn wrapping_shl(self, rhs: u32) -> Self {
1961 self.overflowing_shl(rhs).0
1964 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1965 /// where `mask` removes any high-order bits of `rhs` that
1966 /// would cause the shift to exceed the bitwidth of the type.
1968 /// Note that this is *not* the same as a rotate-right; the
1969 /// RHS of a wrapping shift-right is restricted to the range
1970 /// of the type, rather than the bits shifted out of the LHS
1971 /// being returned to the other end. The primitive integer
1972 /// types all implement a `rotate_right` function, which may
1973 /// be what you want instead.
1980 /// assert_eq!(128u8.wrapping_shr(7), 1);
1981 /// assert_eq!(128u8.wrapping_shr(8), 128);
1983 #[stable(feature = "num_wrapping", since = "1.2.0")]
1986 pub fn wrapping_shr(self, rhs: u32) -> Self {
1988 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1993 #[stable(feature = "num_wrapping", since = "1.2.0")]
1996 pub fn wrapping_shr(self, rhs: u32) -> Self {
1997 self.overflowing_shr(rhs).0
2000 /// Calculates `self` + `rhs`
2002 /// Returns a tuple of the addition along with a boolean indicating
2003 /// whether an arithmetic overflow would occur. If an overflow would
2004 /// have occurred then the wrapped value is returned.
2013 /// assert_eq!(5u32.overflowing_add(2), (7, false));
2014 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
2017 #[stable(feature = "wrapping", since = "1.7.0")]
2018 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2020 let (a, b) = $add_with_overflow(self as $ActualT,
2026 /// Calculates `self` - `rhs`
2028 /// Returns a tuple of the subtraction along with a boolean indicating
2029 /// whether an arithmetic overflow would occur. If an overflow would
2030 /// have occurred then the wrapped value is returned.
2039 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
2040 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
2043 #[stable(feature = "wrapping", since = "1.7.0")]
2044 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2046 let (a, b) = $sub_with_overflow(self as $ActualT,
2052 /// Calculates the multiplication of `self` and `rhs`.
2054 /// Returns a tuple of the multiplication along with a boolean
2055 /// indicating whether an arithmetic overflow would occur. If an
2056 /// overflow would have occurred then the wrapped value is returned.
2063 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2064 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2067 #[stable(feature = "wrapping", since = "1.7.0")]
2068 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2070 let (a, b) = $mul_with_overflow(self as $ActualT,
2076 /// Calculates the divisor when `self` is divided by `rhs`.
2078 /// Returns a tuple of the divisor along with a boolean indicating
2079 /// whether an arithmetic overflow would occur. Note that for unsigned
2080 /// integers overflow never occurs, so the second value is always
2085 /// This function will panic if `rhs` is 0.
2092 /// assert_eq!(5u32.overflowing_div(2), (2, false));
2095 #[stable(feature = "wrapping", since = "1.7.0")]
2096 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2100 /// Calculates the remainder when `self` is divided by `rhs`.
2102 /// Returns a tuple of the remainder after dividing along with a boolean
2103 /// indicating whether an arithmetic overflow would occur. Note that for
2104 /// unsigned integers overflow never occurs, so the second value is
2109 /// This function will panic if `rhs` is 0.
2116 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
2119 #[stable(feature = "wrapping", since = "1.7.0")]
2120 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2124 /// Negates self in an overflowing fashion.
2126 /// Returns `!self + 1` using wrapping operations to return the value
2127 /// that represents the negation of this unsigned value. Note that for
2128 /// positive unsigned values overflow always occurs, but negating 0 does
2136 /// assert_eq!(0u32.overflowing_neg(), (0, false));
2137 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
2140 #[stable(feature = "wrapping", since = "1.7.0")]
2141 pub fn overflowing_neg(self) -> (Self, bool) {
2142 ((!self).wrapping_add(1), self != 0)
2145 /// Shifts self left by `rhs` bits.
2147 /// Returns a tuple of the shifted version of self along with a boolean
2148 /// indicating whether the shift value was larger than or equal to the
2149 /// number of bits. If the shift value is too large, then value is
2150 /// masked (N-1) where N is the number of bits, and this value is then
2151 /// used to perform the shift.
2158 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
2159 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
2162 #[stable(feature = "wrapping", since = "1.7.0")]
2164 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2165 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
2170 #[stable(feature = "wrapping", since = "1.7.0")]
2172 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2173 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
2176 /// Shifts self right by `rhs` bits.
2178 /// Returns a tuple of the shifted version of self along with a boolean
2179 /// indicating whether the shift value was larger than or equal to the
2180 /// number of bits. If the shift value is too large, then value is
2181 /// masked (N-1) where N is the number of bits, and this value is then
2182 /// used to perform the shift.
2189 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
2190 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2193 #[stable(feature = "wrapping", since = "1.7.0")]
2195 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2196 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
2202 #[stable(feature = "wrapping", since = "1.7.0")]
2204 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2205 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
2208 /// Raises self to the power of `exp`, using exponentiation by squaring.
2215 /// assert_eq!(2u32.pow(4), 16);
2217 #[stable(feature = "rust1", since = "1.0.0")]
2219 #[rustc_inherit_overflow_checks]
2220 pub fn pow(self, mut exp: u32) -> Self {
2221 let mut base = self;
2232 // Deal with the final bit of the exponent separately, since
2233 // squaring the base afterwards is not necessary and may cause a
2234 // needless overflow.
2242 /// Returns `true` if and only if `self == 2^k` for some `k`.
2249 /// assert!(16u8.is_power_of_two());
2250 /// assert!(!10u8.is_power_of_two());
2252 #[stable(feature = "rust1", since = "1.0.0")]
2254 pub fn is_power_of_two(self) -> bool {
2255 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2258 /// Returns the smallest power of two greater than or equal to `self`.
2259 /// Unspecified behavior on overflow.
2266 /// assert_eq!(2u8.next_power_of_two(), 2);
2267 /// assert_eq!(3u8.next_power_of_two(), 4);
2269 #[stable(feature = "rust1", since = "1.0.0")]
2271 pub fn next_power_of_two(self) -> Self {
2272 let bits = size_of::<Self>() * 8;
2274 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
2277 /// Returns the smallest power of two greater than or equal to `n`. If
2278 /// the next power of two is greater than the type's maximum value,
2279 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2286 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2287 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2288 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2290 #[stable(feature = "rust1", since = "1.0.0")]
2291 pub fn checked_next_power_of_two(self) -> Option<Self> {
2292 let npot = self.next_power_of_two();
2304 uint_impl! { u8, u8, 8,
2309 intrinsics::add_with_overflow,
2310 intrinsics::sub_with_overflow,
2311 intrinsics::mul_with_overflow }
2316 uint_impl! { u16, u16, 16,
2321 intrinsics::add_with_overflow,
2322 intrinsics::sub_with_overflow,
2323 intrinsics::mul_with_overflow }
2328 uint_impl! { u32, u32, 32,
2333 intrinsics::add_with_overflow,
2334 intrinsics::sub_with_overflow,
2335 intrinsics::mul_with_overflow }
2340 uint_impl! { u64, u64, 64,
2345 intrinsics::add_with_overflow,
2346 intrinsics::sub_with_overflow,
2347 intrinsics::mul_with_overflow }
2352 uint_impl! { u128, u128, 128,
2357 intrinsics::add_with_overflow,
2358 intrinsics::sub_with_overflow,
2359 intrinsics::mul_with_overflow }
2362 #[cfg(target_pointer_width = "16")]
2365 uint_impl! { usize, u16, 16,
2370 intrinsics::add_with_overflow,
2371 intrinsics::sub_with_overflow,
2372 intrinsics::mul_with_overflow }
2374 #[cfg(target_pointer_width = "32")]
2377 uint_impl! { usize, u32, 32,
2382 intrinsics::add_with_overflow,
2383 intrinsics::sub_with_overflow,
2384 intrinsics::mul_with_overflow }
2387 #[cfg(target_pointer_width = "64")]
2390 uint_impl! { usize, u64, 64,
2395 intrinsics::add_with_overflow,
2396 intrinsics::sub_with_overflow,
2397 intrinsics::mul_with_overflow }
2400 /// A classification of floating point numbers.
2402 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
2403 /// their documentation for more.
2405 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
2406 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
2411 /// use std::num::FpCategory;
2414 /// let num = 12.4_f32;
2415 /// let inf = f32::INFINITY;
2416 /// let zero = 0f32;
2417 /// let sub: f32 = 1.1754942e-38;
2418 /// let nan = f32::NAN;
2420 /// assert_eq!(num.classify(), FpCategory::Normal);
2421 /// assert_eq!(inf.classify(), FpCategory::Infinite);
2422 /// assert_eq!(zero.classify(), FpCategory::Zero);
2423 /// assert_eq!(nan.classify(), FpCategory::Nan);
2424 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
2426 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2427 #[stable(feature = "rust1", since = "1.0.0")]
2428 pub enum FpCategory {
2429 /// "Not a Number", often obtained by dividing by zero.
2430 #[stable(feature = "rust1", since = "1.0.0")]
2433 /// Positive or negative infinity.
2434 #[stable(feature = "rust1", since = "1.0.0")]
2437 /// Positive or negative zero.
2438 #[stable(feature = "rust1", since = "1.0.0")]
2441 /// De-normalized floating point representation (less precise than `Normal`).
2442 #[stable(feature = "rust1", since = "1.0.0")]
2445 /// A regular floating point number.
2446 #[stable(feature = "rust1", since = "1.0.0")]
2450 /// A built-in floating point number.
2452 #[unstable(feature = "core_float",
2453 reason = "stable interface is via `impl f{32,64}` in later crates",
2455 pub trait Float: Sized {
2456 /// Returns `true` if this value is NaN and false otherwise.
2457 #[stable(feature = "core", since = "1.6.0")]
2458 fn is_nan(self) -> bool;
2459 /// Returns `true` if this value is positive infinity or negative infinity and
2460 /// false otherwise.
2461 #[stable(feature = "core", since = "1.6.0")]
2462 fn is_infinite(self) -> bool;
2463 /// Returns `true` if this number is neither infinite nor NaN.
2464 #[stable(feature = "core", since = "1.6.0")]
2465 fn is_finite(self) -> bool;
2466 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
2467 #[stable(feature = "core", since = "1.6.0")]
2468 fn is_normal(self) -> bool;
2469 /// Returns the category that this number falls into.
2470 #[stable(feature = "core", since = "1.6.0")]
2471 fn classify(self) -> FpCategory;
2473 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2474 /// number is `Float::nan()`.
2475 #[stable(feature = "core", since = "1.6.0")]
2476 fn abs(self) -> Self;
2477 /// Returns a number that represents the sign of `self`.
2479 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2480 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2481 /// - `Float::nan()` if the number is `Float::nan()`
2482 #[stable(feature = "core", since = "1.6.0")]
2483 fn signum(self) -> Self;
2485 /// Returns `true` if `self` is positive, including `+0.0` and
2486 /// `Float::infinity()`.
2487 #[stable(feature = "core", since = "1.6.0")]
2488 fn is_sign_positive(self) -> bool;
2489 /// Returns `true` if `self` is negative, including `-0.0` and
2490 /// `Float::neg_infinity()`.
2491 #[stable(feature = "core", since = "1.6.0")]
2492 fn is_sign_negative(self) -> bool;
2494 /// Take the reciprocal (inverse) of a number, `1/x`.
2495 #[stable(feature = "core", since = "1.6.0")]
2496 fn recip(self) -> Self;
2498 /// Raise a number to an integer power.
2500 /// Using this function is generally faster than using `powf`
2501 #[stable(feature = "core", since = "1.6.0")]
2502 fn powi(self, n: i32) -> Self;
2504 /// Convert radians to degrees.
2505 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2506 fn to_degrees(self) -> Self;
2507 /// Convert degrees to radians.
2508 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2509 fn to_radians(self) -> Self;
2512 macro_rules! from_str_radix_int_impl {
2514 #[stable(feature = "rust1", since = "1.0.0")]
2515 impl FromStr for $t {
2516 type Err = ParseIntError;
2517 fn from_str(src: &str) -> Result<Self, ParseIntError> {
2518 from_str_radix(src, 10)
2523 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
2525 /// The error type returned when a checked integral type conversion fails.
2526 #[unstable(feature = "try_from", issue = "33417")]
2527 #[derive(Debug, Copy, Clone)]
2528 pub struct TryFromIntError(());
2530 impl TryFromIntError {
2531 #[unstable(feature = "int_error_internals",
2532 reason = "available through Error trait and this method should \
2533 not be exposed publicly",
2536 pub fn __description(&self) -> &str {
2537 "out of range integral type conversion attempted"
2541 #[unstable(feature = "try_from", issue = "33417")]
2542 impl fmt::Display for TryFromIntError {
2543 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2544 self.__description().fmt(fmt)
2548 macro_rules! same_sign_try_from_int_impl {
2549 ($storage:ty, $target:ty, $($source:ty),*) => {$(
2550 #[unstable(feature = "try_from", issue = "33417")]
2551 impl TryFrom<$source> for $target {
2552 type Error = TryFromIntError;
2554 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2555 let min = <$target as FromStrRadixHelper>::min_value() as $storage;
2556 let max = <$target as FromStrRadixHelper>::max_value() as $storage;
2557 if u as $storage < min || u as $storage > max {
2558 Err(TryFromIntError(()))
2567 same_sign_try_from_int_impl!(u128, u8, u8, u16, u32, u64, u128, usize);
2568 same_sign_try_from_int_impl!(i128, i8, i8, i16, i32, i64, i128, isize);
2569 same_sign_try_from_int_impl!(u128, u16, u8, u16, u32, u64, u128, usize);
2570 same_sign_try_from_int_impl!(i128, i16, i8, i16, i32, i64, i128, isize);
2571 same_sign_try_from_int_impl!(u128, u32, u8, u16, u32, u64, u128, usize);
2572 same_sign_try_from_int_impl!(i128, i32, i8, i16, i32, i64, i128, isize);
2573 same_sign_try_from_int_impl!(u128, u64, u8, u16, u32, u64, u128, usize);
2574 same_sign_try_from_int_impl!(i128, i64, i8, i16, i32, i64, i128, isize);
2575 same_sign_try_from_int_impl!(u128, u128, u8, u16, u32, u64, u128, usize);
2576 same_sign_try_from_int_impl!(i128, i128, i8, i16, i32, i64, i128, isize);
2577 same_sign_try_from_int_impl!(u128, usize, u8, u16, u32, u64, u128, usize);
2578 same_sign_try_from_int_impl!(i128, isize, i8, i16, i32, i64, i128, isize);
2580 macro_rules! cross_sign_from_int_impl {
2581 ($unsigned:ty, $($signed:ty),*) => {$(
2582 #[unstable(feature = "try_from", issue = "33417")]
2583 impl TryFrom<$unsigned> for $signed {
2584 type Error = TryFromIntError;
2586 fn try_from(u: $unsigned) -> Result<$signed, TryFromIntError> {
2587 let max = <$signed as FromStrRadixHelper>::max_value() as u128;
2588 if u as u128 > max {
2589 Err(TryFromIntError(()))
2596 #[unstable(feature = "try_from", issue = "33417")]
2597 impl TryFrom<$signed> for $unsigned {
2598 type Error = TryFromIntError;
2600 fn try_from(u: $signed) -> Result<$unsigned, TryFromIntError> {
2601 let max = <$unsigned as FromStrRadixHelper>::max_value() as u128;
2602 if u < 0 || u as u128 > max {
2603 Err(TryFromIntError(()))
2612 cross_sign_from_int_impl!(u8, i8, i16, i32, i64, i128, isize);
2613 cross_sign_from_int_impl!(u16, i8, i16, i32, i64, i128, isize);
2614 cross_sign_from_int_impl!(u32, i8, i16, i32, i64, i128, isize);
2615 cross_sign_from_int_impl!(u64, i8, i16, i32, i64, i128, isize);
2616 cross_sign_from_int_impl!(u128, i8, i16, i32, i64, i128, isize);
2617 cross_sign_from_int_impl!(usize, i8, i16, i32, i64, i128, isize);
2620 trait FromStrRadixHelper: PartialOrd + Copy {
2621 fn min_value() -> Self;
2622 fn max_value() -> Self;
2623 fn from_u32(u: u32) -> Self;
2624 fn checked_mul(&self, other: u32) -> Option<Self>;
2625 fn checked_sub(&self, other: u32) -> Option<Self>;
2626 fn checked_add(&self, other: u32) -> Option<Self>;
2630 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
2631 fn min_value() -> Self { Self::min_value() }
2632 fn max_value() -> Self { Self::max_value() }
2633 fn from_u32(u: u32) -> Self { u as Self }
2634 fn checked_mul(&self, other: u32) -> Option<Self> {
2635 Self::checked_mul(*self, other as Self)
2637 fn checked_sub(&self, other: u32) -> Option<Self> {
2638 Self::checked_sub(*self, other as Self)
2640 fn checked_add(&self, other: u32) -> Option<Self> {
2641 Self::checked_add(*self, other as Self)
2645 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
2647 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
2648 use self::IntErrorKind::*;
2649 use self::ParseIntError as PIE;
2651 assert!(radix >= 2 && radix <= 36,
2652 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2656 return Err(PIE { kind: Empty });
2659 let is_signed_ty = T::from_u32(0) > T::min_value();
2661 // all valid digits are ascii, so we will just iterate over the utf8 bytes
2662 // and cast them to chars. .to_digit() will safely return None for anything
2663 // other than a valid ascii digit for the given radix, including the first-byte
2664 // of multi-byte sequences
2665 let src = src.as_bytes();
2667 let (is_positive, digits) = match src[0] {
2668 b'+' => (true, &src[1..]),
2669 b'-' if is_signed_ty => (false, &src[1..]),
2673 if digits.is_empty() {
2674 return Err(PIE { kind: Empty });
2677 let mut result = T::from_u32(0);
2679 // The number is positive
2681 let x = match (c as char).to_digit(radix) {
2683 None => return Err(PIE { kind: InvalidDigit }),
2685 result = match result.checked_mul(radix) {
2686 Some(result) => result,
2687 None => return Err(PIE { kind: Overflow }),
2689 result = match result.checked_add(x) {
2690 Some(result) => result,
2691 None => return Err(PIE { kind: Overflow }),
2695 // The number is negative
2697 let x = match (c as char).to_digit(radix) {
2699 None => return Err(PIE { kind: InvalidDigit }),
2701 result = match result.checked_mul(radix) {
2702 Some(result) => result,
2703 None => return Err(PIE { kind: Underflow }),
2705 result = match result.checked_sub(x) {
2706 Some(result) => result,
2707 None => return Err(PIE { kind: Underflow }),
2714 /// An error which can be returned when parsing an integer.
2716 /// This error is used as the error type for the `from_str_radix()` functions
2717 /// on the primitive integer types, such as [`i8::from_str_radix`].
2719 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
2720 #[derive(Debug, Clone, PartialEq, Eq)]
2721 #[stable(feature = "rust1", since = "1.0.0")]
2722 pub struct ParseIntError {
2726 #[derive(Debug, Clone, PartialEq, Eq)]
2734 impl ParseIntError {
2735 #[unstable(feature = "int_error_internals",
2736 reason = "available through Error trait and this method should \
2737 not be exposed publicly",
2740 pub fn __description(&self) -> &str {
2742 IntErrorKind::Empty => "cannot parse integer from empty string",
2743 IntErrorKind::InvalidDigit => "invalid digit found in string",
2744 IntErrorKind::Overflow => "number too large to fit in target type",
2745 IntErrorKind::Underflow => "number too small to fit in target type",
2750 #[stable(feature = "rust1", since = "1.0.0")]
2751 impl fmt::Display for ParseIntError {
2752 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2753 self.__description().fmt(f)
2757 #[stable(feature = "rust1", since = "1.0.0")]
2758 pub use num::dec2flt::ParseFloatError;
2760 // Conversion traits for primitive integer and float types
2761 // Conversions T -> T are covered by a blanket impl and therefore excluded
2762 // Some conversions from and to usize/isize are not implemented due to portability concerns
2763 macro_rules! impl_from {
2764 ($Small: ty, $Large: ty) => {
2765 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
2766 impl From<$Small> for $Large {
2768 fn from(small: $Small) -> $Large {
2775 // Unsigned -> Unsigned
2776 impl_from! { u8, u16 }
2777 impl_from! { u8, u32 }
2778 impl_from! { u8, u64 }
2779 impl_from! { u8, u128 }
2780 impl_from! { u8, usize }
2781 impl_from! { u16, u32 }
2782 impl_from! { u16, u64 }
2783 impl_from! { u16, u128 }
2784 impl_from! { u32, u64 }
2785 impl_from! { u32, u128 }
2786 impl_from! { u64, u128 }
2789 impl_from! { i8, i16 }
2790 impl_from! { i8, i32 }
2791 impl_from! { i8, i64 }
2792 impl_from! { i8, i128 }
2793 impl_from! { i8, isize }
2794 impl_from! { i16, i32 }
2795 impl_from! { i16, i64 }
2796 impl_from! { i16, i128 }
2797 impl_from! { i32, i64 }
2798 impl_from! { i32, i128 }
2799 impl_from! { i64, i128 }
2801 // Unsigned -> Signed
2802 impl_from! { u8, i16 }
2803 impl_from! { u8, i32 }
2804 impl_from! { u8, i64 }
2805 impl_from! { u8, i128 }
2806 impl_from! { u16, i32 }
2807 impl_from! { u16, i64 }
2808 impl_from! { u16, i128 }
2809 impl_from! { u32, i64 }
2810 impl_from! { u32, i128 }
2811 impl_from! { u64, i128 }
2813 // Note: integers can only be represented with full precision in a float if
2814 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2815 // Lossy float conversions are not implemented at this time.
2818 impl_from! { i8, f32 }
2819 impl_from! { i8, f64 }
2820 impl_from! { i16, f32 }
2821 impl_from! { i16, f64 }
2822 impl_from! { i32, f64 }
2824 // Unsigned -> Float
2825 impl_from! { u8, f32 }
2826 impl_from! { u8, f64 }
2827 impl_from! { u16, f32 }
2828 impl_from! { u16, f64 }
2829 impl_from! { u32, f64 }
2832 impl_from! { f32, f64 }