1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Numeric traits and functions for the built-in numeric types.
13 #![stable(feature = "rust1", since = "1.0.0")]
14 #![allow(missing_docs)]
17 use cmp::{Eq, PartialOrd};
21 use marker::{Copy, Sized};
23 use option::Option::{self, Some, None};
24 use result::Result::{self, Ok, Err};
25 use str::{FromStr, StrExt};
28 /// Provides intentionally-wrapped arithmetic on `T`.
30 /// Operations like `+` on `u32` values is intended to never overflow,
31 /// and in some debug configurations overflow is detected and results
32 /// in a panic. While most arithmetic falls into this category, some
33 /// code explicitly expects and relies upon modular arithmetic (e.g.,
36 /// Wrapping arithmetic can be achieved either through methods like
37 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
38 /// all standard arithmetic operations on the underlying value are
39 /// intended to have wrapping semantics.
40 #[stable(feature = "rust1", since = "1.0.0")]
41 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
42 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
44 #[stable(feature = "rust1", since = "1.0.0")]
45 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
46 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51 #[stable(feature = "wrapping_display", since = "1.10.0")]
52 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
53 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60 // All these modules are technically private and only exposed for libcoretest:
66 /// Types that have a "zero" value.
68 /// This trait is intended for use in conjunction with `Add`, as an identity:
69 /// `x + T::zero() == x`.
70 #[unstable(feature = "zero_one",
71 reason = "unsure of placement, wants to use associated constants",
73 pub trait Zero: Sized {
74 /// The "zero" (usually, additive identity) for this type.
78 /// Types that have a "one" value.
80 /// This trait is intended for use in conjunction with `Mul`, as an identity:
81 /// `x * T::one() == x`.
82 #[unstable(feature = "zero_one",
83 reason = "unsure of placement, wants to use associated constants",
85 pub trait One: Sized {
86 /// The "one" (usually, multiplicative identity) for this type.
90 macro_rules! zero_one_impl {
92 #[unstable(feature = "zero_one",
93 reason = "unsure of placement, wants to use associated constants",
97 fn zero() -> Self { 0 }
99 #[unstable(feature = "zero_one",
100 reason = "unsure of placement, wants to use associated constants",
104 fn one() -> Self { 1 }
108 zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
110 macro_rules! zero_one_impl_float {
112 #[unstable(feature = "zero_one",
113 reason = "unsure of placement, wants to use associated constants",
117 fn zero() -> Self { 0.0 }
119 #[unstable(feature = "zero_one",
120 reason = "unsure of placement, wants to use associated constants",
124 fn one() -> Self { 1.0 }
128 zero_one_impl_float! { f32 f64 }
130 macro_rules! checked_op {
131 ($U:ty, $op:path, $x:expr, $y:expr) => {{
132 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
133 if overflowed { None } else { Some(result as Self) }
137 // `Int` + `SignedInt` implemented for signed integers
138 macro_rules! int_impl {
139 ($ActualT:ident, $UnsignedT:ty, $BITS:expr,
140 $add_with_overflow:path,
141 $sub_with_overflow:path,
142 $mul_with_overflow:path) => {
143 /// Returns the smallest value that can be represented by this integer type.
144 #[stable(feature = "rust1", since = "1.0.0")]
146 pub const fn min_value() -> Self {
147 (-1 as Self) << ($BITS - 1)
150 /// Returns the largest value that can be represented by this integer type.
151 #[stable(feature = "rust1", since = "1.0.0")]
153 pub const fn max_value() -> Self {
157 /// Converts a string slice in a given base to an integer.
159 /// Leading and trailing whitespace represent an error.
166 /// assert_eq!(i32::from_str_radix("A", 16), Ok(10));
168 #[stable(feature = "rust1", since = "1.0.0")]
169 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
170 from_str_radix(src, radix)
173 /// Returns the number of ones in the binary representation of `self`.
180 /// let n = -0b1000_0000i8;
182 /// assert_eq!(n.count_ones(), 1);
184 #[stable(feature = "rust1", since = "1.0.0")]
186 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
188 /// Returns the number of zeros in the binary representation of `self`.
195 /// let n = -0b1000_0000i8;
197 /// assert_eq!(n.count_zeros(), 7);
199 #[stable(feature = "rust1", since = "1.0.0")]
201 pub fn count_zeros(self) -> u32 {
205 /// Returns the number of leading zeros in the binary representation
215 /// assert_eq!(n.leading_zeros(), 0);
217 #[stable(feature = "rust1", since = "1.0.0")]
219 pub fn leading_zeros(self) -> u32 {
220 (self as $UnsignedT).leading_zeros()
223 /// Returns the number of trailing zeros in the binary representation
233 /// assert_eq!(n.trailing_zeros(), 2);
235 #[stable(feature = "rust1", since = "1.0.0")]
237 pub fn trailing_zeros(self) -> u32 {
238 (self as $UnsignedT).trailing_zeros()
241 /// Shifts the bits to the left by a specified amount, `n`,
242 /// wrapping the truncated bits to the end of the resulting integer.
249 /// let n = 0x0123456789ABCDEFi64;
250 /// let m = -0x76543210FEDCBA99i64;
252 /// assert_eq!(n.rotate_left(32), m);
254 #[stable(feature = "rust1", since = "1.0.0")]
256 pub fn rotate_left(self, n: u32) -> Self {
257 (self as $UnsignedT).rotate_left(n) as Self
260 /// Shifts the bits to the right by a specified amount, `n`,
261 /// wrapping the truncated bits to the beginning of the resulting
269 /// let n = 0x0123456789ABCDEFi64;
270 /// let m = -0xFEDCBA987654322i64;
272 /// assert_eq!(n.rotate_right(4), m);
274 #[stable(feature = "rust1", since = "1.0.0")]
276 pub fn rotate_right(self, n: u32) -> Self {
277 (self as $UnsignedT).rotate_right(n) as Self
280 /// Reverses the byte order of the integer.
287 /// let n = 0x0123456789ABCDEFi64;
288 /// let m = -0x1032547698BADCFFi64;
290 /// assert_eq!(n.swap_bytes(), m);
292 #[stable(feature = "rust1", since = "1.0.0")]
294 pub fn swap_bytes(self) -> Self {
295 (self as $UnsignedT).swap_bytes() as Self
298 /// Converts an integer from big endian to the target's endianness.
300 /// On big endian this is a no-op. On little endian the bytes are
308 /// let n = 0x0123456789ABCDEFi64;
310 /// if cfg!(target_endian = "big") {
311 /// assert_eq!(i64::from_be(n), n)
313 /// assert_eq!(i64::from_be(n), n.swap_bytes())
316 #[stable(feature = "rust1", since = "1.0.0")]
318 pub fn from_be(x: Self) -> Self {
319 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
322 /// Converts an integer from little endian to the target's endianness.
324 /// On little endian this is a no-op. On big endian the bytes are
332 /// let n = 0x0123456789ABCDEFi64;
334 /// if cfg!(target_endian = "little") {
335 /// assert_eq!(i64::from_le(n), n)
337 /// assert_eq!(i64::from_le(n), n.swap_bytes())
340 #[stable(feature = "rust1", since = "1.0.0")]
342 pub fn from_le(x: Self) -> Self {
343 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
346 /// Converts `self` to big endian from the target's endianness.
348 /// On big endian this is a no-op. On little endian the bytes are
356 /// let n = 0x0123456789ABCDEFi64;
358 /// if cfg!(target_endian = "big") {
359 /// assert_eq!(n.to_be(), n)
361 /// assert_eq!(n.to_be(), n.swap_bytes())
364 #[stable(feature = "rust1", since = "1.0.0")]
366 pub fn to_be(self) -> Self { // or not to be?
367 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
370 /// Converts `self` to little endian from the target's endianness.
372 /// On little endian this is a no-op. On big endian the bytes are
380 /// let n = 0x0123456789ABCDEFi64;
382 /// if cfg!(target_endian = "little") {
383 /// assert_eq!(n.to_le(), n)
385 /// assert_eq!(n.to_le(), n.swap_bytes())
388 #[stable(feature = "rust1", since = "1.0.0")]
390 pub fn to_le(self) -> Self {
391 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
394 /// Checked integer addition. Computes `self + other`, returning `None`
395 /// if overflow occurred.
402 /// assert_eq!(7i16.checked_add(32760), Some(32767));
403 /// assert_eq!(8i16.checked_add(32760), None);
405 #[stable(feature = "rust1", since = "1.0.0")]
407 pub fn checked_add(self, other: Self) -> Option<Self> {
408 let (a, b) = self.overflowing_add(other);
409 if b {None} else {Some(a)}
412 /// Checked integer subtraction. Computes `self - other`, returning
413 /// `None` if underflow occurred.
420 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
421 /// assert_eq!((-128i8).checked_sub(1), None);
423 #[stable(feature = "rust1", since = "1.0.0")]
425 pub fn checked_sub(self, other: Self) -> Option<Self> {
426 let (a, b) = self.overflowing_sub(other);
427 if b {None} else {Some(a)}
430 /// Checked integer multiplication. Computes `self * other`, returning
431 /// `None` if underflow or overflow occurred.
438 /// assert_eq!(6i8.checked_mul(21), Some(126));
439 /// assert_eq!(6i8.checked_mul(22), None);
441 #[stable(feature = "rust1", since = "1.0.0")]
443 pub fn checked_mul(self, other: Self) -> Option<Self> {
444 let (a, b) = self.overflowing_mul(other);
445 if b {None} else {Some(a)}
448 /// Checked integer division. Computes `self / other`, returning `None`
449 /// if `other == 0` or the operation results in underflow or overflow.
456 /// assert_eq!((-127i8).checked_div(-1), Some(127));
457 /// assert_eq!((-128i8).checked_div(-1), None);
458 /// assert_eq!((1i8).checked_div(0), None);
460 #[stable(feature = "rust1", since = "1.0.0")]
462 pub fn checked_div(self, other: Self) -> Option<Self> {
466 let (a, b) = self.overflowing_div(other);
467 if b {None} else {Some(a)}
471 /// Checked integer remainder. Computes `self % other`, returning `None`
472 /// if `other == 0` or the operation results in underflow or overflow.
481 /// assert_eq!(5i32.checked_rem(2), Some(1));
482 /// assert_eq!(5i32.checked_rem(0), None);
483 /// assert_eq!(i32::MIN.checked_rem(-1), None);
485 #[stable(feature = "wrapping", since = "1.7.0")]
487 pub fn checked_rem(self, other: Self) -> Option<Self> {
491 let (a, b) = self.overflowing_rem(other);
492 if b {None} else {Some(a)}
496 /// Checked negation. Computes `-self`, returning `None` if `self ==
506 /// assert_eq!(5i32.checked_neg(), Some(-5));
507 /// assert_eq!(i32::MIN.checked_neg(), None);
509 #[stable(feature = "wrapping", since = "1.7.0")]
511 pub fn checked_neg(self) -> Option<Self> {
512 let (a, b) = self.overflowing_neg();
513 if b {None} else {Some(a)}
516 /// Checked shift left. Computes `self << rhs`, returning `None`
517 /// if `rhs` is larger than or equal to the number of bits in `self`.
524 /// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
525 /// assert_eq!(0x10i32.checked_shl(33), None);
527 #[stable(feature = "wrapping", since = "1.7.0")]
529 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
530 let (a, b) = self.overflowing_shl(rhs);
531 if b {None} else {Some(a)}
534 /// Checked shift right. Computes `self >> rhs`, returning `None`
535 /// if `rhs` is larger than or equal to the number of bits in `self`.
542 /// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
543 /// assert_eq!(0x10i32.checked_shr(33), None);
545 #[stable(feature = "wrapping", since = "1.7.0")]
547 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
548 let (a, b) = self.overflowing_shr(rhs);
549 if b {None} else {Some(a)}
552 /// Saturating integer addition. Computes `self + other`, saturating at
553 /// the numeric bounds instead of overflowing.
560 /// assert_eq!(100i8.saturating_add(1), 101);
561 /// assert_eq!(100i8.saturating_add(127), 127);
563 #[stable(feature = "rust1", since = "1.0.0")]
565 pub fn saturating_add(self, other: Self) -> Self {
566 match self.checked_add(other) {
568 None if other >= Self::zero() => Self::max_value(),
569 None => Self::min_value(),
573 /// Saturating integer subtraction. Computes `self - other`, saturating
574 /// at the numeric bounds instead of overflowing.
581 /// assert_eq!(100i8.saturating_sub(127), -27);
582 /// assert_eq!((-100i8).saturating_sub(127), -128);
584 #[stable(feature = "rust1", since = "1.0.0")]
586 pub fn saturating_sub(self, other: Self) -> Self {
587 match self.checked_sub(other) {
589 None if other >= Self::zero() => Self::min_value(),
590 None => Self::max_value(),
594 /// Saturating integer multiplication. Computes `self * other`,
595 /// saturating at the numeric bounds instead of overflowing.
604 /// assert_eq!(100i32.saturating_mul(127), 12700);
605 /// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
606 /// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
608 #[stable(feature = "wrapping", since = "1.7.0")]
610 pub fn saturating_mul(self, other: Self) -> Self {
611 self.checked_mul(other).unwrap_or_else(|| {
612 if (self < 0 && other < 0) || (self > 0 && other > 0) {
620 /// Wrapping (modular) addition. Computes `self + other`,
621 /// wrapping around at the boundary of the type.
628 /// assert_eq!(100i8.wrapping_add(27), 127);
629 /// assert_eq!(100i8.wrapping_add(127), -29);
631 #[stable(feature = "rust1", since = "1.0.0")]
633 pub fn wrapping_add(self, rhs: Self) -> Self {
635 intrinsics::overflowing_add(self, rhs)
639 /// Wrapping (modular) subtraction. Computes `self - other`,
640 /// wrapping around at the boundary of the type.
647 /// assert_eq!(0i8.wrapping_sub(127), -127);
648 /// assert_eq!((-2i8).wrapping_sub(127), 127);
650 #[stable(feature = "rust1", since = "1.0.0")]
652 pub fn wrapping_sub(self, rhs: Self) -> Self {
654 intrinsics::overflowing_sub(self, rhs)
658 /// Wrapping (modular) multiplication. Computes `self *
659 /// other`, wrapping around at the boundary of the type.
666 /// assert_eq!(10i8.wrapping_mul(12), 120);
667 /// assert_eq!(11i8.wrapping_mul(12), -124);
669 #[stable(feature = "rust1", since = "1.0.0")]
671 pub fn wrapping_mul(self, rhs: Self) -> Self {
673 intrinsics::overflowing_mul(self, rhs)
677 /// Wrapping (modular) division. Computes `self / other`,
678 /// wrapping around at the boundary of the type.
680 /// The only case where such wrapping can occur is when one
681 /// divides `MIN / -1` on a signed type (where `MIN` is the
682 /// negative minimal value for the type); this is equivalent
683 /// to `-MIN`, a positive value that is too large to represent
684 /// in the type. In such a case, this function returns `MIN`
689 /// This function will panic if `rhs` is 0.
696 /// assert_eq!(100u8.wrapping_div(10), 10);
697 /// assert_eq!((-128i8).wrapping_div(-1), -128);
699 #[stable(feature = "num_wrapping", since = "1.2.0")]
701 pub fn wrapping_div(self, rhs: Self) -> Self {
702 self.overflowing_div(rhs).0
705 /// Wrapping (modular) remainder. Computes `self % other`,
706 /// wrapping around at the boundary of the type.
708 /// Such wrap-around never actually occurs mathematically;
709 /// implementation artifacts make `x % y` invalid for `MIN /
710 /// -1` on a signed type (where `MIN` is the negative
711 /// minimal value). In such a case, this function returns `0`.
715 /// This function will panic if `rhs` is 0.
722 /// assert_eq!(100i8.wrapping_rem(10), 0);
723 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
725 #[stable(feature = "num_wrapping", since = "1.2.0")]
727 pub fn wrapping_rem(self, rhs: Self) -> Self {
728 self.overflowing_rem(rhs).0
731 /// Wrapping (modular) negation. Computes `-self`,
732 /// wrapping around at the boundary of the type.
734 /// The only case where such wrapping can occur is when one
735 /// negates `MIN` on a signed type (where `MIN` is the
736 /// negative minimal value for the type); this is a positive
737 /// value that is too large to represent in the type. In such
738 /// a case, this function returns `MIN` itself.
745 /// assert_eq!(100i8.wrapping_neg(), -100);
746 /// assert_eq!((-128i8).wrapping_neg(), -128);
748 #[stable(feature = "num_wrapping", since = "1.2.0")]
750 pub fn wrapping_neg(self) -> Self {
751 self.overflowing_neg().0
754 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
755 /// where `mask` removes any high-order bits of `rhs` that
756 /// would cause the shift to exceed the bitwidth of the type.
758 /// Note that this is *not* the same as a rotate-left; the
759 /// RHS of a wrapping shift-left is restricted to the range
760 /// of the type, rather than the bits shifted out of the LHS
761 /// being returned to the other end. The primitive integer
762 /// types all implement a `rotate_left` function, which may
763 /// be what you want instead.
770 /// assert_eq!((-1i8).wrapping_shl(7), -128);
771 /// assert_eq!((-1i8).wrapping_shl(8), -1);
773 #[stable(feature = "num_wrapping", since = "1.2.0")]
775 pub fn wrapping_shl(self, rhs: u32) -> Self {
776 self.overflowing_shl(rhs).0
779 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
780 /// where `mask` removes any high-order bits of `rhs` that
781 /// would cause the shift to exceed the bitwidth of the type.
783 /// Note that this is *not* the same as a rotate-right; the
784 /// RHS of a wrapping shift-right is restricted to the range
785 /// of the type, rather than the bits shifted out of the LHS
786 /// being returned to the other end. The primitive integer
787 /// types all implement a `rotate_right` function, which may
788 /// be what you want instead.
795 /// assert_eq!((-128i8).wrapping_shr(7), -1);
796 /// assert_eq!((-128i8).wrapping_shr(8), -128);
798 #[stable(feature = "num_wrapping", since = "1.2.0")]
800 pub fn wrapping_shr(self, rhs: u32) -> Self {
801 self.overflowing_shr(rhs).0
804 /// Calculates `self` + `rhs`
806 /// Returns a tuple of the addition along with a boolean indicating
807 /// whether an arithmetic overflow would occur. If an overflow would
808 /// have occurred then the wrapped value is returned.
817 /// assert_eq!(5i32.overflowing_add(2), (7, false));
818 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
821 #[stable(feature = "wrapping", since = "1.7.0")]
822 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
824 let (a, b) = $add_with_overflow(self as $ActualT,
830 /// Calculates `self` - `rhs`
832 /// Returns a tuple of the subtraction along with a boolean indicating
833 /// whether an arithmetic overflow would occur. If an overflow would
834 /// have occurred then the wrapped value is returned.
843 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
844 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
847 #[stable(feature = "wrapping", since = "1.7.0")]
848 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
850 let (a, b) = $sub_with_overflow(self as $ActualT,
856 /// Calculates the multiplication of `self` and `rhs`.
858 /// Returns a tuple of the multiplication along with a boolean
859 /// indicating whether an arithmetic overflow would occur. If an
860 /// overflow would have occurred then the wrapped value is returned.
867 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
868 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
871 #[stable(feature = "wrapping", since = "1.7.0")]
872 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
874 let (a, b) = $mul_with_overflow(self as $ActualT,
880 /// Calculates the divisor when `self` is divided by `rhs`.
882 /// Returns a tuple of the divisor along with a boolean indicating
883 /// whether an arithmetic overflow would occur. If an overflow would
884 /// occur then self is returned.
888 /// This function will panic if `rhs` is 0.
897 /// assert_eq!(5i32.overflowing_div(2), (2, false));
898 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
901 #[stable(feature = "wrapping", since = "1.7.0")]
902 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
903 if self == Self::min_value() && rhs == -1 {
910 /// Calculates the remainder when `self` is divided by `rhs`.
912 /// Returns a tuple of the remainder after dividing along with a boolean
913 /// indicating whether an arithmetic overflow would occur. If an
914 /// overflow would occur then 0 is returned.
918 /// This function will panic if `rhs` is 0.
927 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
928 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
931 #[stable(feature = "wrapping", since = "1.7.0")]
932 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
933 if self == Self::min_value() && rhs == -1 {
940 /// Negates self, overflowing if this is equal to the minimum value.
942 /// Returns a tuple of the negated version of self along with a boolean
943 /// indicating whether an overflow happened. If `self` is the minimum
944 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
945 /// value will be returned again and `true` will be returned for an
946 /// overflow happening.
955 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
956 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
959 #[stable(feature = "wrapping", since = "1.7.0")]
960 pub fn overflowing_neg(self) -> (Self, bool) {
961 if self == Self::min_value() {
962 (Self::min_value(), true)
968 /// Shifts self left by `rhs` bits.
970 /// Returns a tuple of the shifted version of self along with a boolean
971 /// indicating whether the shift value was larger than or equal to the
972 /// number of bits. If the shift value is too large, then value is
973 /// masked (N-1) where N is the number of bits, and this value is then
974 /// used to perform the shift.
981 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
982 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
985 #[stable(feature = "wrapping", since = "1.7.0")]
986 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
987 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
990 /// Shifts self right by `rhs` bits.
992 /// Returns a tuple of the shifted version of self along with a boolean
993 /// indicating whether the shift value was larger than or equal to the
994 /// number of bits. If the shift value is too large, then value is
995 /// masked (N-1) where N is the number of bits, and this value is then
996 /// used to perform the shift.
1003 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
1004 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1007 #[stable(feature = "wrapping", since = "1.7.0")]
1008 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1009 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1012 /// Raises self to the power of `exp`, using exponentiation by squaring.
1019 /// let x: i32 = 2; // or any other integer type
1021 /// assert_eq!(x.pow(4), 16);
1023 #[stable(feature = "rust1", since = "1.0.0")]
1025 #[rustc_no_mir] // FIXME #29769 MIR overflow checking is TBD.
1026 pub fn pow(self, mut exp: u32) -> Self {
1027 let mut base = self;
1028 let mut acc = Self::one();
1038 // Deal with the final bit of the exponent separately, since
1039 // squaring the base afterwards is not necessary and may cause a
1040 // needless overflow.
1048 /// Computes the absolute value of `self`.
1050 /// # Overflow behavior
1052 /// The absolute value of `i32::min_value()` cannot be represented as an
1053 /// `i32`, and attempting to calculate it will cause an overflow. This
1054 /// means that code in debug mode will trigger a panic on this case and
1055 /// optimized code will return `i32::min_value()` without a panic.
1062 /// assert_eq!(10i8.abs(), 10);
1063 /// assert_eq!((-10i8).abs(), 10);
1065 #[stable(feature = "rust1", since = "1.0.0")]
1067 #[rustc_no_mir] // FIXME #29769 MIR overflow checking is TBD.
1068 pub fn abs(self) -> Self {
1069 if self.is_negative() {
1070 // Note that the #[inline] above means that the overflow
1071 // semantics of this negation depend on the crate we're being
1079 /// Returns a number representing sign of `self`.
1081 /// - `0` if the number is zero
1082 /// - `1` if the number is positive
1083 /// - `-1` if the number is negative
1090 /// assert_eq!(10i8.signum(), 1);
1091 /// assert_eq!(0i8.signum(), 0);
1092 /// assert_eq!((-10i8).signum(), -1);
1094 #[stable(feature = "rust1", since = "1.0.0")]
1096 pub fn signum(self) -> Self {
1104 /// Returns `true` if `self` is positive and `false` if the number
1105 /// is zero or negative.
1112 /// assert!(10i8.is_positive());
1113 /// assert!(!(-10i8).is_positive());
1115 #[stable(feature = "rust1", since = "1.0.0")]
1117 pub fn is_positive(self) -> bool { self > 0 }
1119 /// Returns `true` if `self` is negative and `false` if the number
1120 /// is zero or positive.
1127 /// assert!((-10i8).is_negative());
1128 /// assert!(!10i8.is_negative());
1130 #[stable(feature = "rust1", since = "1.0.0")]
1132 pub fn is_negative(self) -> bool { self < 0 }
1138 int_impl! { i8, u8, 8,
1139 intrinsics::add_with_overflow,
1140 intrinsics::sub_with_overflow,
1141 intrinsics::mul_with_overflow }
1146 int_impl! { i16, u16, 16,
1147 intrinsics::add_with_overflow,
1148 intrinsics::sub_with_overflow,
1149 intrinsics::mul_with_overflow }
1154 int_impl! { i32, u32, 32,
1155 intrinsics::add_with_overflow,
1156 intrinsics::sub_with_overflow,
1157 intrinsics::mul_with_overflow }
1162 int_impl! { i64, u64, 64,
1163 intrinsics::add_with_overflow,
1164 intrinsics::sub_with_overflow,
1165 intrinsics::mul_with_overflow }
1168 #[cfg(target_pointer_width = "32")]
1171 int_impl! { i32, u32, 32,
1172 intrinsics::add_with_overflow,
1173 intrinsics::sub_with_overflow,
1174 intrinsics::mul_with_overflow }
1177 #[cfg(target_pointer_width = "64")]
1180 int_impl! { i64, u64, 64,
1181 intrinsics::add_with_overflow,
1182 intrinsics::sub_with_overflow,
1183 intrinsics::mul_with_overflow }
1186 // `Int` + `UnsignedInt` implemented for unsigned integers
1187 macro_rules! uint_impl {
1188 ($ActualT:ty, $BITS:expr,
1193 $add_with_overflow:path,
1194 $sub_with_overflow:path,
1195 $mul_with_overflow:path) => {
1196 /// Returns the smallest value that can be represented by this integer type.
1197 #[stable(feature = "rust1", since = "1.0.0")]
1199 pub const fn min_value() -> Self { 0 }
1201 /// Returns the largest value that can be represented by this integer type.
1202 #[stable(feature = "rust1", since = "1.0.0")]
1204 pub const fn max_value() -> Self { !0 }
1206 /// Converts a string slice in a given base to an integer.
1208 /// Leading and trailing whitespace represent an error.
1215 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1219 from_str_radix(src, radix)
1222 /// Returns the number of ones in the binary representation of `self`.
1229 /// let n = 0b01001100u8;
1231 /// assert_eq!(n.count_ones(), 3);
1233 #[stable(feature = "rust1", since = "1.0.0")]
1235 pub fn count_ones(self) -> u32 {
1236 unsafe { $ctpop(self as $ActualT) as u32 }
1239 /// Returns the number of zeros in the binary representation of `self`.
1246 /// let n = 0b01001100u8;
1248 /// assert_eq!(n.count_zeros(), 5);
1250 #[stable(feature = "rust1", since = "1.0.0")]
1252 pub fn count_zeros(self) -> u32 {
1253 (!self).count_ones()
1256 /// Returns the number of leading zeros in the binary representation
1264 /// let n = 0b0101000u16;
1266 /// assert_eq!(n.leading_zeros(), 10);
1268 #[stable(feature = "rust1", since = "1.0.0")]
1270 pub fn leading_zeros(self) -> u32 {
1271 unsafe { $ctlz(self as $ActualT) as u32 }
1274 /// Returns the number of trailing zeros in the binary representation
1282 /// let n = 0b0101000u16;
1284 /// assert_eq!(n.trailing_zeros(), 3);
1286 #[stable(feature = "rust1", since = "1.0.0")]
1288 pub fn trailing_zeros(self) -> u32 {
1289 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1290 // emits two conditional moves on x86_64. By promoting the value to
1291 // u16 and setting bit 8, we get better code without any conditional
1293 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1294 // pending, remove this workaround once LLVM generates better code
1298 intrinsics::cttz(self as u16 | 0x100) as u32
1300 intrinsics::cttz(self) as u32
1305 /// Shifts the bits to the left by a specified amount, `n`,
1306 /// wrapping the truncated bits to the end of the resulting integer.
1313 /// let n = 0x0123456789ABCDEFu64;
1314 /// let m = 0x3456789ABCDEF012u64;
1316 /// assert_eq!(n.rotate_left(12), m);
1318 #[stable(feature = "rust1", since = "1.0.0")]
1320 pub fn rotate_left(self, n: u32) -> Self {
1321 // Protect against undefined behaviour for over-long bit shifts
1323 (self << n) | (self >> (($BITS - n) % $BITS))
1326 /// Shifts the bits to the right by a specified amount, `n`,
1327 /// wrapping the truncated bits to the beginning of the resulting
1335 /// let n = 0x0123456789ABCDEFu64;
1336 /// let m = 0xDEF0123456789ABCu64;
1338 /// assert_eq!(n.rotate_right(12), m);
1340 #[stable(feature = "rust1", since = "1.0.0")]
1342 pub fn rotate_right(self, n: u32) -> Self {
1343 // Protect against undefined behaviour for over-long bit shifts
1345 (self >> n) | (self << (($BITS - n) % $BITS))
1348 /// Reverses the byte order of the integer.
1355 /// let n = 0x0123456789ABCDEFu64;
1356 /// let m = 0xEFCDAB8967452301u64;
1358 /// assert_eq!(n.swap_bytes(), m);
1360 #[stable(feature = "rust1", since = "1.0.0")]
1362 pub fn swap_bytes(self) -> Self {
1363 unsafe { $bswap(self as $ActualT) as Self }
1366 /// Converts an integer from big endian to the target's endianness.
1368 /// On big endian this is a no-op. On little endian the bytes are
1376 /// let n = 0x0123456789ABCDEFu64;
1378 /// if cfg!(target_endian = "big") {
1379 /// assert_eq!(u64::from_be(n), n)
1381 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1384 #[stable(feature = "rust1", since = "1.0.0")]
1386 pub fn from_be(x: Self) -> Self {
1387 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1390 /// Converts an integer from little endian to the target's endianness.
1392 /// On little endian this is a no-op. On big endian the bytes are
1400 /// let n = 0x0123456789ABCDEFu64;
1402 /// if cfg!(target_endian = "little") {
1403 /// assert_eq!(u64::from_le(n), n)
1405 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1408 #[stable(feature = "rust1", since = "1.0.0")]
1410 pub fn from_le(x: Self) -> Self {
1411 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1414 /// Converts `self` to big endian from the target's endianness.
1416 /// On big endian this is a no-op. On little endian the bytes are
1424 /// let n = 0x0123456789ABCDEFu64;
1426 /// if cfg!(target_endian = "big") {
1427 /// assert_eq!(n.to_be(), n)
1429 /// assert_eq!(n.to_be(), n.swap_bytes())
1432 #[stable(feature = "rust1", since = "1.0.0")]
1434 pub fn to_be(self) -> Self { // or not to be?
1435 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1438 /// Converts `self` to little endian from the target's endianness.
1440 /// On little endian this is a no-op. On big endian the bytes are
1448 /// let n = 0x0123456789ABCDEFu64;
1450 /// if cfg!(target_endian = "little") {
1451 /// assert_eq!(n.to_le(), n)
1453 /// assert_eq!(n.to_le(), n.swap_bytes())
1456 #[stable(feature = "rust1", since = "1.0.0")]
1458 pub fn to_le(self) -> Self {
1459 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1462 /// Checked integer addition. Computes `self + other`, returning `None`
1463 /// if overflow occurred.
1470 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1471 /// assert_eq!(6u16.checked_add(65530), None);
1473 #[stable(feature = "rust1", since = "1.0.0")]
1475 pub fn checked_add(self, other: Self) -> Option<Self> {
1476 let (a, b) = self.overflowing_add(other);
1477 if b {None} else {Some(a)}
1480 /// Checked integer subtraction. Computes `self - other`, returning
1481 /// `None` if underflow occurred.
1488 /// assert_eq!(1u8.checked_sub(1), Some(0));
1489 /// assert_eq!(0u8.checked_sub(1), None);
1491 #[stable(feature = "rust1", since = "1.0.0")]
1493 pub fn checked_sub(self, other: Self) -> Option<Self> {
1494 let (a, b) = self.overflowing_sub(other);
1495 if b {None} else {Some(a)}
1498 /// Checked integer multiplication. Computes `self * other`, returning
1499 /// `None` if underflow or overflow occurred.
1506 /// assert_eq!(5u8.checked_mul(51), Some(255));
1507 /// assert_eq!(5u8.checked_mul(52), None);
1509 #[stable(feature = "rust1", since = "1.0.0")]
1511 pub fn checked_mul(self, other: Self) -> Option<Self> {
1512 let (a, b) = self.overflowing_mul(other);
1513 if b {None} else {Some(a)}
1516 /// Checked integer division. Computes `self / other`, returning `None`
1517 /// if `other == 0` or the operation results in underflow or overflow.
1524 /// assert_eq!(128u8.checked_div(2), Some(64));
1525 /// assert_eq!(1u8.checked_div(0), None);
1527 #[stable(feature = "rust1", since = "1.0.0")]
1529 pub fn checked_div(self, other: Self) -> Option<Self> {
1532 other => Some(self / other),
1536 /// Checked integer remainder. Computes `self % other`, returning `None`
1537 /// if `other == 0` or the operation results in underflow or overflow.
1544 /// assert_eq!(5u32.checked_rem(2), Some(1));
1545 /// assert_eq!(5u32.checked_rem(0), None);
1547 #[stable(feature = "wrapping", since = "1.7.0")]
1549 pub fn checked_rem(self, other: Self) -> Option<Self> {
1557 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1560 /// Note that negating any positive integer will overflow.
1567 /// assert_eq!(0u32.checked_neg(), Some(0));
1568 /// assert_eq!(1u32.checked_neg(), None);
1570 #[stable(feature = "wrapping", since = "1.7.0")]
1572 pub fn checked_neg(self) -> Option<Self> {
1573 let (a, b) = self.overflowing_neg();
1574 if b {None} else {Some(a)}
1577 /// Checked shift left. Computes `self << rhs`, returning `None`
1578 /// if `rhs` is larger than or equal to the number of bits in `self`.
1585 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1586 /// assert_eq!(0x10u32.checked_shl(33), None);
1588 #[stable(feature = "wrapping", since = "1.7.0")]
1590 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1591 let (a, b) = self.overflowing_shl(rhs);
1592 if b {None} else {Some(a)}
1595 /// Checked shift right. Computes `self >> rhs`, returning `None`
1596 /// if `rhs` is larger than or equal to the number of bits in `self`.
1603 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1604 /// assert_eq!(0x10u32.checked_shr(33), None);
1606 #[stable(feature = "wrapping", since = "1.7.0")]
1608 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1609 let (a, b) = self.overflowing_shr(rhs);
1610 if b {None} else {Some(a)}
1613 /// Saturating integer addition. Computes `self + other`, saturating at
1614 /// the numeric bounds instead of overflowing.
1621 /// assert_eq!(100u8.saturating_add(1), 101);
1622 /// assert_eq!(200u8.saturating_add(127), 255);
1624 #[stable(feature = "rust1", since = "1.0.0")]
1626 pub fn saturating_add(self, other: Self) -> Self {
1627 match self.checked_add(other) {
1629 None => Self::max_value(),
1633 /// Saturating integer subtraction. Computes `self - other`, saturating
1634 /// at the numeric bounds instead of overflowing.
1641 /// assert_eq!(100u8.saturating_sub(27), 73);
1642 /// assert_eq!(13u8.saturating_sub(127), 0);
1644 #[stable(feature = "rust1", since = "1.0.0")]
1646 pub fn saturating_sub(self, other: Self) -> Self {
1647 match self.checked_sub(other) {
1649 None => Self::min_value(),
1653 /// Saturating integer multiplication. Computes `self * other`,
1654 /// saturating at the numeric bounds instead of overflowing.
1663 /// assert_eq!(100u32.saturating_mul(127), 12700);
1664 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1666 #[stable(feature = "wrapping", since = "1.7.0")]
1668 pub fn saturating_mul(self, other: Self) -> Self {
1669 self.checked_mul(other).unwrap_or(Self::max_value())
1672 /// Wrapping (modular) addition. Computes `self + other`,
1673 /// wrapping around at the boundary of the type.
1680 /// assert_eq!(200u8.wrapping_add(55), 255);
1681 /// assert_eq!(200u8.wrapping_add(155), 99);
1683 #[stable(feature = "rust1", since = "1.0.0")]
1685 pub fn wrapping_add(self, rhs: Self) -> Self {
1687 intrinsics::overflowing_add(self, rhs)
1691 /// Wrapping (modular) subtraction. Computes `self - other`,
1692 /// wrapping around at the boundary of the type.
1699 /// assert_eq!(100u8.wrapping_sub(100), 0);
1700 /// assert_eq!(100u8.wrapping_sub(155), 201);
1702 #[stable(feature = "rust1", since = "1.0.0")]
1704 pub fn wrapping_sub(self, rhs: Self) -> Self {
1706 intrinsics::overflowing_sub(self, rhs)
1710 /// Wrapping (modular) multiplication. Computes `self *
1711 /// other`, wrapping around at the boundary of the type.
1718 /// assert_eq!(10u8.wrapping_mul(12), 120);
1719 /// assert_eq!(25u8.wrapping_mul(12), 44);
1721 #[stable(feature = "rust1", since = "1.0.0")]
1723 pub fn wrapping_mul(self, rhs: Self) -> Self {
1725 intrinsics::overflowing_mul(self, rhs)
1729 /// Wrapping (modular) division. Computes `self / other`.
1730 /// Wrapped division on unsigned types is just normal division.
1731 /// There's no way wrapping could ever happen.
1732 /// This function exists, so that all operations
1733 /// are accounted for in the wrapping operations.
1740 /// assert_eq!(100u8.wrapping_div(10), 10);
1742 #[stable(feature = "num_wrapping", since = "1.2.0")]
1744 pub fn wrapping_div(self, rhs: Self) -> Self {
1748 /// Wrapping (modular) remainder. Computes `self % other`.
1749 /// Wrapped remainder calculation on unsigned types is
1750 /// just the regular remainder calculation.
1751 /// There's no way wrapping could ever happen.
1752 /// This function exists, so that all operations
1753 /// are accounted for in the wrapping operations.
1760 /// assert_eq!(100u8.wrapping_rem(10), 0);
1762 #[stable(feature = "num_wrapping", since = "1.2.0")]
1764 pub fn wrapping_rem(self, rhs: Self) -> Self {
1768 /// Wrapping (modular) negation. Computes `-self`,
1769 /// wrapping around at the boundary of the type.
1771 /// Since unsigned types do not have negative equivalents
1772 /// all applications of this function will wrap (except for `-0`).
1773 /// For values smaller than the corresponding signed type's maximum
1774 /// the result is the same as casting the corresponding signed value.
1775 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1776 /// `MAX` is the corresponding signed type's maximum.
1783 /// assert_eq!(100u8.wrapping_neg(), 156);
1784 /// assert_eq!(0u8.wrapping_neg(), 0);
1785 /// assert_eq!(180u8.wrapping_neg(), 76);
1786 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1788 #[stable(feature = "num_wrapping", since = "1.2.0")]
1790 pub fn wrapping_neg(self) -> Self {
1791 self.overflowing_neg().0
1794 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1795 /// where `mask` removes any high-order bits of `rhs` that
1796 /// would cause the shift to exceed the bitwidth of the type.
1798 /// Note that this is *not* the same as a rotate-left; the
1799 /// RHS of a wrapping shift-left is restricted to the range
1800 /// of the type, rather than the bits shifted out of the LHS
1801 /// being returned to the other end. The primitive integer
1802 /// types all implement a `rotate_left` function, which may
1803 /// be what you want instead.
1810 /// assert_eq!(1u8.wrapping_shl(7), 128);
1811 /// assert_eq!(1u8.wrapping_shl(8), 1);
1813 #[stable(feature = "num_wrapping", since = "1.2.0")]
1815 pub fn wrapping_shl(self, rhs: u32) -> Self {
1816 self.overflowing_shl(rhs).0
1819 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1820 /// where `mask` removes any high-order bits of `rhs` that
1821 /// would cause the shift to exceed the bitwidth of the type.
1823 /// Note that this is *not* the same as a rotate-right; the
1824 /// RHS of a wrapping shift-right is restricted to the range
1825 /// of the type, rather than the bits shifted out of the LHS
1826 /// being returned to the other end. The primitive integer
1827 /// types all implement a `rotate_right` function, which may
1828 /// be what you want instead.
1835 /// assert_eq!(128u8.wrapping_shr(7), 1);
1836 /// assert_eq!(128u8.wrapping_shr(8), 128);
1838 #[stable(feature = "num_wrapping", since = "1.2.0")]
1840 pub fn wrapping_shr(self, rhs: u32) -> Self {
1841 self.overflowing_shr(rhs).0
1844 /// Calculates `self` + `rhs`
1846 /// Returns a tuple of the addition along with a boolean indicating
1847 /// whether an arithmetic overflow would occur. If an overflow would
1848 /// have occurred then the wrapped value is returned.
1857 /// assert_eq!(5u32.overflowing_add(2), (7, false));
1858 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
1861 #[stable(feature = "wrapping", since = "1.7.0")]
1862 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1864 let (a, b) = $add_with_overflow(self as $ActualT,
1870 /// Calculates `self` - `rhs`
1872 /// Returns a tuple of the subtraction along with a boolean indicating
1873 /// whether an arithmetic overflow would occur. If an overflow would
1874 /// have occurred then the wrapped value is returned.
1883 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
1884 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
1887 #[stable(feature = "wrapping", since = "1.7.0")]
1888 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1890 let (a, b) = $sub_with_overflow(self as $ActualT,
1896 /// Calculates the multiplication of `self` and `rhs`.
1898 /// Returns a tuple of the multiplication along with a boolean
1899 /// indicating whether an arithmetic overflow would occur. If an
1900 /// overflow would have occurred then the wrapped value is returned.
1907 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1908 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1911 #[stable(feature = "wrapping", since = "1.7.0")]
1912 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1914 let (a, b) = $mul_with_overflow(self as $ActualT,
1920 /// Calculates the divisor when `self` is divided by `rhs`.
1922 /// Returns a tuple of the divisor along with a boolean indicating
1923 /// whether an arithmetic overflow would occur. Note that for unsigned
1924 /// integers overflow never occurs, so the second value is always
1929 /// This function will panic if `rhs` is 0.
1936 /// assert_eq!(5u32.overflowing_div(2), (2, false));
1939 #[stable(feature = "wrapping", since = "1.7.0")]
1940 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1944 /// Calculates the remainder when `self` is divided by `rhs`.
1946 /// Returns a tuple of the remainder after dividing along with a boolean
1947 /// indicating whether an arithmetic overflow would occur. Note that for
1948 /// unsigned integers overflow never occurs, so the second value is
1953 /// This function will panic if `rhs` is 0.
1960 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
1963 #[stable(feature = "wrapping", since = "1.7.0")]
1964 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1968 /// Negates self in an overflowing fashion.
1970 /// Returns `!self + 1` using wrapping operations to return the value
1971 /// that represents the negation of this unsigned value. Note that for
1972 /// positive unsigned values overflow always occurs, but negating 0 does
1980 /// assert_eq!(0u32.overflowing_neg(), (0, false));
1981 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
1984 #[stable(feature = "wrapping", since = "1.7.0")]
1985 pub fn overflowing_neg(self) -> (Self, bool) {
1986 ((!self).wrapping_add(1), self != 0)
1989 /// Shifts self left by `rhs` bits.
1991 /// Returns a tuple of the shifted version of self along with a boolean
1992 /// indicating whether the shift value was larger than or equal to the
1993 /// number of bits. If the shift value is too large, then value is
1994 /// masked (N-1) where N is the number of bits, and this value is then
1995 /// used to perform the shift.
2002 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
2003 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
2006 #[stable(feature = "wrapping", since = "1.7.0")]
2007 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2008 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
2011 /// Shifts self right by `rhs` bits.
2013 /// Returns a tuple of the shifted version of self along with a boolean
2014 /// indicating whether the shift value was larger than or equal to the
2015 /// number of bits. If the shift value is too large, then value is
2016 /// masked (N-1) where N is the number of bits, and this value is then
2017 /// used to perform the shift.
2024 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
2025 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2028 #[stable(feature = "wrapping", since = "1.7.0")]
2029 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2030 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
2033 /// Raises self to the power of `exp`, using exponentiation by squaring.
2040 /// assert_eq!(2u32.pow(4), 16);
2042 #[stable(feature = "rust1", since = "1.0.0")]
2044 #[rustc_no_mir] // FIXME #29769 MIR overflow checking is TBD.
2045 pub fn pow(self, mut exp: u32) -> Self {
2046 let mut base = self;
2047 let mut acc = Self::one();
2049 let mut prev_base = self;
2050 let mut base_oflo = false;
2054 // ensure overflow occurs in the same manner it
2055 // would have otherwise (i.e. signal any exception
2056 // it would have otherwise).
2057 acc = acc * (prev_base * prev_base);
2063 let (new_base, new_base_oflo) = base.overflowing_mul(base);
2065 base_oflo = new_base_oflo;
2071 /// Returns `true` if and only if `self == 2^k` for some `k`.
2078 /// assert!(16u8.is_power_of_two());
2079 /// assert!(!10u8.is_power_of_two());
2081 #[stable(feature = "rust1", since = "1.0.0")]
2083 pub fn is_power_of_two(self) -> bool {
2084 (self.wrapping_sub(Self::one())) & self == Self::zero() &&
2085 !(self == Self::zero())
2088 /// Returns the smallest power of two greater than or equal to `self`.
2089 /// Unspecified behavior on overflow.
2096 /// assert_eq!(2u8.next_power_of_two(), 2);
2097 /// assert_eq!(3u8.next_power_of_two(), 4);
2099 #[stable(feature = "rust1", since = "1.0.0")]
2101 pub fn next_power_of_two(self) -> Self {
2102 let bits = size_of::<Self>() * 8;
2103 let one: Self = Self::one();
2104 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
2107 /// Returns the smallest power of two greater than or equal to `n`. If
2108 /// the next power of two is greater than the type's maximum value,
2109 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2116 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2117 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2118 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2120 #[stable(feature = "rust1", since = "1.0.0")]
2121 pub fn checked_next_power_of_two(self) -> Option<Self> {
2122 let npot = self.next_power_of_two();
2139 intrinsics::add_with_overflow,
2140 intrinsics::sub_with_overflow,
2141 intrinsics::mul_with_overflow }
2146 uint_impl! { u16, 16,
2151 intrinsics::add_with_overflow,
2152 intrinsics::sub_with_overflow,
2153 intrinsics::mul_with_overflow }
2158 uint_impl! { u32, 32,
2163 intrinsics::add_with_overflow,
2164 intrinsics::sub_with_overflow,
2165 intrinsics::mul_with_overflow }
2170 uint_impl! { u64, 64,
2175 intrinsics::add_with_overflow,
2176 intrinsics::sub_with_overflow,
2177 intrinsics::mul_with_overflow }
2180 #[cfg(target_pointer_width = "32")]
2183 uint_impl! { u32, 32,
2188 intrinsics::add_with_overflow,
2189 intrinsics::sub_with_overflow,
2190 intrinsics::mul_with_overflow }
2193 #[cfg(target_pointer_width = "64")]
2196 uint_impl! { u64, 64,
2201 intrinsics::add_with_overflow,
2202 intrinsics::sub_with_overflow,
2203 intrinsics::mul_with_overflow }
2206 /// A classification of floating point numbers.
2208 /// This `enum` is used as the return type for [`f32::classify()`] and [`f64::classify()`]. See
2209 /// their documentation for more.
2211 /// [`f32::classify()`]: ../../std/primitive.f32.html#method.classify
2212 /// [`f64::classify()`]: ../../std/primitive.f64.html#method.classify
2213 #[derive(Copy, Clone, PartialEq, Debug)]
2214 #[stable(feature = "rust1", since = "1.0.0")]
2215 pub enum FpCategory {
2216 /// "Not a Number", often obtained by dividing by zero
2217 #[stable(feature = "rust1", since = "1.0.0")]
2220 /// Positive or negative infinity
2221 #[stable(feature = "rust1", since = "1.0.0")]
2224 /// Positive or negative zero
2225 #[stable(feature = "rust1", since = "1.0.0")]
2228 /// De-normalized floating point representation (less precise than `Normal`)
2229 #[stable(feature = "rust1", since = "1.0.0")]
2232 /// A regular floating point number
2233 #[stable(feature = "rust1", since = "1.0.0")]
2237 /// A built-in floating point number.
2239 #[unstable(feature = "core_float",
2240 reason = "stable interface is via `impl f{32,64}` in later crates",
2242 pub trait Float: Sized {
2243 /// Returns the NaN value.
2244 #[unstable(feature = "float_extras", reason = "needs removal",
2247 /// Returns the infinite value.
2248 #[unstable(feature = "float_extras", reason = "needs removal",
2250 fn infinity() -> Self;
2251 /// Returns the negative infinite value.
2252 #[unstable(feature = "float_extras", reason = "needs removal",
2254 fn neg_infinity() -> Self;
2256 #[unstable(feature = "float_extras", reason = "needs removal",
2258 fn neg_zero() -> Self;
2260 #[unstable(feature = "float_extras", reason = "needs removal",
2264 #[unstable(feature = "float_extras", reason = "needs removal",
2268 /// Returns true if this value is NaN and false otherwise.
2269 #[stable(feature = "core", since = "1.6.0")]
2270 fn is_nan(self) -> bool;
2271 /// Returns true if this value is positive infinity or negative infinity and
2272 /// false otherwise.
2273 #[stable(feature = "core", since = "1.6.0")]
2274 fn is_infinite(self) -> bool;
2275 /// Returns true if this number is neither infinite nor NaN.
2276 #[stable(feature = "core", since = "1.6.0")]
2277 fn is_finite(self) -> bool;
2278 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
2279 #[stable(feature = "core", since = "1.6.0")]
2280 fn is_normal(self) -> bool;
2281 /// Returns the category that this number falls into.
2282 #[stable(feature = "core", since = "1.6.0")]
2283 fn classify(self) -> FpCategory;
2285 /// Returns the mantissa, exponent and sign as integers, respectively.
2286 #[unstable(feature = "float_extras", reason = "signature is undecided",
2288 fn integer_decode(self) -> (u64, i16, i8);
2290 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2291 /// number is `Float::nan()`.
2292 #[stable(feature = "core", since = "1.6.0")]
2293 fn abs(self) -> Self;
2294 /// Returns a number that represents the sign of `self`.
2296 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2297 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2298 /// - `Float::nan()` if the number is `Float::nan()`
2299 #[stable(feature = "core", since = "1.6.0")]
2300 fn signum(self) -> Self;
2302 /// Returns `true` if `self` is positive, including `+0.0` and
2303 /// `Float::infinity()`.
2304 #[stable(feature = "core", since = "1.6.0")]
2305 fn is_sign_positive(self) -> bool;
2306 /// Returns `true` if `self` is negative, including `-0.0` and
2307 /// `Float::neg_infinity()`.
2308 #[stable(feature = "core", since = "1.6.0")]
2309 fn is_sign_negative(self) -> bool;
2311 /// Take the reciprocal (inverse) of a number, `1/x`.
2312 #[stable(feature = "core", since = "1.6.0")]
2313 fn recip(self) -> Self;
2315 /// Raise a number to an integer power.
2317 /// Using this function is generally faster than using `powf`
2318 #[stable(feature = "core", since = "1.6.0")]
2319 fn powi(self, n: i32) -> Self;
2321 /// Convert radians to degrees.
2322 #[unstable(feature = "float_extras", reason = "desirability is unclear",
2324 fn to_degrees(self) -> Self;
2325 /// Convert degrees to radians.
2326 #[unstable(feature = "float_extras", reason = "desirability is unclear",
2328 fn to_radians(self) -> Self;
2331 macro_rules! from_str_radix_int_impl {
2333 #[stable(feature = "rust1", since = "1.0.0")]
2334 impl FromStr for $t {
2335 type Err = ParseIntError;
2336 fn from_str(src: &str) -> Result<Self, ParseIntError> {
2337 from_str_radix(src, 10)
2342 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
2345 trait FromStrRadixHelper: PartialOrd + Copy {
2346 fn min_value() -> Self;
2347 fn from_u32(u: u32) -> Self;
2348 fn checked_mul(&self, other: u32) -> Option<Self>;
2349 fn checked_sub(&self, other: u32) -> Option<Self>;
2350 fn checked_add(&self, other: u32) -> Option<Self>;
2354 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
2355 fn min_value() -> Self { Self::min_value() }
2356 fn from_u32(u: u32) -> Self { u as Self }
2357 fn checked_mul(&self, other: u32) -> Option<Self> {
2358 Self::checked_mul(*self, other as Self)
2360 fn checked_sub(&self, other: u32) -> Option<Self> {
2361 Self::checked_sub(*self, other as Self)
2363 fn checked_add(&self, other: u32) -> Option<Self> {
2364 Self::checked_add(*self, other as Self)
2368 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
2370 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
2371 -> Result<T, ParseIntError> {
2372 use self::IntErrorKind::*;
2373 use self::ParseIntError as PIE;
2375 assert!(radix >= 2 && radix <= 36,
2376 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2380 return Err(PIE { kind: Empty });
2383 let is_signed_ty = T::from_u32(0) > T::min_value();
2385 // all valid digits are ascii, so we will just iterate over the utf8 bytes
2386 // and cast them to chars. .to_digit() will safely return None for anything
2387 // other than a valid ascii digit for the given radix, including the first-byte
2388 // of multi-byte sequences
2389 let src = src.as_bytes();
2391 let (is_positive, digits) = match src[0] {
2392 b'+' => (true, &src[1..]),
2393 b'-' if is_signed_ty => (false, &src[1..]),
2397 if digits.is_empty() {
2398 return Err(PIE { kind: Empty });
2401 let mut result = T::from_u32(0);
2403 // The number is positive
2405 let x = match (c as char).to_digit(radix) {
2407 None => return Err(PIE { kind: InvalidDigit }),
2409 result = match result.checked_mul(radix) {
2410 Some(result) => result,
2411 None => return Err(PIE { kind: Overflow }),
2413 result = match result.checked_add(x) {
2414 Some(result) => result,
2415 None => return Err(PIE { kind: Overflow }),
2419 // The number is negative
2421 let x = match (c as char).to_digit(radix) {
2423 None => return Err(PIE { kind: InvalidDigit }),
2425 result = match result.checked_mul(radix) {
2426 Some(result) => result,
2427 None => return Err(PIE { kind: Underflow }),
2429 result = match result.checked_sub(x) {
2430 Some(result) => result,
2431 None => return Err(PIE { kind: Underflow }),
2438 /// An error which can be returned when parsing an integer.
2440 /// This error is used as the error type for the `from_str_radix()` functions
2441 /// on the primitive integer types, such as [`i8::from_str_radix()`].
2443 /// [`i8::from_str_radix()`]: ../../std/primitive.i8.html#method.from_str_radix
2444 #[derive(Debug, Clone, PartialEq)]
2445 #[stable(feature = "rust1", since = "1.0.0")]
2446 pub struct ParseIntError { kind: IntErrorKind }
2448 #[derive(Debug, Clone, PartialEq)]
2456 impl ParseIntError {
2457 #[unstable(feature = "int_error_internals",
2458 reason = "available through Error trait and this method should \
2459 not be exposed publicly",
2462 pub fn __description(&self) -> &str {
2464 IntErrorKind::Empty => "cannot parse integer from empty string",
2465 IntErrorKind::InvalidDigit => "invalid digit found in string",
2466 IntErrorKind::Overflow => "number too large to fit in target type",
2467 IntErrorKind::Underflow => "number too small to fit in target type",
2472 #[stable(feature = "rust1", since = "1.0.0")]
2473 impl fmt::Display for ParseIntError {
2474 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2475 self.__description().fmt(f)
2479 #[stable(feature = "rust1", since = "1.0.0")]
2480 pub use num::dec2flt::ParseFloatError;
2482 // Conversion traits for primitive integer and float types
2483 // Conversions T -> T are covered by a blanket impl and therefore excluded
2484 // Some conversions from and to usize/isize are not implemented due to portability concerns
2485 macro_rules! impl_from {
2486 ($Small: ty, $Large: ty) => {
2487 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
2488 impl From<$Small> for $Large {
2490 fn from(small: $Small) -> $Large {
2497 // Unsigned -> Unsigned
2498 impl_from! { u8, u16 }
2499 impl_from! { u8, u32 }
2500 impl_from! { u8, u64 }
2501 impl_from! { u8, usize }
2502 impl_from! { u16, u32 }
2503 impl_from! { u16, u64 }
2504 impl_from! { u32, u64 }
2507 impl_from! { i8, i16 }
2508 impl_from! { i8, i32 }
2509 impl_from! { i8, i64 }
2510 impl_from! { i8, isize }
2511 impl_from! { i16, i32 }
2512 impl_from! { i16, i64 }
2513 impl_from! { i32, i64 }
2515 // Unsigned -> Signed
2516 impl_from! { u8, i16 }
2517 impl_from! { u8, i32 }
2518 impl_from! { u8, i64 }
2519 impl_from! { u16, i32 }
2520 impl_from! { u16, i64 }
2521 impl_from! { u32, i64 }
2523 // Note: integers can only be represented with full precision in a float if
2524 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2525 // Lossy float conversions are not implemented at this time.
2528 impl_from! { i8, f32 }
2529 impl_from! { i8, f64 }
2530 impl_from! { i16, f32 }
2531 impl_from! { i16, f64 }
2532 impl_from! { i32, f64 }
2534 // Unsigned -> Float
2535 impl_from! { u8, f32 }
2536 impl_from! { u8, f64 }
2537 impl_from! { u16, f32 }
2538 impl_from! { u16, f64 }
2539 impl_from! { u32, f64 }
2542 impl_from! { f32, f64 }