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")]
17 use convert::{From, TryFrom};
20 use marker::{Copy, Sized};
22 use option::Option::{self, Some, None};
23 use result::Result::{self, Ok, Err};
24 use str::{FromStr, StrExt};
27 /// Provides intentionally-wrapped arithmetic on `T`.
29 /// Operations like `+` on `u32` values is intended to never overflow,
30 /// and in some debug configurations overflow is detected and results
31 /// in a panic. While most arithmetic falls into this category, some
32 /// code explicitly expects and relies upon modular arithmetic (e.g.,
35 /// Wrapping arithmetic can be achieved either through methods like
36 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
37 /// all standard arithmetic operations on the underlying value are
38 /// intended to have wrapping semantics.
43 /// use std::num::Wrapping;
45 /// let zero = Wrapping(0u32);
46 /// let one = Wrapping(1u32);
48 /// assert_eq!(std::u32::MAX, (zero - one).0);
50 #[stable(feature = "rust1", since = "1.0.0")]
51 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
52 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
54 #[stable(feature = "rust1", since = "1.0.0")]
55 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
56 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61 #[stable(feature = "wrapping_display", since = "1.10.0")]
62 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
63 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
69 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
70 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
75 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
76 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
77 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
82 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
83 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
84 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
89 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
90 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
91 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
98 // All these modules are technically private and only exposed for libcoretest:
104 /// Types that have a "zero" value.
106 /// This trait is intended for use in conjunction with `Add`, as an identity:
107 /// `x + T::zero() == x`.
108 #[unstable(feature = "zero_one",
109 reason = "unsure of placement, wants to use associated constants",
111 #[rustc_deprecated(since = "1.11.0", reason = "no longer used for \
113 pub trait Zero: Sized {
114 /// The "zero" (usually, additive identity) for this type.
118 /// Types that have a "one" value.
120 /// This trait is intended for use in conjunction with `Mul`, as an identity:
121 /// `x * T::one() == x`.
122 #[unstable(feature = "zero_one",
123 reason = "unsure of placement, wants to use associated constants",
125 #[rustc_deprecated(since = "1.11.0", reason = "no longer used for \
127 pub trait One: Sized {
128 /// The "one" (usually, multiplicative identity) for this type.
132 macro_rules! zero_one_impl {
134 #[unstable(feature = "zero_one",
135 reason = "unsure of placement, wants to use associated constants",
140 fn zero() -> Self { 0 }
142 #[unstable(feature = "zero_one",
143 reason = "unsure of placement, wants to use associated constants",
148 fn one() -> Self { 1 }
152 zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
154 macro_rules! zero_one_impl_float {
156 #[unstable(feature = "zero_one",
157 reason = "unsure of placement, wants to use associated constants",
162 fn zero() -> Self { 0.0 }
164 #[unstable(feature = "zero_one",
165 reason = "unsure of placement, wants to use associated constants",
170 fn one() -> Self { 1.0 }
174 zero_one_impl_float! { f32 f64 }
176 macro_rules! checked_op {
177 ($U:ty, $op:path, $x:expr, $y:expr) => {{
178 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
179 if overflowed { None } else { Some(result as Self) }
183 // `Int` + `SignedInt` implemented for signed integers
184 macro_rules! int_impl {
185 ($ActualT:ident, $UnsignedT:ty, $BITS:expr,
186 $add_with_overflow:path,
187 $sub_with_overflow:path,
188 $mul_with_overflow:path) => {
189 /// Returns the smallest value that can be represented by this integer type.
194 /// assert_eq!(i8::min_value(), -128);
196 #[stable(feature = "rust1", since = "1.0.0")]
198 pub const fn min_value() -> Self {
199 (-1 as Self) << ($BITS - 1)
202 /// Returns the largest value that can be represented by this integer type.
207 /// assert_eq!(i8::max_value(), 127);
209 #[stable(feature = "rust1", since = "1.0.0")]
211 pub const fn max_value() -> Self {
215 /// Converts a string slice in a given base to an integer.
217 /// Leading and trailing whitespace represent an error.
224 /// assert_eq!(i32::from_str_radix("A", 16), Ok(10));
226 #[stable(feature = "rust1", since = "1.0.0")]
227 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
228 from_str_radix(src, radix)
231 /// Returns the number of ones in the binary representation of `self`.
238 /// let n = -0b1000_0000i8;
240 /// assert_eq!(n.count_ones(), 1);
242 #[stable(feature = "rust1", since = "1.0.0")]
244 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
246 /// Returns the number of zeros in the binary representation of `self`.
253 /// let n = -0b1000_0000i8;
255 /// assert_eq!(n.count_zeros(), 7);
257 #[stable(feature = "rust1", since = "1.0.0")]
259 pub fn count_zeros(self) -> u32 {
263 /// Returns the number of leading zeros in the binary representation
273 /// assert_eq!(n.leading_zeros(), 0);
275 #[stable(feature = "rust1", since = "1.0.0")]
277 pub fn leading_zeros(self) -> u32 {
278 (self as $UnsignedT).leading_zeros()
281 /// Returns the number of trailing zeros in the binary representation
291 /// assert_eq!(n.trailing_zeros(), 2);
293 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn trailing_zeros(self) -> u32 {
296 (self as $UnsignedT).trailing_zeros()
299 /// Shifts the bits to the left by a specified amount, `n`,
300 /// wrapping the truncated bits to the end of the resulting integer.
302 /// Please note this isn't the same operation as `<<`!
309 /// let n = 0x0123456789ABCDEFi64;
310 /// let m = -0x76543210FEDCBA99i64;
312 /// assert_eq!(n.rotate_left(32), m);
314 #[stable(feature = "rust1", since = "1.0.0")]
316 pub fn rotate_left(self, n: u32) -> Self {
317 (self as $UnsignedT).rotate_left(n) as Self
320 /// Shifts the bits to the right by a specified amount, `n`,
321 /// wrapping the truncated bits to the beginning of the resulting
324 /// Please note this isn't the same operation as `>>`!
331 /// let n = 0x0123456789ABCDEFi64;
332 /// let m = -0xFEDCBA987654322i64;
334 /// assert_eq!(n.rotate_right(4), m);
336 #[stable(feature = "rust1", since = "1.0.0")]
338 pub fn rotate_right(self, n: u32) -> Self {
339 (self as $UnsignedT).rotate_right(n) as Self
342 /// Reverses the byte order of the integer.
349 /// let n = 0x0123456789ABCDEFi64;
350 /// let m = -0x1032547698BADCFFi64;
352 /// assert_eq!(n.swap_bytes(), m);
354 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn swap_bytes(self) -> Self {
357 (self as $UnsignedT).swap_bytes() as Self
360 /// Converts an integer from big endian to the target's endianness.
362 /// On big endian this is a no-op. On little endian the bytes are
370 /// let n = 0x0123456789ABCDEFi64;
372 /// if cfg!(target_endian = "big") {
373 /// assert_eq!(i64::from_be(n), n)
375 /// assert_eq!(i64::from_be(n), n.swap_bytes())
378 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn from_be(x: Self) -> Self {
381 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
384 /// Converts an integer from little endian to the target's endianness.
386 /// On little endian this is a no-op. On big endian the bytes are
394 /// let n = 0x0123456789ABCDEFi64;
396 /// if cfg!(target_endian = "little") {
397 /// assert_eq!(i64::from_le(n), n)
399 /// assert_eq!(i64::from_le(n), n.swap_bytes())
402 #[stable(feature = "rust1", since = "1.0.0")]
404 pub fn from_le(x: Self) -> Self {
405 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
408 /// Converts `self` to big endian from the target's endianness.
410 /// On big endian this is a no-op. On little endian the bytes are
418 /// let n = 0x0123456789ABCDEFi64;
420 /// if cfg!(target_endian = "big") {
421 /// assert_eq!(n.to_be(), n)
423 /// assert_eq!(n.to_be(), n.swap_bytes())
426 #[stable(feature = "rust1", since = "1.0.0")]
428 pub fn to_be(self) -> Self { // or not to be?
429 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
432 /// Converts `self` to little endian from the target's endianness.
434 /// On little endian this is a no-op. On big endian the bytes are
442 /// let n = 0x0123456789ABCDEFi64;
444 /// if cfg!(target_endian = "little") {
445 /// assert_eq!(n.to_le(), n)
447 /// assert_eq!(n.to_le(), n.swap_bytes())
450 #[stable(feature = "rust1", since = "1.0.0")]
452 pub fn to_le(self) -> Self {
453 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
456 /// Checked integer addition. Computes `self + other`, returning `None`
457 /// if overflow occurred.
464 /// assert_eq!(7i16.checked_add(32760), Some(32767));
465 /// assert_eq!(8i16.checked_add(32760), None);
467 #[stable(feature = "rust1", since = "1.0.0")]
469 pub fn checked_add(self, other: Self) -> Option<Self> {
470 let (a, b) = self.overflowing_add(other);
471 if b {None} else {Some(a)}
474 /// Checked integer subtraction. Computes `self - other`, returning
475 /// `None` if underflow occurred.
482 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
483 /// assert_eq!((-128i8).checked_sub(1), None);
485 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn checked_sub(self, other: Self) -> Option<Self> {
488 let (a, b) = self.overflowing_sub(other);
489 if b {None} else {Some(a)}
492 /// Checked integer multiplication. Computes `self * other`, returning
493 /// `None` if underflow or overflow occurred.
500 /// assert_eq!(6i8.checked_mul(21), Some(126));
501 /// assert_eq!(6i8.checked_mul(22), None);
503 #[stable(feature = "rust1", since = "1.0.0")]
505 pub fn checked_mul(self, other: Self) -> Option<Self> {
506 let (a, b) = self.overflowing_mul(other);
507 if b {None} else {Some(a)}
510 /// Checked integer division. Computes `self / other`, returning `None`
511 /// if `other == 0` or the operation results in underflow or overflow.
518 /// assert_eq!((-127i8).checked_div(-1), Some(127));
519 /// assert_eq!((-128i8).checked_div(-1), None);
520 /// assert_eq!((1i8).checked_div(0), None);
522 #[stable(feature = "rust1", since = "1.0.0")]
524 pub fn checked_div(self, other: Self) -> Option<Self> {
528 let (a, b) = self.overflowing_div(other);
529 if b {None} else {Some(a)}
533 /// Checked integer remainder. Computes `self % other`, returning `None`
534 /// if `other == 0` or the operation results in underflow or overflow.
543 /// assert_eq!(5i32.checked_rem(2), Some(1));
544 /// assert_eq!(5i32.checked_rem(0), None);
545 /// assert_eq!(i32::MIN.checked_rem(-1), None);
547 #[stable(feature = "wrapping", since = "1.7.0")]
549 pub fn checked_rem(self, other: Self) -> Option<Self> {
553 let (a, b) = self.overflowing_rem(other);
554 if b {None} else {Some(a)}
558 /// Checked negation. Computes `-self`, returning `None` if `self ==
568 /// assert_eq!(5i32.checked_neg(), Some(-5));
569 /// assert_eq!(i32::MIN.checked_neg(), None);
571 #[stable(feature = "wrapping", since = "1.7.0")]
573 pub fn checked_neg(self) -> Option<Self> {
574 let (a, b) = self.overflowing_neg();
575 if b {None} else {Some(a)}
578 /// Checked shift left. Computes `self << rhs`, returning `None`
579 /// if `rhs` is larger than or equal to the number of bits in `self`.
586 /// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
587 /// assert_eq!(0x10i32.checked_shl(33), None);
589 #[stable(feature = "wrapping", since = "1.7.0")]
591 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
592 let (a, b) = self.overflowing_shl(rhs);
593 if b {None} else {Some(a)}
596 /// Checked shift right. Computes `self >> rhs`, returning `None`
597 /// if `rhs` is larger than or equal to the number of bits in `self`.
604 /// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
605 /// assert_eq!(0x10i32.checked_shr(33), None);
607 #[stable(feature = "wrapping", since = "1.7.0")]
609 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
610 let (a, b) = self.overflowing_shr(rhs);
611 if b {None} else {Some(a)}
614 /// Saturating integer addition. Computes `self + other`, saturating at
615 /// the numeric bounds instead of overflowing.
622 /// assert_eq!(100i8.saturating_add(1), 101);
623 /// assert_eq!(100i8.saturating_add(127), 127);
625 #[stable(feature = "rust1", since = "1.0.0")]
627 pub fn saturating_add(self, other: Self) -> Self {
628 match self.checked_add(other) {
630 None if other >= 0 => Self::max_value(),
631 None => Self::min_value(),
635 /// Saturating integer subtraction. Computes `self - other`, saturating
636 /// at the numeric bounds instead of overflowing.
643 /// assert_eq!(100i8.saturating_sub(127), -27);
644 /// assert_eq!((-100i8).saturating_sub(127), -128);
646 #[stable(feature = "rust1", since = "1.0.0")]
648 pub fn saturating_sub(self, other: Self) -> Self {
649 match self.checked_sub(other) {
651 None if other >= 0 => Self::min_value(),
652 None => Self::max_value(),
656 /// Saturating integer multiplication. Computes `self * other`,
657 /// saturating at the numeric bounds instead of overflowing.
666 /// assert_eq!(100i32.saturating_mul(127), 12700);
667 /// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
668 /// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
670 #[stable(feature = "wrapping", since = "1.7.0")]
672 pub fn saturating_mul(self, other: Self) -> Self {
673 self.checked_mul(other).unwrap_or_else(|| {
674 if (self < 0 && other < 0) || (self > 0 && other > 0) {
682 /// Wrapping (modular) addition. Computes `self + other`,
683 /// wrapping around at the boundary of the type.
690 /// assert_eq!(100i8.wrapping_add(27), 127);
691 /// assert_eq!(100i8.wrapping_add(127), -29);
693 #[stable(feature = "rust1", since = "1.0.0")]
695 pub fn wrapping_add(self, rhs: Self) -> Self {
697 intrinsics::overflowing_add(self, rhs)
701 /// Wrapping (modular) subtraction. Computes `self - other`,
702 /// wrapping around at the boundary of the type.
709 /// assert_eq!(0i8.wrapping_sub(127), -127);
710 /// assert_eq!((-2i8).wrapping_sub(127), 127);
712 #[stable(feature = "rust1", since = "1.0.0")]
714 pub fn wrapping_sub(self, rhs: Self) -> Self {
716 intrinsics::overflowing_sub(self, rhs)
720 /// Wrapping (modular) multiplication. Computes `self *
721 /// other`, wrapping around at the boundary of the type.
728 /// assert_eq!(10i8.wrapping_mul(12), 120);
729 /// assert_eq!(11i8.wrapping_mul(12), -124);
731 #[stable(feature = "rust1", since = "1.0.0")]
733 pub fn wrapping_mul(self, rhs: Self) -> Self {
735 intrinsics::overflowing_mul(self, rhs)
739 /// Wrapping (modular) division. Computes `self / other`,
740 /// wrapping around at the boundary of the type.
742 /// The only case where such wrapping can occur is when one
743 /// divides `MIN / -1` on a signed type (where `MIN` is the
744 /// negative minimal value for the type); this is equivalent
745 /// to `-MIN`, a positive value that is too large to represent
746 /// in the type. In such a case, this function returns `MIN`
751 /// This function will panic if `rhs` is 0.
758 /// assert_eq!(100u8.wrapping_div(10), 10);
759 /// assert_eq!((-128i8).wrapping_div(-1), -128);
761 #[stable(feature = "num_wrapping", since = "1.2.0")]
763 pub fn wrapping_div(self, rhs: Self) -> Self {
764 self.overflowing_div(rhs).0
767 /// Wrapping (modular) remainder. Computes `self % other`,
768 /// wrapping around at the boundary of the type.
770 /// Such wrap-around never actually occurs mathematically;
771 /// implementation artifacts make `x % y` invalid for `MIN /
772 /// -1` on a signed type (where `MIN` is the negative
773 /// minimal value). In such a case, this function returns `0`.
777 /// This function will panic if `rhs` is 0.
784 /// assert_eq!(100i8.wrapping_rem(10), 0);
785 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
787 #[stable(feature = "num_wrapping", since = "1.2.0")]
789 pub fn wrapping_rem(self, rhs: Self) -> Self {
790 self.overflowing_rem(rhs).0
793 /// Wrapping (modular) negation. Computes `-self`,
794 /// wrapping around at the boundary of the type.
796 /// The only case where such wrapping can occur is when one
797 /// negates `MIN` on a signed type (where `MIN` is the
798 /// negative minimal value for the type); this is a positive
799 /// value that is too large to represent in the type. In such
800 /// a case, this function returns `MIN` itself.
807 /// assert_eq!(100i8.wrapping_neg(), -100);
808 /// assert_eq!((-128i8).wrapping_neg(), -128);
810 #[stable(feature = "num_wrapping", since = "1.2.0")]
812 pub fn wrapping_neg(self) -> Self {
813 self.overflowing_neg().0
816 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
817 /// where `mask` removes any high-order bits of `rhs` that
818 /// would cause the shift to exceed the bitwidth of the type.
820 /// Note that this is *not* the same as a rotate-left; the
821 /// RHS of a wrapping shift-left is restricted to the range
822 /// of the type, rather than the bits shifted out of the LHS
823 /// being returned to the other end. The primitive integer
824 /// types all implement a `rotate_left` function, which may
825 /// be what you want instead.
832 /// assert_eq!((-1i8).wrapping_shl(7), -128);
833 /// assert_eq!((-1i8).wrapping_shl(8), -1);
835 #[stable(feature = "num_wrapping", since = "1.2.0")]
837 pub fn wrapping_shl(self, rhs: u32) -> Self {
838 self.overflowing_shl(rhs).0
841 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
842 /// where `mask` removes any high-order bits of `rhs` that
843 /// would cause the shift to exceed the bitwidth of the type.
845 /// Note that this is *not* the same as a rotate-right; the
846 /// RHS of a wrapping shift-right is restricted to the range
847 /// of the type, rather than the bits shifted out of the LHS
848 /// being returned to the other end. The primitive integer
849 /// types all implement a `rotate_right` function, which may
850 /// be what you want instead.
857 /// assert_eq!((-128i8).wrapping_shr(7), -1);
858 /// assert_eq!((-128i8).wrapping_shr(8), -128);
860 #[stable(feature = "num_wrapping", since = "1.2.0")]
862 pub fn wrapping_shr(self, rhs: u32) -> Self {
863 self.overflowing_shr(rhs).0
866 /// Calculates `self` + `rhs`
868 /// Returns a tuple of the addition along with a boolean indicating
869 /// whether an arithmetic overflow would occur. If an overflow would
870 /// have occurred then the wrapped value is returned.
879 /// assert_eq!(5i32.overflowing_add(2), (7, false));
880 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
883 #[stable(feature = "wrapping", since = "1.7.0")]
884 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
886 let (a, b) = $add_with_overflow(self as $ActualT,
892 /// Calculates `self` - `rhs`
894 /// Returns a tuple of the subtraction along with a boolean indicating
895 /// whether an arithmetic overflow would occur. If an overflow would
896 /// have occurred then the wrapped value is returned.
905 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
906 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
909 #[stable(feature = "wrapping", since = "1.7.0")]
910 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
912 let (a, b) = $sub_with_overflow(self as $ActualT,
918 /// Calculates the multiplication of `self` and `rhs`.
920 /// Returns a tuple of the multiplication along with a boolean
921 /// indicating whether an arithmetic overflow would occur. If an
922 /// overflow would have occurred then the wrapped value is returned.
929 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
930 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
933 #[stable(feature = "wrapping", since = "1.7.0")]
934 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
936 let (a, b) = $mul_with_overflow(self as $ActualT,
942 /// Calculates the divisor when `self` is divided by `rhs`.
944 /// Returns a tuple of the divisor along with a boolean indicating
945 /// whether an arithmetic overflow would occur. If an overflow would
946 /// occur then self is returned.
950 /// This function will panic if `rhs` is 0.
959 /// assert_eq!(5i32.overflowing_div(2), (2, false));
960 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
963 #[stable(feature = "wrapping", since = "1.7.0")]
964 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
965 if self == Self::min_value() && rhs == -1 {
972 /// Calculates the remainder when `self` is divided by `rhs`.
974 /// Returns a tuple of the remainder after dividing along with a boolean
975 /// indicating whether an arithmetic overflow would occur. If an
976 /// overflow would occur then 0 is returned.
980 /// This function will panic if `rhs` is 0.
989 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
990 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
993 #[stable(feature = "wrapping", since = "1.7.0")]
994 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
995 if self == Self::min_value() && rhs == -1 {
1002 /// Negates self, overflowing if this is equal to the minimum value.
1004 /// Returns a tuple of the negated version of self along with a boolean
1005 /// indicating whether an overflow happened. If `self` is the minimum
1006 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
1007 /// value will be returned again and `true` will be returned for an
1008 /// overflow happening.
1017 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
1018 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
1021 #[stable(feature = "wrapping", since = "1.7.0")]
1022 pub fn overflowing_neg(self) -> (Self, bool) {
1023 if self == Self::min_value() {
1024 (Self::min_value(), true)
1030 /// Shifts self left by `rhs` bits.
1032 /// Returns a tuple of the shifted version of self along with a boolean
1033 /// indicating whether the shift value was larger than or equal to the
1034 /// number of bits. If the shift value is too large, then value is
1035 /// masked (N-1) where N is the number of bits, and this value is then
1036 /// used to perform the shift.
1043 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
1044 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
1047 #[stable(feature = "wrapping", since = "1.7.0")]
1048 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1049 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1052 /// Shifts self right by `rhs` bits.
1054 /// Returns a tuple of the shifted version of self along with a boolean
1055 /// indicating whether the shift value was larger than or equal to the
1056 /// number of bits. If the shift value is too large, then value is
1057 /// masked (N-1) where N is the number of bits, and this value is then
1058 /// used to perform the shift.
1065 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
1066 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1069 #[stable(feature = "wrapping", since = "1.7.0")]
1070 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1071 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1074 /// Raises self to the power of `exp`, using exponentiation by squaring.
1081 /// let x: i32 = 2; // or any other integer type
1083 /// assert_eq!(x.pow(4), 16);
1085 #[stable(feature = "rust1", since = "1.0.0")]
1087 #[rustc_inherit_overflow_checks]
1088 pub fn pow(self, mut exp: u32) -> Self {
1089 let mut base = self;
1100 // Deal with the final bit of the exponent separately, since
1101 // squaring the base afterwards is not necessary and may cause a
1102 // needless overflow.
1110 /// Computes the absolute value of `self`.
1112 /// # Overflow behavior
1114 /// The absolute value of `i32::min_value()` cannot be represented as an
1115 /// `i32`, and attempting to calculate it will cause an overflow. This
1116 /// means that code in debug mode will trigger a panic on this case and
1117 /// optimized code will return `i32::min_value()` without a panic.
1124 /// assert_eq!(10i8.abs(), 10);
1125 /// assert_eq!((-10i8).abs(), 10);
1127 #[stable(feature = "rust1", since = "1.0.0")]
1129 #[rustc_inherit_overflow_checks]
1130 pub fn abs(self) -> Self {
1131 if self.is_negative() {
1132 // Note that the #[inline] above means that the overflow
1133 // semantics of this negation depend on the crate we're being
1141 /// Returns a number representing sign of `self`.
1143 /// - `0` if the number is zero
1144 /// - `1` if the number is positive
1145 /// - `-1` if the number is negative
1152 /// assert_eq!(10i8.signum(), 1);
1153 /// assert_eq!(0i8.signum(), 0);
1154 /// assert_eq!((-10i8).signum(), -1);
1156 #[stable(feature = "rust1", since = "1.0.0")]
1158 pub fn signum(self) -> Self {
1166 /// Returns `true` if `self` is positive and `false` if the number
1167 /// is zero or negative.
1174 /// assert!(10i8.is_positive());
1175 /// assert!(!(-10i8).is_positive());
1177 #[stable(feature = "rust1", since = "1.0.0")]
1179 pub fn is_positive(self) -> bool { self > 0 }
1181 /// Returns `true` if `self` is negative and `false` if the number
1182 /// is zero or positive.
1189 /// assert!((-10i8).is_negative());
1190 /// assert!(!10i8.is_negative());
1192 #[stable(feature = "rust1", since = "1.0.0")]
1194 pub fn is_negative(self) -> bool { self < 0 }
1200 int_impl! { i8, u8, 8,
1201 intrinsics::add_with_overflow,
1202 intrinsics::sub_with_overflow,
1203 intrinsics::mul_with_overflow }
1208 int_impl! { i16, u16, 16,
1209 intrinsics::add_with_overflow,
1210 intrinsics::sub_with_overflow,
1211 intrinsics::mul_with_overflow }
1216 int_impl! { i32, u32, 32,
1217 intrinsics::add_with_overflow,
1218 intrinsics::sub_with_overflow,
1219 intrinsics::mul_with_overflow }
1224 int_impl! { i64, u64, 64,
1225 intrinsics::add_with_overflow,
1226 intrinsics::sub_with_overflow,
1227 intrinsics::mul_with_overflow }
1230 #[cfg(target_pointer_width = "16")]
1233 int_impl! { i16, u16, 16,
1234 intrinsics::add_with_overflow,
1235 intrinsics::sub_with_overflow,
1236 intrinsics::mul_with_overflow }
1239 #[cfg(target_pointer_width = "32")]
1242 int_impl! { i32, u32, 32,
1243 intrinsics::add_with_overflow,
1244 intrinsics::sub_with_overflow,
1245 intrinsics::mul_with_overflow }
1248 #[cfg(target_pointer_width = "64")]
1251 int_impl! { i64, u64, 64,
1252 intrinsics::add_with_overflow,
1253 intrinsics::sub_with_overflow,
1254 intrinsics::mul_with_overflow }
1257 // `Int` + `UnsignedInt` implemented for unsigned integers
1258 macro_rules! uint_impl {
1259 ($ActualT:ty, $BITS:expr,
1264 $add_with_overflow:path,
1265 $sub_with_overflow:path,
1266 $mul_with_overflow:path) => {
1267 /// Returns the smallest value that can be represented by this integer type.
1272 /// assert_eq!(u8::min_value(), 0);
1274 #[stable(feature = "rust1", since = "1.0.0")]
1276 pub const fn min_value() -> Self { 0 }
1278 /// Returns the largest value that can be represented by this integer type.
1283 /// assert_eq!(u8::max_value(), 255);
1285 #[stable(feature = "rust1", since = "1.0.0")]
1287 pub const fn max_value() -> Self { !0 }
1289 /// Converts a string slice in a given base to an integer.
1291 /// Leading and trailing whitespace represent an error.
1298 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1302 from_str_radix(src, radix)
1305 /// Returns the number of ones in the binary representation of `self`.
1312 /// let n = 0b01001100u8;
1314 /// assert_eq!(n.count_ones(), 3);
1316 #[stable(feature = "rust1", since = "1.0.0")]
1318 pub fn count_ones(self) -> u32 {
1319 unsafe { $ctpop(self as $ActualT) as u32 }
1322 /// Returns the number of zeros in the binary representation of `self`.
1329 /// let n = 0b01001100u8;
1331 /// assert_eq!(n.count_zeros(), 5);
1333 #[stable(feature = "rust1", since = "1.0.0")]
1335 pub fn count_zeros(self) -> u32 {
1336 (!self).count_ones()
1339 /// Returns the number of leading zeros in the binary representation
1347 /// let n = 0b0101000u16;
1349 /// assert_eq!(n.leading_zeros(), 10);
1351 #[stable(feature = "rust1", since = "1.0.0")]
1353 pub fn leading_zeros(self) -> u32 {
1354 unsafe { $ctlz(self as $ActualT) as u32 }
1357 /// Returns the number of trailing zeros in the binary representation
1365 /// let n = 0b0101000u16;
1367 /// assert_eq!(n.trailing_zeros(), 3);
1369 #[stable(feature = "rust1", since = "1.0.0")]
1371 pub fn trailing_zeros(self) -> u32 {
1372 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1373 // emits two conditional moves on x86_64. By promoting the value to
1374 // u16 and setting bit 8, we get better code without any conditional
1376 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1377 // pending, remove this workaround once LLVM generates better code
1381 intrinsics::cttz(self as u16 | 0x100) as u32
1383 intrinsics::cttz(self) as u32
1388 /// Shifts the bits to the left by a specified amount, `n`,
1389 /// wrapping the truncated bits to the end of the resulting integer.
1391 /// Please note this isn't the same operation as `<<`!
1398 /// let n = 0x0123456789ABCDEFu64;
1399 /// let m = 0x3456789ABCDEF012u64;
1401 /// assert_eq!(n.rotate_left(12), m);
1403 #[stable(feature = "rust1", since = "1.0.0")]
1405 pub fn rotate_left(self, n: u32) -> Self {
1406 // Protect against undefined behaviour for over-long bit shifts
1408 (self << n) | (self >> (($BITS - n) % $BITS))
1411 /// Shifts the bits to the right by a specified amount, `n`,
1412 /// wrapping the truncated bits to the beginning of the resulting
1415 /// Please note this isn't the same operation as `>>`!
1422 /// let n = 0x0123456789ABCDEFu64;
1423 /// let m = 0xDEF0123456789ABCu64;
1425 /// assert_eq!(n.rotate_right(12), m);
1427 #[stable(feature = "rust1", since = "1.0.0")]
1429 pub fn rotate_right(self, n: u32) -> Self {
1430 // Protect against undefined behaviour for over-long bit shifts
1432 (self >> n) | (self << (($BITS - n) % $BITS))
1435 /// Reverses the byte order of the integer.
1442 /// let n = 0x0123456789ABCDEFu64;
1443 /// let m = 0xEFCDAB8967452301u64;
1445 /// assert_eq!(n.swap_bytes(), m);
1447 #[stable(feature = "rust1", since = "1.0.0")]
1449 pub fn swap_bytes(self) -> Self {
1450 unsafe { $bswap(self as $ActualT) as Self }
1453 /// Converts an integer from big endian to the target's endianness.
1455 /// On big endian this is a no-op. On little endian the bytes are
1463 /// let n = 0x0123456789ABCDEFu64;
1465 /// if cfg!(target_endian = "big") {
1466 /// assert_eq!(u64::from_be(n), n)
1468 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1471 #[stable(feature = "rust1", since = "1.0.0")]
1473 pub fn from_be(x: Self) -> Self {
1474 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1477 /// Converts an integer from little endian to the target's endianness.
1479 /// On little endian this is a no-op. On big endian the bytes are
1487 /// let n = 0x0123456789ABCDEFu64;
1489 /// if cfg!(target_endian = "little") {
1490 /// assert_eq!(u64::from_le(n), n)
1492 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1495 #[stable(feature = "rust1", since = "1.0.0")]
1497 pub fn from_le(x: Self) -> Self {
1498 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1501 /// Converts `self` to big endian from the target's endianness.
1503 /// On big endian this is a no-op. On little endian the bytes are
1511 /// let n = 0x0123456789ABCDEFu64;
1513 /// if cfg!(target_endian = "big") {
1514 /// assert_eq!(n.to_be(), n)
1516 /// assert_eq!(n.to_be(), n.swap_bytes())
1519 #[stable(feature = "rust1", since = "1.0.0")]
1521 pub fn to_be(self) -> Self { // or not to be?
1522 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1525 /// Converts `self` to little endian from the target's endianness.
1527 /// On little endian this is a no-op. On big endian the bytes are
1535 /// let n = 0x0123456789ABCDEFu64;
1537 /// if cfg!(target_endian = "little") {
1538 /// assert_eq!(n.to_le(), n)
1540 /// assert_eq!(n.to_le(), n.swap_bytes())
1543 #[stable(feature = "rust1", since = "1.0.0")]
1545 pub fn to_le(self) -> Self {
1546 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1549 /// Checked integer addition. Computes `self + other`, returning `None`
1550 /// if overflow occurred.
1557 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1558 /// assert_eq!(6u16.checked_add(65530), None);
1560 #[stable(feature = "rust1", since = "1.0.0")]
1562 pub fn checked_add(self, other: Self) -> Option<Self> {
1563 let (a, b) = self.overflowing_add(other);
1564 if b {None} else {Some(a)}
1567 /// Checked integer subtraction. Computes `self - other`, returning
1568 /// `None` if underflow occurred.
1575 /// assert_eq!(1u8.checked_sub(1), Some(0));
1576 /// assert_eq!(0u8.checked_sub(1), None);
1578 #[stable(feature = "rust1", since = "1.0.0")]
1580 pub fn checked_sub(self, other: Self) -> Option<Self> {
1581 let (a, b) = self.overflowing_sub(other);
1582 if b {None} else {Some(a)}
1585 /// Checked integer multiplication. Computes `self * other`, returning
1586 /// `None` if underflow or overflow occurred.
1593 /// assert_eq!(5u8.checked_mul(51), Some(255));
1594 /// assert_eq!(5u8.checked_mul(52), None);
1596 #[stable(feature = "rust1", since = "1.0.0")]
1598 pub fn checked_mul(self, other: Self) -> Option<Self> {
1599 let (a, b) = self.overflowing_mul(other);
1600 if b {None} else {Some(a)}
1603 /// Checked integer division. Computes `self / other`, returning `None`
1604 /// if `other == 0` or the operation results in underflow or overflow.
1611 /// assert_eq!(128u8.checked_div(2), Some(64));
1612 /// assert_eq!(1u8.checked_div(0), None);
1614 #[stable(feature = "rust1", since = "1.0.0")]
1616 pub fn checked_div(self, other: Self) -> Option<Self> {
1619 other => Some(self / other),
1623 /// Checked integer remainder. Computes `self % other`, returning `None`
1624 /// if `other == 0` or the operation results in underflow or overflow.
1631 /// assert_eq!(5u32.checked_rem(2), Some(1));
1632 /// assert_eq!(5u32.checked_rem(0), None);
1634 #[stable(feature = "wrapping", since = "1.7.0")]
1636 pub fn checked_rem(self, other: Self) -> Option<Self> {
1644 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1647 /// Note that negating any positive integer will overflow.
1654 /// assert_eq!(0u32.checked_neg(), Some(0));
1655 /// assert_eq!(1u32.checked_neg(), None);
1657 #[stable(feature = "wrapping", since = "1.7.0")]
1659 pub fn checked_neg(self) -> Option<Self> {
1660 let (a, b) = self.overflowing_neg();
1661 if b {None} else {Some(a)}
1664 /// Checked shift left. Computes `self << rhs`, returning `None`
1665 /// if `rhs` is larger than or equal to the number of bits in `self`.
1672 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1673 /// assert_eq!(0x10u32.checked_shl(33), None);
1675 #[stable(feature = "wrapping", since = "1.7.0")]
1677 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1678 let (a, b) = self.overflowing_shl(rhs);
1679 if b {None} else {Some(a)}
1682 /// Checked shift right. Computes `self >> rhs`, returning `None`
1683 /// if `rhs` is larger than or equal to the number of bits in `self`.
1690 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1691 /// assert_eq!(0x10u32.checked_shr(33), None);
1693 #[stable(feature = "wrapping", since = "1.7.0")]
1695 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1696 let (a, b) = self.overflowing_shr(rhs);
1697 if b {None} else {Some(a)}
1700 /// Saturating integer addition. Computes `self + other`, saturating at
1701 /// the numeric bounds instead of overflowing.
1708 /// assert_eq!(100u8.saturating_add(1), 101);
1709 /// assert_eq!(200u8.saturating_add(127), 255);
1711 #[stable(feature = "rust1", since = "1.0.0")]
1713 pub fn saturating_add(self, other: Self) -> Self {
1714 match self.checked_add(other) {
1716 None => Self::max_value(),
1720 /// Saturating integer subtraction. Computes `self - other`, saturating
1721 /// at the numeric bounds instead of overflowing.
1728 /// assert_eq!(100u8.saturating_sub(27), 73);
1729 /// assert_eq!(13u8.saturating_sub(127), 0);
1731 #[stable(feature = "rust1", since = "1.0.0")]
1733 pub fn saturating_sub(self, other: Self) -> Self {
1734 match self.checked_sub(other) {
1736 None => Self::min_value(),
1740 /// Saturating integer multiplication. Computes `self * other`,
1741 /// saturating at the numeric bounds instead of overflowing.
1750 /// assert_eq!(100u32.saturating_mul(127), 12700);
1751 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1753 #[stable(feature = "wrapping", since = "1.7.0")]
1755 pub fn saturating_mul(self, other: Self) -> Self {
1756 self.checked_mul(other).unwrap_or(Self::max_value())
1759 /// Wrapping (modular) addition. Computes `self + other`,
1760 /// wrapping around at the boundary of the type.
1767 /// assert_eq!(200u8.wrapping_add(55), 255);
1768 /// assert_eq!(200u8.wrapping_add(155), 99);
1770 #[stable(feature = "rust1", since = "1.0.0")]
1772 pub fn wrapping_add(self, rhs: Self) -> Self {
1774 intrinsics::overflowing_add(self, rhs)
1778 /// Wrapping (modular) subtraction. Computes `self - other`,
1779 /// wrapping around at the boundary of the type.
1786 /// assert_eq!(100u8.wrapping_sub(100), 0);
1787 /// assert_eq!(100u8.wrapping_sub(155), 201);
1789 #[stable(feature = "rust1", since = "1.0.0")]
1791 pub fn wrapping_sub(self, rhs: Self) -> Self {
1793 intrinsics::overflowing_sub(self, rhs)
1797 /// Wrapping (modular) multiplication. Computes `self *
1798 /// other`, wrapping around at the boundary of the type.
1805 /// assert_eq!(10u8.wrapping_mul(12), 120);
1806 /// assert_eq!(25u8.wrapping_mul(12), 44);
1808 #[stable(feature = "rust1", since = "1.0.0")]
1810 pub fn wrapping_mul(self, rhs: Self) -> Self {
1812 intrinsics::overflowing_mul(self, rhs)
1816 /// Wrapping (modular) division. Computes `self / other`.
1817 /// Wrapped division on unsigned types is just normal division.
1818 /// There's no way wrapping could ever happen.
1819 /// This function exists, so that all operations
1820 /// are accounted for in the wrapping operations.
1827 /// assert_eq!(100u8.wrapping_div(10), 10);
1829 #[stable(feature = "num_wrapping", since = "1.2.0")]
1831 pub fn wrapping_div(self, rhs: Self) -> Self {
1835 /// Wrapping (modular) remainder. Computes `self % other`.
1836 /// Wrapped remainder calculation on unsigned types is
1837 /// just the regular remainder calculation.
1838 /// There's no way wrapping could ever happen.
1839 /// This function exists, so that all operations
1840 /// are accounted for in the wrapping operations.
1847 /// assert_eq!(100u8.wrapping_rem(10), 0);
1849 #[stable(feature = "num_wrapping", since = "1.2.0")]
1851 pub fn wrapping_rem(self, rhs: Self) -> Self {
1855 /// Wrapping (modular) negation. Computes `-self`,
1856 /// wrapping around at the boundary of the type.
1858 /// Since unsigned types do not have negative equivalents
1859 /// all applications of this function will wrap (except for `-0`).
1860 /// For values smaller than the corresponding signed type's maximum
1861 /// the result is the same as casting the corresponding signed value.
1862 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1863 /// `MAX` is the corresponding signed type's maximum.
1870 /// assert_eq!(100u8.wrapping_neg(), 156);
1871 /// assert_eq!(0u8.wrapping_neg(), 0);
1872 /// assert_eq!(180u8.wrapping_neg(), 76);
1873 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1875 #[stable(feature = "num_wrapping", since = "1.2.0")]
1877 pub fn wrapping_neg(self) -> Self {
1878 self.overflowing_neg().0
1881 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1882 /// where `mask` removes any high-order bits of `rhs` that
1883 /// would cause the shift to exceed the bitwidth of the type.
1885 /// Note that this is *not* the same as a rotate-left; the
1886 /// RHS of a wrapping shift-left is restricted to the range
1887 /// of the type, rather than the bits shifted out of the LHS
1888 /// being returned to the other end. The primitive integer
1889 /// types all implement a `rotate_left` function, which may
1890 /// be what you want instead.
1897 /// assert_eq!(1u8.wrapping_shl(7), 128);
1898 /// assert_eq!(1u8.wrapping_shl(8), 1);
1900 #[stable(feature = "num_wrapping", since = "1.2.0")]
1902 pub fn wrapping_shl(self, rhs: u32) -> Self {
1903 self.overflowing_shl(rhs).0
1906 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1907 /// where `mask` removes any high-order bits of `rhs` that
1908 /// would cause the shift to exceed the bitwidth of the type.
1910 /// Note that this is *not* the same as a rotate-right; the
1911 /// RHS of a wrapping shift-right is restricted to the range
1912 /// of the type, rather than the bits shifted out of the LHS
1913 /// being returned to the other end. The primitive integer
1914 /// types all implement a `rotate_right` function, which may
1915 /// be what you want instead.
1922 /// assert_eq!(128u8.wrapping_shr(7), 1);
1923 /// assert_eq!(128u8.wrapping_shr(8), 128);
1925 #[stable(feature = "num_wrapping", since = "1.2.0")]
1927 pub fn wrapping_shr(self, rhs: u32) -> Self {
1928 self.overflowing_shr(rhs).0
1931 /// Calculates `self` + `rhs`
1933 /// Returns a tuple of the addition along with a boolean indicating
1934 /// whether an arithmetic overflow would occur. If an overflow would
1935 /// have occurred then the wrapped value is returned.
1944 /// assert_eq!(5u32.overflowing_add(2), (7, false));
1945 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
1948 #[stable(feature = "wrapping", since = "1.7.0")]
1949 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1951 let (a, b) = $add_with_overflow(self as $ActualT,
1957 /// Calculates `self` - `rhs`
1959 /// Returns a tuple of the subtraction along with a boolean indicating
1960 /// whether an arithmetic overflow would occur. If an overflow would
1961 /// have occurred then the wrapped value is returned.
1970 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
1971 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
1974 #[stable(feature = "wrapping", since = "1.7.0")]
1975 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1977 let (a, b) = $sub_with_overflow(self as $ActualT,
1983 /// Calculates the multiplication of `self` and `rhs`.
1985 /// Returns a tuple of the multiplication along with a boolean
1986 /// indicating whether an arithmetic overflow would occur. If an
1987 /// overflow would have occurred then the wrapped value is returned.
1994 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1995 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1998 #[stable(feature = "wrapping", since = "1.7.0")]
1999 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2001 let (a, b) = $mul_with_overflow(self as $ActualT,
2007 /// Calculates the divisor when `self` is divided by `rhs`.
2009 /// Returns a tuple of the divisor along with a boolean indicating
2010 /// whether an arithmetic overflow would occur. Note that for unsigned
2011 /// integers overflow never occurs, so the second value is always
2016 /// This function will panic if `rhs` is 0.
2023 /// assert_eq!(5u32.overflowing_div(2), (2, false));
2026 #[stable(feature = "wrapping", since = "1.7.0")]
2027 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2031 /// Calculates the remainder when `self` is divided by `rhs`.
2033 /// Returns a tuple of the remainder after dividing along with a boolean
2034 /// indicating whether an arithmetic overflow would occur. Note that for
2035 /// unsigned integers overflow never occurs, so the second value is
2040 /// This function will panic if `rhs` is 0.
2047 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
2050 #[stable(feature = "wrapping", since = "1.7.0")]
2051 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2055 /// Negates self in an overflowing fashion.
2057 /// Returns `!self + 1` using wrapping operations to return the value
2058 /// that represents the negation of this unsigned value. Note that for
2059 /// positive unsigned values overflow always occurs, but negating 0 does
2067 /// assert_eq!(0u32.overflowing_neg(), (0, false));
2068 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
2071 #[stable(feature = "wrapping", since = "1.7.0")]
2072 pub fn overflowing_neg(self) -> (Self, bool) {
2073 ((!self).wrapping_add(1), self != 0)
2076 /// Shifts self left by `rhs` bits.
2078 /// Returns a tuple of the shifted version of self along with a boolean
2079 /// indicating whether the shift value was larger than or equal to the
2080 /// number of bits. If the shift value is too large, then value is
2081 /// masked (N-1) where N is the number of bits, and this value is then
2082 /// used to perform the shift.
2089 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
2090 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
2093 #[stable(feature = "wrapping", since = "1.7.0")]
2094 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2095 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
2098 /// Shifts self right by `rhs` bits.
2100 /// Returns a tuple of the shifted version of self along with a boolean
2101 /// indicating whether the shift value was larger than or equal to the
2102 /// number of bits. If the shift value is too large, then value is
2103 /// masked (N-1) where N is the number of bits, and this value is then
2104 /// used to perform the shift.
2111 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
2112 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2115 #[stable(feature = "wrapping", since = "1.7.0")]
2116 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2117 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
2120 /// Raises self to the power of `exp`, using exponentiation by squaring.
2127 /// assert_eq!(2u32.pow(4), 16);
2129 #[stable(feature = "rust1", since = "1.0.0")]
2131 #[rustc_inherit_overflow_checks]
2132 pub fn pow(self, mut exp: u32) -> Self {
2133 let mut base = self;
2136 let mut prev_base = self;
2137 let mut base_oflo = false;
2141 // ensure overflow occurs in the same manner it
2142 // would have otherwise (i.e. signal any exception
2143 // it would have otherwise).
2144 acc = acc * (prev_base * prev_base);
2150 let (new_base, new_base_oflo) = base.overflowing_mul(base);
2152 base_oflo = new_base_oflo;
2158 /// Returns `true` if and only if `self == 2^k` for some `k`.
2165 /// assert!(16u8.is_power_of_two());
2166 /// assert!(!10u8.is_power_of_two());
2168 #[stable(feature = "rust1", since = "1.0.0")]
2170 pub fn is_power_of_two(self) -> bool {
2171 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2174 /// Returns the smallest power of two greater than or equal to `self`.
2175 /// Unspecified behavior on overflow.
2182 /// assert_eq!(2u8.next_power_of_two(), 2);
2183 /// assert_eq!(3u8.next_power_of_two(), 4);
2185 #[stable(feature = "rust1", since = "1.0.0")]
2187 pub fn next_power_of_two(self) -> Self {
2188 let bits = size_of::<Self>() * 8;
2190 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
2193 /// Returns the smallest power of two greater than or equal to `n`. If
2194 /// the next power of two is greater than the type's maximum value,
2195 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2202 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2203 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2204 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2206 #[stable(feature = "rust1", since = "1.0.0")]
2207 pub fn checked_next_power_of_two(self) -> Option<Self> {
2208 let npot = self.next_power_of_two();
2225 intrinsics::add_with_overflow,
2226 intrinsics::sub_with_overflow,
2227 intrinsics::mul_with_overflow }
2232 uint_impl! { u16, 16,
2237 intrinsics::add_with_overflow,
2238 intrinsics::sub_with_overflow,
2239 intrinsics::mul_with_overflow }
2244 uint_impl! { u32, 32,
2249 intrinsics::add_with_overflow,
2250 intrinsics::sub_with_overflow,
2251 intrinsics::mul_with_overflow }
2256 uint_impl! { u64, 64,
2261 intrinsics::add_with_overflow,
2262 intrinsics::sub_with_overflow,
2263 intrinsics::mul_with_overflow }
2266 #[cfg(target_pointer_width = "16")]
2269 uint_impl! { u16, 16,
2274 intrinsics::add_with_overflow,
2275 intrinsics::sub_with_overflow,
2276 intrinsics::mul_with_overflow }
2278 #[cfg(target_pointer_width = "32")]
2281 uint_impl! { u32, 32,
2286 intrinsics::add_with_overflow,
2287 intrinsics::sub_with_overflow,
2288 intrinsics::mul_with_overflow }
2291 #[cfg(target_pointer_width = "64")]
2294 uint_impl! { u64, 64,
2299 intrinsics::add_with_overflow,
2300 intrinsics::sub_with_overflow,
2301 intrinsics::mul_with_overflow }
2304 /// A classification of floating point numbers.
2306 /// This `enum` is used as the return type for [`f32::classify()`] and [`f64::classify()`]. See
2307 /// their documentation for more.
2309 /// [`f32::classify()`]: ../../std/primitive.f32.html#method.classify
2310 /// [`f64::classify()`]: ../../std/primitive.f64.html#method.classify
2315 /// use std::num::FpCategory;
2318 /// let num = 12.4_f32;
2319 /// let inf = f32::INFINITY;
2320 /// let zero = 0f32;
2321 /// let sub: f32 = 1.1754942e-38;
2322 /// let nan = f32::NAN;
2324 /// assert_eq!(num.classify(), FpCategory::Normal);
2325 /// assert_eq!(inf.classify(), FpCategory::Infinite);
2326 /// assert_eq!(zero.classify(), FpCategory::Zero);
2327 /// assert_eq!(nan.classify(), FpCategory::Nan);
2328 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
2330 #[derive(Copy, Clone, PartialEq, Debug)]
2331 #[stable(feature = "rust1", since = "1.0.0")]
2332 pub enum FpCategory {
2333 /// "Not a Number", often obtained by dividing by zero.
2334 #[stable(feature = "rust1", since = "1.0.0")]
2337 /// Positive or negative infinity.
2338 #[stable(feature = "rust1", since = "1.0.0")]
2341 /// Positive or negative zero.
2342 #[stable(feature = "rust1", since = "1.0.0")]
2345 /// De-normalized floating point representation (less precise than `Normal`).
2346 #[stable(feature = "rust1", since = "1.0.0")]
2349 /// A regular floating point number.
2350 #[stable(feature = "rust1", since = "1.0.0")]
2354 /// A built-in floating point number.
2356 #[unstable(feature = "core_float",
2357 reason = "stable interface is via `impl f{32,64}` in later crates",
2359 pub trait Float: Sized {
2360 /// Returns the NaN value.
2361 #[unstable(feature = "float_extras", reason = "needs removal",
2363 #[rustc_deprecated(since = "1.11.0",
2364 reason = "never really came to fruition and easily \
2365 implementable outside the standard library")]
2367 /// Returns the infinite value.
2368 #[unstable(feature = "float_extras", reason = "needs removal",
2370 #[rustc_deprecated(since = "1.11.0",
2371 reason = "never really came to fruition and easily \
2372 implementable outside the standard library")]
2373 fn infinity() -> Self;
2374 /// Returns the negative infinite value.
2375 #[unstable(feature = "float_extras", reason = "needs removal",
2377 #[rustc_deprecated(since = "1.11.0",
2378 reason = "never really came to fruition and easily \
2379 implementable outside the standard library")]
2380 fn neg_infinity() -> Self;
2382 #[unstable(feature = "float_extras", reason = "needs removal",
2384 #[rustc_deprecated(since = "1.11.0",
2385 reason = "never really came to fruition and easily \
2386 implementable outside the standard library")]
2387 fn neg_zero() -> Self;
2389 #[unstable(feature = "float_extras", reason = "needs removal",
2391 #[rustc_deprecated(since = "1.11.0",
2392 reason = "never really came to fruition and easily \
2393 implementable outside the standard library")]
2396 #[unstable(feature = "float_extras", reason = "needs removal",
2398 #[rustc_deprecated(since = "1.11.0",
2399 reason = "never really came to fruition and easily \
2400 implementable outside the standard library")]
2403 /// Returns true if this value is NaN and false otherwise.
2404 #[stable(feature = "core", since = "1.6.0")]
2405 fn is_nan(self) -> bool;
2406 /// Returns true if this value is positive infinity or negative infinity and
2407 /// false otherwise.
2408 #[stable(feature = "core", since = "1.6.0")]
2409 fn is_infinite(self) -> bool;
2410 /// Returns true if this number is neither infinite nor NaN.
2411 #[stable(feature = "core", since = "1.6.0")]
2412 fn is_finite(self) -> bool;
2413 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
2414 #[stable(feature = "core", since = "1.6.0")]
2415 fn is_normal(self) -> bool;
2416 /// Returns the category that this number falls into.
2417 #[stable(feature = "core", since = "1.6.0")]
2418 fn classify(self) -> FpCategory;
2420 /// Returns the mantissa, exponent and sign as integers, respectively.
2421 #[unstable(feature = "float_extras", reason = "signature is undecided",
2423 #[rustc_deprecated(since = "1.11.0",
2424 reason = "never really came to fruition and easily \
2425 implementable outside the standard library")]
2426 fn integer_decode(self) -> (u64, i16, i8);
2428 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2429 /// number is `Float::nan()`.
2430 #[stable(feature = "core", since = "1.6.0")]
2431 fn abs(self) -> Self;
2432 /// Returns a number that represents the sign of `self`.
2434 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2435 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2436 /// - `Float::nan()` if the number is `Float::nan()`
2437 #[stable(feature = "core", since = "1.6.0")]
2438 fn signum(self) -> Self;
2440 /// Returns `true` if `self` is positive, including `+0.0` and
2441 /// `Float::infinity()`.
2442 #[stable(feature = "core", since = "1.6.0")]
2443 fn is_sign_positive(self) -> bool;
2444 /// Returns `true` if `self` is negative, including `-0.0` and
2445 /// `Float::neg_infinity()`.
2446 #[stable(feature = "core", since = "1.6.0")]
2447 fn is_sign_negative(self) -> bool;
2449 /// Take the reciprocal (inverse) of a number, `1/x`.
2450 #[stable(feature = "core", since = "1.6.0")]
2451 fn recip(self) -> Self;
2453 /// Raise a number to an integer power.
2455 /// Using this function is generally faster than using `powf`
2456 #[stable(feature = "core", since = "1.6.0")]
2457 fn powi(self, n: i32) -> Self;
2459 /// Convert radians to degrees.
2460 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2461 fn to_degrees(self) -> Self;
2462 /// Convert degrees to radians.
2463 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2464 fn to_radians(self) -> Self;
2467 macro_rules! from_str_radix_int_impl {
2469 #[stable(feature = "rust1", since = "1.0.0")]
2470 impl FromStr for $t {
2471 type Err = ParseIntError;
2472 fn from_str(src: &str) -> Result<Self, ParseIntError> {
2473 from_str_radix(src, 10)
2478 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
2480 /// The error type returned when a checked integral type conversion fails.
2481 #[unstable(feature = "try_from", issue = "33417")]
2482 #[derive(Debug, Copy, Clone)]
2483 pub struct TryFromIntError(());
2485 impl TryFromIntError {
2486 #[unstable(feature = "int_error_internals",
2487 reason = "available through Error trait and this method should \
2488 not be exposed publicly",
2491 pub fn __description(&self) -> &str {
2492 "out of range integral type conversion attempted"
2496 #[unstable(feature = "try_from", issue = "33417")]
2497 impl fmt::Display for TryFromIntError {
2498 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2499 self.__description().fmt(fmt)
2503 macro_rules! same_sign_from_int_impl {
2504 ($storage:ty, $target:ty, $($source:ty),*) => {$(
2505 #[stable(feature = "rust1", since = "1.0.0")]
2506 impl TryFrom<$source> for $target {
2507 type Err = TryFromIntError;
2509 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2510 let min = <$target as FromStrRadixHelper>::min_value() as $storage;
2511 let max = <$target as FromStrRadixHelper>::max_value() as $storage;
2512 if u as $storage < min || u as $storage > max {
2513 Err(TryFromIntError(()))
2522 same_sign_from_int_impl!(u64, u8, u8, u16, u32, u64, usize);
2523 same_sign_from_int_impl!(i64, i8, i8, i16, i32, i64, isize);
2524 same_sign_from_int_impl!(u64, u16, u8, u16, u32, u64, usize);
2525 same_sign_from_int_impl!(i64, i16, i8, i16, i32, i64, isize);
2526 same_sign_from_int_impl!(u64, u32, u8, u16, u32, u64, usize);
2527 same_sign_from_int_impl!(i64, i32, i8, i16, i32, i64, isize);
2528 same_sign_from_int_impl!(u64, u64, u8, u16, u32, u64, usize);
2529 same_sign_from_int_impl!(i64, i64, i8, i16, i32, i64, isize);
2530 same_sign_from_int_impl!(u64, usize, u8, u16, u32, u64, usize);
2531 same_sign_from_int_impl!(i64, isize, i8, i16, i32, i64, isize);
2533 macro_rules! cross_sign_from_int_impl {
2534 ($unsigned:ty, $($signed:ty),*) => {$(
2535 #[stable(feature = "rust1", since = "1.0.0")]
2536 impl TryFrom<$unsigned> for $signed {
2537 type Err = TryFromIntError;
2539 fn try_from(u: $unsigned) -> Result<$signed, TryFromIntError> {
2540 let max = <$signed as FromStrRadixHelper>::max_value() as u64;
2542 Err(TryFromIntError(()))
2549 #[stable(feature = "rust1", since = "1.0.0")]
2550 impl TryFrom<$signed> for $unsigned {
2551 type Err = TryFromIntError;
2553 fn try_from(u: $signed) -> Result<$unsigned, TryFromIntError> {
2554 let max = <$unsigned as FromStrRadixHelper>::max_value() as u64;
2555 if u < 0 || u as u64 > max {
2556 Err(TryFromIntError(()))
2565 cross_sign_from_int_impl!(u8, i8, i16, i32, i64, isize);
2566 cross_sign_from_int_impl!(u16, i8, i16, i32, i64, isize);
2567 cross_sign_from_int_impl!(u32, i8, i16, i32, i64, isize);
2568 cross_sign_from_int_impl!(u64, i8, i16, i32, i64, isize);
2569 cross_sign_from_int_impl!(usize, i8, i16, i32, i64, isize);
2572 trait FromStrRadixHelper: PartialOrd + Copy {
2573 fn min_value() -> Self;
2574 fn max_value() -> Self;
2575 fn from_u32(u: u32) -> Self;
2576 fn checked_mul(&self, other: u32) -> Option<Self>;
2577 fn checked_sub(&self, other: u32) -> Option<Self>;
2578 fn checked_add(&self, other: u32) -> Option<Self>;
2582 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
2583 fn min_value() -> Self { Self::min_value() }
2584 fn max_value() -> Self { Self::max_value() }
2585 fn from_u32(u: u32) -> Self { u as Self }
2586 fn checked_mul(&self, other: u32) -> Option<Self> {
2587 Self::checked_mul(*self, other as Self)
2589 fn checked_sub(&self, other: u32) -> Option<Self> {
2590 Self::checked_sub(*self, other as Self)
2592 fn checked_add(&self, other: u32) -> Option<Self> {
2593 Self::checked_add(*self, other as Self)
2597 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
2599 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
2600 -> Result<T, ParseIntError> {
2601 use self::IntErrorKind::*;
2602 use self::ParseIntError as PIE;
2604 assert!(radix >= 2 && radix <= 36,
2605 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2609 return Err(PIE { kind: Empty });
2612 let is_signed_ty = T::from_u32(0) > T::min_value();
2614 // all valid digits are ascii, so we will just iterate over the utf8 bytes
2615 // and cast them to chars. .to_digit() will safely return None for anything
2616 // other than a valid ascii digit for the given radix, including the first-byte
2617 // of multi-byte sequences
2618 let src = src.as_bytes();
2620 let (is_positive, digits) = match src[0] {
2621 b'+' => (true, &src[1..]),
2622 b'-' if is_signed_ty => (false, &src[1..]),
2626 if digits.is_empty() {
2627 return Err(PIE { kind: Empty });
2630 let mut result = T::from_u32(0);
2632 // The number is positive
2634 let x = match (c as char).to_digit(radix) {
2636 None => return Err(PIE { kind: InvalidDigit }),
2638 result = match result.checked_mul(radix) {
2639 Some(result) => result,
2640 None => return Err(PIE { kind: Overflow }),
2642 result = match result.checked_add(x) {
2643 Some(result) => result,
2644 None => return Err(PIE { kind: Overflow }),
2648 // The number is negative
2650 let x = match (c as char).to_digit(radix) {
2652 None => return Err(PIE { kind: InvalidDigit }),
2654 result = match result.checked_mul(radix) {
2655 Some(result) => result,
2656 None => return Err(PIE { kind: Underflow }),
2658 result = match result.checked_sub(x) {
2659 Some(result) => result,
2660 None => return Err(PIE { kind: Underflow }),
2667 /// An error which can be returned when parsing an integer.
2669 /// This error is used as the error type for the `from_str_radix()` functions
2670 /// on the primitive integer types, such as [`i8::from_str_radix()`].
2672 /// [`i8::from_str_radix()`]: ../../std/primitive.i8.html#method.from_str_radix
2673 #[derive(Debug, Clone, PartialEq)]
2674 #[stable(feature = "rust1", since = "1.0.0")]
2675 pub struct ParseIntError { kind: IntErrorKind }
2677 #[derive(Debug, Clone, PartialEq)]
2685 impl ParseIntError {
2686 #[unstable(feature = "int_error_internals",
2687 reason = "available through Error trait and this method should \
2688 not be exposed publicly",
2691 pub fn __description(&self) -> &str {
2693 IntErrorKind::Empty => "cannot parse integer from empty string",
2694 IntErrorKind::InvalidDigit => "invalid digit found in string",
2695 IntErrorKind::Overflow => "number too large to fit in target type",
2696 IntErrorKind::Underflow => "number too small to fit in target type",
2701 #[stable(feature = "rust1", since = "1.0.0")]
2702 impl fmt::Display for ParseIntError {
2703 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2704 self.__description().fmt(f)
2708 #[stable(feature = "rust1", since = "1.0.0")]
2709 pub use num::dec2flt::ParseFloatError;
2711 // Conversion traits for primitive integer and float types
2712 // Conversions T -> T are covered by a blanket impl and therefore excluded
2713 // Some conversions from and to usize/isize are not implemented due to portability concerns
2714 macro_rules! impl_from {
2715 ($Small: ty, $Large: ty) => {
2716 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
2717 impl From<$Small> for $Large {
2719 fn from(small: $Small) -> $Large {
2726 // Unsigned -> Unsigned
2727 impl_from! { u8, u16 }
2728 impl_from! { u8, u32 }
2729 impl_from! { u8, u64 }
2730 impl_from! { u8, usize }
2731 impl_from! { u16, u32 }
2732 impl_from! { u16, u64 }
2733 impl_from! { u32, u64 }
2736 impl_from! { i8, i16 }
2737 impl_from! { i8, i32 }
2738 impl_from! { i8, i64 }
2739 impl_from! { i8, isize }
2740 impl_from! { i16, i32 }
2741 impl_from! { i16, i64 }
2742 impl_from! { i32, i64 }
2744 // Unsigned -> Signed
2745 impl_from! { u8, i16 }
2746 impl_from! { u8, i32 }
2747 impl_from! { u8, i64 }
2748 impl_from! { u16, i32 }
2749 impl_from! { u16, i64 }
2750 impl_from! { u32, i64 }
2752 // Note: integers can only be represented with full precision in a float if
2753 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2754 // Lossy float conversions are not implemented at this time.
2757 impl_from! { i8, f32 }
2758 impl_from! { i8, f64 }
2759 impl_from! { i16, f32 }
2760 impl_from! { i16, f64 }
2761 impl_from! { i32, f64 }
2763 // Unsigned -> Float
2764 impl_from! { u8, f32 }
2765 impl_from! { u8, f64 }
2766 impl_from! { u16, f32 }
2767 impl_from! { u16, f64 }
2768 impl_from! { u32, f64 }
2771 impl_from! { f32, f64 }