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, Debug, Default)]
42 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
46 // All these modules are technically private and only exposed for libcoretest:
52 /// Types that have a "zero" value.
54 /// This trait is intended for use in conjunction with `Add`, as an identity:
55 /// `x + T::zero() == x`.
56 #[unstable(feature = "zero_one",
57 reason = "unsure of placement, wants to use associated constants",
59 pub trait Zero: Sized {
60 /// The "zero" (usually, additive identity) for this type.
64 /// Types that have a "one" value.
66 /// This trait is intended for use in conjunction with `Mul`, as an identity:
67 /// `x * T::one() == x`.
68 #[unstable(feature = "zero_one",
69 reason = "unsure of placement, wants to use associated constants",
71 pub trait One: Sized {
72 /// The "one" (usually, multiplicative identity) for this type.
76 macro_rules! zero_one_impl {
78 #[unstable(feature = "zero_one",
79 reason = "unsure of placement, wants to use associated constants",
83 fn zero() -> Self { 0 }
85 #[unstable(feature = "zero_one",
86 reason = "unsure of placement, wants to use associated constants",
90 fn one() -> Self { 1 }
94 zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
96 macro_rules! zero_one_impl_float {
98 #[unstable(feature = "zero_one",
99 reason = "unsure of placement, wants to use associated constants",
103 fn zero() -> Self { 0.0 }
105 #[unstable(feature = "zero_one",
106 reason = "unsure of placement, wants to use associated constants",
110 fn one() -> Self { 1.0 }
114 zero_one_impl_float! { f32 f64 }
116 macro_rules! checked_op {
117 ($U:ty, $op:path, $x:expr, $y:expr) => {{
118 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
119 if overflowed { None } else { Some(result as Self) }
123 // `Int` + `SignedInt` implemented for signed integers
124 macro_rules! int_impl {
125 ($ActualT:ident, $UnsignedT:ty, $BITS:expr,
126 $add_with_overflow:path,
127 $sub_with_overflow:path,
128 $mul_with_overflow:path) => {
129 /// Returns the smallest value that can be represented by this integer type.
130 #[stable(feature = "rust1", since = "1.0.0")]
132 pub const fn min_value() -> Self {
133 (-1 as Self) << ($BITS - 1)
136 /// Returns the largest value that can be represented by this integer type.
137 #[stable(feature = "rust1", since = "1.0.0")]
139 pub const fn max_value() -> Self {
143 /// Converts a string slice in a given base to an integer.
145 /// Leading and trailing whitespace represent an error.
152 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
154 #[stable(feature = "rust1", since = "1.0.0")]
155 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
156 from_str_radix(src, radix)
159 /// Returns the number of ones in the binary representation of `self`.
166 /// let n = 0b01001100u8;
168 /// assert_eq!(n.count_ones(), 3);
170 #[stable(feature = "rust1", since = "1.0.0")]
172 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
174 /// Returns the number of zeros in the binary representation of `self`.
181 /// let n = 0b01001100u8;
183 /// assert_eq!(n.count_zeros(), 5);
185 #[stable(feature = "rust1", since = "1.0.0")]
187 pub fn count_zeros(self) -> u32 {
191 /// Returns the number of leading zeros in the binary representation
199 /// let n = 0b0101000u16;
201 /// assert_eq!(n.leading_zeros(), 10);
203 #[stable(feature = "rust1", since = "1.0.0")]
205 pub fn leading_zeros(self) -> u32 {
206 (self as $UnsignedT).leading_zeros()
209 /// Returns the number of trailing zeros in the binary representation
217 /// let n = 0b0101000u16;
219 /// assert_eq!(n.trailing_zeros(), 3);
221 #[stable(feature = "rust1", since = "1.0.0")]
223 pub fn trailing_zeros(self) -> u32 {
224 (self as $UnsignedT).trailing_zeros()
227 /// Shifts the bits to the left by a specified amount, `n`,
228 /// wrapping the truncated bits to the end of the resulting integer.
235 /// let n = 0x0123456789ABCDEFu64;
236 /// let m = 0x3456789ABCDEF012u64;
238 /// assert_eq!(n.rotate_left(12), m);
240 #[stable(feature = "rust1", since = "1.0.0")]
242 pub fn rotate_left(self, n: u32) -> Self {
243 (self as $UnsignedT).rotate_left(n) as Self
246 /// Shifts the bits to the right by a specified amount, `n`,
247 /// wrapping the truncated bits to the beginning of the resulting
255 /// let n = 0x0123456789ABCDEFu64;
256 /// let m = 0xDEF0123456789ABCu64;
258 /// assert_eq!(n.rotate_right(12), m);
260 #[stable(feature = "rust1", since = "1.0.0")]
262 pub fn rotate_right(self, n: u32) -> Self {
263 (self as $UnsignedT).rotate_right(n) as Self
266 /// Reverses the byte order of the integer.
273 /// let n = 0x0123456789ABCDEFu64;
274 /// let m = 0xEFCDAB8967452301u64;
276 /// assert_eq!(n.swap_bytes(), m);
278 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn swap_bytes(self) -> Self {
281 (self as $UnsignedT).swap_bytes() as Self
284 /// Converts an integer from big endian to the target's endianness.
286 /// On big endian this is a no-op. On little endian the bytes are
294 /// let n = 0x0123456789ABCDEFu64;
296 /// if cfg!(target_endian = "big") {
297 /// assert_eq!(u64::from_be(n), n)
299 /// assert_eq!(u64::from_be(n), n.swap_bytes())
302 #[stable(feature = "rust1", since = "1.0.0")]
304 pub fn from_be(x: Self) -> Self {
305 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
308 /// Converts an integer from little endian to the target's endianness.
310 /// On little endian this is a no-op. On big endian the bytes are
318 /// let n = 0x0123456789ABCDEFu64;
320 /// if cfg!(target_endian = "little") {
321 /// assert_eq!(u64::from_le(n), n)
323 /// assert_eq!(u64::from_le(n), n.swap_bytes())
326 #[stable(feature = "rust1", since = "1.0.0")]
328 pub fn from_le(x: Self) -> Self {
329 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
332 /// Converts `self` to big endian from the target's endianness.
334 /// On big endian this is a no-op. On little endian the bytes are
342 /// let n = 0x0123456789ABCDEFu64;
344 /// if cfg!(target_endian = "big") {
345 /// assert_eq!(n.to_be(), n)
347 /// assert_eq!(n.to_be(), n.swap_bytes())
350 #[stable(feature = "rust1", since = "1.0.0")]
352 pub fn to_be(self) -> Self { // or not to be?
353 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
356 /// Converts `self` to little endian from the target's endianness.
358 /// On little endian this is a no-op. On big endian the bytes are
366 /// let n = 0x0123456789ABCDEFu64;
368 /// if cfg!(target_endian = "little") {
369 /// assert_eq!(n.to_le(), n)
371 /// assert_eq!(n.to_le(), n.swap_bytes())
374 #[stable(feature = "rust1", since = "1.0.0")]
376 pub fn to_le(self) -> Self {
377 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
380 /// Checked integer addition. Computes `self + other`, returning `None`
381 /// if overflow occurred.
388 /// assert_eq!(5u16.checked_add(65530), Some(65535));
389 /// assert_eq!(6u16.checked_add(65530), None);
391 #[stable(feature = "rust1", since = "1.0.0")]
393 pub fn checked_add(self, other: Self) -> Option<Self> {
394 let (a, b) = self.overflowing_add(other);
395 if b {None} else {Some(a)}
398 /// Checked integer subtraction. Computes `self - other`, returning
399 /// `None` if underflow occurred.
406 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
407 /// assert_eq!((-128i8).checked_sub(1), None);
409 #[stable(feature = "rust1", since = "1.0.0")]
411 pub fn checked_sub(self, other: Self) -> Option<Self> {
412 let (a, b) = self.overflowing_sub(other);
413 if b {None} else {Some(a)}
416 /// Checked integer multiplication. Computes `self * other`, returning
417 /// `None` if underflow or overflow occurred.
424 /// assert_eq!(5u8.checked_mul(51), Some(255));
425 /// assert_eq!(5u8.checked_mul(52), None);
427 #[stable(feature = "rust1", since = "1.0.0")]
429 pub fn checked_mul(self, other: Self) -> Option<Self> {
430 let (a, b) = self.overflowing_mul(other);
431 if b {None} else {Some(a)}
434 /// Checked integer division. Computes `self / other`, returning `None`
435 /// if `other == 0` or the operation results in underflow or overflow.
442 /// assert_eq!((-127i8).checked_div(-1), Some(127));
443 /// assert_eq!((-128i8).checked_div(-1), None);
444 /// assert_eq!((1i8).checked_div(0), None);
446 #[stable(feature = "rust1", since = "1.0.0")]
448 pub fn checked_div(self, other: Self) -> Option<Self> {
452 let (a, b) = self.overflowing_div(other);
453 if b {None} else {Some(a)}
457 /// Checked integer remainder. Computes `self % other`, returning `None`
458 /// if `other == 0` or the operation results in underflow or overflow.
467 /// assert_eq!(5i32.checked_rem(2), Some(1));
468 /// assert_eq!(5i32.checked_rem(0), None);
469 /// assert_eq!(i32::MIN.checked_rem(-1), None);
471 #[stable(feature = "wrapping", since = "1.7.0")]
473 pub fn checked_rem(self, other: Self) -> Option<Self> {
477 let (a, b) = self.overflowing_rem(other);
478 if b {None} else {Some(a)}
482 /// Checked negation. Computes `-self`, returning `None` if `self ==
492 /// assert_eq!(5i32.checked_neg(), Some(-5));
493 /// assert_eq!(i32::MIN.checked_neg(), None);
495 #[stable(feature = "wrapping", since = "1.7.0")]
497 pub fn checked_neg(self) -> Option<Self> {
498 let (a, b) = self.overflowing_neg();
499 if b {None} else {Some(a)}
502 /// Checked shift left. Computes `self << rhs`, returning `None`
503 /// if `rhs` is larger than or equal to the number of bits in `self`.
510 /// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
511 /// assert_eq!(0x10i32.checked_shl(33), None);
513 #[stable(feature = "wrapping", since = "1.7.0")]
515 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
516 let (a, b) = self.overflowing_shl(rhs);
517 if b {None} else {Some(a)}
520 /// Checked shift right. Computes `self >> rhs`, returning `None`
521 /// if `rhs` is larger than or equal to the number of bits in `self`.
528 /// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
529 /// assert_eq!(0x10i32.checked_shr(33), None);
531 #[stable(feature = "wrapping", since = "1.7.0")]
533 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
534 let (a, b) = self.overflowing_shr(rhs);
535 if b {None} else {Some(a)}
538 /// Saturating integer addition. Computes `self + other`, saturating at
539 /// the numeric bounds instead of overflowing.
546 /// assert_eq!(100i8.saturating_add(1), 101);
547 /// assert_eq!(100i8.saturating_add(127), 127);
549 #[stable(feature = "rust1", since = "1.0.0")]
551 pub fn saturating_add(self, other: Self) -> Self {
552 match self.checked_add(other) {
554 None if other >= Self::zero() => Self::max_value(),
555 None => Self::min_value(),
559 /// Saturating integer subtraction. Computes `self - other`, saturating
560 /// at the numeric bounds instead of overflowing.
567 /// assert_eq!(100i8.saturating_sub(127), -27);
568 /// assert_eq!((-100i8).saturating_sub(127), -128);
570 #[stable(feature = "rust1", since = "1.0.0")]
572 pub fn saturating_sub(self, other: Self) -> Self {
573 match self.checked_sub(other) {
575 None if other >= Self::zero() => Self::min_value(),
576 None => Self::max_value(),
580 /// Saturating integer multiplication. Computes `self * other`,
581 /// saturating at the numeric bounds instead of overflowing.
590 /// assert_eq!(100i32.saturating_mul(127), 12700);
591 /// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
592 /// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
594 #[stable(feature = "wrapping", since = "1.7.0")]
596 pub fn saturating_mul(self, other: Self) -> Self {
597 self.checked_mul(other).unwrap_or_else(|| {
598 if (self < 0 && other < 0) || (self > 0 && other > 0) {
606 /// Wrapping (modular) addition. Computes `self + other`,
607 /// wrapping around at the boundary of the type.
614 /// assert_eq!(100i8.wrapping_add(27), 127);
615 /// assert_eq!(100i8.wrapping_add(127), -29);
617 #[stable(feature = "rust1", since = "1.0.0")]
619 pub fn wrapping_add(self, rhs: Self) -> Self {
621 intrinsics::overflowing_add(self, rhs)
625 /// Wrapping (modular) subtraction. Computes `self - other`,
626 /// wrapping around at the boundary of the type.
633 /// assert_eq!(0i8.wrapping_sub(127), -127);
634 /// assert_eq!((-2i8).wrapping_sub(127), 127);
636 #[stable(feature = "rust1", since = "1.0.0")]
638 pub fn wrapping_sub(self, rhs: Self) -> Self {
640 intrinsics::overflowing_sub(self, rhs)
644 /// Wrapping (modular) multiplication. Computes `self *
645 /// other`, wrapping around at the boundary of the type.
652 /// assert_eq!(10i8.wrapping_mul(12), 120);
653 /// assert_eq!(11i8.wrapping_mul(12), -124);
655 #[stable(feature = "rust1", since = "1.0.0")]
657 pub fn wrapping_mul(self, rhs: Self) -> Self {
659 intrinsics::overflowing_mul(self, rhs)
663 /// Wrapping (modular) division. Computes `self / other`,
664 /// wrapping around at the boundary of the type.
666 /// The only case where such wrapping can occur is when one
667 /// divides `MIN / -1` on a signed type (where `MIN` is the
668 /// negative minimal value for the type); this is equivalent
669 /// to `-MIN`, a positive value that is too large to represent
670 /// in the type. In such a case, this function returns `MIN`
675 /// This function will panic if `rhs` is 0.
682 /// assert_eq!(100u8.wrapping_div(10), 10);
683 /// assert_eq!((-128i8).wrapping_div(-1), -128);
685 #[stable(feature = "num_wrapping", since = "1.2.0")]
687 pub fn wrapping_div(self, rhs: Self) -> Self {
688 self.overflowing_div(rhs).0
691 /// Wrapping (modular) remainder. Computes `self % other`,
692 /// wrapping around at the boundary of the type.
694 /// Such wrap-around never actually occurs mathematically;
695 /// implementation artifacts make `x % y` invalid for `MIN /
696 /// -1` on a signed type (where `MIN` is the negative
697 /// minimal value). In such a case, this function returns `0`.
701 /// This function will panic if `rhs` is 0.
708 /// assert_eq!(100i8.wrapping_rem(10), 0);
709 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
711 #[stable(feature = "num_wrapping", since = "1.2.0")]
713 pub fn wrapping_rem(self, rhs: Self) -> Self {
714 self.overflowing_rem(rhs).0
717 /// Wrapping (modular) negation. Computes `-self`,
718 /// wrapping around at the boundary of the type.
720 /// The only case where such wrapping can occur is when one
721 /// negates `MIN` on a signed type (where `MIN` is the
722 /// negative minimal value for the type); this is a positive
723 /// value that is too large to represent in the type. In such
724 /// a case, this function returns `MIN` itself.
731 /// assert_eq!(100i8.wrapping_neg(), -100);
732 /// assert_eq!((-128i8).wrapping_neg(), -128);
734 #[stable(feature = "num_wrapping", since = "1.2.0")]
736 pub fn wrapping_neg(self) -> Self {
737 self.overflowing_neg().0
740 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
741 /// where `mask` removes any high-order bits of `rhs` that
742 /// would cause the shift to exceed the bitwidth of the type.
744 /// Note that this is *not* the same as a rotate-left; the
745 /// RHS of a wrapping shift-left is restricted to the range
746 /// of the type, rather than the bits shifted out of the LHS
747 /// being returned to the other end. The primitive integer
748 /// types all implement a `rotate_left` function, which may
749 /// be what you want instead.
756 /// assert_eq!(1u8.wrapping_shl(7), 128);
757 /// assert_eq!(1u8.wrapping_shl(8), 1);
759 #[stable(feature = "num_wrapping", since = "1.2.0")]
761 pub fn wrapping_shl(self, rhs: u32) -> Self {
762 self.overflowing_shl(rhs).0
765 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
766 /// where `mask` removes any high-order bits of `rhs` that
767 /// would cause the shift to exceed the bitwidth of the type.
769 /// Note that this is *not* the same as a rotate-right; the
770 /// RHS of a wrapping shift-right is restricted to the range
771 /// of the type, rather than the bits shifted out of the LHS
772 /// being returned to the other end. The primitive integer
773 /// types all implement a `rotate_right` function, which may
774 /// be what you want instead.
781 /// assert_eq!(128u8.wrapping_shr(7), 1);
782 /// assert_eq!(128u8.wrapping_shr(8), 128);
784 #[stable(feature = "num_wrapping", since = "1.2.0")]
786 pub fn wrapping_shr(self, rhs: u32) -> Self {
787 self.overflowing_shr(rhs).0
790 /// Calculates `self` + `rhs`
792 /// Returns a tuple of the addition along with a boolean indicating
793 /// whether an arithmetic overflow would occur. If an overflow would
794 /// have occurred then the wrapped value is returned.
803 /// assert_eq!(5i32.overflowing_add(2), (7, false));
804 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
807 #[stable(feature = "wrapping", since = "1.7.0")]
808 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
810 let (a, b) = $add_with_overflow(self as $ActualT,
816 /// Calculates `self` - `rhs`
818 /// Returns a tuple of the subtraction along with a boolean indicating
819 /// whether an arithmetic overflow would occur. If an overflow would
820 /// have occurred then the wrapped value is returned.
829 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
830 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
833 #[stable(feature = "wrapping", since = "1.7.0")]
834 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
836 let (a, b) = $sub_with_overflow(self as $ActualT,
842 /// Calculates the multiplication of `self` and `rhs`.
844 /// Returns a tuple of the multiplication along with a boolean
845 /// indicating whether an arithmetic overflow would occur. If an
846 /// overflow would have occurred then the wrapped value is returned.
853 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
854 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
857 #[stable(feature = "wrapping", since = "1.7.0")]
858 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
860 let (a, b) = $mul_with_overflow(self as $ActualT,
866 /// Calculates the divisor when `self` is divided by `rhs`.
868 /// Returns a tuple of the divisor along with a boolean indicating
869 /// whether an arithmetic overflow would occur. If an overflow would
870 /// occur then self is returned.
874 /// This function will panic if `rhs` is 0.
883 /// assert_eq!(5i32.overflowing_div(2), (2, false));
884 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
887 #[stable(feature = "wrapping", since = "1.7.0")]
888 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
889 if self == Self::min_value() && rhs == -1 {
896 /// Calculates the remainder when `self` is divided by `rhs`.
898 /// Returns a tuple of the remainder after dividing along with a boolean
899 /// indicating whether an arithmetic overflow would occur. If an
900 /// overflow would occur then 0 is returned.
904 /// This function will panic if `rhs` is 0.
913 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
914 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
917 #[stable(feature = "wrapping", since = "1.7.0")]
918 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
919 if self == Self::min_value() && rhs == -1 {
926 /// Negates self, overflowing if this is equal to the minimum value.
928 /// Returns a tuple of the negated version of self along with a boolean
929 /// indicating whether an overflow happened. If `self` is the minimum
930 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
931 /// value will be returned again and `true` will be returned for an
932 /// overflow happening.
941 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
942 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
945 #[stable(feature = "wrapping", since = "1.7.0")]
946 pub fn overflowing_neg(self) -> (Self, bool) {
947 if self == Self::min_value() {
948 (Self::min_value(), true)
954 /// Shifts self left by `rhs` bits.
956 /// Returns a tuple of the shifted version of self along with a boolean
957 /// indicating whether the shift value was larger than or equal to the
958 /// number of bits. If the shift value is too large, then value is
959 /// masked (N-1) where N is the number of bits, and this value is then
960 /// used to perform the shift.
967 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
968 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
971 #[stable(feature = "wrapping", since = "1.7.0")]
972 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
973 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
976 /// Shifts self right by `rhs` bits.
978 /// Returns a tuple of the shifted version of self along with a boolean
979 /// indicating whether the shift value was larger than or equal to the
980 /// number of bits. If the shift value is too large, then value is
981 /// masked (N-1) where N is the number of bits, and this value is then
982 /// used to perform the shift.
989 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
990 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
993 #[stable(feature = "wrapping", since = "1.7.0")]
994 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
995 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
998 /// Raises self to the power of `exp`, using exponentiation by squaring.
1005 /// let x: i32 = 2; // or any other integer type
1007 /// assert_eq!(x.pow(4), 16);
1009 #[stable(feature = "rust1", since = "1.0.0")]
1011 pub fn pow(self, mut exp: u32) -> Self {
1012 let mut base = self;
1013 let mut acc = Self::one();
1023 // Deal with the final bit of the exponent separately, since
1024 // squaring the base afterwards is not necessary and may cause a
1025 // needless overflow.
1033 /// Computes the absolute value of `self`.
1035 /// # Overflow behavior
1037 /// The absolute value of `i32::min_value()` cannot be represented as an
1038 /// `i32`, and attempting to calculate it will cause an overflow. This
1039 /// means that code in debug mode will trigger a panic on this case and
1040 /// optimized code will return `i32::min_value()` without a panic.
1047 /// assert_eq!(10i8.abs(), 10);
1048 /// assert_eq!((-10i8).abs(), 10);
1050 #[stable(feature = "rust1", since = "1.0.0")]
1052 pub fn abs(self) -> Self {
1053 if self.is_negative() {
1054 // Note that the #[inline] above means that the overflow
1055 // semantics of this negation depend on the crate we're being
1063 /// Returns a number representing sign of `self`.
1065 /// - `0` if the number is zero
1066 /// - `1` if the number is positive
1067 /// - `-1` if the number is negative
1074 /// assert_eq!(10i8.signum(), 1);
1075 /// assert_eq!(0i8.signum(), 0);
1076 /// assert_eq!((-10i8).signum(), -1);
1078 #[stable(feature = "rust1", since = "1.0.0")]
1080 pub fn signum(self) -> Self {
1088 /// Returns `true` if `self` is positive and `false` if the number
1089 /// is zero or negative.
1096 /// assert!(10i8.is_positive());
1097 /// assert!(!(-10i8).is_positive());
1099 #[stable(feature = "rust1", since = "1.0.0")]
1101 pub fn is_positive(self) -> bool { self > 0 }
1103 /// Returns `true` if `self` is negative and `false` if the number
1104 /// is zero or positive.
1111 /// assert!((-10i8).is_negative());
1112 /// assert!(!10i8.is_negative());
1114 #[stable(feature = "rust1", since = "1.0.0")]
1116 pub fn is_negative(self) -> bool { self < 0 }
1122 int_impl! { i8, u8, 8,
1123 intrinsics::add_with_overflow,
1124 intrinsics::sub_with_overflow,
1125 intrinsics::mul_with_overflow }
1130 int_impl! { i16, u16, 16,
1131 intrinsics::add_with_overflow,
1132 intrinsics::sub_with_overflow,
1133 intrinsics::mul_with_overflow }
1138 int_impl! { i32, u32, 32,
1139 intrinsics::add_with_overflow,
1140 intrinsics::sub_with_overflow,
1141 intrinsics::mul_with_overflow }
1146 int_impl! { i64, u64, 64,
1147 intrinsics::add_with_overflow,
1148 intrinsics::sub_with_overflow,
1149 intrinsics::mul_with_overflow }
1152 #[cfg(target_pointer_width = "32")]
1155 int_impl! { i32, u32, 32,
1156 intrinsics::add_with_overflow,
1157 intrinsics::sub_with_overflow,
1158 intrinsics::mul_with_overflow }
1161 #[cfg(target_pointer_width = "64")]
1164 int_impl! { i64, u64, 64,
1165 intrinsics::add_with_overflow,
1166 intrinsics::sub_with_overflow,
1167 intrinsics::mul_with_overflow }
1170 // `Int` + `UnsignedInt` implemented for unsigned integers
1171 macro_rules! uint_impl {
1172 ($ActualT:ty, $BITS:expr,
1177 $add_with_overflow:path,
1178 $sub_with_overflow:path,
1179 $mul_with_overflow:path) => {
1180 /// Returns the smallest value that can be represented by this integer type.
1181 #[stable(feature = "rust1", since = "1.0.0")]
1183 pub const fn min_value() -> Self { 0 }
1185 /// Returns the largest value that can be represented by this integer type.
1186 #[stable(feature = "rust1", since = "1.0.0")]
1188 pub const fn max_value() -> Self { !0 }
1190 /// Converts a string slice in a given base to an integer.
1192 /// Leading and trailing whitespace represent an error.
1196 /// * src - A string slice
1197 /// * radix - The base to use. Must lie in the range [2 .. 36]
1201 /// `Err(ParseIntError)` if the string did not represent a valid number.
1202 /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
1203 #[stable(feature = "rust1", since = "1.0.0")]
1204 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1205 from_str_radix(src, radix)
1208 /// Returns the number of ones in the binary representation of `self`.
1215 /// let n = 0b01001100u8;
1217 /// assert_eq!(n.count_ones(), 3);
1219 #[stable(feature = "rust1", since = "1.0.0")]
1221 pub fn count_ones(self) -> u32 {
1222 unsafe { $ctpop(self as $ActualT) as u32 }
1225 /// Returns the number of zeros in the binary representation of `self`.
1232 /// let n = 0b01001100u8;
1234 /// assert_eq!(n.count_zeros(), 5);
1236 #[stable(feature = "rust1", since = "1.0.0")]
1238 pub fn count_zeros(self) -> u32 {
1239 (!self).count_ones()
1242 /// Returns the number of leading zeros in the binary representation
1250 /// let n = 0b0101000u16;
1252 /// assert_eq!(n.leading_zeros(), 10);
1254 #[stable(feature = "rust1", since = "1.0.0")]
1256 pub fn leading_zeros(self) -> u32 {
1257 unsafe { $ctlz(self as $ActualT) as u32 }
1260 /// Returns the number of trailing zeros in the binary representation
1268 /// let n = 0b0101000u16;
1270 /// assert_eq!(n.trailing_zeros(), 3);
1272 #[stable(feature = "rust1", since = "1.0.0")]
1274 pub fn trailing_zeros(self) -> u32 {
1275 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1276 // emits two conditional moves on x86_64. By promoting the value to
1277 // u16 and setting bit 8, we get better code without any conditional
1279 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1280 // pending, remove this workaround once LLVM generates better code
1284 intrinsics::cttz(self as u16 | 0x100) as u32
1286 intrinsics::cttz(self) as u32
1291 /// Shifts the bits to the left by a specified amount, `n`,
1292 /// wrapping the truncated bits to the end of the resulting integer.
1299 /// let n = 0x0123456789ABCDEFu64;
1300 /// let m = 0x3456789ABCDEF012u64;
1302 /// assert_eq!(n.rotate_left(12), m);
1304 #[stable(feature = "rust1", since = "1.0.0")]
1306 pub fn rotate_left(self, n: u32) -> Self {
1307 // Protect against undefined behaviour for over-long bit shifts
1309 (self << n) | (self >> (($BITS - n) % $BITS))
1312 /// Shifts the bits to the right by a specified amount, `n`,
1313 /// wrapping the truncated bits to the beginning of the resulting
1321 /// let n = 0x0123456789ABCDEFu64;
1322 /// let m = 0xDEF0123456789ABCu64;
1324 /// assert_eq!(n.rotate_right(12), m);
1326 #[stable(feature = "rust1", since = "1.0.0")]
1328 pub fn rotate_right(self, n: u32) -> Self {
1329 // Protect against undefined behaviour for over-long bit shifts
1331 (self >> n) | (self << (($BITS - n) % $BITS))
1334 /// Reverses the byte order of the integer.
1341 /// let n = 0x0123456789ABCDEFu64;
1342 /// let m = 0xEFCDAB8967452301u64;
1344 /// assert_eq!(n.swap_bytes(), m);
1346 #[stable(feature = "rust1", since = "1.0.0")]
1348 pub fn swap_bytes(self) -> Self {
1349 unsafe { $bswap(self as $ActualT) as Self }
1352 /// Converts an integer from big endian to the target's endianness.
1354 /// On big endian this is a no-op. On little endian the bytes are
1362 /// let n = 0x0123456789ABCDEFu64;
1364 /// if cfg!(target_endian = "big") {
1365 /// assert_eq!(u64::from_be(n), n)
1367 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1370 #[stable(feature = "rust1", since = "1.0.0")]
1372 pub fn from_be(x: Self) -> Self {
1373 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1376 /// Converts an integer from little endian to the target's endianness.
1378 /// On little endian this is a no-op. On big endian the bytes are
1386 /// let n = 0x0123456789ABCDEFu64;
1388 /// if cfg!(target_endian = "little") {
1389 /// assert_eq!(u64::from_le(n), n)
1391 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1394 #[stable(feature = "rust1", since = "1.0.0")]
1396 pub fn from_le(x: Self) -> Self {
1397 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1400 /// Converts `self` to big endian from the target's endianness.
1402 /// On big endian this is a no-op. On little endian the bytes are
1410 /// let n = 0x0123456789ABCDEFu64;
1412 /// if cfg!(target_endian = "big") {
1413 /// assert_eq!(n.to_be(), n)
1415 /// assert_eq!(n.to_be(), n.swap_bytes())
1418 #[stable(feature = "rust1", since = "1.0.0")]
1420 pub fn to_be(self) -> Self { // or not to be?
1421 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1424 /// Converts `self` to little endian from the target's endianness.
1426 /// On little endian this is a no-op. On big endian the bytes are
1434 /// let n = 0x0123456789ABCDEFu64;
1436 /// if cfg!(target_endian = "little") {
1437 /// assert_eq!(n.to_le(), n)
1439 /// assert_eq!(n.to_le(), n.swap_bytes())
1442 #[stable(feature = "rust1", since = "1.0.0")]
1444 pub fn to_le(self) -> Self {
1445 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1448 /// Checked integer addition. Computes `self + other`, returning `None`
1449 /// if overflow occurred.
1456 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1457 /// assert_eq!(6u16.checked_add(65530), None);
1459 #[stable(feature = "rust1", since = "1.0.0")]
1461 pub fn checked_add(self, other: Self) -> Option<Self> {
1462 let (a, b) = self.overflowing_add(other);
1463 if b {None} else {Some(a)}
1466 /// Checked integer subtraction. Computes `self - other`, returning
1467 /// `None` if underflow occurred.
1474 /// assert_eq!(1u8.checked_sub(1), Some(0));
1475 /// assert_eq!(0u8.checked_sub(1), None);
1477 #[stable(feature = "rust1", since = "1.0.0")]
1479 pub fn checked_sub(self, other: Self) -> Option<Self> {
1480 let (a, b) = self.overflowing_sub(other);
1481 if b {None} else {Some(a)}
1484 /// Checked integer multiplication. Computes `self * other`, returning
1485 /// `None` if underflow or overflow occurred.
1492 /// assert_eq!(5u8.checked_mul(51), Some(255));
1493 /// assert_eq!(5u8.checked_mul(52), None);
1495 #[stable(feature = "rust1", since = "1.0.0")]
1497 pub fn checked_mul(self, other: Self) -> Option<Self> {
1498 let (a, b) = self.overflowing_mul(other);
1499 if b {None} else {Some(a)}
1502 /// Checked integer division. Computes `self / other`, returning `None`
1503 /// if `other == 0` or the operation results in underflow or overflow.
1510 /// assert_eq!(128u8.checked_div(2), Some(64));
1511 /// assert_eq!(1u8.checked_div(0), None);
1513 #[stable(feature = "rust1", since = "1.0.0")]
1515 pub fn checked_div(self, other: Self) -> Option<Self> {
1518 other => Some(self / other),
1522 /// Checked integer remainder. Computes `self % other`, returning `None`
1523 /// if `other == 0` or the operation results in underflow or overflow.
1530 /// assert_eq!(5u32.checked_rem(2), Some(1));
1531 /// assert_eq!(5u32.checked_rem(0), None);
1533 #[stable(feature = "wrapping", since = "1.7.0")]
1535 pub fn checked_rem(self, other: Self) -> Option<Self> {
1543 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1546 /// Note that negating any positive integer will overflow.
1553 /// assert_eq!(0u32.checked_neg(), Some(0));
1554 /// assert_eq!(1u32.checked_neg(), None);
1556 #[stable(feature = "wrapping", since = "1.7.0")]
1558 pub fn checked_neg(self) -> Option<Self> {
1559 let (a, b) = self.overflowing_neg();
1560 if b {None} else {Some(a)}
1563 /// Checked shift left. Computes `self << rhs`, returning `None`
1564 /// if `rhs` is larger than or equal to the number of bits in `self`.
1571 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1572 /// assert_eq!(0x10u32.checked_shl(33), None);
1574 #[stable(feature = "wrapping", since = "1.7.0")]
1576 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1577 let (a, b) = self.overflowing_shl(rhs);
1578 if b {None} else {Some(a)}
1581 /// Checked shift right. Computes `self >> rhs`, returning `None`
1582 /// if `rhs` is larger than or equal to the number of bits in `self`.
1589 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1590 /// assert_eq!(0x10u32.checked_shr(33), None);
1592 #[stable(feature = "wrapping", since = "1.7.0")]
1594 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1595 let (a, b) = self.overflowing_shr(rhs);
1596 if b {None} else {Some(a)}
1599 /// Saturating integer addition. Computes `self + other`, saturating at
1600 /// the numeric bounds instead of overflowing.
1607 /// assert_eq!(100u8.saturating_add(1), 101);
1608 /// assert_eq!(200u8.saturating_add(127), 255);
1610 #[stable(feature = "rust1", since = "1.0.0")]
1612 pub fn saturating_add(self, other: Self) -> Self {
1613 match self.checked_add(other) {
1615 None => Self::max_value(),
1619 /// Saturating integer subtraction. Computes `self - other`, saturating
1620 /// at the numeric bounds instead of overflowing.
1627 /// assert_eq!(100u8.saturating_sub(27), 73);
1628 /// assert_eq!(13u8.saturating_sub(127), 0);
1630 #[stable(feature = "rust1", since = "1.0.0")]
1632 pub fn saturating_sub(self, other: Self) -> Self {
1633 match self.checked_sub(other) {
1635 None => Self::min_value(),
1639 /// Saturating integer multiplication. Computes `self * other`,
1640 /// saturating at the numeric bounds instead of overflowing.
1649 /// assert_eq!(100u32.saturating_mul(127), 12700);
1650 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1652 #[stable(feature = "wrapping", since = "1.7.0")]
1654 pub fn saturating_mul(self, other: Self) -> Self {
1655 self.checked_mul(other).unwrap_or(Self::max_value())
1658 /// Wrapping (modular) addition. Computes `self + other`,
1659 /// wrapping around at the boundary of the type.
1666 /// assert_eq!(200u8.wrapping_add(55), 255);
1667 /// assert_eq!(200u8.wrapping_add(155), 99);
1669 #[stable(feature = "rust1", since = "1.0.0")]
1671 pub fn wrapping_add(self, rhs: Self) -> Self {
1673 intrinsics::overflowing_add(self, rhs)
1677 /// Wrapping (modular) subtraction. Computes `self - other`,
1678 /// wrapping around at the boundary of the type.
1685 /// assert_eq!(100u8.wrapping_sub(100), 0);
1686 /// assert_eq!(100u8.wrapping_sub(155), 201);
1688 #[stable(feature = "rust1", since = "1.0.0")]
1690 pub fn wrapping_sub(self, rhs: Self) -> Self {
1692 intrinsics::overflowing_sub(self, rhs)
1696 /// Wrapping (modular) multiplication. Computes `self *
1697 /// other`, wrapping around at the boundary of the type.
1704 /// assert_eq!(10u8.wrapping_mul(12), 120);
1705 /// assert_eq!(25u8.wrapping_mul(12), 44);
1707 #[stable(feature = "rust1", since = "1.0.0")]
1709 pub fn wrapping_mul(self, rhs: Self) -> Self {
1711 intrinsics::overflowing_mul(self, rhs)
1715 /// Wrapping (modular) division. Computes `self / other`.
1716 /// Wrapped division on unsigned types is just normal division.
1717 /// There's no way wrapping could ever happen.
1718 /// This function exists, so that all operations
1719 /// are accounted for in the wrapping operations.
1726 /// assert_eq!(100u8.wrapping_div(10), 10);
1728 #[stable(feature = "num_wrapping", since = "1.2.0")]
1730 pub fn wrapping_div(self, rhs: Self) -> Self {
1734 /// Wrapping (modular) remainder. Computes `self % other`.
1735 /// Wrapped remainder calculation on unsigned types is
1736 /// just the regular remainder calculation.
1737 /// There's no way wrapping could ever happen.
1738 /// This function exists, so that all operations
1739 /// are accounted for in the wrapping operations.
1746 /// assert_eq!(100i8.wrapping_rem(10), 0);
1748 #[stable(feature = "num_wrapping", since = "1.2.0")]
1750 pub fn wrapping_rem(self, rhs: Self) -> Self {
1754 /// Wrapping (modular) negation. Computes `-self`,
1755 /// wrapping around at the boundary of the type.
1757 /// Since unsigned types do not have negative equivalents
1758 /// all applications of this function will wrap (except for `-0`).
1759 /// For values smaller than the corresponding signed type's maximum
1760 /// the result is the same as casting the corresponding signed value.
1761 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1762 /// `MAX` is the corresponding signed type's maximum.
1769 /// assert_eq!(100u8.wrapping_neg(), 156);
1770 /// assert_eq!(0u8.wrapping_neg(), 0);
1771 /// assert_eq!(180u8.wrapping_neg(), 76);
1772 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1774 #[stable(feature = "num_wrapping", since = "1.2.0")]
1776 pub fn wrapping_neg(self) -> Self {
1777 self.overflowing_neg().0
1780 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1781 /// where `mask` removes any high-order bits of `rhs` that
1782 /// would cause the shift to exceed the bitwidth of the type.
1789 /// assert_eq!(1u8.wrapping_shl(7), 128);
1790 /// assert_eq!(1u8.wrapping_shl(8), 1);
1792 #[stable(feature = "num_wrapping", since = "1.2.0")]
1794 pub fn wrapping_shl(self, rhs: u32) -> Self {
1795 self.overflowing_shl(rhs).0
1798 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1799 /// where `mask` removes any high-order bits of `rhs` that
1800 /// would cause the shift to exceed the bitwidth of the type.
1807 /// assert_eq!(128u8.wrapping_shr(7), 1);
1808 /// assert_eq!(128u8.wrapping_shr(8), 128);
1810 #[stable(feature = "num_wrapping", since = "1.2.0")]
1812 pub fn wrapping_shr(self, rhs: u32) -> Self {
1813 self.overflowing_shr(rhs).0
1816 /// Calculates `self` + `rhs`
1818 /// Returns a tuple of the addition along with a boolean indicating
1819 /// whether an arithmetic overflow would occur. If an overflow would
1820 /// have occurred then the wrapped value is returned.
1829 /// assert_eq!(5u32.overflowing_add(2), (7, false));
1830 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
1833 #[stable(feature = "wrapping", since = "1.7.0")]
1834 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1836 let (a, b) = $add_with_overflow(self as $ActualT,
1842 /// Calculates `self` - `rhs`
1844 /// Returns a tuple of the subtraction along with a boolean indicating
1845 /// whether an arithmetic overflow would occur. If an overflow would
1846 /// have occurred then the wrapped value is returned.
1855 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
1856 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
1859 #[stable(feature = "wrapping", since = "1.7.0")]
1860 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1862 let (a, b) = $sub_with_overflow(self as $ActualT,
1868 /// Calculates the multiplication of `self` and `rhs`.
1870 /// Returns a tuple of the multiplication along with a boolean
1871 /// indicating whether an arithmetic overflow would occur. If an
1872 /// overflow would have occurred then the wrapped value is returned.
1879 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1880 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1883 #[stable(feature = "wrapping", since = "1.7.0")]
1884 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1886 let (a, b) = $mul_with_overflow(self as $ActualT,
1892 /// Calculates the divisor when `self` is divided by `rhs`.
1894 /// Returns a tuple of the divisor along with a boolean indicating
1895 /// whether an arithmetic overflow would occur. Note that for unsigned
1896 /// integers overflow never occurs, so the second value is always
1901 /// This function will panic if `rhs` is 0.
1908 /// assert_eq!(5u32.overflowing_div(2), (2, false));
1911 #[stable(feature = "wrapping", since = "1.7.0")]
1912 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1916 /// Calculates the remainder when `self` is divided by `rhs`.
1918 /// Returns a tuple of the remainder after dividing along with a boolean
1919 /// indicating whether an arithmetic overflow would occur. Note that for
1920 /// unsigned integers overflow never occurs, so the second value is
1925 /// This function will panic if `rhs` is 0.
1932 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
1935 #[stable(feature = "wrapping", since = "1.7.0")]
1936 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1940 /// Negates self in an overflowing fashion.
1942 /// Returns `!self + 1` using wrapping operations to return the value
1943 /// that represents the negation of this unsigned value. Note that for
1944 /// positive unsigned values overflow always occurs, but negating 0 does
1952 /// assert_eq!(0u32.overflowing_neg(), (0, false));
1953 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
1956 #[stable(feature = "wrapping", since = "1.7.0")]
1957 pub fn overflowing_neg(self) -> (Self, bool) {
1958 ((!self).wrapping_add(1), self != 0)
1961 /// Shifts self left by `rhs` bits.
1963 /// Returns a tuple of the shifted version of self along with a boolean
1964 /// indicating whether the shift value was larger than or equal to the
1965 /// number of bits. If the shift value is too large, then value is
1966 /// masked (N-1) where N is the number of bits, and this value is then
1967 /// used to perform the shift.
1974 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
1975 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
1978 #[stable(feature = "wrapping", since = "1.7.0")]
1979 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1980 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1983 /// Shifts self right by `rhs` bits.
1985 /// Returns a tuple of the shifted version of self along with a boolean
1986 /// indicating whether the shift value was larger than or equal to the
1987 /// number of bits. If the shift value is too large, then value is
1988 /// masked (N-1) where N is the number of bits, and this value is then
1989 /// used to perform the shift.
1996 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
1997 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2000 #[stable(feature = "wrapping", since = "1.7.0")]
2001 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2002 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
2005 /// Raises self to the power of `exp`, using exponentiation by squaring.
2012 /// assert_eq!(2u32.pow(4), 16);
2014 #[stable(feature = "rust1", since = "1.0.0")]
2016 pub fn pow(self, mut exp: u32) -> Self {
2017 let mut base = self;
2018 let mut acc = Self::one();
2020 let mut prev_base = self;
2021 let mut base_oflo = false;
2025 // ensure overflow occurs in the same manner it
2026 // would have otherwise (i.e. signal any exception
2027 // it would have otherwise).
2028 acc = acc * (prev_base * prev_base);
2034 let (new_base, new_base_oflo) = base.overflowing_mul(base);
2036 base_oflo = new_base_oflo;
2042 /// Returns `true` if and only if `self == 2^k` for some `k`.
2049 /// assert!(16u8.is_power_of_two());
2050 /// assert!(!10u8.is_power_of_two());
2052 #[stable(feature = "rust1", since = "1.0.0")]
2054 pub fn is_power_of_two(self) -> bool {
2055 (self.wrapping_sub(Self::one())) & self == Self::zero() &&
2056 !(self == Self::zero())
2059 /// Returns the smallest power of two greater than or equal to `self`.
2060 /// Unspecified behavior on overflow.
2067 /// assert_eq!(2u8.next_power_of_two(), 2);
2068 /// assert_eq!(3u8.next_power_of_two(), 4);
2070 #[stable(feature = "rust1", since = "1.0.0")]
2072 pub fn next_power_of_two(self) -> Self {
2073 let bits = size_of::<Self>() * 8;
2074 let one: Self = Self::one();
2075 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
2078 /// Returns the smallest power of two greater than or equal to `n`. If
2079 /// the next power of two is greater than the type's maximum value,
2080 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2087 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2088 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2089 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2091 #[stable(feature = "rust1", since = "1.0.0")]
2092 pub fn checked_next_power_of_two(self) -> Option<Self> {
2093 let npot = self.next_power_of_two();
2110 intrinsics::add_with_overflow,
2111 intrinsics::sub_with_overflow,
2112 intrinsics::mul_with_overflow }
2117 uint_impl! { u16, 16,
2122 intrinsics::add_with_overflow,
2123 intrinsics::sub_with_overflow,
2124 intrinsics::mul_with_overflow }
2129 uint_impl! { u32, 32,
2134 intrinsics::add_with_overflow,
2135 intrinsics::sub_with_overflow,
2136 intrinsics::mul_with_overflow }
2141 uint_impl! { u64, 64,
2146 intrinsics::add_with_overflow,
2147 intrinsics::sub_with_overflow,
2148 intrinsics::mul_with_overflow }
2151 #[cfg(target_pointer_width = "32")]
2154 uint_impl! { u32, 32,
2159 intrinsics::add_with_overflow,
2160 intrinsics::sub_with_overflow,
2161 intrinsics::mul_with_overflow }
2164 #[cfg(target_pointer_width = "64")]
2167 uint_impl! { u64, 64,
2172 intrinsics::add_with_overflow,
2173 intrinsics::sub_with_overflow,
2174 intrinsics::mul_with_overflow }
2177 /// A classification of floating point numbers.
2179 /// This `enum` is used as the return type for [`f32::classify()`] and [`f64::classify()`]. See
2180 /// their documentation for more.
2182 /// [`f32::classify()`]: ../../std/primitive.f32.html#method.classify
2183 /// [`f64::classify()`]: ../../std/primitive.f64.html#method.classify
2184 #[derive(Copy, Clone, PartialEq, Debug)]
2185 #[stable(feature = "rust1", since = "1.0.0")]
2186 pub enum FpCategory {
2187 /// "Not a Number", often obtained by dividing by zero
2188 #[stable(feature = "rust1", since = "1.0.0")]
2191 /// Positive or negative infinity
2192 #[stable(feature = "rust1", since = "1.0.0")]
2195 /// Positive or negative zero
2196 #[stable(feature = "rust1", since = "1.0.0")]
2199 /// De-normalized floating point representation (less precise than `Normal`)
2200 #[stable(feature = "rust1", since = "1.0.0")]
2203 /// A regular floating point number
2204 #[stable(feature = "rust1", since = "1.0.0")]
2208 /// A built-in floating point number.
2210 #[unstable(feature = "core_float",
2211 reason = "stable interface is via `impl f{32,64}` in later crates",
2213 pub trait Float: Sized {
2214 /// Returns the NaN value.
2215 #[unstable(feature = "float_extras", reason = "needs removal",
2218 /// Returns the infinite value.
2219 #[unstable(feature = "float_extras", reason = "needs removal",
2221 fn infinity() -> Self;
2222 /// Returns the negative infinite value.
2223 #[unstable(feature = "float_extras", reason = "needs removal",
2225 fn neg_infinity() -> Self;
2227 #[unstable(feature = "float_extras", reason = "needs removal",
2229 fn neg_zero() -> Self;
2231 #[unstable(feature = "float_extras", reason = "needs removal",
2235 #[unstable(feature = "float_extras", reason = "needs removal",
2239 /// Returns true if this value is NaN and false otherwise.
2240 #[stable(feature = "core", since = "1.6.0")]
2241 fn is_nan(self) -> bool;
2242 /// Returns true if this value is positive infinity or negative infinity and
2243 /// false otherwise.
2244 #[stable(feature = "core", since = "1.6.0")]
2245 fn is_infinite(self) -> bool;
2246 /// Returns true if this number is neither infinite nor NaN.
2247 #[stable(feature = "core", since = "1.6.0")]
2248 fn is_finite(self) -> bool;
2249 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
2250 #[stable(feature = "core", since = "1.6.0")]
2251 fn is_normal(self) -> bool;
2252 /// Returns the category that this number falls into.
2253 #[stable(feature = "core", since = "1.6.0")]
2254 fn classify(self) -> FpCategory;
2256 /// Returns the mantissa, exponent and sign as integers, respectively.
2257 #[unstable(feature = "float_extras", reason = "signature is undecided",
2259 fn integer_decode(self) -> (u64, i16, i8);
2261 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2262 /// number is `Float::nan()`.
2263 #[stable(feature = "core", since = "1.6.0")]
2264 fn abs(self) -> Self;
2265 /// Returns a number that represents the sign of `self`.
2267 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2268 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2269 /// - `Float::nan()` if the number is `Float::nan()`
2270 #[stable(feature = "core", since = "1.6.0")]
2271 fn signum(self) -> Self;
2273 /// Returns `true` if `self` is positive, including `+0.0` and
2274 /// `Float::infinity()`.
2275 #[stable(feature = "core", since = "1.6.0")]
2276 fn is_sign_positive(self) -> bool;
2277 /// Returns `true` if `self` is negative, including `-0.0` and
2278 /// `Float::neg_infinity()`.
2279 #[stable(feature = "core", since = "1.6.0")]
2280 fn is_sign_negative(self) -> bool;
2282 /// Take the reciprocal (inverse) of a number, `1/x`.
2283 #[stable(feature = "core", since = "1.6.0")]
2284 fn recip(self) -> Self;
2286 /// Raise a number to an integer power.
2288 /// Using this function is generally faster than using `powf`
2289 #[stable(feature = "core", since = "1.6.0")]
2290 fn powi(self, n: i32) -> Self;
2292 /// Convert radians to degrees.
2293 #[unstable(feature = "float_extras", reason = "desirability is unclear",
2295 fn to_degrees(self) -> Self;
2296 /// Convert degrees to radians.
2297 #[unstable(feature = "float_extras", reason = "desirability is unclear",
2299 fn to_radians(self) -> Self;
2302 macro_rules! from_str_radix_int_impl {
2304 #[stable(feature = "rust1", since = "1.0.0")]
2305 impl FromStr for $t {
2306 type Err = ParseIntError;
2307 fn from_str(src: &str) -> Result<Self, ParseIntError> {
2308 from_str_radix(src, 10)
2313 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
2316 trait FromStrRadixHelper: PartialOrd + Copy {
2317 fn min_value() -> Self;
2318 fn from_u32(u: u32) -> Self;
2319 fn checked_mul(&self, other: u32) -> Option<Self>;
2320 fn checked_sub(&self, other: u32) -> Option<Self>;
2321 fn checked_add(&self, other: u32) -> Option<Self>;
2325 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
2326 fn min_value() -> Self { Self::min_value() }
2327 fn from_u32(u: u32) -> Self { u as Self }
2328 fn checked_mul(&self, other: u32) -> Option<Self> {
2329 Self::checked_mul(*self, other as Self)
2331 fn checked_sub(&self, other: u32) -> Option<Self> {
2332 Self::checked_sub(*self, other as Self)
2334 fn checked_add(&self, other: u32) -> Option<Self> {
2335 Self::checked_add(*self, other as Self)
2339 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
2341 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
2342 -> Result<T, ParseIntError> {
2343 use self::IntErrorKind::*;
2344 use self::ParseIntError as PIE;
2346 assert!(radix >= 2 && radix <= 36,
2347 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2351 return Err(PIE { kind: Empty });
2354 let is_signed_ty = T::from_u32(0) > T::min_value();
2356 // all valid digits are ascii, so we will just iterate over the utf8 bytes
2357 // and cast them to chars. .to_digit() will safely return None for anything
2358 // other than a valid ascii digit for the given radix, including the first-byte
2359 // of multi-byte sequences
2360 let src = src.as_bytes();
2362 let (is_positive, digits) = match src[0] {
2363 b'+' => (true, &src[1..]),
2364 b'-' if is_signed_ty => (false, &src[1..]),
2368 if digits.is_empty() {
2369 return Err(PIE { kind: Empty });
2372 let mut result = T::from_u32(0);
2374 // The number is positive
2376 let x = match (c as char).to_digit(radix) {
2378 None => return Err(PIE { kind: InvalidDigit }),
2380 result = match result.checked_mul(radix) {
2381 Some(result) => result,
2382 None => return Err(PIE { kind: Overflow }),
2384 result = match result.checked_add(x) {
2385 Some(result) => result,
2386 None => return Err(PIE { kind: Overflow }),
2390 // The number is negative
2392 let x = match (c as char).to_digit(radix) {
2394 None => return Err(PIE { kind: InvalidDigit }),
2396 result = match result.checked_mul(radix) {
2397 Some(result) => result,
2398 None => return Err(PIE { kind: Underflow }),
2400 result = match result.checked_sub(x) {
2401 Some(result) => result,
2402 None => return Err(PIE { kind: Underflow }),
2409 /// An error which can be returned when parsing an integer.
2411 /// This error is used as the error type for the `from_str_radix()` functions
2412 /// on the primitive integer types, such as [`i8::from_str_radix()`].
2414 /// [`i8::from_str_radix()`]: ../../std/primitive.i8.html#method.from_str_radix
2415 #[derive(Debug, Clone, PartialEq)]
2416 #[stable(feature = "rust1", since = "1.0.0")]
2417 pub struct ParseIntError { kind: IntErrorKind }
2419 #[derive(Debug, Clone, PartialEq)]
2427 impl ParseIntError {
2428 #[unstable(feature = "int_error_internals",
2429 reason = "available through Error trait and this method should \
2430 not be exposed publicly",
2433 pub fn __description(&self) -> &str {
2435 IntErrorKind::Empty => "cannot parse integer from empty string",
2436 IntErrorKind::InvalidDigit => "invalid digit found in string",
2437 IntErrorKind::Overflow => "number too large to fit in target type",
2438 IntErrorKind::Underflow => "number too small to fit in target type",
2443 #[stable(feature = "rust1", since = "1.0.0")]
2444 impl fmt::Display for ParseIntError {
2445 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2446 self.__description().fmt(f)
2450 #[stable(feature = "rust1", since = "1.0.0")]
2451 pub use num::dec2flt::ParseFloatError;
2453 // Conversion traits for primitive integer and float types
2454 // Conversions T -> T are covered by a blanket impl and therefore excluded
2455 // Some conversions from and to usize/isize are not implemented due to portability concerns
2456 macro_rules! impl_from {
2457 ($Small: ty, $Large: ty) => {
2458 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
2459 impl From<$Small> for $Large {
2461 fn from(small: $Small) -> $Large {
2468 // Unsigned -> Unsigned
2469 impl_from! { u8, u16 }
2470 impl_from! { u8, u32 }
2471 impl_from! { u8, u64 }
2472 impl_from! { u8, usize }
2473 impl_from! { u16, u32 }
2474 impl_from! { u16, u64 }
2475 impl_from! { u32, u64 }
2478 impl_from! { i8, i16 }
2479 impl_from! { i8, i32 }
2480 impl_from! { i8, i64 }
2481 impl_from! { i8, isize }
2482 impl_from! { i16, i32 }
2483 impl_from! { i16, i64 }
2484 impl_from! { i32, i64 }
2486 // Unsigned -> Signed
2487 impl_from! { u8, i16 }
2488 impl_from! { u8, i32 }
2489 impl_from! { u8, i64 }
2490 impl_from! { u16, i32 }
2491 impl_from! { u16, i64 }
2492 impl_from! { u32, i64 }
2494 // Note: integers can only be represented with full precision in a float if
2495 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2496 // Lossy float conversions are not implemented at this time.
2499 impl_from! { i8, f32 }
2500 impl_from! { i8, f64 }
2501 impl_from! { i16, f32 }
2502 impl_from! { i16, f64 }
2503 impl_from! { i32, f64 }
2505 // Unsigned -> Float
2506 impl_from! { u8, f32 }
2507 impl_from! { u8, f64 }
2508 impl_from! { u16, f32 }
2509 impl_from! { u16, f64 }
2510 impl_from! { u32, f64 }
2513 impl_from! { f32, f64 }