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 #[rustc_no_mir] // FIXME #29769 MIR overflow checking is TBD.
1012 pub fn pow(self, mut exp
: u32) -> Self {
1013 let mut base
= self;
1014 let mut acc
= Self::one();
1024 // Deal with the final bit of the exponent separately, since
1025 // squaring the base afterwards is not necessary and may cause a
1026 // needless overflow.
1034 /// Computes the absolute value of `self`.
1036 /// # Overflow behavior
1038 /// The absolute value of `i32::min_value()` cannot be represented as an
1039 /// `i32`, and attempting to calculate it will cause an overflow. This
1040 /// means that code in debug mode will trigger a panic on this case and
1041 /// optimized code will return `i32::min_value()` without a panic.
1048 /// assert_eq!(10i8.abs(), 10);
1049 /// assert_eq!((-10i8).abs(), 10);
1051 #[stable(feature = "rust1", since = "1.0.0")]
1053 #[rustc_no_mir] // FIXME #29769 MIR overflow checking is TBD.
1054 pub fn abs(self) -> Self {
1055 if self.is_negative() {
1056 // Note that the #[inline] above means that the overflow
1057 // semantics of this negation depend on the crate we're being
1065 /// Returns a number representing sign of `self`.
1067 /// - `0` if the number is zero
1068 /// - `1` if the number is positive
1069 /// - `-1` if the number is negative
1076 /// assert_eq!(10i8.signum(), 1);
1077 /// assert_eq!(0i8.signum(), 0);
1078 /// assert_eq!((-10i8).signum(), -1);
1080 #[stable(feature = "rust1", since = "1.0.0")]
1082 pub fn signum(self) -> Self {
1090 /// Returns `true` if `self` is positive and `false` if the number
1091 /// is zero or negative.
1098 /// assert!(10i8.is_positive());
1099 /// assert!(!(-10i8).is_positive());
1101 #[stable(feature = "rust1", since = "1.0.0")]
1103 pub fn is_positive(self) -> bool { self > 0 }
1105 /// Returns `true` if `self` is negative and `false` if the number
1106 /// is zero or positive.
1113 /// assert!((-10i8).is_negative());
1114 /// assert!(!10i8.is_negative());
1116 #[stable(feature = "rust1", since = "1.0.0")]
1118 pub fn is_negative(self) -> bool { self < 0 }
1124 int_impl
! { i8, u8, 8,
1125 intrinsics
::add_with_overflow
,
1126 intrinsics
::sub_with_overflow
,
1127 intrinsics
::mul_with_overflow
}
1132 int_impl
! { i16, u16, 16,
1133 intrinsics
::add_with_overflow
,
1134 intrinsics
::sub_with_overflow
,
1135 intrinsics
::mul_with_overflow
}
1140 int_impl
! { i32, u32, 32,
1141 intrinsics
::add_with_overflow
,
1142 intrinsics
::sub_with_overflow
,
1143 intrinsics
::mul_with_overflow
}
1148 int_impl
! { i64, u64, 64,
1149 intrinsics
::add_with_overflow
,
1150 intrinsics
::sub_with_overflow
,
1151 intrinsics
::mul_with_overflow
}
1154 #[cfg(target_pointer_width = "32")]
1157 int_impl
! { i32, u32, 32,
1158 intrinsics
::add_with_overflow
,
1159 intrinsics
::sub_with_overflow
,
1160 intrinsics
::mul_with_overflow
}
1163 #[cfg(target_pointer_width = "64")]
1166 int_impl
! { i64, u64, 64,
1167 intrinsics
::add_with_overflow
,
1168 intrinsics
::sub_with_overflow
,
1169 intrinsics
::mul_with_overflow
}
1172 // `Int` + `UnsignedInt` implemented for unsigned integers
1173 macro_rules
! uint_impl
{
1174 ($ActualT
:ty
, $BITS
:expr
,
1179 $add_with_overflow
:path
,
1180 $sub_with_overflow
:path
,
1181 $mul_with_overflow
:path
) => {
1182 /// Returns the smallest value that can be represented by this integer type.
1183 #[stable(feature = "rust1", since = "1.0.0")]
1185 pub const fn min_value() -> Self { 0 }
1187 /// Returns the largest value that can be represented by this integer type.
1188 #[stable(feature = "rust1", since = "1.0.0")]
1190 pub const fn max_value() -> Self { !0 }
1192 /// Converts a string slice in a given base to an integer.
1194 /// Leading and trailing whitespace represent an error.
1198 /// * src - A string slice
1199 /// * radix - The base to use. Must lie in the range [2 .. 36]
1203 /// `Err(ParseIntError)` if the string did not represent a valid number.
1204 /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 pub fn from_str_radix(src
: &str, radix
: u32) -> Result
<Self, ParseIntError
> {
1207 from_str_radix(src
, radix
)
1210 /// Returns the number of ones in the binary representation of `self`.
1217 /// let n = 0b01001100u8;
1219 /// assert_eq!(n.count_ones(), 3);
1221 #[stable(feature = "rust1", since = "1.0.0")]
1223 pub fn count_ones(self) -> u32 {
1224 unsafe { $ctpop(self as $ActualT) as u32 }
1227 /// Returns the number of zeros in the binary representation of `self`.
1234 /// let n = 0b01001100u8;
1236 /// assert_eq!(n.count_zeros(), 5);
1238 #[stable(feature = "rust1", since = "1.0.0")]
1240 pub fn count_zeros(self) -> u32 {
1241 (!self).count_ones()
1244 /// Returns the number of leading zeros in the binary representation
1252 /// let n = 0b0101000u16;
1254 /// assert_eq!(n.leading_zeros(), 10);
1256 #[stable(feature = "rust1", since = "1.0.0")]
1258 pub fn leading_zeros(self) -> u32 {
1259 unsafe { $ctlz(self as $ActualT) as u32 }
1262 /// Returns the number of trailing zeros in the binary representation
1270 /// let n = 0b0101000u16;
1272 /// assert_eq!(n.trailing_zeros(), 3);
1274 #[stable(feature = "rust1", since = "1.0.0")]
1276 pub fn trailing_zeros(self) -> u32 {
1277 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1278 // emits two conditional moves on x86_64. By promoting the value to
1279 // u16 and setting bit 8, we get better code without any conditional
1281 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1282 // pending, remove this workaround once LLVM generates better code
1286 intrinsics
::cttz(self as u16 | 0x100) as u32
1288 intrinsics
::cttz(self) as u32
1293 /// Shifts the bits to the left by a specified amount, `n`,
1294 /// wrapping the truncated bits to the end of the resulting integer.
1301 /// let n = 0x0123456789ABCDEFu64;
1302 /// let m = 0x3456789ABCDEF012u64;
1304 /// assert_eq!(n.rotate_left(12), m);
1306 #[stable(feature = "rust1", since = "1.0.0")]
1308 pub fn rotate_left(self, n
: u32) -> Self {
1309 // Protect against undefined behaviour for over-long bit shifts
1311 (self << n
) | (self >> (($BITS
- n
) % $BITS
))
1314 /// Shifts the bits to the right by a specified amount, `n`,
1315 /// wrapping the truncated bits to the beginning of the resulting
1323 /// let n = 0x0123456789ABCDEFu64;
1324 /// let m = 0xDEF0123456789ABCu64;
1326 /// assert_eq!(n.rotate_right(12), m);
1328 #[stable(feature = "rust1", since = "1.0.0")]
1330 pub fn rotate_right(self, n
: u32) -> Self {
1331 // Protect against undefined behaviour for over-long bit shifts
1333 (self >> n
) | (self << (($BITS
- n
) % $BITS
))
1336 /// Reverses the byte order of the integer.
1343 /// let n = 0x0123456789ABCDEFu64;
1344 /// let m = 0xEFCDAB8967452301u64;
1346 /// assert_eq!(n.swap_bytes(), m);
1348 #[stable(feature = "rust1", since = "1.0.0")]
1350 pub fn swap_bytes(self) -> Self {
1351 unsafe { $bswap(self as $ActualT) as Self }
1354 /// Converts an integer from big endian to the target's endianness.
1356 /// On big endian this is a no-op. On little endian the bytes are
1364 /// let n = 0x0123456789ABCDEFu64;
1366 /// if cfg!(target_endian = "big") {
1367 /// assert_eq!(u64::from_be(n), n)
1369 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1372 #[stable(feature = "rust1", since = "1.0.0")]
1374 pub fn from_be(x
: Self) -> Self {
1375 if cfg
!(target_endian
= "big") { x }
else { x.swap_bytes() }
1378 /// Converts an integer from little endian to the target's endianness.
1380 /// On little endian this is a no-op. On big endian the bytes are
1388 /// let n = 0x0123456789ABCDEFu64;
1390 /// if cfg!(target_endian = "little") {
1391 /// assert_eq!(u64::from_le(n), n)
1393 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1396 #[stable(feature = "rust1", since = "1.0.0")]
1398 pub fn from_le(x
: Self) -> Self {
1399 if cfg
!(target_endian
= "little") { x }
else { x.swap_bytes() }
1402 /// Converts `self` to big endian from the target's endianness.
1404 /// On big endian this is a no-op. On little endian the bytes are
1412 /// let n = 0x0123456789ABCDEFu64;
1414 /// if cfg!(target_endian = "big") {
1415 /// assert_eq!(n.to_be(), n)
1417 /// assert_eq!(n.to_be(), n.swap_bytes())
1420 #[stable(feature = "rust1", since = "1.0.0")]
1422 pub fn to_be(self) -> Self { // or not to be?
1423 if cfg
!(target_endian
= "big") { self }
else { self.swap_bytes() }
1426 /// Converts `self` to little endian from the target's endianness.
1428 /// On little endian this is a no-op. On big endian the bytes are
1436 /// let n = 0x0123456789ABCDEFu64;
1438 /// if cfg!(target_endian = "little") {
1439 /// assert_eq!(n.to_le(), n)
1441 /// assert_eq!(n.to_le(), n.swap_bytes())
1444 #[stable(feature = "rust1", since = "1.0.0")]
1446 pub fn to_le(self) -> Self {
1447 if cfg
!(target_endian
= "little") { self }
else { self.swap_bytes() }
1450 /// Checked integer addition. Computes `self + other`, returning `None`
1451 /// if overflow occurred.
1458 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1459 /// assert_eq!(6u16.checked_add(65530), None);
1461 #[stable(feature = "rust1", since = "1.0.0")]
1463 pub fn checked_add(self, other
: Self) -> Option
<Self> {
1464 let (a
, b
) = self.overflowing_add(other
);
1465 if b {None}
else {Some(a)}
1468 /// Checked integer subtraction. Computes `self - other`, returning
1469 /// `None` if underflow occurred.
1476 /// assert_eq!(1u8.checked_sub(1), Some(0));
1477 /// assert_eq!(0u8.checked_sub(1), None);
1479 #[stable(feature = "rust1", since = "1.0.0")]
1481 pub fn checked_sub(self, other
: Self) -> Option
<Self> {
1482 let (a
, b
) = self.overflowing_sub(other
);
1483 if b {None}
else {Some(a)}
1486 /// Checked integer multiplication. Computes `self * other`, returning
1487 /// `None` if underflow or overflow occurred.
1494 /// assert_eq!(5u8.checked_mul(51), Some(255));
1495 /// assert_eq!(5u8.checked_mul(52), None);
1497 #[stable(feature = "rust1", since = "1.0.0")]
1499 pub fn checked_mul(self, other
: Self) -> Option
<Self> {
1500 let (a
, b
) = self.overflowing_mul(other
);
1501 if b {None}
else {Some(a)}
1504 /// Checked integer division. Computes `self / other`, returning `None`
1505 /// if `other == 0` or the operation results in underflow or overflow.
1512 /// assert_eq!(128u8.checked_div(2), Some(64));
1513 /// assert_eq!(1u8.checked_div(0), None);
1515 #[stable(feature = "rust1", since = "1.0.0")]
1517 pub fn checked_div(self, other
: Self) -> Option
<Self> {
1520 other
=> Some(self / other
),
1524 /// Checked integer remainder. Computes `self % other`, returning `None`
1525 /// if `other == 0` or the operation results in underflow or overflow.
1532 /// assert_eq!(5u32.checked_rem(2), Some(1));
1533 /// assert_eq!(5u32.checked_rem(0), None);
1535 #[stable(feature = "wrapping", since = "1.7.0")]
1537 pub fn checked_rem(self, other
: Self) -> Option
<Self> {
1545 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1548 /// Note that negating any positive integer will overflow.
1555 /// assert_eq!(0u32.checked_neg(), Some(0));
1556 /// assert_eq!(1u32.checked_neg(), None);
1558 #[stable(feature = "wrapping", since = "1.7.0")]
1560 pub fn checked_neg(self) -> Option
<Self> {
1561 let (a
, b
) = self.overflowing_neg();
1562 if b {None}
else {Some(a)}
1565 /// Checked shift left. Computes `self << rhs`, returning `None`
1566 /// if `rhs` is larger than or equal to the number of bits in `self`.
1573 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1574 /// assert_eq!(0x10u32.checked_shl(33), None);
1576 #[stable(feature = "wrapping", since = "1.7.0")]
1578 pub fn checked_shl(self, rhs
: u32) -> Option
<Self> {
1579 let (a
, b
) = self.overflowing_shl(rhs
);
1580 if b {None}
else {Some(a)}
1583 /// Checked shift right. Computes `self >> rhs`, returning `None`
1584 /// if `rhs` is larger than or equal to the number of bits in `self`.
1591 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1592 /// assert_eq!(0x10u32.checked_shr(33), None);
1594 #[stable(feature = "wrapping", since = "1.7.0")]
1596 pub fn checked_shr(self, rhs
: u32) -> Option
<Self> {
1597 let (a
, b
) = self.overflowing_shr(rhs
);
1598 if b {None}
else {Some(a)}
1601 /// Saturating integer addition. Computes `self + other`, saturating at
1602 /// the numeric bounds instead of overflowing.
1609 /// assert_eq!(100u8.saturating_add(1), 101);
1610 /// assert_eq!(200u8.saturating_add(127), 255);
1612 #[stable(feature = "rust1", since = "1.0.0")]
1614 pub fn saturating_add(self, other
: Self) -> Self {
1615 match self.checked_add(other
) {
1617 None
=> Self::max_value(),
1621 /// Saturating integer subtraction. Computes `self - other`, saturating
1622 /// at the numeric bounds instead of overflowing.
1629 /// assert_eq!(100u8.saturating_sub(27), 73);
1630 /// assert_eq!(13u8.saturating_sub(127), 0);
1632 #[stable(feature = "rust1", since = "1.0.0")]
1634 pub fn saturating_sub(self, other
: Self) -> Self {
1635 match self.checked_sub(other
) {
1637 None
=> Self::min_value(),
1641 /// Saturating integer multiplication. Computes `self * other`,
1642 /// saturating at the numeric bounds instead of overflowing.
1651 /// assert_eq!(100u32.saturating_mul(127), 12700);
1652 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1654 #[stable(feature = "wrapping", since = "1.7.0")]
1656 pub fn saturating_mul(self, other
: Self) -> Self {
1657 self.checked_mul(other
).unwrap_or(Self::max_value())
1660 /// Wrapping (modular) addition. Computes `self + other`,
1661 /// wrapping around at the boundary of the type.
1668 /// assert_eq!(200u8.wrapping_add(55), 255);
1669 /// assert_eq!(200u8.wrapping_add(155), 99);
1671 #[stable(feature = "rust1", since = "1.0.0")]
1673 pub fn wrapping_add(self, rhs
: Self) -> Self {
1675 intrinsics
::overflowing_add(self, rhs
)
1679 /// Wrapping (modular) subtraction. Computes `self - other`,
1680 /// wrapping around at the boundary of the type.
1687 /// assert_eq!(100u8.wrapping_sub(100), 0);
1688 /// assert_eq!(100u8.wrapping_sub(155), 201);
1690 #[stable(feature = "rust1", since = "1.0.0")]
1692 pub fn wrapping_sub(self, rhs
: Self) -> Self {
1694 intrinsics
::overflowing_sub(self, rhs
)
1698 /// Wrapping (modular) multiplication. Computes `self *
1699 /// other`, wrapping around at the boundary of the type.
1706 /// assert_eq!(10u8.wrapping_mul(12), 120);
1707 /// assert_eq!(25u8.wrapping_mul(12), 44);
1709 #[stable(feature = "rust1", since = "1.0.0")]
1711 pub fn wrapping_mul(self, rhs
: Self) -> Self {
1713 intrinsics
::overflowing_mul(self, rhs
)
1717 /// Wrapping (modular) division. Computes `self / other`.
1718 /// Wrapped division on unsigned types is just normal division.
1719 /// There's no way wrapping could ever happen.
1720 /// This function exists, so that all operations
1721 /// are accounted for in the wrapping operations.
1728 /// assert_eq!(100u8.wrapping_div(10), 10);
1730 #[stable(feature = "num_wrapping", since = "1.2.0")]
1732 pub fn wrapping_div(self, rhs
: Self) -> Self {
1736 /// Wrapping (modular) remainder. Computes `self % other`.
1737 /// Wrapped remainder calculation on unsigned types is
1738 /// just the regular remainder calculation.
1739 /// There's no way wrapping could ever happen.
1740 /// This function exists, so that all operations
1741 /// are accounted for in the wrapping operations.
1748 /// assert_eq!(100i8.wrapping_rem(10), 0);
1750 #[stable(feature = "num_wrapping", since = "1.2.0")]
1752 pub fn wrapping_rem(self, rhs
: Self) -> Self {
1756 /// Wrapping (modular) negation. Computes `-self`,
1757 /// wrapping around at the boundary of the type.
1759 /// Since unsigned types do not have negative equivalents
1760 /// all applications of this function will wrap (except for `-0`).
1761 /// For values smaller than the corresponding signed type's maximum
1762 /// the result is the same as casting the corresponding signed value.
1763 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1764 /// `MAX` is the corresponding signed type's maximum.
1771 /// assert_eq!(100u8.wrapping_neg(), 156);
1772 /// assert_eq!(0u8.wrapping_neg(), 0);
1773 /// assert_eq!(180u8.wrapping_neg(), 76);
1774 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1776 #[stable(feature = "num_wrapping", since = "1.2.0")]
1778 pub fn wrapping_neg(self) -> Self {
1779 self.overflowing_neg().0
1782 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1783 /// where `mask` removes any high-order bits of `rhs` that
1784 /// would cause the shift to exceed the bitwidth of the type.
1791 /// assert_eq!(1u8.wrapping_shl(7), 128);
1792 /// assert_eq!(1u8.wrapping_shl(8), 1);
1794 #[stable(feature = "num_wrapping", since = "1.2.0")]
1796 pub fn wrapping_shl(self, rhs
: u32) -> Self {
1797 self.overflowing_shl(rhs
).0
1800 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1801 /// where `mask` removes any high-order bits of `rhs` that
1802 /// would cause the shift to exceed the bitwidth of the type.
1809 /// assert_eq!(128u8.wrapping_shr(7), 1);
1810 /// assert_eq!(128u8.wrapping_shr(8), 128);
1812 #[stable(feature = "num_wrapping", since = "1.2.0")]
1814 pub fn wrapping_shr(self, rhs
: u32) -> Self {
1815 self.overflowing_shr(rhs
).0
1818 /// Calculates `self` + `rhs`
1820 /// Returns a tuple of the addition along with a boolean indicating
1821 /// whether an arithmetic overflow would occur. If an overflow would
1822 /// have occurred then the wrapped value is returned.
1831 /// assert_eq!(5u32.overflowing_add(2), (7, false));
1832 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
1835 #[stable(feature = "wrapping", since = "1.7.0")]
1836 pub fn overflowing_add(self, rhs
: Self) -> (Self, bool
) {
1838 let (a
, b
) = $
add_with_overflow(self as $ActualT
,
1844 /// Calculates `self` - `rhs`
1846 /// Returns a tuple of the subtraction 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_sub(2), (3, false));
1858 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
1861 #[stable(feature = "wrapping", since = "1.7.0")]
1862 pub fn overflowing_sub(self, rhs
: Self) -> (Self, bool
) {
1864 let (a
, b
) = $
sub_with_overflow(self as $ActualT
,
1870 /// Calculates the multiplication of `self` and `rhs`.
1872 /// Returns a tuple of the multiplication along with a boolean
1873 /// indicating whether an arithmetic overflow would occur. If an
1874 /// overflow would have occurred then the wrapped value is returned.
1881 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1882 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1885 #[stable(feature = "wrapping", since = "1.7.0")]
1886 pub fn overflowing_mul(self, rhs
: Self) -> (Self, bool
) {
1888 let (a
, b
) = $
mul_with_overflow(self as $ActualT
,
1894 /// Calculates the divisor when `self` is divided by `rhs`.
1896 /// Returns a tuple of the divisor along with a boolean indicating
1897 /// whether an arithmetic overflow would occur. Note that for unsigned
1898 /// integers overflow never occurs, so the second value is always
1903 /// This function will panic if `rhs` is 0.
1910 /// assert_eq!(5u32.overflowing_div(2), (2, false));
1913 #[stable(feature = "wrapping", since = "1.7.0")]
1914 pub fn overflowing_div(self, rhs
: Self) -> (Self, bool
) {
1918 /// Calculates the remainder when `self` is divided by `rhs`.
1920 /// Returns a tuple of the remainder after dividing along with a boolean
1921 /// indicating whether an arithmetic overflow would occur. Note that for
1922 /// unsigned integers overflow never occurs, so the second value is
1927 /// This function will panic if `rhs` is 0.
1934 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
1937 #[stable(feature = "wrapping", since = "1.7.0")]
1938 pub fn overflowing_rem(self, rhs
: Self) -> (Self, bool
) {
1942 /// Negates self in an overflowing fashion.
1944 /// Returns `!self + 1` using wrapping operations to return the value
1945 /// that represents the negation of this unsigned value. Note that for
1946 /// positive unsigned values overflow always occurs, but negating 0 does
1954 /// assert_eq!(0u32.overflowing_neg(), (0, false));
1955 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
1958 #[stable(feature = "wrapping", since = "1.7.0")]
1959 pub fn overflowing_neg(self) -> (Self, bool
) {
1960 ((!self).wrapping_add(1), self != 0)
1963 /// Shifts self left by `rhs` bits.
1965 /// Returns a tuple of the shifted version of self along with a boolean
1966 /// indicating whether the shift value was larger than or equal to the
1967 /// number of bits. If the shift value is too large, then value is
1968 /// masked (N-1) where N is the number of bits, and this value is then
1969 /// used to perform the shift.
1976 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
1977 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
1980 #[stable(feature = "wrapping", since = "1.7.0")]
1981 pub fn overflowing_shl(self, rhs
: u32) -> (Self, bool
) {
1982 (self << (rhs
& ($BITS
- 1)), (rhs
> ($BITS
- 1)))
1985 /// Shifts self right by `rhs` bits.
1987 /// Returns a tuple of the shifted version of self along with a boolean
1988 /// indicating whether the shift value was larger than or equal to the
1989 /// number of bits. If the shift value is too large, then value is
1990 /// masked (N-1) where N is the number of bits, and this value is then
1991 /// used to perform the shift.
1998 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
1999 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2002 #[stable(feature = "wrapping", since = "1.7.0")]
2003 pub fn overflowing_shr(self, rhs
: u32) -> (Self, bool
) {
2004 (self >> (rhs
& ($BITS
- 1)), (rhs
> ($BITS
- 1)))
2007 /// Raises self to the power of `exp`, using exponentiation by squaring.
2014 /// assert_eq!(2u32.pow(4), 16);
2016 #[stable(feature = "rust1", since = "1.0.0")]
2018 #[rustc_no_mir] // FIXME #29769 MIR overflow checking is TBD.
2019 pub fn pow(self, mut exp
: u32) -> Self {
2020 let mut base
= self;
2021 let mut acc
= Self::one();
2023 let mut prev_base
= self;
2024 let mut base_oflo
= false;
2028 // ensure overflow occurs in the same manner it
2029 // would have otherwise (i.e. signal any exception
2030 // it would have otherwise).
2031 acc
= acc
* (prev_base
* prev_base
);
2037 let (new_base
, new_base_oflo
) = base
.overflowing_mul(base
);
2039 base_oflo
= new_base_oflo
;
2045 /// Returns `true` if and only if `self == 2^k` for some `k`.
2052 /// assert!(16u8.is_power_of_two());
2053 /// assert!(!10u8.is_power_of_two());
2055 #[stable(feature = "rust1", since = "1.0.0")]
2057 pub fn is_power_of_two(self) -> bool
{
2058 (self.wrapping_sub(Self::one())) & self == Self::zero() &&
2059 !(self == Self::zero())
2062 /// Returns the smallest power of two greater than or equal to `self`.
2063 /// Unspecified behavior on overflow.
2070 /// assert_eq!(2u8.next_power_of_two(), 2);
2071 /// assert_eq!(3u8.next_power_of_two(), 4);
2073 #[stable(feature = "rust1", since = "1.0.0")]
2075 pub fn next_power_of_two(self) -> Self {
2076 let bits
= size_of
::<Self>() * 8;
2077 let one
: Self = Self::one();
2078 one
<< ((bits
- self.wrapping_sub(one
).leading_zeros() as usize) % bits
)
2081 /// Returns the smallest power of two greater than or equal to `n`. If
2082 /// the next power of two is greater than the type's maximum value,
2083 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2090 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2091 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2092 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2094 #[stable(feature = "rust1", since = "1.0.0")]
2095 pub fn checked_next_power_of_two(self) -> Option
<Self> {
2096 let npot
= self.next_power_of_two();
2113 intrinsics
::add_with_overflow
,
2114 intrinsics
::sub_with_overflow
,
2115 intrinsics
::mul_with_overflow
}
2120 uint_impl
! { u16, 16,
2125 intrinsics
::add_with_overflow
,
2126 intrinsics
::sub_with_overflow
,
2127 intrinsics
::mul_with_overflow
}
2132 uint_impl
! { u32, 32,
2137 intrinsics
::add_with_overflow
,
2138 intrinsics
::sub_with_overflow
,
2139 intrinsics
::mul_with_overflow
}
2144 uint_impl
! { u64, 64,
2149 intrinsics
::add_with_overflow
,
2150 intrinsics
::sub_with_overflow
,
2151 intrinsics
::mul_with_overflow
}
2154 #[cfg(target_pointer_width = "32")]
2157 uint_impl
! { u32, 32,
2162 intrinsics
::add_with_overflow
,
2163 intrinsics
::sub_with_overflow
,
2164 intrinsics
::mul_with_overflow
}
2167 #[cfg(target_pointer_width = "64")]
2170 uint_impl
! { u64, 64,
2175 intrinsics
::add_with_overflow
,
2176 intrinsics
::sub_with_overflow
,
2177 intrinsics
::mul_with_overflow
}
2180 /// A classification of floating point numbers.
2182 /// This `enum` is used as the return type for [`f32::classify()`] and [`f64::classify()`]. See
2183 /// their documentation for more.
2185 /// [`f32::classify()`]: ../../std/primitive.f32.html#method.classify
2186 /// [`f64::classify()`]: ../../std/primitive.f64.html#method.classify
2187 #[derive(Copy, Clone, PartialEq, Debug)]
2188 #[stable(feature = "rust1", since = "1.0.0")]
2189 pub enum FpCategory
{
2190 /// "Not a Number", often obtained by dividing by zero
2191 #[stable(feature = "rust1", since = "1.0.0")]
2194 /// Positive or negative infinity
2195 #[stable(feature = "rust1", since = "1.0.0")]
2198 /// Positive or negative zero
2199 #[stable(feature = "rust1", since = "1.0.0")]
2202 /// De-normalized floating point representation (less precise than `Normal`)
2203 #[stable(feature = "rust1", since = "1.0.0")]
2206 /// A regular floating point number
2207 #[stable(feature = "rust1", since = "1.0.0")]
2211 /// A built-in floating point number.
2213 #[unstable(feature = "core_float",
2214 reason
= "stable interface is via `impl f{32,64}` in later crates",
2216 pub trait Float
: Sized
{
2217 /// Returns the NaN value.
2218 #[unstable(feature = "float_extras", reason = "needs removal",
2221 /// Returns the infinite value.
2222 #[unstable(feature = "float_extras", reason = "needs removal",
2224 fn infinity() -> Self;
2225 /// Returns the negative infinite value.
2226 #[unstable(feature = "float_extras", reason = "needs removal",
2228 fn neg_infinity() -> Self;
2230 #[unstable(feature = "float_extras", reason = "needs removal",
2232 fn neg_zero() -> Self;
2234 #[unstable(feature = "float_extras", reason = "needs removal",
2238 #[unstable(feature = "float_extras", reason = "needs removal",
2242 /// Returns true if this value is NaN and false otherwise.
2243 #[stable(feature = "core", since = "1.6.0")]
2244 fn is_nan(self) -> bool
;
2245 /// Returns true if this value is positive infinity or negative infinity and
2246 /// false otherwise.
2247 #[stable(feature = "core", since = "1.6.0")]
2248 fn is_infinite(self) -> bool
;
2249 /// Returns true if this number is neither infinite nor NaN.
2250 #[stable(feature = "core", since = "1.6.0")]
2251 fn is_finite(self) -> bool
;
2252 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
2253 #[stable(feature = "core", since = "1.6.0")]
2254 fn is_normal(self) -> bool
;
2255 /// Returns the category that this number falls into.
2256 #[stable(feature = "core", since = "1.6.0")]
2257 fn classify(self) -> FpCategory
;
2259 /// Returns the mantissa, exponent and sign as integers, respectively.
2260 #[unstable(feature = "float_extras", reason = "signature is undecided",
2262 fn integer_decode(self) -> (u64, i16, i8);
2264 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2265 /// number is `Float::nan()`.
2266 #[stable(feature = "core", since = "1.6.0")]
2267 fn abs(self) -> Self;
2268 /// Returns a number that represents the sign of `self`.
2270 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2271 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2272 /// - `Float::nan()` if the number is `Float::nan()`
2273 #[stable(feature = "core", since = "1.6.0")]
2274 fn signum(self) -> Self;
2276 /// Returns `true` if `self` is positive, including `+0.0` and
2277 /// `Float::infinity()`.
2278 #[stable(feature = "core", since = "1.6.0")]
2279 fn is_sign_positive(self) -> bool
;
2280 /// Returns `true` if `self` is negative, including `-0.0` and
2281 /// `Float::neg_infinity()`.
2282 #[stable(feature = "core", since = "1.6.0")]
2283 fn is_sign_negative(self) -> bool
;
2285 /// Take the reciprocal (inverse) of a number, `1/x`.
2286 #[stable(feature = "core", since = "1.6.0")]
2287 fn recip(self) -> Self;
2289 /// Raise a number to an integer power.
2291 /// Using this function is generally faster than using `powf`
2292 #[stable(feature = "core", since = "1.6.0")]
2293 fn powi(self, n
: i32) -> Self;
2295 /// Convert radians to degrees.
2296 #[unstable(feature = "float_extras", reason = "desirability is unclear",
2298 fn to_degrees(self) -> Self;
2299 /// Convert degrees to radians.
2300 #[unstable(feature = "float_extras", reason = "desirability is unclear",
2302 fn to_radians(self) -> Self;
2305 macro_rules
! from_str_radix_int_impl
{
2307 #[stable(feature = "rust1", since = "1.0.0")]
2308 impl FromStr
for $t
{
2309 type Err
= ParseIntError
;
2310 fn from_str(src
: &str) -> Result
<Self, ParseIntError
> {
2311 from_str_radix(src
, 10)
2316 from_str_radix_int_impl
! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
2319 trait FromStrRadixHelper
: PartialOrd
+ Copy
{
2320 fn min_value() -> Self;
2321 fn from_u32(u
: u32) -> Self;
2322 fn checked_mul(&self, other
: u32) -> Option
<Self>;
2323 fn checked_sub(&self, other
: u32) -> Option
<Self>;
2324 fn checked_add(&self, other
: u32) -> Option
<Self>;
2328 ($
($t
:ty
)*) => ($
(impl FromStrRadixHelper
for $t
{
2329 fn min_value() -> Self { Self::min_value() }
2330 fn from_u32(u
: u32) -> Self { u as Self }
2331 fn checked_mul(&self, other
: u32) -> Option
<Self> {
2332 Self::checked_mul(*self, other
as Self)
2334 fn checked_sub(&self, other
: u32) -> Option
<Self> {
2335 Self::checked_sub(*self, other
as Self)
2337 fn checked_add(&self, other
: u32) -> Option
<Self> {
2338 Self::checked_add(*self, other
as Self)
2342 doit
! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
2344 fn from_str_radix
<T
: FromStrRadixHelper
>(src
: &str, radix
: u32)
2345 -> Result
<T
, ParseIntError
> {
2346 use self::IntErrorKind
::*;
2347 use self::ParseIntError
as PIE
;
2349 assert
!(radix
>= 2 && radix
<= 36,
2350 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2354 return Err(PIE { kind: Empty }
);
2357 let is_signed_ty
= T
::from_u32(0) > T
::min_value();
2359 // all valid digits are ascii, so we will just iterate over the utf8 bytes
2360 // and cast them to chars. .to_digit() will safely return None for anything
2361 // other than a valid ascii digit for the given radix, including the first-byte
2362 // of multi-byte sequences
2363 let src
= src
.as_bytes();
2365 let (is_positive
, digits
) = match src
[0] {
2366 b'
+'
=> (true, &src
[1..]),
2367 b'
-'
if is_signed_ty
=> (false, &src
[1..]),
2371 if digits
.is_empty() {
2372 return Err(PIE { kind: Empty }
);
2375 let mut result
= T
::from_u32(0);
2377 // The number is positive
2379 let x
= match (c
as char).to_digit(radix
) {
2381 None
=> return Err(PIE { kind: InvalidDigit }
),
2383 result
= match result
.checked_mul(radix
) {
2384 Some(result
) => result
,
2385 None
=> return Err(PIE { kind: Overflow }
),
2387 result
= match result
.checked_add(x
) {
2388 Some(result
) => result
,
2389 None
=> return Err(PIE { kind: Overflow }
),
2393 // The number is negative
2395 let x
= match (c
as char).to_digit(radix
) {
2397 None
=> return Err(PIE { kind: InvalidDigit }
),
2399 result
= match result
.checked_mul(radix
) {
2400 Some(result
) => result
,
2401 None
=> return Err(PIE { kind: Underflow }
),
2403 result
= match result
.checked_sub(x
) {
2404 Some(result
) => result
,
2405 None
=> return Err(PIE { kind: Underflow }
),
2412 /// An error which can be returned when parsing an integer.
2414 /// This error is used as the error type for the `from_str_radix()` functions
2415 /// on the primitive integer types, such as [`i8::from_str_radix()`].
2417 /// [`i8::from_str_radix()`]: ../../std/primitive.i8.html#method.from_str_radix
2418 #[derive(Debug, Clone, PartialEq)]
2419 #[stable(feature = "rust1", since = "1.0.0")]
2420 pub struct ParseIntError { kind: IntErrorKind }
2422 #[derive(Debug, Clone, PartialEq)]
2430 impl ParseIntError
{
2431 #[unstable(feature = "int_error_internals",
2432 reason
= "available through Error trait and this method should \
2433 not be exposed publicly",
2436 pub fn __description(&self) -> &str {
2438 IntErrorKind
::Empty
=> "cannot parse integer from empty string",
2439 IntErrorKind
::InvalidDigit
=> "invalid digit found in string",
2440 IntErrorKind
::Overflow
=> "number too large to fit in target type",
2441 IntErrorKind
::Underflow
=> "number too small to fit in target type",
2446 #[stable(feature = "rust1", since = "1.0.0")]
2447 impl fmt
::Display
for ParseIntError
{
2448 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2449 self.__description().fmt(f
)
2453 #[stable(feature = "rust1", since = "1.0.0")]
2454 pub use num
::dec2flt
::ParseFloatError
;
2456 // Conversion traits for primitive integer and float types
2457 // Conversions T -> T are covered by a blanket impl and therefore excluded
2458 // Some conversions from and to usize/isize are not implemented due to portability concerns
2459 macro_rules
! impl_from
{
2460 ($Small
: ty
, $Large
: ty
) => {
2461 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
2462 impl From
<$Small
> for $Large
{
2464 fn from(small
: $Small
) -> $Large
{
2471 // Unsigned -> Unsigned
2472 impl_from
! { u8, u16 }
2473 impl_from
! { u8, u32 }
2474 impl_from
! { u8, u64 }
2475 impl_from
! { u8, usize }
2476 impl_from
! { u16, u32 }
2477 impl_from
! { u16, u64 }
2478 impl_from
! { u32, u64 }
2481 impl_from
! { i8, i16 }
2482 impl_from
! { i8, i32 }
2483 impl_from
! { i8, i64 }
2484 impl_from
! { i8, isize }
2485 impl_from
! { i16, i32 }
2486 impl_from
! { i16, i64 }
2487 impl_from
! { i32, i64 }
2489 // Unsigned -> Signed
2490 impl_from
! { u8, i16 }
2491 impl_from
! { u8, i32 }
2492 impl_from
! { u8, i64 }
2493 impl_from
! { u16, i32 }
2494 impl_from
! { u16, i64 }
2495 impl_from
! { u32, i64 }
2497 // Note: integers can only be represented with full precision in a float if
2498 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2499 // Lossy float conversions are not implemented at this time.
2502 impl_from
! { i8, f32 }
2503 impl_from
! { i8, f64 }
2504 impl_from
! { i16, f32 }
2505 impl_from
! { i16, f64 }
2506 impl_from
! { i32, f64 }
2508 // Unsigned -> Float
2509 impl_from
! { u8, f32 }
2510 impl_from
! { u8, f64 }
2511 impl_from
! { u16, f32 }
2512 impl_from
! { u16, f64 }
2513 impl_from
! { u32, f64 }
2516 impl_from
! { f32, f64 }