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);
44 #[unstable(feature = "core", reason = "may be removed or relocated")]
47 #[unstable(feature = "core", reason = "internal routines only exposed for testing")]
50 /// Types that have a "zero" value.
52 /// This trait is intended for use in conjunction with `Add`, as an identity:
53 /// `x + T::zero() == x`.
54 #[unstable(feature = "zero_one",
55 reason = "unsure of placement, wants to use associated constants")]
57 /// The "zero" (usually, additive identity) for this type.
61 /// Types that have a "one" value.
63 /// This trait is intended for use in conjunction with `Mul`, as an identity:
64 /// `x * T::one() == x`.
65 #[unstable(feature = "zero_one",
66 reason = "unsure of placement, wants to use associated constants")]
68 /// The "one" (usually, multiplicative identity) for this type.
72 macro_rules! zero_one_impl {
84 zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
86 macro_rules! zero_one_impl_float {
90 fn zero() -> $t { 0.0 }
94 fn one() -> $t { 1.0 }
98 zero_one_impl_float! { f32 f64 }
100 macro_rules! checked_op {
101 ($T:ty, $U:ty, $op:path, $x:expr, $y:expr) => {{
102 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
103 if overflowed { None } else { Some(result as $T) }
107 /// Swapping a single byte is a no-op. This is marked as `unsafe` for
108 /// consistency with the other `bswap` intrinsics.
109 unsafe fn bswap8(x: u8) -> u8 { x }
111 // `Int` + `SignedInt` implemented for signed integers
112 macro_rules! int_impl {
113 ($T:ident = $ActualT:ty, $UnsignedT:ty, $BITS:expr,
114 $add_with_overflow:path,
115 $sub_with_overflow:path,
116 $mul_with_overflow:path) => {
117 /// Returns the smallest value that can be represented by this integer type.
118 #[stable(feature = "rust1", since = "1.0.0")]
120 pub fn min_value() -> $T {
121 (-1 as $T) << ($BITS - 1)
124 /// Returns the largest value that can be represented by this integer type.
125 #[stable(feature = "rust1", since = "1.0.0")]
127 pub fn max_value() -> $T {
128 let min = $T::min_value(); !min
131 /// Converts a string slice in a given base to an integer.
133 /// Leading and trailing whitespace represent an error.
137 /// * src - A string slice
138 /// * radix - The base to use. Must lie in the range [2 .. 36]
142 /// `Err(ParseIntError)` if the string did not represent a valid number.
143 /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
144 #[stable(feature = "rust1", since = "1.0.0")]
146 pub fn from_str_radix(src: &str, radix: u32) -> Result<$T, ParseIntError> {
147 from_str_radix(src, radix)
150 /// Returns the number of ones in the binary representation of `self`.
155 /// let n = 0b01001100u8;
157 /// assert_eq!(n.count_ones(), 3);
159 #[stable(feature = "rust1", since = "1.0.0")]
161 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
163 /// Returns the number of zeros in the binary representation of `self`.
168 /// let n = 0b01001100u8;
170 /// assert_eq!(n.count_zeros(), 5);
172 #[stable(feature = "rust1", since = "1.0.0")]
174 pub fn count_zeros(self) -> u32 {
178 /// Returns the number of leading zeros in the binary representation
184 /// let n = 0b0101000u16;
186 /// assert_eq!(n.leading_zeros(), 10);
188 #[stable(feature = "rust1", since = "1.0.0")]
190 pub fn leading_zeros(self) -> u32 {
191 (self as $UnsignedT).leading_zeros()
194 /// Returns the number of trailing zeros in the binary representation
200 /// let n = 0b0101000u16;
202 /// assert_eq!(n.trailing_zeros(), 3);
204 #[stable(feature = "rust1", since = "1.0.0")]
206 pub fn trailing_zeros(self) -> u32 {
207 (self as $UnsignedT).trailing_zeros()
210 /// Shifts the bits to the left by a specified amount, `n`,
211 /// wrapping the truncated bits to the end of the resulting integer.
216 /// let n = 0x0123456789ABCDEFu64;
217 /// let m = 0x3456789ABCDEF012u64;
219 /// assert_eq!(n.rotate_left(12), m);
221 #[stable(feature = "rust1", since = "1.0.0")]
223 pub fn rotate_left(self, n: u32) -> $T {
224 (self as $UnsignedT).rotate_left(n) as $T
227 /// Shifts the bits to the right by a specified amount, `n`,
228 /// wrapping the truncated bits to the beginning of the resulting
234 /// let n = 0x0123456789ABCDEFu64;
235 /// let m = 0xDEF0123456789ABCu64;
237 /// assert_eq!(n.rotate_right(12), m);
239 #[stable(feature = "rust1", since = "1.0.0")]
241 pub fn rotate_right(self, n: u32) -> $T {
242 (self as $UnsignedT).rotate_right(n) as $T
245 /// Reverses the byte order of the integer.
250 /// let n = 0x0123456789ABCDEFu64;
251 /// let m = 0xEFCDAB8967452301u64;
253 /// assert_eq!(n.swap_bytes(), m);
255 #[stable(feature = "rust1", since = "1.0.0")]
257 pub fn swap_bytes(self) -> $T {
258 (self as $UnsignedT).swap_bytes() as $T
261 /// Converts an integer from big endian to the target's endianness.
263 /// On big endian this is a no-op. On little endian the bytes are
269 /// let n = 0x0123456789ABCDEFu64;
271 /// if cfg!(target_endian = "big") {
272 /// assert_eq!(u64::from_be(n), n)
274 /// assert_eq!(u64::from_be(n), n.swap_bytes())
277 #[stable(feature = "rust1", since = "1.0.0")]
279 pub fn from_be(x: $T) -> $T {
280 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
283 /// Converts an integer from little endian to the target's endianness.
285 /// On little endian this is a no-op. On big endian the bytes are
291 /// let n = 0x0123456789ABCDEFu64;
293 /// if cfg!(target_endian = "little") {
294 /// assert_eq!(u64::from_le(n), n)
296 /// assert_eq!(u64::from_le(n), n.swap_bytes())
299 #[stable(feature = "rust1", since = "1.0.0")]
301 pub fn from_le(x: $T) -> $T {
302 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
305 /// Converts `self` to big endian from the target's endianness.
307 /// On big endian this is a no-op. On little endian the bytes are
313 /// let n = 0x0123456789ABCDEFu64;
315 /// if cfg!(target_endian = "big") {
316 /// assert_eq!(n.to_be(), n)
318 /// assert_eq!(n.to_be(), n.swap_bytes())
321 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn to_be(self) -> $T { // or not to be?
324 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
327 /// Converts `self` to little endian from the target's endianness.
329 /// On little endian this is a no-op. On big endian the bytes are
335 /// let n = 0x0123456789ABCDEFu64;
337 /// if cfg!(target_endian = "little") {
338 /// assert_eq!(n.to_le(), n)
340 /// assert_eq!(n.to_le(), n.swap_bytes())
343 #[stable(feature = "rust1", since = "1.0.0")]
345 pub fn to_le(self) -> $T {
346 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
349 /// Checked integer addition. Computes `self + other`, returning `None`
350 /// if overflow occurred.
355 /// assert_eq!(5u16.checked_add(65530), Some(65535));
356 /// assert_eq!(6u16.checked_add(65530), None);
358 #[stable(feature = "rust1", since = "1.0.0")]
360 pub fn checked_add(self, other: $T) -> Option<$T> {
361 checked_op!($T, $ActualT, $add_with_overflow, self, other)
364 /// Checked integer subtraction. Computes `self - other`, returning
365 /// `None` if underflow occurred.
370 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
371 /// assert_eq!((-128i8).checked_sub(1), None);
373 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn checked_sub(self, other: $T) -> Option<$T> {
376 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
379 /// Checked integer multiplication. Computes `self * other`, returning
380 /// `None` if underflow or overflow occurred.
385 /// assert_eq!(5u8.checked_mul(51), Some(255));
386 /// assert_eq!(5u8.checked_mul(52), None);
388 #[stable(feature = "rust1", since = "1.0.0")]
390 pub fn checked_mul(self, other: $T) -> Option<$T> {
391 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
394 /// Checked integer division. Computes `self / other`, returning `None`
395 /// if `other == 0` or the operation results in underflow or overflow.
400 /// assert_eq!((-127i8).checked_div(-1), Some(127));
401 /// assert_eq!((-128i8).checked_div(-1), None);
402 /// assert_eq!((1i8).checked_div(0), None);
404 #[stable(feature = "rust1", since = "1.0.0")]
406 pub fn checked_div(self, v: $T) -> Option<$T> {
409 -1 if self == <$T>::min_value()
415 /// Saturating integer addition. Computes `self + other`, saturating at
416 /// the numeric bounds instead of overflowing.
417 #[stable(feature = "rust1", since = "1.0.0")]
419 pub fn saturating_add(self, other: $T) -> $T {
420 match self.checked_add(other) {
422 None if other >= <$T as Zero>::zero() => <$T>::max_value(),
423 None => <$T>::min_value(),
427 /// Saturating integer subtraction. Computes `self - other`, saturating
428 /// at the numeric bounds instead of overflowing.
429 #[stable(feature = "rust1", since = "1.0.0")]
431 pub fn saturating_sub(self, other: $T) -> $T {
432 match self.checked_sub(other) {
434 None if other >= <$T as Zero>::zero() => <$T>::min_value(),
435 None => <$T>::max_value(),
439 /// Wrapping (modular) addition. Computes `self + other`,
440 /// wrapping around at the boundary of the type.
441 #[stable(feature = "rust1", since = "1.0.0")]
443 pub fn wrapping_add(self, rhs: $T) -> $T {
445 intrinsics::overflowing_add(self, rhs)
449 /// Wrapping (modular) subtraction. Computes `self - other`,
450 /// wrapping around at the boundary of the type.
451 #[stable(feature = "rust1", since = "1.0.0")]
453 pub fn wrapping_sub(self, rhs: $T) -> $T {
455 intrinsics::overflowing_sub(self, rhs)
459 /// Wrapping (modular) multiplication. Computes `self *
460 /// other`, wrapping around at the boundary of the type.
461 #[stable(feature = "rust1", since = "1.0.0")]
463 pub fn wrapping_mul(self, rhs: $T) -> $T {
465 intrinsics::overflowing_mul(self, rhs)
469 /// Wrapping (modular) division. Computes `floor(self / other)`,
470 /// wrapping around at the boundary of the type.
472 /// The only case where such wrapping can occur is when one
473 /// divides `MIN / -1` on a signed type (where `MIN` is the
474 /// negative minimal value for the type); this is equivalent
475 /// to `-MIN`, a positive value that is too large to represent
476 /// in the type. In such a case, this function returns `MIN`
478 #[unstable(feature = "core", since = "1.0.0")]
480 pub fn wrapping_div(self, rhs: $T) -> $T {
481 self.overflowing_div(rhs).0
484 /// Wrapping (modular) remainder. Computes `self % other`,
485 /// wrapping around at the boundary of the type.
487 /// Such wrap-around never actually occurs mathematically;
488 /// implementation artifacts make `x % y` illegal for `MIN /
489 /// -1` on a signed type illegal (where `MIN` is the negative
490 /// minimal value). In such a case, this function returns `0`.
491 #[unstable(feature = "core", since = "1.0.0")]
493 pub fn wrapping_rem(self, rhs: $T) -> $T {
494 self.overflowing_rem(rhs).0
497 /// Wrapping (modular) negation. Computes `-self`,
498 /// wrapping around at the boundary of the type.
500 /// The only case where such wrapping can occur is when one
501 /// negates `MIN` on a signed type (where `MIN` is the
502 /// negative minimal value for the type); this is a positive
503 /// value that is too large to represent in the type. In such
504 /// a case, this function returns `MIN` itself.
505 #[unstable(feature = "core", since = "1.0.0")]
507 pub fn wrapping_neg(self) -> $T {
508 self.overflowing_neg().0
511 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
512 /// where `mask` removes any high-order bits of `rhs` that
513 /// would cause the shift to exceed the bitwidth of the type.
514 #[unstable(feature = "core", since = "1.0.0")]
516 pub fn wrapping_shl(self, rhs: u32) -> $T {
517 self.overflowing_shl(rhs).0
520 /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
521 /// where `mask` removes any high-order bits of `rhs` that
522 /// would cause the shift to exceed the bitwidth of the type.
523 #[unstable(feature = "core", since = "1.0.0")]
525 pub fn wrapping_shr(self, rhs: u32) -> $T {
526 self.overflowing_shr(rhs).0
529 /// Raises self to the power of `exp`, using exponentiation by squaring.
534 /// let x: i32 = 2; // or any other integer type
536 /// assert_eq!(x.pow(4), 16);
538 #[stable(feature = "rust1", since = "1.0.0")]
540 pub fn pow(self, mut exp: u32) -> $T {
542 let mut acc = <$T as One>::one();
544 let mut prev_base = self;
545 let mut base_oflo = false;
549 // ensure overflow occurs in the same manner it
550 // would have otherwise (i.e. signal any exception
551 // it would have otherwise).
552 acc = acc * (prev_base * prev_base);
558 let (new_base, new_base_oflo) = base.overflowing_mul(base);
560 base_oflo = new_base_oflo;
566 /// Computes the absolute value of `self`. `Int::min_value()` will be
567 /// returned if the number is `Int::min_value()`.
568 #[stable(feature = "rust1", since = "1.0.0")]
570 pub fn abs(self) -> $T {
571 if self.is_negative() {
578 /// Returns a number representing sign of `self`.
580 /// - `0` if the number is zero
581 /// - `1` if the number is positive
582 /// - `-1` if the number is negative
583 #[stable(feature = "rust1", since = "1.0.0")]
585 pub fn signum(self) -> $T {
593 /// Returns `true` if `self` is positive and `false` if the number
594 /// is zero or negative.
595 #[stable(feature = "rust1", since = "1.0.0")]
597 pub fn is_positive(self) -> bool { self > 0 }
599 /// Returns `true` if `self` is negative and `false` if the number
600 /// is zero or positive.
601 #[stable(feature = "rust1", since = "1.0.0")]
603 pub fn is_negative(self) -> bool { self < 0 }
609 int_impl! { i8 = i8, u8, 8,
610 intrinsics::i8_add_with_overflow,
611 intrinsics::i8_sub_with_overflow,
612 intrinsics::i8_mul_with_overflow }
617 int_impl! { i16 = i16, u16, 16,
618 intrinsics::i16_add_with_overflow,
619 intrinsics::i16_sub_with_overflow,
620 intrinsics::i16_mul_with_overflow }
625 int_impl! { i32 = i32, u32, 32,
626 intrinsics::i32_add_with_overflow,
627 intrinsics::i32_sub_with_overflow,
628 intrinsics::i32_mul_with_overflow }
633 int_impl! { i64 = i64, u64, 64,
634 intrinsics::i64_add_with_overflow,
635 intrinsics::i64_sub_with_overflow,
636 intrinsics::i64_mul_with_overflow }
639 #[cfg(target_pointer_width = "32")]
642 int_impl! { isize = i32, u32, 32,
643 intrinsics::i32_add_with_overflow,
644 intrinsics::i32_sub_with_overflow,
645 intrinsics::i32_mul_with_overflow }
648 #[cfg(target_pointer_width = "64")]
651 int_impl! { isize = i64, u64, 64,
652 intrinsics::i64_add_with_overflow,
653 intrinsics::i64_sub_with_overflow,
654 intrinsics::i64_mul_with_overflow }
657 // `Int` + `UnsignedInt` implemented for signed integers
658 macro_rules! uint_impl {
659 ($T:ty = $ActualT:ty, $BITS:expr,
664 $add_with_overflow:path,
665 $sub_with_overflow:path,
666 $mul_with_overflow:path) => {
667 /// Returns the smallest value that can be represented by this integer type.
668 #[stable(feature = "rust1", since = "1.0.0")]
669 pub fn min_value() -> $T { 0 }
671 /// Returns the largest value that can be represented by this integer type.
672 #[stable(feature = "rust1", since = "1.0.0")]
673 pub fn max_value() -> $T { !0 }
675 /// Converts a string slice in a given base to an integer.
677 /// Leading and trailing whitespace represent an error.
681 /// * src - A string slice
682 /// * radix - The base to use. Must lie in the range [2 .. 36]
686 /// `Err(ParseIntError)` if the string did not represent a valid number.
687 /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
688 #[stable(feature = "rust1", since = "1.0.0")]
690 pub fn from_str_radix(src: &str, radix: u32) -> Result<$T, ParseIntError> {
691 from_str_radix(src, radix)
694 /// Returns the number of ones in the binary representation of `self`.
699 /// let n = 0b01001100u8;
701 /// assert_eq!(n.count_ones(), 3);
703 #[stable(feature = "rust1", since = "1.0.0")]
705 pub fn count_ones(self) -> u32 {
706 unsafe { $ctpop(self as $ActualT) as u32 }
709 /// Returns the number of zeros in the binary representation of `self`.
714 /// let n = 0b01001100u8;
716 /// assert_eq!(n.count_zeros(), 5);
718 #[stable(feature = "rust1", since = "1.0.0")]
720 pub fn count_zeros(self) -> u32 {
724 /// Returns the number of leading zeros in the binary representation
730 /// let n = 0b0101000u16;
732 /// assert_eq!(n.leading_zeros(), 10);
734 #[stable(feature = "rust1", since = "1.0.0")]
736 pub fn leading_zeros(self) -> u32 {
737 unsafe { $ctlz(self as $ActualT) as u32 }
740 /// Returns the number of trailing zeros in the binary representation
746 /// let n = 0b0101000u16;
748 /// assert_eq!(n.trailing_zeros(), 3);
750 #[stable(feature = "rust1", since = "1.0.0")]
752 pub fn trailing_zeros(self) -> u32 {
753 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
754 // emits two conditional moves on x86_64. By promoting the value to
755 // u16 and setting bit 8, we get better code without any conditional
757 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
758 // pending, remove this workaround once LLVM generates better code
762 intrinsics::cttz16(self as u16 | 0x100) as u32
764 $cttz(self as $ActualT) as u32
769 /// Shifts the bits to the left by a specified amount, `n`,
770 /// wrapping the truncated bits to the end of the resulting integer.
775 /// let n = 0x0123456789ABCDEFu64;
776 /// let m = 0x3456789ABCDEF012u64;
778 /// assert_eq!(n.rotate_left(12), m);
780 #[stable(feature = "rust1", since = "1.0.0")]
782 pub fn rotate_left(self, n: u32) -> $T {
783 // Protect against undefined behaviour for over-long bit shifts
785 (self << n) | (self >> (($BITS - n) % $BITS))
788 /// Shifts the bits to the right by a specified amount, `n`,
789 /// wrapping the truncated bits to the beginning of the resulting
795 /// let n = 0x0123456789ABCDEFu64;
796 /// let m = 0xDEF0123456789ABCu64;
798 /// assert_eq!(n.rotate_right(12), m);
800 #[stable(feature = "rust1", since = "1.0.0")]
802 pub fn rotate_right(self, n: u32) -> $T {
803 // Protect against undefined behaviour for over-long bit shifts
805 (self >> n) | (self << (($BITS - n) % $BITS))
808 /// Reverses the byte order of the integer.
813 /// let n = 0x0123456789ABCDEFu64;
814 /// let m = 0xEFCDAB8967452301u64;
816 /// assert_eq!(n.swap_bytes(), m);
818 #[stable(feature = "rust1", since = "1.0.0")]
820 pub fn swap_bytes(self) -> $T {
821 unsafe { $bswap(self as $ActualT) as $T }
824 /// Converts an integer from big endian to the target's endianness.
826 /// On big endian this is a no-op. On little endian the bytes are
832 /// let n = 0x0123456789ABCDEFu64;
834 /// if cfg!(target_endian = "big") {
835 /// assert_eq!(u64::from_be(n), n)
837 /// assert_eq!(u64::from_be(n), n.swap_bytes())
840 #[stable(feature = "rust1", since = "1.0.0")]
842 pub fn from_be(x: $T) -> $T {
843 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
846 /// Converts an integer from little endian to the target's endianness.
848 /// On little endian this is a no-op. On big endian the bytes are
854 /// let n = 0x0123456789ABCDEFu64;
856 /// if cfg!(target_endian = "little") {
857 /// assert_eq!(u64::from_le(n), n)
859 /// assert_eq!(u64::from_le(n), n.swap_bytes())
862 #[stable(feature = "rust1", since = "1.0.0")]
864 pub fn from_le(x: $T) -> $T {
865 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
868 /// Converts `self` to big endian from the target's endianness.
870 /// On big endian this is a no-op. On little endian the bytes are
876 /// let n = 0x0123456789ABCDEFu64;
878 /// if cfg!(target_endian = "big") {
879 /// assert_eq!(n.to_be(), n)
881 /// assert_eq!(n.to_be(), n.swap_bytes())
884 #[stable(feature = "rust1", since = "1.0.0")]
886 pub fn to_be(self) -> $T { // or not to be?
887 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
890 /// Converts `self` to little endian from the target's endianness.
892 /// On little endian this is a no-op. On big endian the bytes are
898 /// let n = 0x0123456789ABCDEFu64;
900 /// if cfg!(target_endian = "little") {
901 /// assert_eq!(n.to_le(), n)
903 /// assert_eq!(n.to_le(), n.swap_bytes())
906 #[stable(feature = "rust1", since = "1.0.0")]
908 pub fn to_le(self) -> $T {
909 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
912 /// Checked integer addition. Computes `self + other`, returning `None`
913 /// if overflow occurred.
918 /// assert_eq!(5u16.checked_add(65530), Some(65535));
919 /// assert_eq!(6u16.checked_add(65530), None);
921 #[stable(feature = "rust1", since = "1.0.0")]
923 pub fn checked_add(self, other: $T) -> Option<$T> {
924 checked_op!($T, $ActualT, $add_with_overflow, self, other)
927 /// Checked integer subtraction. Computes `self - other`, returning
928 /// `None` if underflow occurred.
933 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
934 /// assert_eq!((-128i8).checked_sub(1), None);
936 #[stable(feature = "rust1", since = "1.0.0")]
938 pub fn checked_sub(self, other: $T) -> Option<$T> {
939 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
942 /// Checked integer multiplication. Computes `self * other`, returning
943 /// `None` if underflow or overflow occurred.
948 /// assert_eq!(5u8.checked_mul(51), Some(255));
949 /// assert_eq!(5u8.checked_mul(52), None);
951 #[stable(feature = "rust1", since = "1.0.0")]
953 pub fn checked_mul(self, other: $T) -> Option<$T> {
954 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
957 /// Checked integer division. Computes `self / other`, returning `None`
958 /// if `other == 0` or the operation results in underflow or overflow.
963 /// assert_eq!((-127i8).checked_div(-1), Some(127));
964 /// assert_eq!((-128i8).checked_div(-1), None);
965 /// assert_eq!((1i8).checked_div(0), None);
967 #[stable(feature = "rust1", since = "1.0.0")]
969 pub fn checked_div(self, v: $T) -> Option<$T> {
976 /// Saturating integer addition. Computes `self + other`, saturating at
977 /// the numeric bounds instead of overflowing.
978 #[stable(feature = "rust1", since = "1.0.0")]
980 pub fn saturating_add(self, other: $T) -> $T {
981 match self.checked_add(other) {
983 None if other >= <$T as Zero>::zero() => <$T>::max_value(),
984 None => <$T>::min_value(),
988 /// Saturating integer subtraction. Computes `self - other`, saturating
989 /// at the numeric bounds instead of overflowing.
990 #[stable(feature = "rust1", since = "1.0.0")]
992 pub fn saturating_sub(self, other: $T) -> $T {
993 match self.checked_sub(other) {
995 None if other >= <$T as Zero>::zero() => <$T>::min_value(),
996 None => <$T>::max_value(),
1000 /// Wrapping (modular) addition. Computes `self + other`,
1001 /// wrapping around at the boundary of the type.
1002 #[stable(feature = "rust1", since = "1.0.0")]
1004 pub fn wrapping_add(self, rhs: $T) -> $T {
1006 intrinsics::overflowing_add(self, rhs)
1010 /// Wrapping (modular) subtraction. Computes `self - other`,
1011 /// wrapping around at the boundary of the type.
1012 #[stable(feature = "rust1", since = "1.0.0")]
1014 pub fn wrapping_sub(self, rhs: $T) -> $T {
1016 intrinsics::overflowing_sub(self, rhs)
1020 /// Wrapping (modular) multiplication. Computes `self *
1021 /// other`, wrapping around at the boundary of the type.
1022 #[stable(feature = "rust1", since = "1.0.0")]
1024 pub fn wrapping_mul(self, rhs: $T) -> $T {
1026 intrinsics::overflowing_mul(self, rhs)
1030 /// Wrapping (modular) division. Computes `floor(self / other)`,
1031 /// wrapping around at the boundary of the type.
1033 /// The only case where such wrapping can occur is when one
1034 /// divides `MIN / -1` on a signed type (where `MIN` is the
1035 /// negative minimal value for the type); this is equivalent
1036 /// to `-MIN`, a positive value that is too large to represent
1037 /// in the type. In such a case, this function returns `MIN`
1039 #[unstable(feature = "core", since = "1.0.0")]
1041 pub fn wrapping_div(self, rhs: $T) -> $T {
1042 self.overflowing_div(rhs).0
1045 /// Wrapping (modular) remainder. Computes `self % other`,
1046 /// wrapping around at the boundary of the type.
1048 /// Such wrap-around never actually occurs mathematically;
1049 /// implementation artifacts make `x % y` illegal for `MIN /
1050 /// -1` on a signed type illegal (where `MIN` is the negative
1051 /// minimal value). In such a case, this function returns `0`.
1052 #[unstable(feature = "core", since = "1.0.0")]
1054 pub fn wrapping_rem(self, rhs: $T) -> $T {
1055 self.overflowing_rem(rhs).0
1058 /// Wrapping (modular) negation. Computes `-self`,
1059 /// wrapping around at the boundary of the type.
1061 /// The only case where such wrapping can occur is when one
1062 /// negates `MIN` on a signed type (where `MIN` is the
1063 /// negative minimal value for the type); this is a positive
1064 /// value that is too large to represent in the type. In such
1065 /// a case, this function returns `MIN` itself.
1066 #[unstable(feature = "core", since = "1.0.0")]
1068 pub fn wrapping_neg(self) -> $T {
1069 self.overflowing_neg().0
1072 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1073 /// where `mask` removes any high-order bits of `rhs` that
1074 /// would cause the shift to exceed the bitwidth of the type.
1075 #[unstable(feature = "core", since = "1.0.0")]
1077 pub fn wrapping_shl(self, rhs: u32) -> $T {
1078 self.overflowing_shl(rhs).0
1081 /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
1082 /// where `mask` removes any high-order bits of `rhs` that
1083 /// would cause the shift to exceed the bitwidth of the type.
1084 #[unstable(feature = "core", since = "1.0.0")]
1086 pub fn wrapping_shr(self, rhs: u32) -> $T {
1087 self.overflowing_shr(rhs).0
1090 /// Raises self to the power of `exp`, using exponentiation by squaring.
1095 /// assert_eq!(2i32.pow(4), 16);
1097 #[stable(feature = "rust1", since = "1.0.0")]
1099 pub fn pow(self, mut exp: u32) -> $T {
1100 let mut base = self;
1101 let mut acc = <$T as One>::one();
1103 let mut prev_base = self;
1104 let mut base_oflo = false;
1108 // ensure overflow occurs in the same manner it
1109 // would have otherwise (i.e. signal any exception
1110 // it would have otherwise).
1111 acc = acc * (prev_base * prev_base);
1117 let (new_base, new_base_oflo) = base.overflowing_mul(base);
1119 base_oflo = new_base_oflo;
1125 /// Returns `true` iff `self == 2^k` for some `k`.
1126 #[stable(feature = "rust1", since = "1.0.0")]
1128 pub fn is_power_of_two(self) -> bool {
1129 (self.wrapping_sub(<$T as One>::one())) & self == <$T as Zero>::zero() &&
1130 !(self == <$T as Zero>::zero())
1133 /// Returns the smallest power of two greater than or equal to `self`.
1134 /// Unspecified behavior on overflow.
1135 #[stable(feature = "rust1", since = "1.0.0")]
1137 pub fn next_power_of_two(self) -> $T {
1138 let bits = size_of::<$T>() * 8;
1139 let one: $T = <$T as One>::one();
1140 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
1143 /// Returns the smallest power of two greater than or equal to `n`. If
1144 /// the next power of two is greater than the type's maximum value,
1145 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 pub fn checked_next_power_of_two(self) -> Option<$T> {
1148 let npot = self.next_power_of_two();
1160 uint_impl! { u8 = u8, 8,
1165 intrinsics::u8_add_with_overflow,
1166 intrinsics::u8_sub_with_overflow,
1167 intrinsics::u8_mul_with_overflow }
1172 uint_impl! { u16 = u16, 16,
1173 intrinsics::ctpop16,
1176 intrinsics::bswap16,
1177 intrinsics::u16_add_with_overflow,
1178 intrinsics::u16_sub_with_overflow,
1179 intrinsics::u16_mul_with_overflow }
1184 uint_impl! { u32 = u32, 32,
1185 intrinsics::ctpop32,
1188 intrinsics::bswap32,
1189 intrinsics::u32_add_with_overflow,
1190 intrinsics::u32_sub_with_overflow,
1191 intrinsics::u32_mul_with_overflow }
1197 uint_impl! { u64 = u64, 64,
1198 intrinsics::ctpop64,
1201 intrinsics::bswap64,
1202 intrinsics::u64_add_with_overflow,
1203 intrinsics::u64_sub_with_overflow,
1204 intrinsics::u64_mul_with_overflow }
1207 #[cfg(target_pointer_width = "32")]
1210 uint_impl! { usize = u32, 32,
1211 intrinsics::ctpop32,
1214 intrinsics::bswap32,
1215 intrinsics::u32_add_with_overflow,
1216 intrinsics::u32_sub_with_overflow,
1217 intrinsics::u32_mul_with_overflow }
1220 #[cfg(target_pointer_width = "64")]
1223 uint_impl! { usize = u64, 64,
1224 intrinsics::ctpop64,
1227 intrinsics::bswap64,
1228 intrinsics::u64_add_with_overflow,
1229 intrinsics::u64_sub_with_overflow,
1230 intrinsics::u64_mul_with_overflow }
1233 /// Used for representing the classification of floating point numbers
1234 #[derive(Copy, Clone, PartialEq, Debug)]
1235 #[stable(feature = "rust1", since = "1.0.0")]
1236 pub enum FpCategory {
1237 /// "Not a Number", often obtained by dividing by zero
1238 #[stable(feature = "rust1", since = "1.0.0")]
1241 /// Positive or negative infinity
1242 #[stable(feature = "rust1", since = "1.0.0")]
1245 /// Positive or negative zero
1246 #[stable(feature = "rust1", since = "1.0.0")]
1249 /// De-normalized floating point representation (less precise than `Normal`)
1250 #[stable(feature = "rust1", since = "1.0.0")]
1253 /// A regular floating point number
1254 #[stable(feature = "rust1", since = "1.0.0")]
1258 /// A built-in floating point number.
1261 /// Returns the NaN value.
1263 /// Returns the infinite value.
1264 fn infinity() -> Self;
1265 /// Returns the negative infinite value.
1266 fn neg_infinity() -> Self;
1268 fn neg_zero() -> Self;
1273 /// Parses the string `s` with the radix `r` as a float.
1274 fn from_str_radix(s: &str, r: u32) -> Result<Self, ParseFloatError>;
1276 /// Returns true if this value is NaN and false otherwise.
1277 fn is_nan(self) -> bool;
1278 /// Returns true if this value is positive infinity or negative infinity and
1279 /// false otherwise.
1280 fn is_infinite(self) -> bool;
1281 /// Returns true if this number is neither infinite nor NaN.
1282 fn is_finite(self) -> bool;
1283 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1284 fn is_normal(self) -> bool;
1285 /// Returns the category that this number falls into.
1286 fn classify(self) -> FpCategory;
1288 /// Returns the mantissa, exponent and sign as integers, respectively.
1289 fn integer_decode(self) -> (u64, i16, i8);
1291 /// Return the largest integer less than or equal to a number.
1292 fn floor(self) -> Self;
1293 /// Return the smallest integer greater than or equal to a number.
1294 fn ceil(self) -> Self;
1295 /// Return the nearest integer to a number. Round half-way cases away from
1297 fn round(self) -> Self;
1298 /// Return the integer part of a number.
1299 fn trunc(self) -> Self;
1300 /// Return the fractional part of a number.
1301 fn fract(self) -> Self;
1303 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1304 /// number is `Float::nan()`.
1305 fn abs(self) -> Self;
1306 /// Returns a number that represents the sign of `self`.
1308 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1309 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1310 /// - `Float::nan()` if the number is `Float::nan()`
1311 fn signum(self) -> Self;
1312 /// Returns `true` if `self` is positive, including `+0.0` and
1313 /// `Float::infinity()`.
1314 fn is_positive(self) -> bool;
1315 /// Returns `true` if `self` is negative, including `-0.0` and
1316 /// `Float::neg_infinity()`.
1317 fn is_negative(self) -> bool;
1319 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1320 /// error. This produces a more accurate result with better performance than
1321 /// a separate multiplication operation followed by an add.
1322 fn mul_add(self, a: Self, b: Self) -> Self;
1323 /// Take the reciprocal (inverse) of a number, `1/x`.
1324 fn recip(self) -> Self;
1326 /// Raise a number to an integer power.
1328 /// Using this function is generally faster than using `powf`
1329 fn powi(self, n: i32) -> Self;
1330 /// Raise a number to a floating point power.
1331 fn powf(self, n: Self) -> Self;
1333 /// Take the square root of a number.
1335 /// Returns NaN if `self` is a negative number.
1336 fn sqrt(self) -> Self;
1337 /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1338 fn rsqrt(self) -> Self;
1340 /// Returns `e^(self)`, (the exponential function).
1341 fn exp(self) -> Self;
1342 /// Returns 2 raised to the power of the number, `2^(self)`.
1343 fn exp2(self) -> Self;
1344 /// Returns the natural logarithm of the number.
1345 fn ln(self) -> Self;
1346 /// Returns the logarithm of the number with respect to an arbitrary base.
1347 fn log(self, base: Self) -> Self;
1348 /// Returns the base 2 logarithm of the number.
1349 fn log2(self) -> Self;
1350 /// Returns the base 10 logarithm of the number.
1351 fn log10(self) -> Self;
1353 /// Convert radians to degrees.
1354 fn to_degrees(self) -> Self;
1355 /// Convert degrees to radians.
1356 fn to_radians(self) -> Self;
1359 macro_rules! from_str_float_impl {
1361 #[stable(feature = "rust1", since = "1.0.0")]
1362 impl FromStr for $T {
1363 type Err = ParseFloatError;
1365 /// Converts a string in base 10 to a float.
1366 /// Accepts an optional decimal exponent.
1368 /// This function accepts strings such as
1371 /// * '+3.14', equivalent to '3.14'
1373 /// * '2.5E10', or equivalently, '2.5e10'
1375 /// * '.' (understood as 0)
1377 /// * '.5', or, equivalently, '0.5'
1378 /// * '+inf', 'inf', '-inf', 'NaN'
1380 /// Leading and trailing whitespace represent an error.
1384 /// * src - A string
1388 /// `Err(ParseFloatError)` if the string did not represent a valid
1389 /// number. Otherwise, `Ok(n)` where `n` is the floating-point
1390 /// number represented by `src`.
1392 #[allow(deprecated)]
1393 fn from_str(src: &str) -> Result<$T, ParseFloatError> {
1394 $T::from_str_radix(src, 10)
1399 from_str_float_impl!(f32);
1400 from_str_float_impl!(f64);
1402 macro_rules! from_str_radix_int_impl {
1403 ($($T:ident)*) => {$(
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 #[allow(deprecated)]
1406 impl FromStr for $T {
1407 type Err = ParseIntError;
1408 fn from_str(src: &str) -> Result<$T, ParseIntError> {
1409 from_str_radix(src, 10)
1414 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
1417 trait FromStrRadixHelper: PartialOrd + Copy {
1418 fn min_value() -> Self;
1419 fn from_u32(u: u32) -> Self;
1420 fn checked_mul(&self, other: u32) -> Option<Self>;
1421 fn checked_sub(&self, other: u32) -> Option<Self>;
1422 fn checked_add(&self, other: u32) -> Option<Self>;
1426 ($($t:ident)*) => ($(impl FromStrRadixHelper for $t {
1427 fn min_value() -> Self { <$t>::min_value() }
1428 fn from_u32(u: u32) -> Self { u as $t }
1429 fn checked_mul(&self, other: u32) -> Option<Self> {
1430 <$t>::checked_mul(*self, other as $t)
1432 fn checked_sub(&self, other: u32) -> Option<Self> {
1433 <$t>::checked_sub(*self, other as $t)
1435 fn checked_add(&self, other: u32) -> Option<Self> {
1436 <$t>::checked_add(*self, other as $t)
1440 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1442 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
1443 -> Result<T, ParseIntError> {
1444 use self::IntErrorKind::*;
1445 use self::ParseIntError as PIE;
1446 assert!(radix >= 2 && radix <= 36,
1447 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1450 let is_signed_ty = T::from_u32(0) > T::min_value();
1452 match src.slice_shift_char() {
1453 Some(('-', "")) => Err(PIE { kind: Empty }),
1454 Some(('-', src)) if is_signed_ty => {
1455 // The number is negative
1456 let mut result = T::from_u32(0);
1457 for c in src.chars() {
1458 let x = match c.to_digit(radix) {
1460 None => return Err(PIE { kind: InvalidDigit }),
1462 result = match result.checked_mul(radix) {
1463 Some(result) => result,
1464 None => return Err(PIE { kind: Underflow }),
1466 result = match result.checked_sub(x) {
1467 Some(result) => result,
1468 None => return Err(PIE { kind: Underflow }),
1474 // The number is signed
1475 let mut result = T::from_u32(0);
1476 for c in src.chars() {
1477 let x = match c.to_digit(radix) {
1479 None => return Err(PIE { kind: InvalidDigit }),
1481 result = match result.checked_mul(radix) {
1482 Some(result) => result,
1483 None => return Err(PIE { kind: Overflow }),
1485 result = match result.checked_add(x) {
1486 Some(result) => result,
1487 None => return Err(PIE { kind: Overflow }),
1492 None => Err(ParseIntError { kind: Empty }),
1496 /// An error which can be returned when parsing an integer.
1497 #[derive(Debug, Clone, PartialEq)]
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 pub struct ParseIntError { kind: IntErrorKind }
1501 #[derive(Debug, Clone, PartialEq)]
1509 impl ParseIntError {
1510 #[unstable(feature = "core", reason = "available through Error trait")]
1511 pub fn description(&self) -> &str {
1513 IntErrorKind::Empty => "cannot parse integer from empty string",
1514 IntErrorKind::InvalidDigit => "invalid digit found in string",
1515 IntErrorKind::Overflow => "number too large to fit in target type",
1516 IntErrorKind::Underflow => "number too small to fit in target type",
1521 #[stable(feature = "rust1", since = "1.0.0")]
1522 impl fmt::Display for ParseIntError {
1523 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1524 self.description().fmt(f)
1528 /// An error which can be returned when parsing a float.
1529 #[derive(Debug, Clone, PartialEq)]
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 pub struct ParseFloatError {
1533 pub __kind: FloatErrorKind
1536 #[derive(Debug, Clone, PartialEq)]
1537 pub enum FloatErrorKind {
1542 impl ParseFloatError {
1544 pub fn __description(&self) -> &str {
1546 FloatErrorKind::Empty => "cannot parse float from empty string",
1547 FloatErrorKind::Invalid => "invalid float literal",
1552 #[stable(feature = "rust1", since = "1.0.0")]
1553 impl fmt::Display for ParseFloatError {
1554 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1555 self.__description().fmt(f)