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")]
781 pub fn wrapping_shl(self, rhs: u32) -> Self {
783 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
787 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
788 /// where `mask` removes any high-order bits of `rhs` that
789 /// would cause the shift to exceed the bitwidth of the type.
791 /// Note that this is *not* the same as a rotate-right; the
792 /// RHS of a wrapping shift-right is restricted to the range
793 /// of the type, rather than the bits shifted out of the LHS
794 /// being returned to the other end. The primitive integer
795 /// types all implement a `rotate_right` function, which may
796 /// be what you want instead.
803 /// assert_eq!((-128i8).wrapping_shr(7), -1);
804 /// assert_eq!((-128i8).wrapping_shr(8), -128);
806 #[stable(feature = "num_wrapping", since = "1.2.0")]
808 pub fn wrapping_shr(self, rhs: u32) -> Self {
810 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
814 /// Wrapping (modular) absolute value. Computes `self.abs()`,
815 /// wrapping around at the boundary of the type.
817 /// The only case where such wrapping can occur is when one takes
818 /// the absolute value of the negative minimal value for the type
819 /// this is a positive value that is too large to represent in the
820 /// type. In such a case, this function returns `MIN` itself.
827 /// assert_eq!(100i8.wrapping_abs(), 100);
828 /// assert_eq!((-100i8).wrapping_abs(), 100);
829 /// assert_eq!((-128i8).wrapping_abs(), -128);
830 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
832 #[stable(feature = "no_panic_abs", since = "1.13.0")]
834 pub fn wrapping_abs(self) -> Self {
835 if self.is_negative() {
842 /// Calculates `self` + `rhs`
844 /// Returns a tuple of the addition along with a boolean indicating
845 /// whether an arithmetic overflow would occur. If an overflow would
846 /// have occurred then the wrapped value is returned.
855 /// assert_eq!(5i32.overflowing_add(2), (7, false));
856 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
859 #[stable(feature = "wrapping", since = "1.7.0")]
860 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
862 let (a, b) = $add_with_overflow(self as $ActualT,
868 /// Calculates `self` - `rhs`
870 /// Returns a tuple of the subtraction along with a boolean indicating
871 /// whether an arithmetic overflow would occur. If an overflow would
872 /// have occurred then the wrapped value is returned.
881 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
882 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
885 #[stable(feature = "wrapping", since = "1.7.0")]
886 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
888 let (a, b) = $sub_with_overflow(self as $ActualT,
894 /// Calculates the multiplication of `self` and `rhs`.
896 /// Returns a tuple of the multiplication along with a boolean
897 /// indicating whether an arithmetic overflow would occur. If an
898 /// overflow would have occurred then the wrapped value is returned.
905 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
906 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
909 #[stable(feature = "wrapping", since = "1.7.0")]
910 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
912 let (a, b) = $mul_with_overflow(self as $ActualT,
918 /// Calculates the divisor when `self` is divided by `rhs`.
920 /// Returns a tuple of the divisor along with a boolean indicating
921 /// whether an arithmetic overflow would occur. If an overflow would
922 /// occur then self is returned.
926 /// This function will panic if `rhs` is 0.
935 /// assert_eq!(5i32.overflowing_div(2), (2, false));
936 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
939 #[stable(feature = "wrapping", since = "1.7.0")]
940 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
941 if self == Self::min_value() && rhs == -1 {
948 /// Calculates the remainder when `self` is divided by `rhs`.
950 /// Returns a tuple of the remainder after dividing along with a boolean
951 /// indicating whether an arithmetic overflow would occur. If an
952 /// overflow would occur then 0 is returned.
956 /// This function will panic if `rhs` is 0.
965 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
966 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
969 #[stable(feature = "wrapping", since = "1.7.0")]
970 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
971 if self == Self::min_value() && rhs == -1 {
978 /// Negates self, overflowing if this is equal to the minimum value.
980 /// Returns a tuple of the negated version of self along with a boolean
981 /// indicating whether an overflow happened. If `self` is the minimum
982 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
983 /// value will be returned again and `true` will be returned for an
984 /// overflow happening.
993 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
994 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
997 #[stable(feature = "wrapping", since = "1.7.0")]
998 pub fn overflowing_neg(self) -> (Self, bool) {
999 if self == Self::min_value() {
1000 (Self::min_value(), true)
1006 /// Shifts self left by `rhs` bits.
1008 /// Returns a tuple of the shifted version of self along with a boolean
1009 /// indicating whether the shift value was larger than or equal to the
1010 /// number of bits. If the shift value is too large, then value is
1011 /// masked (N-1) where N is the number of bits, and this value is then
1012 /// used to perform the shift.
1019 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
1020 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
1023 #[stable(feature = "wrapping", since = "1.7.0")]
1024 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1025 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1028 /// Shifts self right by `rhs` bits.
1030 /// Returns a tuple of the shifted version of self along with a boolean
1031 /// indicating whether the shift value was larger than or equal to the
1032 /// number of bits. If the shift value is too large, then value is
1033 /// masked (N-1) where N is the number of bits, and this value is then
1034 /// used to perform the shift.
1041 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
1042 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1045 #[stable(feature = "wrapping", since = "1.7.0")]
1046 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1047 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1050 /// Computes the absolute value of `self`.
1052 /// Returns a tuple of the absolute version of self along with a
1053 /// boolean indicating whether an overflow happened. If self is the
1054 /// minimum value (e.g. i32::MIN for values of type i32), then the
1055 /// minimum value will be returned again and true will be returned for
1056 /// an overflow happening.
1063 /// assert_eq!(10i8.overflowing_abs(), (10,false));
1064 /// assert_eq!((-10i8).overflowing_abs(), (10,false));
1065 /// assert_eq!((-128i8).overflowing_abs(), (-128,true));
1067 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1069 pub fn overflowing_abs(self) -> (Self, bool) {
1070 if self.is_negative() {
1071 self.overflowing_neg()
1077 /// Raises self to the power of `exp`, using exponentiation by squaring.
1084 /// let x: i32 = 2; // or any other integer type
1086 /// assert_eq!(x.pow(4), 16);
1088 #[stable(feature = "rust1", since = "1.0.0")]
1090 #[rustc_inherit_overflow_checks]
1091 pub fn pow(self, mut exp: u32) -> Self {
1092 let mut base = self;
1103 // Deal with the final bit of the exponent separately, since
1104 // squaring the base afterwards is not necessary and may cause a
1105 // needless overflow.
1113 /// Computes the absolute value of `self`.
1115 /// # Overflow behavior
1117 /// The absolute value of `i32::min_value()` cannot be represented as an
1118 /// `i32`, and attempting to calculate it will cause an overflow. This
1119 /// means that code in debug mode will trigger a panic on this case and
1120 /// optimized code will return `i32::min_value()` without a panic.
1127 /// assert_eq!(10i8.abs(), 10);
1128 /// assert_eq!((-10i8).abs(), 10);
1130 #[stable(feature = "rust1", since = "1.0.0")]
1132 #[rustc_inherit_overflow_checks]
1133 pub fn abs(self) -> Self {
1134 if self.is_negative() {
1135 // Note that the #[inline] above means that the overflow
1136 // semantics of this negation depend on the crate we're being
1144 /// Returns a number representing sign of `self`.
1146 /// - `0` if the number is zero
1147 /// - `1` if the number is positive
1148 /// - `-1` if the number is negative
1155 /// assert_eq!(10i8.signum(), 1);
1156 /// assert_eq!(0i8.signum(), 0);
1157 /// assert_eq!((-10i8).signum(), -1);
1159 #[stable(feature = "rust1", since = "1.0.0")]
1161 pub fn signum(self) -> Self {
1169 /// Returns `true` if `self` is positive and `false` if the number
1170 /// is zero or negative.
1177 /// assert!(10i8.is_positive());
1178 /// assert!(!(-10i8).is_positive());
1180 #[stable(feature = "rust1", since = "1.0.0")]
1182 pub fn is_positive(self) -> bool { self > 0 }
1184 /// Returns `true` if `self` is negative and `false` if the number
1185 /// is zero or positive.
1192 /// assert!((-10i8).is_negative());
1193 /// assert!(!10i8.is_negative());
1195 #[stable(feature = "rust1", since = "1.0.0")]
1197 pub fn is_negative(self) -> bool { self < 0 }
1203 int_impl! { i8, i8, u8, 8,
1204 intrinsics::add_with_overflow,
1205 intrinsics::sub_with_overflow,
1206 intrinsics::mul_with_overflow }
1211 int_impl! { i16, i16, u16, 16,
1212 intrinsics::add_with_overflow,
1213 intrinsics::sub_with_overflow,
1214 intrinsics::mul_with_overflow }
1219 int_impl! { i32, i32, u32, 32,
1220 intrinsics::add_with_overflow,
1221 intrinsics::sub_with_overflow,
1222 intrinsics::mul_with_overflow }
1227 int_impl! { i64, i64, u64, 64,
1228 intrinsics::add_with_overflow,
1229 intrinsics::sub_with_overflow,
1230 intrinsics::mul_with_overflow }
1235 int_impl! { i128, i128, u128, 128,
1236 intrinsics::add_with_overflow,
1237 intrinsics::sub_with_overflow,
1238 intrinsics::mul_with_overflow }
1241 #[cfg(target_pointer_width = "16")]
1244 int_impl! { isize, i16, u16, 16,
1245 intrinsics::add_with_overflow,
1246 intrinsics::sub_with_overflow,
1247 intrinsics::mul_with_overflow }
1250 #[cfg(target_pointer_width = "32")]
1253 int_impl! { isize, i32, u32, 32,
1254 intrinsics::add_with_overflow,
1255 intrinsics::sub_with_overflow,
1256 intrinsics::mul_with_overflow }
1259 #[cfg(target_pointer_width = "64")]
1262 int_impl! { isize, i64, u64, 64,
1263 intrinsics::add_with_overflow,
1264 intrinsics::sub_with_overflow,
1265 intrinsics::mul_with_overflow }
1268 // `Int` + `UnsignedInt` implemented for unsigned integers
1269 macro_rules! uint_impl {
1270 ($SelfT:ty, $ActualT:ty, $BITS:expr,
1275 $add_with_overflow:path,
1276 $sub_with_overflow:path,
1277 $mul_with_overflow:path) => {
1278 /// Returns the smallest value that can be represented by this integer type.
1283 /// assert_eq!(u8::min_value(), 0);
1285 #[stable(feature = "rust1", since = "1.0.0")]
1287 pub const fn min_value() -> Self { 0 }
1289 /// Returns the largest value that can be represented by this integer type.
1294 /// assert_eq!(u8::max_value(), 255);
1296 #[stable(feature = "rust1", since = "1.0.0")]
1298 pub const fn max_value() -> Self { !0 }
1300 /// Converts a string slice in a given base to an integer.
1302 /// Leading and trailing whitespace represent an error.
1309 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1313 from_str_radix(src, radix)
1316 /// Returns the number of ones in the binary representation of `self`.
1323 /// let n = 0b01001100u8;
1325 /// assert_eq!(n.count_ones(), 3);
1327 #[stable(feature = "rust1", since = "1.0.0")]
1329 pub fn count_ones(self) -> u32 {
1330 unsafe { $ctpop(self as $ActualT) as u32 }
1333 /// Returns the number of zeros in the binary representation of `self`.
1340 /// let n = 0b01001100u8;
1342 /// assert_eq!(n.count_zeros(), 5);
1344 #[stable(feature = "rust1", since = "1.0.0")]
1346 pub fn count_zeros(self) -> u32 {
1347 (!self).count_ones()
1350 /// Returns the number of leading zeros in the binary representation
1358 /// let n = 0b0101000u16;
1360 /// assert_eq!(n.leading_zeros(), 10);
1362 #[stable(feature = "rust1", since = "1.0.0")]
1364 pub fn leading_zeros(self) -> u32 {
1365 unsafe { $ctlz(self as $ActualT) as u32 }
1368 /// Returns the number of trailing zeros in the binary representation
1376 /// let n = 0b0101000u16;
1378 /// assert_eq!(n.trailing_zeros(), 3);
1380 #[stable(feature = "rust1", since = "1.0.0")]
1382 pub fn trailing_zeros(self) -> u32 {
1383 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1384 // emits two conditional moves on x86_64. By promoting the value to
1385 // u16 and setting bit 8, we get better code without any conditional
1387 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1388 // pending, remove this workaround once LLVM generates better code
1392 intrinsics::cttz(self as u16 | 0x100) as u32
1394 intrinsics::cttz(self) as u32
1399 /// Shifts the bits to the left by a specified amount, `n`,
1400 /// wrapping the truncated bits to the end of the resulting integer.
1402 /// Please note this isn't the same operation as `<<`!
1409 /// let n = 0x0123456789ABCDEFu64;
1410 /// let m = 0x3456789ABCDEF012u64;
1412 /// assert_eq!(n.rotate_left(12), m);
1414 #[stable(feature = "rust1", since = "1.0.0")]
1416 pub fn rotate_left(self, n: u32) -> Self {
1417 // Protect against undefined behaviour for over-long bit shifts
1419 (self << n) | (self >> (($BITS - n) % $BITS))
1422 /// Shifts the bits to the right by a specified amount, `n`,
1423 /// wrapping the truncated bits to the beginning of the resulting
1426 /// Please note this isn't the same operation as `>>`!
1433 /// let n = 0x0123456789ABCDEFu64;
1434 /// let m = 0xDEF0123456789ABCu64;
1436 /// assert_eq!(n.rotate_right(12), m);
1438 #[stable(feature = "rust1", since = "1.0.0")]
1440 pub fn rotate_right(self, n: u32) -> Self {
1441 // Protect against undefined behaviour for over-long bit shifts
1443 (self >> n) | (self << (($BITS - n) % $BITS))
1446 /// Reverses the byte order of the integer.
1453 /// let n = 0x0123456789ABCDEFu64;
1454 /// let m = 0xEFCDAB8967452301u64;
1456 /// assert_eq!(n.swap_bytes(), m);
1458 #[stable(feature = "rust1", since = "1.0.0")]
1460 pub fn swap_bytes(self) -> Self {
1461 unsafe { $bswap(self as $ActualT) as Self }
1464 /// Converts an integer from big endian to the target's endianness.
1466 /// On big endian this is a no-op. On little endian the bytes are
1474 /// let n = 0x0123456789ABCDEFu64;
1476 /// if cfg!(target_endian = "big") {
1477 /// assert_eq!(u64::from_be(n), n)
1479 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1482 #[stable(feature = "rust1", since = "1.0.0")]
1484 pub fn from_be(x: Self) -> Self {
1485 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1488 /// Converts an integer from little endian to the target's endianness.
1490 /// On little endian this is a no-op. On big endian the bytes are
1498 /// let n = 0x0123456789ABCDEFu64;
1500 /// if cfg!(target_endian = "little") {
1501 /// assert_eq!(u64::from_le(n), n)
1503 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1506 #[stable(feature = "rust1", since = "1.0.0")]
1508 pub fn from_le(x: Self) -> Self {
1509 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1512 /// Converts `self` to big endian from the target's endianness.
1514 /// On big endian this is a no-op. On little endian the bytes are
1522 /// let n = 0x0123456789ABCDEFu64;
1524 /// if cfg!(target_endian = "big") {
1525 /// assert_eq!(n.to_be(), n)
1527 /// assert_eq!(n.to_be(), n.swap_bytes())
1530 #[stable(feature = "rust1", since = "1.0.0")]
1532 pub fn to_be(self) -> Self { // or not to be?
1533 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1536 /// Converts `self` to little endian from the target's endianness.
1538 /// On little endian this is a no-op. On big endian the bytes are
1546 /// let n = 0x0123456789ABCDEFu64;
1548 /// if cfg!(target_endian = "little") {
1549 /// assert_eq!(n.to_le(), n)
1551 /// assert_eq!(n.to_le(), n.swap_bytes())
1554 #[stable(feature = "rust1", since = "1.0.0")]
1556 pub fn to_le(self) -> Self {
1557 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1560 /// Checked integer addition. Computes `self + other`, returning `None`
1561 /// if overflow occurred.
1568 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1569 /// assert_eq!(6u16.checked_add(65530), None);
1571 #[stable(feature = "rust1", since = "1.0.0")]
1573 pub fn checked_add(self, other: Self) -> Option<Self> {
1574 let (a, b) = self.overflowing_add(other);
1575 if b {None} else {Some(a)}
1578 /// Checked integer subtraction. Computes `self - other`, returning
1579 /// `None` if underflow occurred.
1586 /// assert_eq!(1u8.checked_sub(1), Some(0));
1587 /// assert_eq!(0u8.checked_sub(1), None);
1589 #[stable(feature = "rust1", since = "1.0.0")]
1591 pub fn checked_sub(self, other: Self) -> Option<Self> {
1592 let (a, b) = self.overflowing_sub(other);
1593 if b {None} else {Some(a)}
1596 /// Checked integer multiplication. Computes `self * other`, returning
1597 /// `None` if underflow or overflow occurred.
1604 /// assert_eq!(5u8.checked_mul(51), Some(255));
1605 /// assert_eq!(5u8.checked_mul(52), None);
1607 #[stable(feature = "rust1", since = "1.0.0")]
1609 pub fn checked_mul(self, other: Self) -> Option<Self> {
1610 let (a, b) = self.overflowing_mul(other);
1611 if b {None} else {Some(a)}
1614 /// Checked integer division. Computes `self / other`, returning `None`
1615 /// if `other == 0` or the operation results in underflow or overflow.
1622 /// assert_eq!(128u8.checked_div(2), Some(64));
1623 /// assert_eq!(1u8.checked_div(0), None);
1625 #[stable(feature = "rust1", since = "1.0.0")]
1627 pub fn checked_div(self, other: Self) -> Option<Self> {
1630 other => Some(unsafe { intrinsics::unchecked_div(self, other) }),
1634 /// Checked integer remainder. Computes `self % other`, returning `None`
1635 /// if `other == 0` or the operation results in underflow or overflow.
1642 /// assert_eq!(5u32.checked_rem(2), Some(1));
1643 /// assert_eq!(5u32.checked_rem(0), None);
1645 #[stable(feature = "wrapping", since = "1.7.0")]
1647 pub fn checked_rem(self, other: Self) -> Option<Self> {
1651 Some(unsafe { intrinsics::unchecked_rem(self, other) })
1655 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1658 /// Note that negating any positive integer will overflow.
1665 /// assert_eq!(0u32.checked_neg(), Some(0));
1666 /// assert_eq!(1u32.checked_neg(), None);
1668 #[stable(feature = "wrapping", since = "1.7.0")]
1670 pub fn checked_neg(self) -> Option<Self> {
1671 let (a, b) = self.overflowing_neg();
1672 if b {None} else {Some(a)}
1675 /// Checked shift left. Computes `self << rhs`, returning `None`
1676 /// if `rhs` is larger than or equal to the number of bits in `self`.
1683 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1684 /// assert_eq!(0x10u32.checked_shl(33), None);
1686 #[stable(feature = "wrapping", since = "1.7.0")]
1688 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1689 let (a, b) = self.overflowing_shl(rhs);
1690 if b {None} else {Some(a)}
1693 /// Checked shift right. Computes `self >> rhs`, returning `None`
1694 /// if `rhs` is larger than or equal to the number of bits in `self`.
1701 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1702 /// assert_eq!(0x10u32.checked_shr(33), None);
1704 #[stable(feature = "wrapping", since = "1.7.0")]
1706 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1707 let (a, b) = self.overflowing_shr(rhs);
1708 if b {None} else {Some(a)}
1711 /// Saturating integer addition. Computes `self + other`, saturating at
1712 /// the numeric bounds instead of overflowing.
1719 /// assert_eq!(100u8.saturating_add(1), 101);
1720 /// assert_eq!(200u8.saturating_add(127), 255);
1722 #[stable(feature = "rust1", since = "1.0.0")]
1724 pub fn saturating_add(self, other: Self) -> Self {
1725 match self.checked_add(other) {
1727 None => Self::max_value(),
1731 /// Saturating integer subtraction. Computes `self - other`, saturating
1732 /// at the numeric bounds instead of overflowing.
1739 /// assert_eq!(100u8.saturating_sub(27), 73);
1740 /// assert_eq!(13u8.saturating_sub(127), 0);
1742 #[stable(feature = "rust1", since = "1.0.0")]
1744 pub fn saturating_sub(self, other: Self) -> Self {
1745 match self.checked_sub(other) {
1747 None => Self::min_value(),
1751 /// Saturating integer multiplication. Computes `self * other`,
1752 /// saturating at the numeric bounds instead of overflowing.
1761 /// assert_eq!(100u32.saturating_mul(127), 12700);
1762 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1764 #[stable(feature = "wrapping", since = "1.7.0")]
1766 pub fn saturating_mul(self, other: Self) -> Self {
1767 self.checked_mul(other).unwrap_or(Self::max_value())
1770 /// Wrapping (modular) addition. Computes `self + other`,
1771 /// wrapping around at the boundary of the type.
1778 /// assert_eq!(200u8.wrapping_add(55), 255);
1779 /// assert_eq!(200u8.wrapping_add(155), 99);
1781 #[stable(feature = "rust1", since = "1.0.0")]
1783 pub fn wrapping_add(self, rhs: Self) -> Self {
1785 intrinsics::overflowing_add(self, rhs)
1789 /// Wrapping (modular) subtraction. Computes `self - other`,
1790 /// wrapping around at the boundary of the type.
1797 /// assert_eq!(100u8.wrapping_sub(100), 0);
1798 /// assert_eq!(100u8.wrapping_sub(155), 201);
1800 #[stable(feature = "rust1", since = "1.0.0")]
1802 pub fn wrapping_sub(self, rhs: Self) -> Self {
1804 intrinsics::overflowing_sub(self, rhs)
1808 /// Wrapping (modular) multiplication. Computes `self *
1809 /// other`, wrapping around at the boundary of the type.
1816 /// assert_eq!(10u8.wrapping_mul(12), 120);
1817 /// assert_eq!(25u8.wrapping_mul(12), 44);
1819 #[stable(feature = "rust1", since = "1.0.0")]
1821 pub fn wrapping_mul(self, rhs: Self) -> Self {
1823 intrinsics::overflowing_mul(self, rhs)
1827 /// Wrapping (modular) division. Computes `self / other`.
1828 /// Wrapped division on unsigned types is just normal division.
1829 /// There's no way wrapping could ever happen.
1830 /// This function exists, so that all operations
1831 /// are accounted for in the wrapping operations.
1838 /// assert_eq!(100u8.wrapping_div(10), 10);
1840 #[stable(feature = "num_wrapping", since = "1.2.0")]
1842 pub fn wrapping_div(self, rhs: Self) -> Self {
1846 /// Wrapping (modular) remainder. Computes `self % other`.
1847 /// Wrapped remainder calculation on unsigned types is
1848 /// just the regular remainder calculation.
1849 /// There's no way wrapping could ever happen.
1850 /// This function exists, so that all operations
1851 /// are accounted for in the wrapping operations.
1858 /// assert_eq!(100u8.wrapping_rem(10), 0);
1860 #[stable(feature = "num_wrapping", since = "1.2.0")]
1862 pub fn wrapping_rem(self, rhs: Self) -> Self {
1866 /// Wrapping (modular) negation. Computes `-self`,
1867 /// wrapping around at the boundary of the type.
1869 /// Since unsigned types do not have negative equivalents
1870 /// all applications of this function will wrap (except for `-0`).
1871 /// For values smaller than the corresponding signed type's maximum
1872 /// the result is the same as casting the corresponding signed value.
1873 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1874 /// `MAX` is the corresponding signed type's maximum.
1881 /// assert_eq!(100u8.wrapping_neg(), 156);
1882 /// assert_eq!(0u8.wrapping_neg(), 0);
1883 /// assert_eq!(180u8.wrapping_neg(), 76);
1884 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1886 #[stable(feature = "num_wrapping", since = "1.2.0")]
1888 pub fn wrapping_neg(self) -> Self {
1889 self.overflowing_neg().0
1892 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1893 /// where `mask` removes any high-order bits of `rhs` that
1894 /// would cause the shift to exceed the bitwidth of the type.
1896 /// Note that this is *not* the same as a rotate-left; the
1897 /// RHS of a wrapping shift-left is restricted to the range
1898 /// of the type, rather than the bits shifted out of the LHS
1899 /// being returned to the other end. The primitive integer
1900 /// types all implement a `rotate_left` function, which may
1901 /// be what you want instead.
1908 /// assert_eq!(1u8.wrapping_shl(7), 128);
1909 /// assert_eq!(1u8.wrapping_shl(8), 1);
1911 #[stable(feature = "num_wrapping", since = "1.2.0")]
1913 pub fn wrapping_shl(self, rhs: u32) -> Self {
1915 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1919 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1920 /// where `mask` removes any high-order bits of `rhs` that
1921 /// would cause the shift to exceed the bitwidth of the type.
1923 /// Note that this is *not* the same as a rotate-right; the
1924 /// RHS of a wrapping shift-right is restricted to the range
1925 /// of the type, rather than the bits shifted out of the LHS
1926 /// being returned to the other end. The primitive integer
1927 /// types all implement a `rotate_right` function, which may
1928 /// be what you want instead.
1935 /// assert_eq!(128u8.wrapping_shr(7), 1);
1936 /// assert_eq!(128u8.wrapping_shr(8), 128);
1938 #[stable(feature = "num_wrapping", since = "1.2.0")]
1940 pub fn wrapping_shr(self, rhs: u32) -> Self {
1942 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1946 /// Calculates `self` + `rhs`
1948 /// Returns a tuple of the addition along with a boolean indicating
1949 /// whether an arithmetic overflow would occur. If an overflow would
1950 /// have occurred then the wrapped value is returned.
1959 /// assert_eq!(5u32.overflowing_add(2), (7, false));
1960 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
1963 #[stable(feature = "wrapping", since = "1.7.0")]
1964 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1966 let (a, b) = $add_with_overflow(self as $ActualT,
1972 /// Calculates `self` - `rhs`
1974 /// Returns a tuple of the subtraction along with a boolean indicating
1975 /// whether an arithmetic overflow would occur. If an overflow would
1976 /// have occurred then the wrapped value is returned.
1985 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
1986 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
1989 #[stable(feature = "wrapping", since = "1.7.0")]
1990 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1992 let (a, b) = $sub_with_overflow(self as $ActualT,
1998 /// Calculates the multiplication of `self` and `rhs`.
2000 /// Returns a tuple of the multiplication along with a boolean
2001 /// indicating whether an arithmetic overflow would occur. If an
2002 /// overflow would have occurred then the wrapped value is returned.
2009 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2010 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2013 #[stable(feature = "wrapping", since = "1.7.0")]
2014 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2016 let (a, b) = $mul_with_overflow(self as $ActualT,
2022 /// Calculates the divisor when `self` is divided by `rhs`.
2024 /// Returns a tuple of the divisor along with a boolean indicating
2025 /// whether an arithmetic overflow would occur. Note that for unsigned
2026 /// integers overflow never occurs, so the second value is always
2031 /// This function will panic if `rhs` is 0.
2038 /// assert_eq!(5u32.overflowing_div(2), (2, false));
2041 #[stable(feature = "wrapping", since = "1.7.0")]
2042 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2046 /// Calculates the remainder when `self` is divided by `rhs`.
2048 /// Returns a tuple of the remainder after dividing along with a boolean
2049 /// indicating whether an arithmetic overflow would occur. Note that for
2050 /// unsigned integers overflow never occurs, so the second value is
2055 /// This function will panic if `rhs` is 0.
2062 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
2065 #[stable(feature = "wrapping", since = "1.7.0")]
2066 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2070 /// Negates self in an overflowing fashion.
2072 /// Returns `!self + 1` using wrapping operations to return the value
2073 /// that represents the negation of this unsigned value. Note that for
2074 /// positive unsigned values overflow always occurs, but negating 0 does
2082 /// assert_eq!(0u32.overflowing_neg(), (0, false));
2083 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
2086 #[stable(feature = "wrapping", since = "1.7.0")]
2087 pub fn overflowing_neg(self) -> (Self, bool) {
2088 ((!self).wrapping_add(1), self != 0)
2091 /// Shifts self left by `rhs` bits.
2093 /// Returns a tuple of the shifted version of self along with a boolean
2094 /// indicating whether the shift value was larger than or equal to the
2095 /// number of bits. If the shift value is too large, then value is
2096 /// masked (N-1) where N is the number of bits, and this value is then
2097 /// used to perform the shift.
2104 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
2105 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
2108 #[stable(feature = "wrapping", since = "1.7.0")]
2109 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2110 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
2113 /// Shifts self right by `rhs` bits.
2115 /// Returns a tuple of the shifted version of self along with a boolean
2116 /// indicating whether the shift value was larger than or equal to the
2117 /// number of bits. If the shift value is too large, then value is
2118 /// masked (N-1) where N is the number of bits, and this value is then
2119 /// used to perform the shift.
2126 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
2127 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2130 #[stable(feature = "wrapping", since = "1.7.0")]
2131 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2132 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
2136 /// Raises self to the power of `exp`, using exponentiation by squaring.
2143 /// assert_eq!(2u32.pow(4), 16);
2145 #[stable(feature = "rust1", since = "1.0.0")]
2147 #[rustc_inherit_overflow_checks]
2148 pub fn pow(self, mut exp: u32) -> Self {
2149 let mut base = self;
2160 // Deal with the final bit of the exponent separately, since
2161 // squaring the base afterwards is not necessary and may cause a
2162 // needless overflow.
2170 /// Returns `true` if and only if `self == 2^k` for some `k`.
2177 /// assert!(16u8.is_power_of_two());
2178 /// assert!(!10u8.is_power_of_two());
2180 #[stable(feature = "rust1", since = "1.0.0")]
2182 pub fn is_power_of_two(self) -> bool {
2183 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2186 /// Returns the smallest power of two greater than or equal to `self`.
2187 /// Unspecified behavior on overflow.
2194 /// assert_eq!(2u8.next_power_of_two(), 2);
2195 /// assert_eq!(3u8.next_power_of_two(), 4);
2197 #[stable(feature = "rust1", since = "1.0.0")]
2199 pub fn next_power_of_two(self) -> Self {
2200 let bits = size_of::<Self>() * 8;
2202 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
2205 /// Returns the smallest power of two greater than or equal to `n`. If
2206 /// the next power of two is greater than the type's maximum value,
2207 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2214 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2215 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2216 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2218 #[stable(feature = "rust1", since = "1.0.0")]
2219 pub fn checked_next_power_of_two(self) -> Option<Self> {
2220 let npot = self.next_power_of_two();
2232 uint_impl! { u8, u8, 8,
2237 intrinsics::add_with_overflow,
2238 intrinsics::sub_with_overflow,
2239 intrinsics::mul_with_overflow }
2244 uint_impl! { u16, u16, 16,
2249 intrinsics::add_with_overflow,
2250 intrinsics::sub_with_overflow,
2251 intrinsics::mul_with_overflow }
2256 uint_impl! { u32, u32, 32,
2261 intrinsics::add_with_overflow,
2262 intrinsics::sub_with_overflow,
2263 intrinsics::mul_with_overflow }
2268 uint_impl! { u64, u64, 64,
2273 intrinsics::add_with_overflow,
2274 intrinsics::sub_with_overflow,
2275 intrinsics::mul_with_overflow }
2280 uint_impl! { u128, u128, 128,
2285 intrinsics::add_with_overflow,
2286 intrinsics::sub_with_overflow,
2287 intrinsics::mul_with_overflow }
2290 #[cfg(target_pointer_width = "16")]
2293 uint_impl! { usize, u16, 16,
2298 intrinsics::add_with_overflow,
2299 intrinsics::sub_with_overflow,
2300 intrinsics::mul_with_overflow }
2302 #[cfg(target_pointer_width = "32")]
2305 uint_impl! { usize, u32, 32,
2310 intrinsics::add_with_overflow,
2311 intrinsics::sub_with_overflow,
2312 intrinsics::mul_with_overflow }
2315 #[cfg(target_pointer_width = "64")]
2318 uint_impl! { usize, u64, 64,
2323 intrinsics::add_with_overflow,
2324 intrinsics::sub_with_overflow,
2325 intrinsics::mul_with_overflow }
2328 /// A classification of floating point numbers.
2330 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
2331 /// their documentation for more.
2333 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
2334 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
2339 /// use std::num::FpCategory;
2342 /// let num = 12.4_f32;
2343 /// let inf = f32::INFINITY;
2344 /// let zero = 0f32;
2345 /// let sub: f32 = 1.1754942e-38;
2346 /// let nan = f32::NAN;
2348 /// assert_eq!(num.classify(), FpCategory::Normal);
2349 /// assert_eq!(inf.classify(), FpCategory::Infinite);
2350 /// assert_eq!(zero.classify(), FpCategory::Zero);
2351 /// assert_eq!(nan.classify(), FpCategory::Nan);
2352 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
2354 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2355 #[stable(feature = "rust1", since = "1.0.0")]
2356 pub enum FpCategory {
2357 /// "Not a Number", often obtained by dividing by zero.
2358 #[stable(feature = "rust1", since = "1.0.0")]
2361 /// Positive or negative infinity.
2362 #[stable(feature = "rust1", since = "1.0.0")]
2365 /// Positive or negative zero.
2366 #[stable(feature = "rust1", since = "1.0.0")]
2369 /// De-normalized floating point representation (less precise than `Normal`).
2370 #[stable(feature = "rust1", since = "1.0.0")]
2373 /// A regular floating point number.
2374 #[stable(feature = "rust1", since = "1.0.0")]
2378 /// A built-in floating point number.
2380 #[unstable(feature = "core_float",
2381 reason = "stable interface is via `impl f{32,64}` in later crates",
2383 pub trait Float: Sized {
2384 /// Returns `true` if this value is NaN and false otherwise.
2385 #[stable(feature = "core", since = "1.6.0")]
2386 fn is_nan(self) -> bool;
2387 /// Returns `true` if this value is positive infinity or negative infinity and
2388 /// false otherwise.
2389 #[stable(feature = "core", since = "1.6.0")]
2390 fn is_infinite(self) -> bool;
2391 /// Returns `true` if this number is neither infinite nor NaN.
2392 #[stable(feature = "core", since = "1.6.0")]
2393 fn is_finite(self) -> bool;
2394 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
2395 #[stable(feature = "core", since = "1.6.0")]
2396 fn is_normal(self) -> bool;
2397 /// Returns the category that this number falls into.
2398 #[stable(feature = "core", since = "1.6.0")]
2399 fn classify(self) -> FpCategory;
2401 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2402 /// number is `Float::nan()`.
2403 #[stable(feature = "core", since = "1.6.0")]
2404 fn abs(self) -> Self;
2405 /// Returns a number that represents the sign of `self`.
2407 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2408 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2409 /// - `Float::nan()` if the number is `Float::nan()`
2410 #[stable(feature = "core", since = "1.6.0")]
2411 fn signum(self) -> Self;
2413 /// Returns `true` if `self` is positive, including `+0.0` and
2414 /// `Float::infinity()`.
2415 #[stable(feature = "core", since = "1.6.0")]
2416 fn is_sign_positive(self) -> bool;
2417 /// Returns `true` if `self` is negative, including `-0.0` and
2418 /// `Float::neg_infinity()`.
2419 #[stable(feature = "core", since = "1.6.0")]
2420 fn is_sign_negative(self) -> bool;
2422 /// Take the reciprocal (inverse) of a number, `1/x`.
2423 #[stable(feature = "core", since = "1.6.0")]
2424 fn recip(self) -> Self;
2426 /// Raise a number to an integer power.
2428 /// Using this function is generally faster than using `powf`
2429 #[stable(feature = "core", since = "1.6.0")]
2430 fn powi(self, n: i32) -> Self;
2432 /// Convert radians to degrees.
2433 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2434 fn to_degrees(self) -> Self;
2435 /// Convert degrees to radians.
2436 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2437 fn to_radians(self) -> Self;
2440 macro_rules! from_str_radix_int_impl {
2442 #[stable(feature = "rust1", since = "1.0.0")]
2443 impl FromStr for $t {
2444 type Err = ParseIntError;
2445 fn from_str(src: &str) -> Result<Self, ParseIntError> {
2446 from_str_radix(src, 10)
2451 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
2453 /// The error type returned when a checked integral type conversion fails.
2454 #[unstable(feature = "try_from", issue = "33417")]
2455 #[derive(Debug, Copy, Clone)]
2456 pub struct TryFromIntError(());
2458 impl TryFromIntError {
2459 #[unstable(feature = "int_error_internals",
2460 reason = "available through Error trait and this method should \
2461 not be exposed publicly",
2464 pub fn __description(&self) -> &str {
2465 "out of range integral type conversion attempted"
2469 #[unstable(feature = "try_from", issue = "33417")]
2470 impl fmt::Display for TryFromIntError {
2471 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2472 self.__description().fmt(fmt)
2476 macro_rules! same_sign_try_from_int_impl {
2477 ($storage:ty, $target:ty, $($source:ty),*) => {$(
2478 #[unstable(feature = "try_from", issue = "33417")]
2479 impl TryFrom<$source> for $target {
2480 type Error = TryFromIntError;
2482 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2483 let min = <$target as FromStrRadixHelper>::min_value() as $storage;
2484 let max = <$target as FromStrRadixHelper>::max_value() as $storage;
2485 if u as $storage < min || u as $storage > max {
2486 Err(TryFromIntError(()))
2495 same_sign_try_from_int_impl!(u128, u8, u8, u16, u32, u64, u128, usize);
2496 same_sign_try_from_int_impl!(i128, i8, i8, i16, i32, i64, i128, isize);
2497 same_sign_try_from_int_impl!(u128, u16, u8, u16, u32, u64, u128, usize);
2498 same_sign_try_from_int_impl!(i128, i16, i8, i16, i32, i64, i128, isize);
2499 same_sign_try_from_int_impl!(u128, u32, u8, u16, u32, u64, u128, usize);
2500 same_sign_try_from_int_impl!(i128, i32, i8, i16, i32, i64, i128, isize);
2501 same_sign_try_from_int_impl!(u128, u64, u8, u16, u32, u64, u128, usize);
2502 same_sign_try_from_int_impl!(i128, i64, i8, i16, i32, i64, i128, isize);
2503 same_sign_try_from_int_impl!(u128, u128, u8, u16, u32, u64, u128, usize);
2504 same_sign_try_from_int_impl!(i128, i128, i8, i16, i32, i64, i128, isize);
2505 same_sign_try_from_int_impl!(u128, usize, u8, u16, u32, u64, u128, usize);
2506 same_sign_try_from_int_impl!(i128, isize, i8, i16, i32, i64, i128, isize);
2508 macro_rules! cross_sign_from_int_impl {
2509 ($unsigned:ty, $($signed:ty),*) => {$(
2510 #[unstable(feature = "try_from", issue = "33417")]
2511 impl TryFrom<$unsigned> for $signed {
2512 type Error = TryFromIntError;
2514 fn try_from(u: $unsigned) -> Result<$signed, TryFromIntError> {
2515 let max = <$signed as FromStrRadixHelper>::max_value() as u128;
2516 if u as u128 > max {
2517 Err(TryFromIntError(()))
2524 #[unstable(feature = "try_from", issue = "33417")]
2525 impl TryFrom<$signed> for $unsigned {
2526 type Error = TryFromIntError;
2528 fn try_from(u: $signed) -> Result<$unsigned, TryFromIntError> {
2529 let max = <$unsigned as FromStrRadixHelper>::max_value() as u128;
2530 if u < 0 || u as u128 > max {
2531 Err(TryFromIntError(()))
2540 cross_sign_from_int_impl!(u8, i8, i16, i32, i64, i128, isize);
2541 cross_sign_from_int_impl!(u16, i8, i16, i32, i64, i128, isize);
2542 cross_sign_from_int_impl!(u32, i8, i16, i32, i64, i128, isize);
2543 cross_sign_from_int_impl!(u64, i8, i16, i32, i64, i128, isize);
2544 cross_sign_from_int_impl!(u128, i8, i16, i32, i64, i128, isize);
2545 cross_sign_from_int_impl!(usize, i8, i16, i32, i64, i128, isize);
2548 trait FromStrRadixHelper: PartialOrd + Copy {
2549 fn min_value() -> Self;
2550 fn max_value() -> Self;
2551 fn from_u32(u: u32) -> Self;
2552 fn checked_mul(&self, other: u32) -> Option<Self>;
2553 fn checked_sub(&self, other: u32) -> Option<Self>;
2554 fn checked_add(&self, other: u32) -> Option<Self>;
2558 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
2559 fn min_value() -> Self { Self::min_value() }
2560 fn max_value() -> Self { Self::max_value() }
2561 fn from_u32(u: u32) -> Self { u as Self }
2562 fn checked_mul(&self, other: u32) -> Option<Self> {
2563 Self::checked_mul(*self, other as Self)
2565 fn checked_sub(&self, other: u32) -> Option<Self> {
2566 Self::checked_sub(*self, other as Self)
2568 fn checked_add(&self, other: u32) -> Option<Self> {
2569 Self::checked_add(*self, other as Self)
2573 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
2575 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
2576 use self::IntErrorKind::*;
2577 use self::ParseIntError as PIE;
2579 assert!(radix >= 2 && radix <= 36,
2580 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2584 return Err(PIE { kind: Empty });
2587 let is_signed_ty = T::from_u32(0) > T::min_value();
2589 // all valid digits are ascii, so we will just iterate over the utf8 bytes
2590 // and cast them to chars. .to_digit() will safely return None for anything
2591 // other than a valid ascii digit for the given radix, including the first-byte
2592 // of multi-byte sequences
2593 let src = src.as_bytes();
2595 let (is_positive, digits) = match src[0] {
2596 b'+' => (true, &src[1..]),
2597 b'-' if is_signed_ty => (false, &src[1..]),
2601 if digits.is_empty() {
2602 return Err(PIE { kind: Empty });
2605 let mut result = T::from_u32(0);
2607 // The number is positive
2609 let x = match (c as char).to_digit(radix) {
2611 None => return Err(PIE { kind: InvalidDigit }),
2613 result = match result.checked_mul(radix) {
2614 Some(result) => result,
2615 None => return Err(PIE { kind: Overflow }),
2617 result = match result.checked_add(x) {
2618 Some(result) => result,
2619 None => return Err(PIE { kind: Overflow }),
2623 // The number is negative
2625 let x = match (c as char).to_digit(radix) {
2627 None => return Err(PIE { kind: InvalidDigit }),
2629 result = match result.checked_mul(radix) {
2630 Some(result) => result,
2631 None => return Err(PIE { kind: Underflow }),
2633 result = match result.checked_sub(x) {
2634 Some(result) => result,
2635 None => return Err(PIE { kind: Underflow }),
2642 /// An error which can be returned when parsing an integer.
2644 /// This error is used as the error type for the `from_str_radix()` functions
2645 /// on the primitive integer types, such as [`i8::from_str_radix`].
2647 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
2648 #[derive(Debug, Clone, PartialEq, Eq)]
2649 #[stable(feature = "rust1", since = "1.0.0")]
2650 pub struct ParseIntError {
2654 #[derive(Debug, Clone, PartialEq, Eq)]
2662 impl ParseIntError {
2663 #[unstable(feature = "int_error_internals",
2664 reason = "available through Error trait and this method should \
2665 not be exposed publicly",
2668 pub fn __description(&self) -> &str {
2670 IntErrorKind::Empty => "cannot parse integer from empty string",
2671 IntErrorKind::InvalidDigit => "invalid digit found in string",
2672 IntErrorKind::Overflow => "number too large to fit in target type",
2673 IntErrorKind::Underflow => "number too small to fit in target type",
2678 #[stable(feature = "rust1", since = "1.0.0")]
2679 impl fmt::Display for ParseIntError {
2680 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2681 self.__description().fmt(f)
2685 #[stable(feature = "rust1", since = "1.0.0")]
2686 pub use num::dec2flt::ParseFloatError;
2688 // Conversion traits for primitive integer and float types
2689 // Conversions T -> T are covered by a blanket impl and therefore excluded
2690 // Some conversions from and to usize/isize are not implemented due to portability concerns
2691 macro_rules! impl_from {
2692 ($Small: ty, $Large: ty) => {
2693 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
2694 impl From<$Small> for $Large {
2696 fn from(small: $Small) -> $Large {
2703 // Unsigned -> Unsigned
2704 impl_from! { u8, u16 }
2705 impl_from! { u8, u32 }
2706 impl_from! { u8, u64 }
2707 impl_from! { u8, u128 }
2708 impl_from! { u8, usize }
2709 impl_from! { u16, u32 }
2710 impl_from! { u16, u64 }
2711 impl_from! { u16, u128 }
2712 impl_from! { u32, u64 }
2713 impl_from! { u32, u128 }
2714 impl_from! { u64, u128 }
2717 impl_from! { i8, i16 }
2718 impl_from! { i8, i32 }
2719 impl_from! { i8, i64 }
2720 impl_from! { i8, i128 }
2721 impl_from! { i8, isize }
2722 impl_from! { i16, i32 }
2723 impl_from! { i16, i64 }
2724 impl_from! { i16, i128 }
2725 impl_from! { i32, i64 }
2726 impl_from! { i32, i128 }
2727 impl_from! { i64, i128 }
2729 // Unsigned -> Signed
2730 impl_from! { u8, i16 }
2731 impl_from! { u8, i32 }
2732 impl_from! { u8, i64 }
2733 impl_from! { u8, i128 }
2734 impl_from! { u16, i32 }
2735 impl_from! { u16, i64 }
2736 impl_from! { u16, i128 }
2737 impl_from! { u32, i64 }
2738 impl_from! { u32, i128 }
2739 impl_from! { u64, i128 }
2741 // Note: integers can only be represented with full precision in a float if
2742 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2743 // Lossy float conversions are not implemented at this time.
2746 impl_from! { i8, f32 }
2747 impl_from! { i8, f64 }
2748 impl_from! { i16, f32 }
2749 impl_from! { i16, f64 }
2750 impl_from! { i32, f64 }
2752 // Unsigned -> Float
2753 impl_from! { u8, f32 }
2754 impl_from! { u8, f64 }
2755 impl_from! { u16, f32 }
2756 impl_from! { u16, f64 }
2757 impl_from! { u32, f64 }
2760 impl_from! { f32, f64 }