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.
749 /// assert_eq!(1u8.wrapping_shl(7), 128);
750 /// assert_eq!(1u8.wrapping_shl(8), 1);
752 #[stable(feature = "num_wrapping", since = "1.2.0")]
754 pub fn wrapping_shl(self, rhs: u32) -> Self {
755 self.overflowing_shl(rhs).0
758 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
759 /// where `mask` removes any high-order bits of `rhs` that
760 /// would cause the shift to exceed the bitwidth of the type.
767 /// assert_eq!(128u8.wrapping_shr(7), 1);
768 /// assert_eq!(128u8.wrapping_shr(8), 128);
770 #[stable(feature = "num_wrapping", since = "1.2.0")]
772 pub fn wrapping_shr(self, rhs: u32) -> Self {
773 self.overflowing_shr(rhs).0
776 /// Calculates `self` + `rhs`
778 /// Returns a tuple of the addition along with a boolean indicating
779 /// whether an arithmetic overflow would occur. If an overflow would
780 /// have occurred then the wrapped value is returned.
789 /// assert_eq!(5i32.overflowing_add(2), (7, false));
790 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
793 #[stable(feature = "wrapping", since = "1.7.0")]
794 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
796 let (a, b) = $add_with_overflow(self as $ActualT,
802 /// Calculates `self` - `rhs`
804 /// Returns a tuple of the subtraction along with a boolean indicating
805 /// whether an arithmetic overflow would occur. If an overflow would
806 /// have occurred then the wrapped value is returned.
815 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
816 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
819 #[stable(feature = "wrapping", since = "1.7.0")]
820 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
822 let (a, b) = $sub_with_overflow(self as $ActualT,
828 /// Calculates the multiplication of `self` and `rhs`.
830 /// Returns a tuple of the multiplication along with a boolean
831 /// indicating whether an arithmetic overflow would occur. If an
832 /// overflow would have occurred then the wrapped value is returned.
839 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
840 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
843 #[stable(feature = "wrapping", since = "1.7.0")]
844 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
846 let (a, b) = $mul_with_overflow(self as $ActualT,
852 /// Calculates the divisor when `self` is divided by `rhs`.
854 /// Returns a tuple of the divisor along with a boolean indicating
855 /// whether an arithmetic overflow would occur. If an overflow would
856 /// occur then self is returned.
860 /// This function will panic if `rhs` is 0.
869 /// assert_eq!(5i32.overflowing_div(2), (2, false));
870 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
873 #[stable(feature = "wrapping", since = "1.7.0")]
874 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
875 if self == Self::min_value() && rhs == -1 {
882 /// Calculates the remainder when `self` is divided by `rhs`.
884 /// Returns a tuple of the remainder after dividing along with a boolean
885 /// indicating whether an arithmetic overflow would occur. If an
886 /// overflow would occur then 0 is returned.
890 /// This function will panic if `rhs` is 0.
899 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
900 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
903 #[stable(feature = "wrapping", since = "1.7.0")]
904 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
905 if self == Self::min_value() && rhs == -1 {
912 /// Negates self, overflowing if this is equal to the minimum value.
914 /// Returns a tuple of the negated version of self along with a boolean
915 /// indicating whether an overflow happened. If `self` is the minimum
916 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
917 /// value will be returned again and `true` will be returned for an
918 /// overflow happening.
927 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
928 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
931 #[stable(feature = "wrapping", since = "1.7.0")]
932 pub fn overflowing_neg(self) -> (Self, bool) {
933 if self == Self::min_value() {
934 (Self::min_value(), true)
940 /// Shifts self left by `rhs` bits.
942 /// Returns a tuple of the shifted version of self along with a boolean
943 /// indicating whether the shift value was larger than or equal to the
944 /// number of bits. If the shift value is too large, then value is
945 /// masked (N-1) where N is the number of bits, and this value is then
946 /// used to perform the shift.
953 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
954 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
957 #[stable(feature = "wrapping", since = "1.7.0")]
958 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
959 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
962 /// Shifts self right by `rhs` bits.
964 /// Returns a tuple of the shifted version of self along with a boolean
965 /// indicating whether the shift value was larger than or equal to the
966 /// number of bits. If the shift value is too large, then value is
967 /// masked (N-1) where N is the number of bits, and this value is then
968 /// used to perform the shift.
975 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
976 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
979 #[stable(feature = "wrapping", since = "1.7.0")]
980 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
981 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
984 /// Raises self to the power of `exp`, using exponentiation by squaring.
991 /// let x: i32 = 2; // or any other integer type
993 /// assert_eq!(x.pow(4), 16);
995 #[stable(feature = "rust1", since = "1.0.0")]
997 pub fn pow(self, mut exp: u32) -> Self {
999 let mut acc = Self::one();
1009 // Deal with the final bit of the exponent separately, since
1010 // squaring the base afterwards is not necessary and may cause a
1011 // needless overflow.
1019 /// Computes the absolute value of `self`.
1021 /// # Overflow behavior
1023 /// The absolute value of `i32::min_value()` cannot be represented as an
1024 /// `i32`, and attempting to calculate it will cause an overflow. This
1025 /// means that code in debug mode will trigger a panic on this case and
1026 /// optimized code will return `i32::min_value()` without a panic.
1033 /// assert_eq!(10i8.abs(), 10);
1034 /// assert_eq!((-10i8).abs(), 10);
1036 #[stable(feature = "rust1", since = "1.0.0")]
1038 pub fn abs(self) -> Self {
1039 if self.is_negative() {
1040 // Note that the #[inline] above means that the overflow
1041 // semantics of this negation depend on the crate we're being
1049 /// Returns a number representing sign of `self`.
1051 /// - `0` if the number is zero
1052 /// - `1` if the number is positive
1053 /// - `-1` if the number is negative
1060 /// assert_eq!(10i8.signum(), 1);
1061 /// assert_eq!(0i8.signum(), 0);
1062 /// assert_eq!((-10i8).signum(), -1);
1064 #[stable(feature = "rust1", since = "1.0.0")]
1066 pub fn signum(self) -> Self {
1074 /// Returns `true` if `self` is positive and `false` if the number
1075 /// is zero or negative.
1082 /// assert!(10i8.is_positive());
1083 /// assert!(!(-10i8).is_positive());
1085 #[stable(feature = "rust1", since = "1.0.0")]
1087 pub fn is_positive(self) -> bool { self > 0 }
1089 /// Returns `true` if `self` is negative and `false` if the number
1090 /// is zero or positive.
1097 /// assert!((-10i8).is_negative());
1098 /// assert!(!10i8.is_negative());
1100 #[stable(feature = "rust1", since = "1.0.0")]
1102 pub fn is_negative(self) -> bool { self < 0 }
1108 int_impl! { i8, u8, 8,
1109 intrinsics::add_with_overflow,
1110 intrinsics::sub_with_overflow,
1111 intrinsics::mul_with_overflow }
1116 int_impl! { i16, u16, 16,
1117 intrinsics::add_with_overflow,
1118 intrinsics::sub_with_overflow,
1119 intrinsics::mul_with_overflow }
1124 int_impl! { i32, u32, 32,
1125 intrinsics::add_with_overflow,
1126 intrinsics::sub_with_overflow,
1127 intrinsics::mul_with_overflow }
1132 int_impl! { i64, u64, 64,
1133 intrinsics::add_with_overflow,
1134 intrinsics::sub_with_overflow,
1135 intrinsics::mul_with_overflow }
1138 #[cfg(target_pointer_width = "32")]
1141 int_impl! { i32, u32, 32,
1142 intrinsics::add_with_overflow,
1143 intrinsics::sub_with_overflow,
1144 intrinsics::mul_with_overflow }
1147 #[cfg(target_pointer_width = "64")]
1150 int_impl! { i64, u64, 64,
1151 intrinsics::add_with_overflow,
1152 intrinsics::sub_with_overflow,
1153 intrinsics::mul_with_overflow }
1156 // `Int` + `UnsignedInt` implemented for unsigned integers
1157 macro_rules! uint_impl {
1158 ($ActualT:ty, $BITS:expr,
1163 $add_with_overflow:path,
1164 $sub_with_overflow:path,
1165 $mul_with_overflow:path) => {
1166 /// Returns the smallest value that can be represented by this integer type.
1167 #[stable(feature = "rust1", since = "1.0.0")]
1169 pub const fn min_value() -> Self { 0 }
1171 /// Returns the largest value that can be represented by this integer type.
1172 #[stable(feature = "rust1", since = "1.0.0")]
1174 pub const fn max_value() -> Self { !0 }
1176 /// Converts a string slice in a given base to an integer.
1178 /// Leading and trailing whitespace represent an error.
1182 /// * src - A string slice
1183 /// * radix - The base to use. Must lie in the range [2 .. 36]
1187 /// `Err(ParseIntError)` if the string did not represent a valid number.
1188 /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1191 from_str_radix(src, radix)
1194 /// Returns the number of ones in the binary representation of `self`.
1201 /// let n = 0b01001100u8;
1203 /// assert_eq!(n.count_ones(), 3);
1205 #[stable(feature = "rust1", since = "1.0.0")]
1207 pub fn count_ones(self) -> u32 {
1208 unsafe { $ctpop(self as $ActualT) as u32 }
1211 /// Returns the number of zeros in the binary representation of `self`.
1218 /// let n = 0b01001100u8;
1220 /// assert_eq!(n.count_zeros(), 5);
1222 #[stable(feature = "rust1", since = "1.0.0")]
1224 pub fn count_zeros(self) -> u32 {
1225 (!self).count_ones()
1228 /// Returns the number of leading zeros in the binary representation
1236 /// let n = 0b0101000u16;
1238 /// assert_eq!(n.leading_zeros(), 10);
1240 #[stable(feature = "rust1", since = "1.0.0")]
1242 pub fn leading_zeros(self) -> u32 {
1243 unsafe { $ctlz(self as $ActualT) as u32 }
1246 /// Returns the number of trailing zeros in the binary representation
1254 /// let n = 0b0101000u16;
1256 /// assert_eq!(n.trailing_zeros(), 3);
1258 #[stable(feature = "rust1", since = "1.0.0")]
1260 pub fn trailing_zeros(self) -> u32 {
1261 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1262 // emits two conditional moves on x86_64. By promoting the value to
1263 // u16 and setting bit 8, we get better code without any conditional
1265 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1266 // pending, remove this workaround once LLVM generates better code
1270 intrinsics::cttz(self as u16 | 0x100) as u32
1272 intrinsics::cttz(self) as u32
1277 /// Shifts the bits to the left by a specified amount, `n`,
1278 /// wrapping the truncated bits to the end of the resulting integer.
1285 /// let n = 0x0123456789ABCDEFu64;
1286 /// let m = 0x3456789ABCDEF012u64;
1288 /// assert_eq!(n.rotate_left(12), m);
1290 #[stable(feature = "rust1", since = "1.0.0")]
1292 pub fn rotate_left(self, n: u32) -> Self {
1293 // Protect against undefined behaviour for over-long bit shifts
1295 (self << n) | (self >> (($BITS - n) % $BITS))
1298 /// Shifts the bits to the right by a specified amount, `n`,
1299 /// wrapping the truncated bits to the beginning of the resulting
1307 /// let n = 0x0123456789ABCDEFu64;
1308 /// let m = 0xDEF0123456789ABCu64;
1310 /// assert_eq!(n.rotate_right(12), m);
1312 #[stable(feature = "rust1", since = "1.0.0")]
1314 pub fn rotate_right(self, n: u32) -> Self {
1315 // Protect against undefined behaviour for over-long bit shifts
1317 (self >> n) | (self << (($BITS - n) % $BITS))
1320 /// Reverses the byte order of the integer.
1327 /// let n = 0x0123456789ABCDEFu64;
1328 /// let m = 0xEFCDAB8967452301u64;
1330 /// assert_eq!(n.swap_bytes(), m);
1332 #[stable(feature = "rust1", since = "1.0.0")]
1334 pub fn swap_bytes(self) -> Self {
1335 unsafe { $bswap(self as $ActualT) as Self }
1338 /// Converts an integer from big endian to the target's endianness.
1340 /// On big endian this is a no-op. On little endian the bytes are
1348 /// let n = 0x0123456789ABCDEFu64;
1350 /// if cfg!(target_endian = "big") {
1351 /// assert_eq!(u64::from_be(n), n)
1353 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1356 #[stable(feature = "rust1", since = "1.0.0")]
1358 pub fn from_be(x: Self) -> Self {
1359 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1362 /// Converts an integer from little endian to the target's endianness.
1364 /// On little endian this is a no-op. On big endian the bytes are
1372 /// let n = 0x0123456789ABCDEFu64;
1374 /// if cfg!(target_endian = "little") {
1375 /// assert_eq!(u64::from_le(n), n)
1377 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1380 #[stable(feature = "rust1", since = "1.0.0")]
1382 pub fn from_le(x: Self) -> Self {
1383 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1386 /// Converts `self` to big endian from the target's endianness.
1388 /// On big endian this is a no-op. On little endian the bytes are
1396 /// let n = 0x0123456789ABCDEFu64;
1398 /// if cfg!(target_endian = "big") {
1399 /// assert_eq!(n.to_be(), n)
1401 /// assert_eq!(n.to_be(), n.swap_bytes())
1404 #[stable(feature = "rust1", since = "1.0.0")]
1406 pub fn to_be(self) -> Self { // or not to be?
1407 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1410 /// Converts `self` to little endian from the target's endianness.
1412 /// On little endian this is a no-op. On big endian the bytes are
1420 /// let n = 0x0123456789ABCDEFu64;
1422 /// if cfg!(target_endian = "little") {
1423 /// assert_eq!(n.to_le(), n)
1425 /// assert_eq!(n.to_le(), n.swap_bytes())
1428 #[stable(feature = "rust1", since = "1.0.0")]
1430 pub fn to_le(self) -> Self {
1431 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1434 /// Checked integer addition. Computes `self + other`, returning `None`
1435 /// if overflow occurred.
1442 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1443 /// assert_eq!(6u16.checked_add(65530), None);
1445 #[stable(feature = "rust1", since = "1.0.0")]
1447 pub fn checked_add(self, other: Self) -> Option<Self> {
1448 let (a, b) = self.overflowing_add(other);
1449 if b {None} else {Some(a)}
1452 /// Checked integer subtraction. Computes `self - other`, returning
1453 /// `None` if underflow occurred.
1460 /// assert_eq!(1u8.checked_sub(1), Some(0));
1461 /// assert_eq!(0u8.checked_sub(1), None);
1463 #[stable(feature = "rust1", since = "1.0.0")]
1465 pub fn checked_sub(self, other: Self) -> Option<Self> {
1466 let (a, b) = self.overflowing_sub(other);
1467 if b {None} else {Some(a)}
1470 /// Checked integer multiplication. Computes `self * other`, returning
1471 /// `None` if underflow or overflow occurred.
1478 /// assert_eq!(5u8.checked_mul(51), Some(255));
1479 /// assert_eq!(5u8.checked_mul(52), None);
1481 #[stable(feature = "rust1", since = "1.0.0")]
1483 pub fn checked_mul(self, other: Self) -> Option<Self> {
1484 let (a, b) = self.overflowing_mul(other);
1485 if b {None} else {Some(a)}
1488 /// Checked integer division. Computes `self / other`, returning `None`
1489 /// if `other == 0` or the operation results in underflow or overflow.
1496 /// assert_eq!(128u8.checked_div(2), Some(64));
1497 /// assert_eq!(1u8.checked_div(0), None);
1499 #[stable(feature = "rust1", since = "1.0.0")]
1501 pub fn checked_div(self, other: Self) -> Option<Self> {
1504 other => Some(self / other),
1508 /// Checked integer remainder. Computes `self % other`, returning `None`
1509 /// if `other == 0` or the operation results in underflow or overflow.
1516 /// assert_eq!(5u32.checked_rem(2), Some(1));
1517 /// assert_eq!(5u32.checked_rem(0), None);
1519 #[stable(feature = "wrapping", since = "1.7.0")]
1521 pub fn checked_rem(self, other: Self) -> Option<Self> {
1529 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1532 /// Note that negating any positive integer will overflow.
1539 /// assert_eq!(0u32.checked_neg(), Some(0));
1540 /// assert_eq!(1u32.checked_neg(), None);
1542 #[stable(feature = "wrapping", since = "1.7.0")]
1544 pub fn checked_neg(self) -> Option<Self> {
1545 let (a, b) = self.overflowing_neg();
1546 if b {None} else {Some(a)}
1549 /// Checked shift left. Computes `self << rhs`, returning `None`
1550 /// if `rhs` is larger than or equal to the number of bits in `self`.
1557 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1558 /// assert_eq!(0x10u32.checked_shl(33), None);
1560 #[stable(feature = "wrapping", since = "1.7.0")]
1562 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1563 let (a, b) = self.overflowing_shl(rhs);
1564 if b {None} else {Some(a)}
1567 /// Checked shift right. Computes `self >> rhs`, returning `None`
1568 /// if `rhs` is larger than or equal to the number of bits in `self`.
1575 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1576 /// assert_eq!(0x10u32.checked_shr(33), None);
1578 #[stable(feature = "wrapping", since = "1.7.0")]
1580 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1581 let (a, b) = self.overflowing_shr(rhs);
1582 if b {None} else {Some(a)}
1585 /// Saturating integer addition. Computes `self + other`, saturating at
1586 /// the numeric bounds instead of overflowing.
1593 /// assert_eq!(100u8.saturating_add(1), 101);
1594 /// assert_eq!(200u8.saturating_add(127), 255);
1596 #[stable(feature = "rust1", since = "1.0.0")]
1598 pub fn saturating_add(self, other: Self) -> Self {
1599 match self.checked_add(other) {
1601 None => Self::max_value(),
1605 /// Saturating integer subtraction. Computes `self - other`, saturating
1606 /// at the numeric bounds instead of overflowing.
1613 /// assert_eq!(100u8.saturating_sub(27), 73);
1614 /// assert_eq!(13u8.saturating_sub(127), 0);
1616 #[stable(feature = "rust1", since = "1.0.0")]
1618 pub fn saturating_sub(self, other: Self) -> Self {
1619 match self.checked_sub(other) {
1621 None => Self::min_value(),
1625 /// Saturating integer multiplication. Computes `self * other`,
1626 /// saturating at the numeric bounds instead of overflowing.
1635 /// assert_eq!(100u32.saturating_mul(127), 12700);
1636 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1638 #[stable(feature = "wrapping", since = "1.7.0")]
1640 pub fn saturating_mul(self, other: Self) -> Self {
1641 self.checked_mul(other).unwrap_or(Self::max_value())
1644 /// Wrapping (modular) addition. Computes `self + other`,
1645 /// wrapping around at the boundary of the type.
1652 /// assert_eq!(200u8.wrapping_add(55), 255);
1653 /// assert_eq!(200u8.wrapping_add(155), 99);
1655 #[stable(feature = "rust1", since = "1.0.0")]
1657 pub fn wrapping_add(self, rhs: Self) -> Self {
1659 intrinsics::overflowing_add(self, rhs)
1663 /// Wrapping (modular) subtraction. Computes `self - other`,
1664 /// wrapping around at the boundary of the type.
1671 /// assert_eq!(100u8.wrapping_sub(100), 0);
1672 /// assert_eq!(100u8.wrapping_sub(155), 201);
1674 #[stable(feature = "rust1", since = "1.0.0")]
1676 pub fn wrapping_sub(self, rhs: Self) -> Self {
1678 intrinsics::overflowing_sub(self, rhs)
1682 /// Wrapping (modular) multiplication. Computes `self *
1683 /// other`, wrapping around at the boundary of the type.
1690 /// assert_eq!(10u8.wrapping_mul(12), 120);
1691 /// assert_eq!(25u8.wrapping_mul(12), 44);
1693 #[stable(feature = "rust1", since = "1.0.0")]
1695 pub fn wrapping_mul(self, rhs: Self) -> Self {
1697 intrinsics::overflowing_mul(self, rhs)
1701 /// Wrapping (modular) division. Computes `self / other`.
1702 /// Wrapped division on unsigned types is just normal division.
1703 /// There's no way wrapping could ever happen.
1704 /// This function exists, so that all operations
1705 /// are accounted for in the wrapping operations.
1712 /// assert_eq!(100u8.wrapping_div(10), 10);
1714 #[stable(feature = "num_wrapping", since = "1.2.0")]
1716 pub fn wrapping_div(self, rhs: Self) -> Self {
1720 /// Wrapping (modular) remainder. Computes `self % other`.
1721 /// Wrapped remainder calculation on unsigned types is
1722 /// just the regular remainder calculation.
1723 /// There's no way wrapping could ever happen.
1724 /// This function exists, so that all operations
1725 /// are accounted for in the wrapping operations.
1732 /// assert_eq!(100i8.wrapping_rem(10), 0);
1734 #[stable(feature = "num_wrapping", since = "1.2.0")]
1736 pub fn wrapping_rem(self, rhs: Self) -> Self {
1740 /// Wrapping (modular) negation. Computes `-self`,
1741 /// wrapping around at the boundary of the type.
1743 /// Since unsigned types do not have negative equivalents
1744 /// all applications of this function will wrap (except for `-0`).
1745 /// For values smaller than the corresponding signed type's maximum
1746 /// the result is the same as casting the corresponding signed value.
1747 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1748 /// `MAX` is the corresponding signed type's maximum.
1755 /// assert_eq!(100u8.wrapping_neg(), 156);
1756 /// assert_eq!(0u8.wrapping_neg(), 0);
1757 /// assert_eq!(180u8.wrapping_neg(), 76);
1758 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1760 #[stable(feature = "num_wrapping", since = "1.2.0")]
1762 pub fn wrapping_neg(self) -> Self {
1763 self.overflowing_neg().0
1766 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1767 /// where `mask` removes any high-order bits of `rhs` that
1768 /// would cause the shift to exceed the bitwidth of the type.
1775 /// assert_eq!(1u8.wrapping_shl(7), 128);
1776 /// assert_eq!(1u8.wrapping_shl(8), 1);
1778 #[stable(feature = "num_wrapping", since = "1.2.0")]
1780 pub fn wrapping_shl(self, rhs: u32) -> Self {
1781 self.overflowing_shl(rhs).0
1784 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1785 /// where `mask` removes any high-order bits of `rhs` that
1786 /// would cause the shift to exceed the bitwidth of the type.
1793 /// assert_eq!(128u8.wrapping_shr(7), 1);
1794 /// assert_eq!(128u8.wrapping_shr(8), 128);
1796 #[stable(feature = "num_wrapping", since = "1.2.0")]
1798 pub fn wrapping_shr(self, rhs: u32) -> Self {
1799 self.overflowing_shr(rhs).0
1802 /// Calculates `self` + `rhs`
1804 /// Returns a tuple of the addition along with a boolean indicating
1805 /// whether an arithmetic overflow would occur. If an overflow would
1806 /// have occurred then the wrapped value is returned.
1815 /// assert_eq!(5u32.overflowing_add(2), (7, false));
1816 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
1819 #[stable(feature = "wrapping", since = "1.7.0")]
1820 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1822 let (a, b) = $add_with_overflow(self as $ActualT,
1828 /// Calculates `self` - `rhs`
1830 /// Returns a tuple of the subtraction along with a boolean indicating
1831 /// whether an arithmetic overflow would occur. If an overflow would
1832 /// have occurred then the wrapped value is returned.
1841 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
1842 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
1845 #[stable(feature = "wrapping", since = "1.7.0")]
1846 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1848 let (a, b) = $sub_with_overflow(self as $ActualT,
1854 /// Calculates the multiplication of `self` and `rhs`.
1856 /// Returns a tuple of the multiplication along with a boolean
1857 /// indicating whether an arithmetic overflow would occur. If an
1858 /// overflow would have occurred then the wrapped value is returned.
1865 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1866 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1869 #[stable(feature = "wrapping", since = "1.7.0")]
1870 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1872 let (a, b) = $mul_with_overflow(self as $ActualT,
1878 /// Calculates the divisor when `self` is divided by `rhs`.
1880 /// Returns a tuple of the divisor along with a boolean indicating
1881 /// whether an arithmetic overflow would occur. Note that for unsigned
1882 /// integers overflow never occurs, so the second value is always
1887 /// This function will panic if `rhs` is 0.
1894 /// assert_eq!(5u32.overflowing_div(2), (2, false));
1897 #[stable(feature = "wrapping", since = "1.7.0")]
1898 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1902 /// Calculates the remainder when `self` is divided by `rhs`.
1904 /// Returns a tuple of the remainder after dividing along with a boolean
1905 /// indicating whether an arithmetic overflow would occur. Note that for
1906 /// unsigned integers overflow never occurs, so the second value is
1911 /// This function will panic if `rhs` is 0.
1918 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
1921 #[stable(feature = "wrapping", since = "1.7.0")]
1922 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1926 /// Negates self in an overflowing fashion.
1928 /// Returns `!self + 1` using wrapping operations to return the value
1929 /// that represents the negation of this unsigned value. Note that for
1930 /// positive unsigned values overflow always occurs, but negating 0 does
1938 /// assert_eq!(0u32.overflowing_neg(), (0, false));
1939 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
1942 #[stable(feature = "wrapping", since = "1.7.0")]
1943 pub fn overflowing_neg(self) -> (Self, bool) {
1944 ((!self).wrapping_add(1), self != 0)
1947 /// Shifts self left by `rhs` bits.
1949 /// Returns a tuple of the shifted version of self along with a boolean
1950 /// indicating whether the shift value was larger than or equal to the
1951 /// number of bits. If the shift value is too large, then value is
1952 /// masked (N-1) where N is the number of bits, and this value is then
1953 /// used to perform the shift.
1960 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
1961 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
1964 #[stable(feature = "wrapping", since = "1.7.0")]
1965 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1966 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1969 /// Shifts self right by `rhs` bits.
1971 /// Returns a tuple of the shifted version of self along with a boolean
1972 /// indicating whether the shift value was larger than or equal to the
1973 /// number of bits. If the shift value is too large, then value is
1974 /// masked (N-1) where N is the number of bits, and this value is then
1975 /// used to perform the shift.
1982 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
1983 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
1986 #[stable(feature = "wrapping", since = "1.7.0")]
1987 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1988 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1991 /// Raises self to the power of `exp`, using exponentiation by squaring.
1998 /// assert_eq!(2u32.pow(4), 16);
2000 #[stable(feature = "rust1", since = "1.0.0")]
2002 pub fn pow(self, mut exp: u32) -> Self {
2003 let mut base = self;
2004 let mut acc = Self::one();
2006 let mut prev_base = self;
2007 let mut base_oflo = false;
2011 // ensure overflow occurs in the same manner it
2012 // would have otherwise (i.e. signal any exception
2013 // it would have otherwise).
2014 acc = acc * (prev_base * prev_base);
2020 let (new_base, new_base_oflo) = base.overflowing_mul(base);
2022 base_oflo = new_base_oflo;
2028 /// Returns `true` if and only if `self == 2^k` for some `k`.
2035 /// assert!(16u8.is_power_of_two());
2036 /// assert!(!10u8.is_power_of_two());
2038 #[stable(feature = "rust1", since = "1.0.0")]
2040 pub fn is_power_of_two(self) -> bool {
2041 (self.wrapping_sub(Self::one())) & self == Self::zero() &&
2042 !(self == Self::zero())
2045 /// Returns the smallest power of two greater than or equal to `self`.
2046 /// Unspecified behavior on overflow.
2053 /// assert_eq!(2u8.next_power_of_two(), 2);
2054 /// assert_eq!(3u8.next_power_of_two(), 4);
2056 #[stable(feature = "rust1", since = "1.0.0")]
2058 pub fn next_power_of_two(self) -> Self {
2059 let bits = size_of::<Self>() * 8;
2060 let one: Self = Self::one();
2061 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
2064 /// Returns the smallest power of two greater than or equal to `n`. If
2065 /// the next power of two is greater than the type's maximum value,
2066 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2073 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2074 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2075 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2077 #[stable(feature = "rust1", since = "1.0.0")]
2078 pub fn checked_next_power_of_two(self) -> Option<Self> {
2079 let npot = self.next_power_of_two();
2096 intrinsics::add_with_overflow,
2097 intrinsics::sub_with_overflow,
2098 intrinsics::mul_with_overflow }
2103 uint_impl! { u16, 16,
2108 intrinsics::add_with_overflow,
2109 intrinsics::sub_with_overflow,
2110 intrinsics::mul_with_overflow }
2115 uint_impl! { u32, 32,
2120 intrinsics::add_with_overflow,
2121 intrinsics::sub_with_overflow,
2122 intrinsics::mul_with_overflow }
2127 uint_impl! { u64, 64,
2132 intrinsics::add_with_overflow,
2133 intrinsics::sub_with_overflow,
2134 intrinsics::mul_with_overflow }
2137 #[cfg(target_pointer_width = "32")]
2140 uint_impl! { u32, 32,
2145 intrinsics::add_with_overflow,
2146 intrinsics::sub_with_overflow,
2147 intrinsics::mul_with_overflow }
2150 #[cfg(target_pointer_width = "64")]
2153 uint_impl! { u64, 64,
2158 intrinsics::add_with_overflow,
2159 intrinsics::sub_with_overflow,
2160 intrinsics::mul_with_overflow }
2163 /// A classification of floating point numbers.
2165 /// This `enum` is used as the return type for [`f32::classify()`] and [`f64::classify()`]. See
2166 /// their documentation for more.
2168 /// [`f32::classify()`]: ../primitive.f32.html#method.classify
2169 /// [`f64::classify()`]: ../primitive.f64.html#method.classify
2170 #[derive(Copy, Clone, PartialEq, Debug)]
2171 #[stable(feature = "rust1", since = "1.0.0")]
2172 pub enum FpCategory {
2173 /// "Not a Number", often obtained by dividing by zero
2174 #[stable(feature = "rust1", since = "1.0.0")]
2177 /// Positive or negative infinity
2178 #[stable(feature = "rust1", since = "1.0.0")]
2181 /// Positive or negative zero
2182 #[stable(feature = "rust1", since = "1.0.0")]
2185 /// De-normalized floating point representation (less precise than `Normal`)
2186 #[stable(feature = "rust1", since = "1.0.0")]
2189 /// A regular floating point number
2190 #[stable(feature = "rust1", since = "1.0.0")]
2194 /// A built-in floating point number.
2196 #[unstable(feature = "core_float",
2197 reason = "stable interface is via `impl f{32,64}` in later crates",
2199 pub trait Float: Sized {
2200 /// Returns the NaN value.
2201 #[unstable(feature = "float_extras", reason = "needs removal",
2204 /// Returns the infinite value.
2205 #[unstable(feature = "float_extras", reason = "needs removal",
2207 fn infinity() -> Self;
2208 /// Returns the negative infinite value.
2209 #[unstable(feature = "float_extras", reason = "needs removal",
2211 fn neg_infinity() -> Self;
2213 #[unstable(feature = "float_extras", reason = "needs removal",
2215 fn neg_zero() -> Self;
2217 #[unstable(feature = "float_extras", reason = "needs removal",
2221 #[unstable(feature = "float_extras", reason = "needs removal",
2225 /// Returns true if this value is NaN and false otherwise.
2226 #[stable(feature = "core", since = "1.6.0")]
2227 fn is_nan(self) -> bool;
2228 /// Returns true if this value is positive infinity or negative infinity and
2229 /// false otherwise.
2230 #[stable(feature = "core", since = "1.6.0")]
2231 fn is_infinite(self) -> bool;
2232 /// Returns true if this number is neither infinite nor NaN.
2233 #[stable(feature = "core", since = "1.6.0")]
2234 fn is_finite(self) -> bool;
2235 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
2236 #[stable(feature = "core", since = "1.6.0")]
2237 fn is_normal(self) -> bool;
2238 /// Returns the category that this number falls into.
2239 #[stable(feature = "core", since = "1.6.0")]
2240 fn classify(self) -> FpCategory;
2242 /// Returns the mantissa, exponent and sign as integers, respectively.
2243 #[unstable(feature = "float_extras", reason = "signature is undecided",
2245 fn integer_decode(self) -> (u64, i16, i8);
2247 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2248 /// number is `Float::nan()`.
2249 #[stable(feature = "core", since = "1.6.0")]
2250 fn abs(self) -> Self;
2251 /// Returns a number that represents the sign of `self`.
2253 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2254 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2255 /// - `Float::nan()` if the number is `Float::nan()`
2256 #[stable(feature = "core", since = "1.6.0")]
2257 fn signum(self) -> Self;
2259 /// Returns `true` if `self` is positive, including `+0.0` and
2260 /// `Float::infinity()`.
2261 #[stable(feature = "core", since = "1.6.0")]
2262 fn is_sign_positive(self) -> bool;
2263 /// Returns `true` if `self` is negative, including `-0.0` and
2264 /// `Float::neg_infinity()`.
2265 #[stable(feature = "core", since = "1.6.0")]
2266 fn is_sign_negative(self) -> bool;
2268 /// Take the reciprocal (inverse) of a number, `1/x`.
2269 #[stable(feature = "core", since = "1.6.0")]
2270 fn recip(self) -> Self;
2272 /// Raise a number to an integer power.
2274 /// Using this function is generally faster than using `powf`
2275 #[stable(feature = "core", since = "1.6.0")]
2276 fn powi(self, n: i32) -> Self;
2278 /// Convert radians to degrees.
2279 #[unstable(feature = "float_extras", reason = "desirability is unclear",
2281 fn to_degrees(self) -> Self;
2282 /// Convert degrees to radians.
2283 #[unstable(feature = "float_extras", reason = "desirability is unclear",
2285 fn to_radians(self) -> Self;
2288 macro_rules! from_str_radix_int_impl {
2290 #[stable(feature = "rust1", since = "1.0.0")]
2291 impl FromStr for $t {
2292 type Err = ParseIntError;
2293 fn from_str(src: &str) -> Result<Self, ParseIntError> {
2294 from_str_radix(src, 10)
2299 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
2302 trait FromStrRadixHelper: PartialOrd + Copy {
2303 fn min_value() -> Self;
2304 fn from_u32(u: u32) -> Self;
2305 fn checked_mul(&self, other: u32) -> Option<Self>;
2306 fn checked_sub(&self, other: u32) -> Option<Self>;
2307 fn checked_add(&self, other: u32) -> Option<Self>;
2311 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
2312 fn min_value() -> Self { Self::min_value() }
2313 fn from_u32(u: u32) -> Self { u as Self }
2314 fn checked_mul(&self, other: u32) -> Option<Self> {
2315 Self::checked_mul(*self, other as Self)
2317 fn checked_sub(&self, other: u32) -> Option<Self> {
2318 Self::checked_sub(*self, other as Self)
2320 fn checked_add(&self, other: u32) -> Option<Self> {
2321 Self::checked_add(*self, other as Self)
2325 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
2327 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
2328 -> Result<T, ParseIntError> {
2329 use self::IntErrorKind::*;
2330 use self::ParseIntError as PIE;
2332 assert!(radix >= 2 && radix <= 36,
2333 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2337 return Err(PIE { kind: Empty });
2340 let is_signed_ty = T::from_u32(0) > T::min_value();
2342 // all valid digits are ascii, so we will just iterate over the utf8 bytes
2343 // and cast them to chars. .to_digit() will safely return None for anything
2344 // other than a valid ascii digit for the given radix, including the first-byte
2345 // of multi-byte sequences
2346 let src = src.as_bytes();
2348 let (is_positive, digits) = match src[0] {
2349 b'+' => (true, &src[1..]),
2350 b'-' if is_signed_ty => (false, &src[1..]),
2354 if digits.is_empty() {
2355 return Err(PIE { kind: Empty });
2358 let mut result = T::from_u32(0);
2360 // The number is positive
2362 let x = match (c as char).to_digit(radix) {
2364 None => return Err(PIE { kind: InvalidDigit }),
2366 result = match result.checked_mul(radix) {
2367 Some(result) => result,
2368 None => return Err(PIE { kind: Overflow }),
2370 result = match result.checked_add(x) {
2371 Some(result) => result,
2372 None => return Err(PIE { kind: Overflow }),
2376 // The number is negative
2378 let x = match (c as char).to_digit(radix) {
2380 None => return Err(PIE { kind: InvalidDigit }),
2382 result = match result.checked_mul(radix) {
2383 Some(result) => result,
2384 None => return Err(PIE { kind: Underflow }),
2386 result = match result.checked_sub(x) {
2387 Some(result) => result,
2388 None => return Err(PIE { kind: Underflow }),
2395 /// An error which can be returned when parsing an integer.
2397 /// This error is used as the error type for the `from_str_radix()` functions
2398 /// on the primitive integer types, such as [`i8::from_str_radix()`].
2400 /// [`i8::from_str_radix()`]: ../std/primitive.i8.html#method.from_str_radix
2401 #[derive(Debug, Clone, PartialEq)]
2402 #[stable(feature = "rust1", since = "1.0.0")]
2403 pub struct ParseIntError { kind: IntErrorKind }
2405 #[derive(Debug, Clone, PartialEq)]
2413 impl ParseIntError {
2414 #[unstable(feature = "int_error_internals",
2415 reason = "available through Error trait and this method should \
2416 not be exposed publicly",
2419 pub fn __description(&self) -> &str {
2421 IntErrorKind::Empty => "cannot parse integer from empty string",
2422 IntErrorKind::InvalidDigit => "invalid digit found in string",
2423 IntErrorKind::Overflow => "number too large to fit in target type",
2424 IntErrorKind::Underflow => "number too small to fit in target type",
2429 #[stable(feature = "rust1", since = "1.0.0")]
2430 impl fmt::Display for ParseIntError {
2431 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2432 self.__description().fmt(f)
2436 #[stable(feature = "rust1", since = "1.0.0")]
2437 pub use num::dec2flt::ParseFloatError;
2439 // Conversion traits for primitive integer and float types
2440 // Conversions T -> T are covered by a blanket impl and therefore excluded
2441 // Some conversions from and to usize/isize are not implemented due to portability concerns
2442 macro_rules! impl_from {
2443 ($Small: ty, $Large: ty) => {
2444 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
2445 impl From<$Small> for $Large {
2447 fn from(small: $Small) -> $Large {
2454 // Unsigned -> Unsigned
2455 impl_from! { u8, u16 }
2456 impl_from! { u8, u32 }
2457 impl_from! { u8, u64 }
2458 impl_from! { u8, usize }
2459 impl_from! { u16, u32 }
2460 impl_from! { u16, u64 }
2461 impl_from! { u32, u64 }
2464 impl_from! { i8, i16 }
2465 impl_from! { i8, i32 }
2466 impl_from! { i8, i64 }
2467 impl_from! { i8, isize }
2468 impl_from! { i16, i32 }
2469 impl_from! { i16, i64 }
2470 impl_from! { i32, i64 }
2472 // Unsigned -> Signed
2473 impl_from! { u8, i16 }
2474 impl_from! { u8, i32 }
2475 impl_from! { u8, i64 }
2476 impl_from! { u16, i32 }
2477 impl_from! { u16, i64 }
2478 impl_from! { u32, i64 }
2480 // Note: integers can only be represented with full precision in a float if
2481 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2482 // Lossy float conversions are not implemented at this time.
2485 impl_from! { i8, f32 }
2486 impl_from! { i8, f64 }
2487 impl_from! { i16, f32 }
2488 impl_from! { i16, f64 }
2489 impl_from! { i32, f64 }
2491 // Unsigned -> Float
2492 impl_from! { u8, f32 }
2493 impl_from! { u8, f64 }
2494 impl_from! { u16, f32 }
2495 impl_from! { u16, f64 }
2496 impl_from! { u32, f64 }
2499 impl_from! { f32, f64 }