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)]
16 use self::wrapping::OverflowingOps;
19 use cmp::{Eq, PartialOrd};
24 use option::Option::{self, Some, None};
25 use result::Result::{self, Ok, Err};
26 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)]
42 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
47 /// Types that have a "zero" value.
49 /// This trait is intended for use in conjunction with `Add`, as an identity:
50 /// `x + T::zero() == x`.
51 #[unstable(feature = "zero_one",
52 reason = "unsure of placement, wants to use associated constants")]
54 /// The "zero" (usually, additive identity) for this type.
58 /// Types that have a "one" value.
60 /// This trait is intended for use in conjunction with `Mul`, as an identity:
61 /// `x * T::one() == x`.
62 #[unstable(feature = "zero_one",
63 reason = "unsure of placement, wants to use associated constants")]
65 /// The "one" (usually, multiplicative identity) for this type.
69 macro_rules! zero_one_impl {
73 fn zero() -> Self { 0 }
77 fn one() -> Self { 1 }
81 zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
83 macro_rules! zero_one_impl_float {
87 fn zero() -> Self { 0.0 }
91 fn one() -> Self { 1.0 }
95 zero_one_impl_float! { f32 f64 }
97 macro_rules! checked_op {
98 ($U:ty, $op:path, $x:expr, $y:expr) => {{
99 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
100 if overflowed { None } else { Some(result as Self) }
104 /// Swapping a single byte is a no-op. This is marked as `unsafe` for
105 /// consistency with the other `bswap` intrinsics.
106 unsafe fn bswap8(x: u8) -> u8 { x }
108 // `Int` + `SignedInt` implemented for signed integers
109 macro_rules! int_impl {
110 ($ActualT:ty, $UnsignedT:ty, $BITS:expr,
111 $add_with_overflow:path,
112 $sub_with_overflow:path,
113 $mul_with_overflow:path) => {
114 /// Returns the smallest value that can be represented by this integer type.
115 #[stable(feature = "rust1", since = "1.0.0")]
117 pub fn min_value() -> Self {
118 (-1 as Self) << ($BITS - 1)
121 /// Returns the largest value that can be represented by this integer type.
122 #[stable(feature = "rust1", since = "1.0.0")]
124 pub fn max_value() -> Self {
125 let min = Self::min_value(); !min
128 /// Converts a string slice in a given base to an integer.
130 /// Leading and trailing whitespace represent an error.
135 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
137 #[stable(feature = "rust1", since = "1.0.0")]
139 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
140 from_str_radix(src, radix)
143 /// Returns the number of ones in the binary representation of `self`.
148 /// let n = 0b01001100u8;
150 /// assert_eq!(n.count_ones(), 3);
152 #[stable(feature = "rust1", since = "1.0.0")]
154 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
156 /// Returns the number of zeros in the binary representation of `self`.
161 /// let n = 0b01001100u8;
163 /// assert_eq!(n.count_zeros(), 5);
165 #[stable(feature = "rust1", since = "1.0.0")]
167 pub fn count_zeros(self) -> u32 {
171 /// Returns the number of leading zeros in the binary representation
177 /// let n = 0b0101000u16;
179 /// assert_eq!(n.leading_zeros(), 10);
181 #[stable(feature = "rust1", since = "1.0.0")]
183 pub fn leading_zeros(self) -> u32 {
184 (self as $UnsignedT).leading_zeros()
187 /// Returns the number of trailing zeros in the binary representation
193 /// let n = 0b0101000u16;
195 /// assert_eq!(n.trailing_zeros(), 3);
197 #[stable(feature = "rust1", since = "1.0.0")]
199 pub fn trailing_zeros(self) -> u32 {
200 (self as $UnsignedT).trailing_zeros()
203 /// Shifts the bits to the left by a specified amount, `n`,
204 /// wrapping the truncated bits to the end of the resulting integer.
209 /// let n = 0x0123456789ABCDEFu64;
210 /// let m = 0x3456789ABCDEF012u64;
212 /// assert_eq!(n.rotate_left(12), m);
214 #[stable(feature = "rust1", since = "1.0.0")]
216 pub fn rotate_left(self, n: u32) -> Self {
217 (self as $UnsignedT).rotate_left(n) as Self
220 /// Shifts the bits to the right by a specified amount, `n`,
221 /// wrapping the truncated bits to the beginning of the resulting
227 /// let n = 0x0123456789ABCDEFu64;
228 /// let m = 0xDEF0123456789ABCu64;
230 /// assert_eq!(n.rotate_right(12), m);
232 #[stable(feature = "rust1", since = "1.0.0")]
234 pub fn rotate_right(self, n: u32) -> Self {
235 (self as $UnsignedT).rotate_right(n) as Self
238 /// Reverses the byte order of the integer.
243 /// let n = 0x0123456789ABCDEFu64;
244 /// let m = 0xEFCDAB8967452301u64;
246 /// assert_eq!(n.swap_bytes(), m);
248 #[stable(feature = "rust1", since = "1.0.0")]
250 pub fn swap_bytes(self) -> Self {
251 (self as $UnsignedT).swap_bytes() as Self
254 /// Converts an integer from big endian to the target's endianness.
256 /// On big endian this is a no-op. On little endian the bytes are
262 /// let n = 0x0123456789ABCDEFu64;
264 /// if cfg!(target_endian = "big") {
265 /// assert_eq!(u64::from_be(n), n)
267 /// assert_eq!(u64::from_be(n), n.swap_bytes())
270 #[stable(feature = "rust1", since = "1.0.0")]
272 pub fn from_be(x: Self) -> Self {
273 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
276 /// Converts an integer from little endian to the target's endianness.
278 /// On little endian this is a no-op. On big endian the bytes are
284 /// let n = 0x0123456789ABCDEFu64;
286 /// if cfg!(target_endian = "little") {
287 /// assert_eq!(u64::from_le(n), n)
289 /// assert_eq!(u64::from_le(n), n.swap_bytes())
292 #[stable(feature = "rust1", since = "1.0.0")]
294 pub fn from_le(x: Self) -> Self {
295 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
298 /// Converts `self` to big endian from the target's endianness.
300 /// On big endian this is a no-op. On little endian the bytes are
306 /// let n = 0x0123456789ABCDEFu64;
308 /// if cfg!(target_endian = "big") {
309 /// assert_eq!(n.to_be(), n)
311 /// assert_eq!(n.to_be(), n.swap_bytes())
314 #[stable(feature = "rust1", since = "1.0.0")]
316 pub fn to_be(self) -> Self { // or not to be?
317 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
320 /// Converts `self` to little endian from the target's endianness.
322 /// On little endian this is a no-op. On big endian the bytes are
328 /// let n = 0x0123456789ABCDEFu64;
330 /// if cfg!(target_endian = "little") {
331 /// assert_eq!(n.to_le(), n)
333 /// assert_eq!(n.to_le(), n.swap_bytes())
336 #[stable(feature = "rust1", since = "1.0.0")]
338 pub fn to_le(self) -> Self {
339 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
342 /// Checked integer addition. Computes `self + other`, returning `None`
343 /// if overflow occurred.
348 /// assert_eq!(5u16.checked_add(65530), Some(65535));
349 /// assert_eq!(6u16.checked_add(65530), None);
351 #[stable(feature = "rust1", since = "1.0.0")]
353 pub fn checked_add(self, other: Self) -> Option<Self> {
354 checked_op!($ActualT, $add_with_overflow, self, other)
357 /// Checked integer subtraction. Computes `self - other`, returning
358 /// `None` if underflow occurred.
363 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
364 /// assert_eq!((-128i8).checked_sub(1), None);
366 #[stable(feature = "rust1", since = "1.0.0")]
368 pub fn checked_sub(self, other: Self) -> Option<Self> {
369 checked_op!($ActualT, $sub_with_overflow, self, other)
372 /// Checked integer multiplication. Computes `self * other`, returning
373 /// `None` if underflow or overflow occurred.
378 /// assert_eq!(5u8.checked_mul(51), Some(255));
379 /// assert_eq!(5u8.checked_mul(52), None);
381 #[stable(feature = "rust1", since = "1.0.0")]
383 pub fn checked_mul(self, other: Self) -> Option<Self> {
384 checked_op!($ActualT, $mul_with_overflow, self, other)
387 /// Checked integer division. Computes `self / other`, returning `None`
388 /// if `other == 0` or the operation results in underflow or overflow.
393 /// assert_eq!((-127i8).checked_div(-1), Some(127));
394 /// assert_eq!((-128i8).checked_div(-1), None);
395 /// assert_eq!((1i8).checked_div(0), None);
397 #[stable(feature = "rust1", since = "1.0.0")]
399 pub fn checked_div(self, v: Self) -> Option<Self> {
402 -1 if self == Self::min_value()
408 /// Saturating integer addition. Computes `self + other`, saturating at
409 /// the numeric bounds instead of overflowing.
410 #[stable(feature = "rust1", since = "1.0.0")]
412 pub fn saturating_add(self, other: Self) -> Self {
413 match self.checked_add(other) {
415 None if other >= Self::zero() => Self::max_value(),
416 None => Self::min_value(),
420 /// Saturating integer subtraction. Computes `self - other`, saturating
421 /// at the numeric bounds instead of overflowing.
422 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn saturating_sub(self, other: Self) -> Self {
425 match self.checked_sub(other) {
427 None if other >= Self::zero() => Self::min_value(),
428 None => Self::max_value(),
432 /// Wrapping (modular) addition. Computes `self + other`,
433 /// wrapping around at the boundary of the type.
434 #[stable(feature = "rust1", since = "1.0.0")]
436 pub fn wrapping_add(self, rhs: Self) -> Self {
438 intrinsics::overflowing_add(self, rhs)
442 /// Wrapping (modular) subtraction. Computes `self - other`,
443 /// wrapping around at the boundary of the type.
444 #[stable(feature = "rust1", since = "1.0.0")]
446 pub fn wrapping_sub(self, rhs: Self) -> Self {
448 intrinsics::overflowing_sub(self, rhs)
452 /// Wrapping (modular) multiplication. Computes `self *
453 /// other`, wrapping around at the boundary of the type.
454 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn wrapping_mul(self, rhs: Self) -> Self {
458 intrinsics::overflowing_mul(self, rhs)
462 /// Wrapping (modular) division. Computes `floor(self / other)`,
463 /// wrapping around at the boundary of the type.
465 /// The only case where such wrapping can occur is when one
466 /// divides `MIN / -1` on a signed type (where `MIN` is the
467 /// negative minimal value for the type); this is equivalent
468 /// to `-MIN`, a positive value that is too large to represent
469 /// in the type. In such a case, this function returns `MIN`
471 #[unstable(feature = "num_wrapping")]
473 pub fn wrapping_div(self, rhs: Self) -> Self {
474 self.overflowing_div(rhs).0
477 /// Wrapping (modular) remainder. Computes `self % other`,
478 /// wrapping around at the boundary of the type.
480 /// Such wrap-around never actually occurs mathematically;
481 /// implementation artifacts make `x % y` illegal for `MIN /
482 /// -1` on a signed type illegal (where `MIN` is the negative
483 /// minimal value). In such a case, this function returns `0`.
484 #[unstable(feature = "num_wrapping")]
486 pub fn wrapping_rem(self, rhs: Self) -> Self {
487 self.overflowing_rem(rhs).0
490 /// Wrapping (modular) negation. Computes `-self`,
491 /// wrapping around at the boundary of the type.
493 /// The only case where such wrapping can occur is when one
494 /// negates `MIN` on a signed type (where `MIN` is the
495 /// negative minimal value for the type); this is a positive
496 /// value that is too large to represent in the type. In such
497 /// a case, this function returns `MIN` itself.
498 #[unstable(feature = "num_wrapping")]
500 pub fn wrapping_neg(self) -> Self {
501 self.overflowing_neg().0
504 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
505 /// where `mask` removes any high-order bits of `rhs` that
506 /// would cause the shift to exceed the bitwidth of the type.
507 #[unstable(feature = "num_wrapping")]
509 pub fn wrapping_shl(self, rhs: u32) -> Self {
510 self.overflowing_shl(rhs).0
513 /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
514 /// where `mask` removes any high-order bits of `rhs` that
515 /// would cause the shift to exceed the bitwidth of the type.
516 #[unstable(feature = "num_wrapping")]
518 pub fn wrapping_shr(self, rhs: u32) -> Self {
519 self.overflowing_shr(rhs).0
522 /// Raises self to the power of `exp`, using exponentiation by squaring.
527 /// let x: i32 = 2; // or any other integer type
529 /// assert_eq!(x.pow(4), 16);
531 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn pow(self, mut exp: u32) -> Self {
535 let mut acc = Self::one();
537 let mut prev_base = self;
538 let mut base_oflo = false;
542 // ensure overflow occurs in the same manner it
543 // would have otherwise (i.e. signal any exception
544 // it would have otherwise).
545 acc = acc * (prev_base * prev_base);
551 let (new_base, new_base_oflo) = base.overflowing_mul(base);
553 base_oflo = new_base_oflo;
559 /// Computes the absolute value of `self`.
561 /// # Overflow behavior
563 /// The absolute value of `i32::min_value()` cannot be represented as an
564 /// `i32`, and attempting to calculate it will cause an overflow. This
565 /// means that code in debug mode will trigger a panic on this case and
566 /// optimized code will return `i32::min_value()` without a panic.
567 #[stable(feature = "rust1", since = "1.0.0")]
569 pub fn abs(self) -> Self {
570 if self.is_negative() {
571 // Note that the #[inline] above means that the overflow
572 // semantics of this negation depend on the crate we're being
580 /// Returns a number representing sign of `self`.
582 /// - `0` if the number is zero
583 /// - `1` if the number is positive
584 /// - `-1` if the number is negative
585 #[stable(feature = "rust1", since = "1.0.0")]
587 pub fn signum(self) -> Self {
595 /// Returns `true` if `self` is positive and `false` if the number
596 /// is zero or negative.
597 #[stable(feature = "rust1", since = "1.0.0")]
599 pub fn is_positive(self) -> bool { self > 0 }
601 /// Returns `true` if `self` is negative and `false` if the number
602 /// is zero or positive.
603 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn is_negative(self) -> bool { self < 0 }
611 int_impl! { i8, u8, 8,
612 intrinsics::i8_add_with_overflow,
613 intrinsics::i8_sub_with_overflow,
614 intrinsics::i8_mul_with_overflow }
619 int_impl! { i16, u16, 16,
620 intrinsics::i16_add_with_overflow,
621 intrinsics::i16_sub_with_overflow,
622 intrinsics::i16_mul_with_overflow }
627 int_impl! { i32, u32, 32,
628 intrinsics::i32_add_with_overflow,
629 intrinsics::i32_sub_with_overflow,
630 intrinsics::i32_mul_with_overflow }
635 int_impl! { i64, u64, 64,
636 intrinsics::i64_add_with_overflow,
637 intrinsics::i64_sub_with_overflow,
638 intrinsics::i64_mul_with_overflow }
641 #[cfg(target_pointer_width = "32")]
644 int_impl! { i32, u32, 32,
645 intrinsics::i32_add_with_overflow,
646 intrinsics::i32_sub_with_overflow,
647 intrinsics::i32_mul_with_overflow }
650 #[cfg(target_pointer_width = "64")]
653 int_impl! { i64, u64, 64,
654 intrinsics::i64_add_with_overflow,
655 intrinsics::i64_sub_with_overflow,
656 intrinsics::i64_mul_with_overflow }
659 // `Int` + `UnsignedInt` implemented for signed integers
660 macro_rules! uint_impl {
661 ($ActualT:ty, $BITS:expr,
666 $add_with_overflow:path,
667 $sub_with_overflow:path,
668 $mul_with_overflow:path) => {
669 /// Returns the smallest value that can be represented by this integer type.
670 #[stable(feature = "rust1", since = "1.0.0")]
671 pub fn min_value() -> Self { 0 }
673 /// Returns the largest value that can be represented by this integer type.
674 #[stable(feature = "rust1", since = "1.0.0")]
675 pub fn max_value() -> Self { !0 }
677 /// Converts a string slice in a given base to an integer.
679 /// Leading and trailing whitespace represent an error.
683 /// * src - A string slice
684 /// * radix - The base to use. Must lie in the range [2 .. 36]
688 /// `Err(ParseIntError)` if the string did not represent a valid number.
689 /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
690 #[stable(feature = "rust1", since = "1.0.0")]
692 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
693 from_str_radix(src, radix)
696 /// Returns the number of ones in the binary representation of `self`.
701 /// let n = 0b01001100u8;
703 /// assert_eq!(n.count_ones(), 3);
705 #[stable(feature = "rust1", since = "1.0.0")]
707 pub fn count_ones(self) -> u32 {
708 unsafe { $ctpop(self as $ActualT) as u32 }
711 /// Returns the number of zeros in the binary representation of `self`.
716 /// let n = 0b01001100u8;
718 /// assert_eq!(n.count_zeros(), 5);
720 #[stable(feature = "rust1", since = "1.0.0")]
722 pub fn count_zeros(self) -> u32 {
726 /// Returns the number of leading zeros in the binary representation
732 /// let n = 0b0101000u16;
734 /// assert_eq!(n.leading_zeros(), 10);
736 #[stable(feature = "rust1", since = "1.0.0")]
738 pub fn leading_zeros(self) -> u32 {
739 unsafe { $ctlz(self as $ActualT) as u32 }
742 /// Returns the number of trailing zeros in the binary representation
748 /// let n = 0b0101000u16;
750 /// assert_eq!(n.trailing_zeros(), 3);
752 #[stable(feature = "rust1", since = "1.0.0")]
754 pub fn trailing_zeros(self) -> u32 {
755 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
756 // emits two conditional moves on x86_64. By promoting the value to
757 // u16 and setting bit 8, we get better code without any conditional
759 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
760 // pending, remove this workaround once LLVM generates better code
764 intrinsics::cttz16(self as u16 | 0x100) as u32
766 $cttz(self as $ActualT) as u32
771 /// Shifts the bits to the left by a specified amount, `n`,
772 /// wrapping the truncated bits to the end of the resulting integer.
777 /// let n = 0x0123456789ABCDEFu64;
778 /// let m = 0x3456789ABCDEF012u64;
780 /// assert_eq!(n.rotate_left(12), m);
782 #[stable(feature = "rust1", since = "1.0.0")]
784 pub fn rotate_left(self, n: u32) -> Self {
785 // Protect against undefined behaviour for over-long bit shifts
787 (self << n) | (self >> (($BITS - n) % $BITS))
790 /// Shifts the bits to the right by a specified amount, `n`,
791 /// wrapping the truncated bits to the beginning of the resulting
797 /// let n = 0x0123456789ABCDEFu64;
798 /// let m = 0xDEF0123456789ABCu64;
800 /// assert_eq!(n.rotate_right(12), m);
802 #[stable(feature = "rust1", since = "1.0.0")]
804 pub fn rotate_right(self, n: u32) -> Self {
805 // Protect against undefined behaviour for over-long bit shifts
807 (self >> n) | (self << (($BITS - n) % $BITS))
810 /// Reverses the byte order of the integer.
815 /// let n = 0x0123456789ABCDEFu64;
816 /// let m = 0xEFCDAB8967452301u64;
818 /// assert_eq!(n.swap_bytes(), m);
820 #[stable(feature = "rust1", since = "1.0.0")]
822 pub fn swap_bytes(self) -> Self {
823 unsafe { $bswap(self as $ActualT) as Self }
826 /// Converts an integer from big endian to the target's endianness.
828 /// On big endian this is a no-op. On little endian the bytes are
834 /// let n = 0x0123456789ABCDEFu64;
836 /// if cfg!(target_endian = "big") {
837 /// assert_eq!(u64::from_be(n), n)
839 /// assert_eq!(u64::from_be(n), n.swap_bytes())
842 #[stable(feature = "rust1", since = "1.0.0")]
844 pub fn from_be(x: Self) -> Self {
845 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
848 /// Converts an integer from little endian to the target's endianness.
850 /// On little endian this is a no-op. On big endian the bytes are
856 /// let n = 0x0123456789ABCDEFu64;
858 /// if cfg!(target_endian = "little") {
859 /// assert_eq!(u64::from_le(n), n)
861 /// assert_eq!(u64::from_le(n), n.swap_bytes())
864 #[stable(feature = "rust1", since = "1.0.0")]
866 pub fn from_le(x: Self) -> Self {
867 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
870 /// Converts `self` to big endian from the target's endianness.
872 /// On big endian this is a no-op. On little endian the bytes are
878 /// let n = 0x0123456789ABCDEFu64;
880 /// if cfg!(target_endian = "big") {
881 /// assert_eq!(n.to_be(), n)
883 /// assert_eq!(n.to_be(), n.swap_bytes())
886 #[stable(feature = "rust1", since = "1.0.0")]
888 pub fn to_be(self) -> Self { // or not to be?
889 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
892 /// Converts `self` to little endian from the target's endianness.
894 /// On little endian this is a no-op. On big endian the bytes are
900 /// let n = 0x0123456789ABCDEFu64;
902 /// if cfg!(target_endian = "little") {
903 /// assert_eq!(n.to_le(), n)
905 /// assert_eq!(n.to_le(), n.swap_bytes())
908 #[stable(feature = "rust1", since = "1.0.0")]
910 pub fn to_le(self) -> Self {
911 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
914 /// Checked integer addition. Computes `self + other`, returning `None`
915 /// if overflow occurred.
920 /// assert_eq!(5u16.checked_add(65530), Some(65535));
921 /// assert_eq!(6u16.checked_add(65530), None);
923 #[stable(feature = "rust1", since = "1.0.0")]
925 pub fn checked_add(self, other: Self) -> Option<Self> {
926 checked_op!($ActualT, $add_with_overflow, self, other)
929 /// Checked integer subtraction. Computes `self - other`, returning
930 /// `None` if underflow occurred.
935 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
936 /// assert_eq!((-128i8).checked_sub(1), None);
938 #[stable(feature = "rust1", since = "1.0.0")]
940 pub fn checked_sub(self, other: Self) -> Option<Self> {
941 checked_op!($ActualT, $sub_with_overflow, self, other)
944 /// Checked integer multiplication. Computes `self * other`, returning
945 /// `None` if underflow or overflow occurred.
950 /// assert_eq!(5u8.checked_mul(51), Some(255));
951 /// assert_eq!(5u8.checked_mul(52), None);
953 #[stable(feature = "rust1", since = "1.0.0")]
955 pub fn checked_mul(self, other: Self) -> Option<Self> {
956 checked_op!($ActualT, $mul_with_overflow, self, other)
959 /// Checked integer division. Computes `self / other`, returning `None`
960 /// if `other == 0` or the operation results in underflow or overflow.
965 /// assert_eq!((-127i8).checked_div(-1), Some(127));
966 /// assert_eq!((-128i8).checked_div(-1), None);
967 /// assert_eq!((1i8).checked_div(0), None);
969 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn checked_div(self, v: Self) -> Option<Self> {
978 /// Saturating integer addition. Computes `self + other`, saturating at
979 /// the numeric bounds instead of overflowing.
980 #[stable(feature = "rust1", since = "1.0.0")]
982 pub fn saturating_add(self, other: Self) -> Self {
983 match self.checked_add(other) {
985 None if other >= Self::zero() => Self::max_value(),
986 None => Self::min_value(),
990 /// Saturating integer subtraction. Computes `self - other`, saturating
991 /// at the numeric bounds instead of overflowing.
992 #[stable(feature = "rust1", since = "1.0.0")]
994 pub fn saturating_sub(self, other: Self) -> Self {
995 match self.checked_sub(other) {
997 None if other >= Self::zero() => Self::min_value(),
998 None => Self::max_value(),
1002 /// Wrapping (modular) addition. Computes `self + other`,
1003 /// wrapping around at the boundary of the type.
1004 #[stable(feature = "rust1", since = "1.0.0")]
1006 pub fn wrapping_add(self, rhs: Self) -> Self {
1008 intrinsics::overflowing_add(self, rhs)
1012 /// Wrapping (modular) subtraction. Computes `self - other`,
1013 /// wrapping around at the boundary of the type.
1014 #[stable(feature = "rust1", since = "1.0.0")]
1016 pub fn wrapping_sub(self, rhs: Self) -> Self {
1018 intrinsics::overflowing_sub(self, rhs)
1022 /// Wrapping (modular) multiplication. Computes `self *
1023 /// other`, wrapping around at the boundary of the type.
1024 #[stable(feature = "rust1", since = "1.0.0")]
1026 pub fn wrapping_mul(self, rhs: Self) -> Self {
1028 intrinsics::overflowing_mul(self, rhs)
1032 /// Wrapping (modular) division. Computes `floor(self / other)`,
1033 /// wrapping around at the boundary of the type.
1035 /// The only case where such wrapping can occur is when one
1036 /// divides `MIN / -1` on a signed type (where `MIN` is the
1037 /// negative minimal value for the type); this is equivalent
1038 /// to `-MIN`, a positive value that is too large to represent
1039 /// in the type. In such a case, this function returns `MIN`
1041 #[unstable(feature = "num_wrapping")]
1043 pub fn wrapping_div(self, rhs: Self) -> Self {
1044 self.overflowing_div(rhs).0
1047 /// Wrapping (modular) remainder. Computes `self % other`,
1048 /// wrapping around at the boundary of the type.
1050 /// Such wrap-around never actually occurs mathematically;
1051 /// implementation artifacts make `x % y` illegal for `MIN /
1052 /// -1` on a signed type illegal (where `MIN` is the negative
1053 /// minimal value). In such a case, this function returns `0`.
1054 #[unstable(feature = "num_wrapping")]
1056 pub fn wrapping_rem(self, rhs: Self) -> Self {
1057 self.overflowing_rem(rhs).0
1060 /// Wrapping (modular) negation. Computes `-self`,
1061 /// wrapping around at the boundary of the type.
1063 /// The only case where such wrapping can occur is when one
1064 /// negates `MIN` on a signed type (where `MIN` is the
1065 /// negative minimal value for the type); this is a positive
1066 /// value that is too large to represent in the type. In such
1067 /// a case, this function returns `MIN` itself.
1068 #[unstable(feature = "num_wrapping")]
1070 pub fn wrapping_neg(self) -> Self {
1071 self.overflowing_neg().0
1074 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1075 /// where `mask` removes any high-order bits of `rhs` that
1076 /// would cause the shift to exceed the bitwidth of the type.
1077 #[unstable(feature = "num_wrapping")]
1079 pub fn wrapping_shl(self, rhs: u32) -> Self {
1080 self.overflowing_shl(rhs).0
1083 /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
1084 /// where `mask` removes any high-order bits of `rhs` that
1085 /// would cause the shift to exceed the bitwidth of the type.
1086 #[unstable(feature = "num_wrapping")]
1088 pub fn wrapping_shr(self, rhs: u32) -> Self {
1089 self.overflowing_shr(rhs).0
1092 /// Raises self to the power of `exp`, using exponentiation by squaring.
1097 /// assert_eq!(2i32.pow(4), 16);
1099 #[stable(feature = "rust1", since = "1.0.0")]
1101 pub fn pow(self, mut exp: u32) -> Self {
1102 let mut base = self;
1103 let mut acc = Self::one();
1105 let mut prev_base = self;
1106 let mut base_oflo = false;
1110 // ensure overflow occurs in the same manner it
1111 // would have otherwise (i.e. signal any exception
1112 // it would have otherwise).
1113 acc = acc * (prev_base * prev_base);
1119 let (new_base, new_base_oflo) = base.overflowing_mul(base);
1121 base_oflo = new_base_oflo;
1127 /// Returns `true` iff `self == 2^k` for some `k`.
1128 #[stable(feature = "rust1", since = "1.0.0")]
1130 pub fn is_power_of_two(self) -> bool {
1131 (self.wrapping_sub(Self::one())) & self == Self::zero() &&
1132 !(self == Self::zero())
1135 /// Returns the smallest power of two greater than or equal to `self`.
1136 /// Unspecified behavior on overflow.
1137 #[stable(feature = "rust1", since = "1.0.0")]
1139 pub fn next_power_of_two(self) -> Self {
1140 let bits = size_of::<Self>() * 8;
1141 let one: Self = Self::one();
1142 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
1145 /// Returns the smallest power of two greater than or equal to `n`. If
1146 /// the next power of two is greater than the type's maximum value,
1147 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
1148 #[stable(feature = "rust1", since = "1.0.0")]
1149 pub fn checked_next_power_of_two(self) -> Option<Self> {
1150 let npot = self.next_power_of_two();
1167 intrinsics::u8_add_with_overflow,
1168 intrinsics::u8_sub_with_overflow,
1169 intrinsics::u8_mul_with_overflow }
1174 uint_impl! { u16, 16,
1175 intrinsics::ctpop16,
1178 intrinsics::bswap16,
1179 intrinsics::u16_add_with_overflow,
1180 intrinsics::u16_sub_with_overflow,
1181 intrinsics::u16_mul_with_overflow }
1186 uint_impl! { u32, 32,
1187 intrinsics::ctpop32,
1190 intrinsics::bswap32,
1191 intrinsics::u32_add_with_overflow,
1192 intrinsics::u32_sub_with_overflow,
1193 intrinsics::u32_mul_with_overflow }
1199 uint_impl! { u64, 64,
1200 intrinsics::ctpop64,
1203 intrinsics::bswap64,
1204 intrinsics::u64_add_with_overflow,
1205 intrinsics::u64_sub_with_overflow,
1206 intrinsics::u64_mul_with_overflow }
1209 #[cfg(target_pointer_width = "32")]
1212 uint_impl! { u32, 32,
1213 intrinsics::ctpop32,
1216 intrinsics::bswap32,
1217 intrinsics::u32_add_with_overflow,
1218 intrinsics::u32_sub_with_overflow,
1219 intrinsics::u32_mul_with_overflow }
1222 #[cfg(target_pointer_width = "64")]
1225 uint_impl! { u64, 64,
1226 intrinsics::ctpop64,
1229 intrinsics::bswap64,
1230 intrinsics::u64_add_with_overflow,
1231 intrinsics::u64_sub_with_overflow,
1232 intrinsics::u64_mul_with_overflow }
1235 /// Used for representing the classification of floating point numbers
1236 #[derive(Copy, Clone, PartialEq, Debug)]
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 pub enum FpCategory {
1239 /// "Not a Number", often obtained by dividing by zero
1240 #[stable(feature = "rust1", since = "1.0.0")]
1243 /// Positive or negative infinity
1244 #[stable(feature = "rust1", since = "1.0.0")]
1247 /// Positive or negative zero
1248 #[stable(feature = "rust1", since = "1.0.0")]
1251 /// De-normalized floating point representation (less precise than `Normal`)
1252 #[stable(feature = "rust1", since = "1.0.0")]
1255 /// A regular floating point number
1256 #[stable(feature = "rust1", since = "1.0.0")]
1260 /// A built-in floating point number.
1262 #[unstable(feature = "core_float",
1263 reason = "stable interface is via `impl f{32,64}` in later crates")]
1265 /// Returns the NaN value.
1267 /// Returns the infinite value.
1268 fn infinity() -> Self;
1269 /// Returns the negative infinite value.
1270 fn neg_infinity() -> Self;
1272 fn neg_zero() -> Self;
1277 /// Parses the string `s` with the radix `r` as a float.
1278 fn from_str_radix(s: &str, r: u32) -> Result<Self, ParseFloatError>;
1280 /// Returns true if this value is NaN and false otherwise.
1281 fn is_nan(self) -> bool;
1282 /// Returns true if this value is positive infinity or negative infinity and
1283 /// false otherwise.
1284 fn is_infinite(self) -> bool;
1285 /// Returns true if this number is neither infinite nor NaN.
1286 fn is_finite(self) -> bool;
1287 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1288 fn is_normal(self) -> bool;
1289 /// Returns the category that this number falls into.
1290 fn classify(self) -> FpCategory;
1292 /// Returns the mantissa, exponent and sign as integers, respectively.
1293 fn integer_decode(self) -> (u64, i16, i8);
1295 /// Return the largest integer less than or equal to a number.
1296 fn floor(self) -> Self;
1297 /// Return the smallest integer greater than or equal to a number.
1298 fn ceil(self) -> Self;
1299 /// Return the nearest integer to a number. Round half-way cases away from
1301 fn round(self) -> Self;
1302 /// Return the integer part of a number.
1303 fn trunc(self) -> Self;
1304 /// Return the fractional part of a number.
1305 fn fract(self) -> Self;
1307 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1308 /// number is `Float::nan()`.
1309 fn abs(self) -> Self;
1310 /// Returns a number that represents the sign of `self`.
1312 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1313 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1314 /// - `Float::nan()` if the number is `Float::nan()`
1315 fn signum(self) -> Self;
1316 /// Returns `true` if `self` is positive, including `+0.0` and
1317 /// `Float::infinity()`.
1318 fn is_positive(self) -> bool;
1319 /// Returns `true` if `self` is negative, including `-0.0` and
1320 /// `Float::neg_infinity()`.
1321 fn is_negative(self) -> bool;
1323 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1324 /// error. This produces a more accurate result with better performance than
1325 /// a separate multiplication operation followed by an add.
1326 fn mul_add(self, a: Self, b: Self) -> Self;
1327 /// Take the reciprocal (inverse) of a number, `1/x`.
1328 fn recip(self) -> Self;
1330 /// Raise a number to an integer power.
1332 /// Using this function is generally faster than using `powf`
1333 fn powi(self, n: i32) -> Self;
1334 /// Raise a number to a floating point power.
1335 fn powf(self, n: Self) -> Self;
1337 /// Take the square root of a number.
1339 /// Returns NaN if `self` is a negative number.
1340 fn sqrt(self) -> Self;
1341 /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1342 fn rsqrt(self) -> Self;
1344 /// Returns `e^(self)`, (the exponential function).
1345 fn exp(self) -> Self;
1346 /// Returns 2 raised to the power of the number, `2^(self)`.
1347 fn exp2(self) -> Self;
1348 /// Returns the natural logarithm of the number.
1349 fn ln(self) -> Self;
1350 /// Returns the logarithm of the number with respect to an arbitrary base.
1351 fn log(self, base: Self) -> Self;
1352 /// Returns the base 2 logarithm of the number.
1353 fn log2(self) -> Self;
1354 /// Returns the base 10 logarithm of the number.
1355 fn log10(self) -> Self;
1357 /// Convert radians to degrees.
1358 fn to_degrees(self) -> Self;
1359 /// Convert degrees to radians.
1360 fn to_radians(self) -> Self;
1363 macro_rules! from_str_float_impl {
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 impl FromStr for $t {
1367 type Err = ParseFloatError;
1369 /// Converts a string in base 10 to a float.
1370 /// Accepts an optional decimal exponent.
1372 /// This function accepts strings such as
1375 /// * '+3.14', equivalent to '3.14'
1377 /// * '2.5E10', or equivalently, '2.5e10'
1379 /// * '.' (understood as 0)
1381 /// * '.5', or, equivalently, '0.5'
1382 /// * '+inf', 'inf', '-inf', 'NaN'
1384 /// Leading and trailing whitespace represent an error.
1388 /// * src - A string
1392 /// `Err(ParseFloatError)` if the string did not represent a valid
1393 /// number. Otherwise, `Ok(n)` where `n` is the floating-point
1394 /// number represented by `src`.
1396 #[allow(deprecated)]
1397 fn from_str(src: &str) -> Result<Self, ParseFloatError> {
1398 Self::from_str_radix(src, 10)
1403 from_str_float_impl!(f32);
1404 from_str_float_impl!(f64);
1406 macro_rules! from_str_radix_int_impl {
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 #[allow(deprecated)]
1410 impl FromStr for $t {
1411 type Err = ParseIntError;
1412 fn from_str(src: &str) -> Result<Self, ParseIntError> {
1413 from_str_radix(src, 10)
1418 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
1421 trait FromStrRadixHelper: PartialOrd + Copy {
1422 fn min_value() -> Self;
1423 fn from_u32(u: u32) -> Self;
1424 fn checked_mul(&self, other: u32) -> Option<Self>;
1425 fn checked_sub(&self, other: u32) -> Option<Self>;
1426 fn checked_add(&self, other: u32) -> Option<Self>;
1430 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
1431 fn min_value() -> Self { Self::min_value() }
1432 fn from_u32(u: u32) -> Self { u as Self }
1433 fn checked_mul(&self, other: u32) -> Option<Self> {
1434 Self::checked_mul(*self, other as Self)
1436 fn checked_sub(&self, other: u32) -> Option<Self> {
1437 Self::checked_sub(*self, other as Self)
1439 fn checked_add(&self, other: u32) -> Option<Self> {
1440 Self::checked_add(*self, other as Self)
1444 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1446 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
1447 -> Result<T, ParseIntError> {
1448 use self::IntErrorKind::*;
1449 use self::ParseIntError as PIE;
1450 assert!(radix >= 2 && radix <= 36,
1451 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1454 let is_signed_ty = T::from_u32(0) > T::min_value();
1456 match src.slice_shift_char() {
1457 Some(('-', "")) => Err(PIE { kind: Empty }),
1458 Some(('-', src)) if is_signed_ty => {
1459 // The number is negative
1460 let mut result = T::from_u32(0);
1461 for c in src.chars() {
1462 let x = match c.to_digit(radix) {
1464 None => return Err(PIE { kind: InvalidDigit }),
1466 result = match result.checked_mul(radix) {
1467 Some(result) => result,
1468 None => return Err(PIE { kind: Underflow }),
1470 result = match result.checked_sub(x) {
1471 Some(result) => result,
1472 None => return Err(PIE { kind: Underflow }),
1478 // The number is signed
1479 let mut result = T::from_u32(0);
1480 for c in src.chars() {
1481 let x = match c.to_digit(radix) {
1483 None => return Err(PIE { kind: InvalidDigit }),
1485 result = match result.checked_mul(radix) {
1486 Some(result) => result,
1487 None => return Err(PIE { kind: Overflow }),
1489 result = match result.checked_add(x) {
1490 Some(result) => result,
1491 None => return Err(PIE { kind: Overflow }),
1496 None => Err(ParseIntError { kind: Empty }),
1500 /// An error which can be returned when parsing an integer.
1501 #[derive(Debug, Clone, PartialEq)]
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 pub struct ParseIntError { kind: IntErrorKind }
1505 #[derive(Debug, Clone, PartialEq)]
1513 impl ParseIntError {
1514 #[unstable(feature = "int_error_internals",
1515 reason = "available through Error trait and this method should \
1516 not be exposed publicly")]
1517 pub fn description(&self) -> &str {
1519 IntErrorKind::Empty => "cannot parse integer from empty string",
1520 IntErrorKind::InvalidDigit => "invalid digit found in string",
1521 IntErrorKind::Overflow => "number too large to fit in target type",
1522 IntErrorKind::Underflow => "number too small to fit in target type",
1527 #[stable(feature = "rust1", since = "1.0.0")]
1528 impl fmt::Display for ParseIntError {
1529 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1530 self.description().fmt(f)
1534 /// An error which can be returned when parsing a float.
1535 #[derive(Debug, Clone, PartialEq)]
1536 #[stable(feature = "rust1", since = "1.0.0")]
1537 pub struct ParseFloatError {
1539 #[unstable(feature = "float_error_internals",
1540 reason = "should not be exposed publicly")]
1541 pub __kind: FloatErrorKind
1544 #[derive(Debug, Clone, PartialEq)]
1545 #[unstable(feature = "float_error_internals",
1546 reason = "should not be exposed publicly")]
1547 pub enum FloatErrorKind {
1552 impl ParseFloatError {
1554 pub fn __description(&self) -> &str {
1556 FloatErrorKind::Empty => "cannot parse float from empty string",
1557 FloatErrorKind::Invalid => "invalid float literal",
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 impl fmt::Display for ParseFloatError {
1564 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1565 self.__description().fmt(f)