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`.
568 /// # Overflow behavior
570 /// The absolute value of `i32::min_value()` cannot be represented as an
571 /// `i32`, and attempting to calculate it will cause an overflow. This
572 /// means that code in debug mode will trigger a panic on this case and
573 /// optimized code will return `i32::min_value()` without a panic.
574 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn abs(self) -> $T {
577 if self.is_negative() {
578 // Note that the #[inline] above means that the overflow
579 // semantics of this negation depend on the crate we're being
587 /// Returns a number representing sign of `self`.
589 /// - `0` if the number is zero
590 /// - `1` if the number is positive
591 /// - `-1` if the number is negative
592 #[stable(feature = "rust1", since = "1.0.0")]
594 pub fn signum(self) -> $T {
602 /// Returns `true` if `self` is positive and `false` if the number
603 /// is zero or negative.
604 #[stable(feature = "rust1", since = "1.0.0")]
606 pub fn is_positive(self) -> bool { self > 0 }
608 /// Returns `true` if `self` is negative and `false` if the number
609 /// is zero or positive.
610 #[stable(feature = "rust1", since = "1.0.0")]
612 pub fn is_negative(self) -> bool { self < 0 }
618 int_impl! { i8 = i8, u8, 8,
619 intrinsics::i8_add_with_overflow,
620 intrinsics::i8_sub_with_overflow,
621 intrinsics::i8_mul_with_overflow }
626 int_impl! { i16 = i16, u16, 16,
627 intrinsics::i16_add_with_overflow,
628 intrinsics::i16_sub_with_overflow,
629 intrinsics::i16_mul_with_overflow }
634 int_impl! { i32 = i32, u32, 32,
635 intrinsics::i32_add_with_overflow,
636 intrinsics::i32_sub_with_overflow,
637 intrinsics::i32_mul_with_overflow }
642 int_impl! { i64 = i64, u64, 64,
643 intrinsics::i64_add_with_overflow,
644 intrinsics::i64_sub_with_overflow,
645 intrinsics::i64_mul_with_overflow }
648 #[cfg(target_pointer_width = "32")]
651 int_impl! { isize = i32, u32, 32,
652 intrinsics::i32_add_with_overflow,
653 intrinsics::i32_sub_with_overflow,
654 intrinsics::i32_mul_with_overflow }
657 #[cfg(target_pointer_width = "64")]
660 int_impl! { isize = i64, u64, 64,
661 intrinsics::i64_add_with_overflow,
662 intrinsics::i64_sub_with_overflow,
663 intrinsics::i64_mul_with_overflow }
666 // `Int` + `UnsignedInt` implemented for signed integers
667 macro_rules! uint_impl {
668 ($T:ty = $ActualT:ty, $BITS:expr,
673 $add_with_overflow:path,
674 $sub_with_overflow:path,
675 $mul_with_overflow:path) => {
676 /// Returns the smallest value that can be represented by this integer type.
677 #[stable(feature = "rust1", since = "1.0.0")]
678 pub fn min_value() -> $T { 0 }
680 /// Returns the largest value that can be represented by this integer type.
681 #[stable(feature = "rust1", since = "1.0.0")]
682 pub fn max_value() -> $T { !0 }
684 /// Converts a string slice in a given base to an integer.
686 /// Leading and trailing whitespace represent an error.
690 /// * src - A string slice
691 /// * radix - The base to use. Must lie in the range [2 .. 36]
695 /// `Err(ParseIntError)` if the string did not represent a valid number.
696 /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
697 #[stable(feature = "rust1", since = "1.0.0")]
699 pub fn from_str_radix(src: &str, radix: u32) -> Result<$T, ParseIntError> {
700 from_str_radix(src, radix)
703 /// Returns the number of ones in the binary representation of `self`.
708 /// let n = 0b01001100u8;
710 /// assert_eq!(n.count_ones(), 3);
712 #[stable(feature = "rust1", since = "1.0.0")]
714 pub fn count_ones(self) -> u32 {
715 unsafe { $ctpop(self as $ActualT) as u32 }
718 /// Returns the number of zeros in the binary representation of `self`.
723 /// let n = 0b01001100u8;
725 /// assert_eq!(n.count_zeros(), 5);
727 #[stable(feature = "rust1", since = "1.0.0")]
729 pub fn count_zeros(self) -> u32 {
733 /// Returns the number of leading zeros in the binary representation
739 /// let n = 0b0101000u16;
741 /// assert_eq!(n.leading_zeros(), 10);
743 #[stable(feature = "rust1", since = "1.0.0")]
745 pub fn leading_zeros(self) -> u32 {
746 unsafe { $ctlz(self as $ActualT) as u32 }
749 /// Returns the number of trailing zeros in the binary representation
755 /// let n = 0b0101000u16;
757 /// assert_eq!(n.trailing_zeros(), 3);
759 #[stable(feature = "rust1", since = "1.0.0")]
761 pub fn trailing_zeros(self) -> u32 {
762 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
763 // emits two conditional moves on x86_64. By promoting the value to
764 // u16 and setting bit 8, we get better code without any conditional
766 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
767 // pending, remove this workaround once LLVM generates better code
771 intrinsics::cttz16(self as u16 | 0x100) as u32
773 $cttz(self as $ActualT) as u32
778 /// Shifts the bits to the left by a specified amount, `n`,
779 /// wrapping the truncated bits to the end of the resulting integer.
784 /// let n = 0x0123456789ABCDEFu64;
785 /// let m = 0x3456789ABCDEF012u64;
787 /// assert_eq!(n.rotate_left(12), m);
789 #[stable(feature = "rust1", since = "1.0.0")]
791 pub fn rotate_left(self, n: u32) -> $T {
792 // Protect against undefined behaviour for over-long bit shifts
794 (self << n) | (self >> (($BITS - n) % $BITS))
797 /// Shifts the bits to the right by a specified amount, `n`,
798 /// wrapping the truncated bits to the beginning of the resulting
804 /// let n = 0x0123456789ABCDEFu64;
805 /// let m = 0xDEF0123456789ABCu64;
807 /// assert_eq!(n.rotate_right(12), m);
809 #[stable(feature = "rust1", since = "1.0.0")]
811 pub fn rotate_right(self, n: u32) -> $T {
812 // Protect against undefined behaviour for over-long bit shifts
814 (self >> n) | (self << (($BITS - n) % $BITS))
817 /// Reverses the byte order of the integer.
822 /// let n = 0x0123456789ABCDEFu64;
823 /// let m = 0xEFCDAB8967452301u64;
825 /// assert_eq!(n.swap_bytes(), m);
827 #[stable(feature = "rust1", since = "1.0.0")]
829 pub fn swap_bytes(self) -> $T {
830 unsafe { $bswap(self as $ActualT) as $T }
833 /// Converts an integer from big endian to the target's endianness.
835 /// On big endian this is a no-op. On little endian the bytes are
841 /// let n = 0x0123456789ABCDEFu64;
843 /// if cfg!(target_endian = "big") {
844 /// assert_eq!(u64::from_be(n), n)
846 /// assert_eq!(u64::from_be(n), n.swap_bytes())
849 #[stable(feature = "rust1", since = "1.0.0")]
851 pub fn from_be(x: $T) -> $T {
852 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
855 /// Converts an integer from little endian to the target's endianness.
857 /// On little endian this is a no-op. On big endian the bytes are
863 /// let n = 0x0123456789ABCDEFu64;
865 /// if cfg!(target_endian = "little") {
866 /// assert_eq!(u64::from_le(n), n)
868 /// assert_eq!(u64::from_le(n), n.swap_bytes())
871 #[stable(feature = "rust1", since = "1.0.0")]
873 pub fn from_le(x: $T) -> $T {
874 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
877 /// Converts `self` to big endian from the target's endianness.
879 /// On big endian this is a no-op. On little endian the bytes are
885 /// let n = 0x0123456789ABCDEFu64;
887 /// if cfg!(target_endian = "big") {
888 /// assert_eq!(n.to_be(), n)
890 /// assert_eq!(n.to_be(), n.swap_bytes())
893 #[stable(feature = "rust1", since = "1.0.0")]
895 pub fn to_be(self) -> $T { // or not to be?
896 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
899 /// Converts `self` to little endian from the target's endianness.
901 /// On little endian this is a no-op. On big endian the bytes are
907 /// let n = 0x0123456789ABCDEFu64;
909 /// if cfg!(target_endian = "little") {
910 /// assert_eq!(n.to_le(), n)
912 /// assert_eq!(n.to_le(), n.swap_bytes())
915 #[stable(feature = "rust1", since = "1.0.0")]
917 pub fn to_le(self) -> $T {
918 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
921 /// Checked integer addition. Computes `self + other`, returning `None`
922 /// if overflow occurred.
927 /// assert_eq!(5u16.checked_add(65530), Some(65535));
928 /// assert_eq!(6u16.checked_add(65530), None);
930 #[stable(feature = "rust1", since = "1.0.0")]
932 pub fn checked_add(self, other: $T) -> Option<$T> {
933 checked_op!($T, $ActualT, $add_with_overflow, self, other)
936 /// Checked integer subtraction. Computes `self - other`, returning
937 /// `None` if underflow occurred.
942 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
943 /// assert_eq!((-128i8).checked_sub(1), None);
945 #[stable(feature = "rust1", since = "1.0.0")]
947 pub fn checked_sub(self, other: $T) -> Option<$T> {
948 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
951 /// Checked integer multiplication. Computes `self * other`, returning
952 /// `None` if underflow or overflow occurred.
957 /// assert_eq!(5u8.checked_mul(51), Some(255));
958 /// assert_eq!(5u8.checked_mul(52), None);
960 #[stable(feature = "rust1", since = "1.0.0")]
962 pub fn checked_mul(self, other: $T) -> Option<$T> {
963 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
966 /// Checked integer division. Computes `self / other`, returning `None`
967 /// if `other == 0` or the operation results in underflow or overflow.
972 /// assert_eq!((-127i8).checked_div(-1), Some(127));
973 /// assert_eq!((-128i8).checked_div(-1), None);
974 /// assert_eq!((1i8).checked_div(0), None);
976 #[stable(feature = "rust1", since = "1.0.0")]
978 pub fn checked_div(self, v: $T) -> Option<$T> {
985 /// Saturating integer addition. Computes `self + other`, saturating at
986 /// the numeric bounds instead of overflowing.
987 #[stable(feature = "rust1", since = "1.0.0")]
989 pub fn saturating_add(self, other: $T) -> $T {
990 match self.checked_add(other) {
992 None if other >= <$T as Zero>::zero() => <$T>::max_value(),
993 None => <$T>::min_value(),
997 /// Saturating integer subtraction. Computes `self - other`, saturating
998 /// at the numeric bounds instead of overflowing.
999 #[stable(feature = "rust1", since = "1.0.0")]
1001 pub fn saturating_sub(self, other: $T) -> $T {
1002 match self.checked_sub(other) {
1004 None if other >= <$T as Zero>::zero() => <$T>::min_value(),
1005 None => <$T>::max_value(),
1009 /// Wrapping (modular) addition. Computes `self + other`,
1010 /// wrapping around at the boundary of the type.
1011 #[stable(feature = "rust1", since = "1.0.0")]
1013 pub fn wrapping_add(self, rhs: $T) -> $T {
1015 intrinsics::overflowing_add(self, rhs)
1019 /// Wrapping (modular) subtraction. Computes `self - other`,
1020 /// wrapping around at the boundary of the type.
1021 #[stable(feature = "rust1", since = "1.0.0")]
1023 pub fn wrapping_sub(self, rhs: $T) -> $T {
1025 intrinsics::overflowing_sub(self, rhs)
1029 /// Wrapping (modular) multiplication. Computes `self *
1030 /// other`, wrapping around at the boundary of the type.
1031 #[stable(feature = "rust1", since = "1.0.0")]
1033 pub fn wrapping_mul(self, rhs: $T) -> $T {
1035 intrinsics::overflowing_mul(self, rhs)
1039 /// Wrapping (modular) division. Computes `floor(self / other)`,
1040 /// wrapping around at the boundary of the type.
1042 /// The only case where such wrapping can occur is when one
1043 /// divides `MIN / -1` on a signed type (where `MIN` is the
1044 /// negative minimal value for the type); this is equivalent
1045 /// to `-MIN`, a positive value that is too large to represent
1046 /// in the type. In such a case, this function returns `MIN`
1048 #[unstable(feature = "core", since = "1.0.0")]
1050 pub fn wrapping_div(self, rhs: $T) -> $T {
1051 self.overflowing_div(rhs).0
1054 /// Wrapping (modular) remainder. Computes `self % other`,
1055 /// wrapping around at the boundary of the type.
1057 /// Such wrap-around never actually occurs mathematically;
1058 /// implementation artifacts make `x % y` illegal for `MIN /
1059 /// -1` on a signed type illegal (where `MIN` is the negative
1060 /// minimal value). In such a case, this function returns `0`.
1061 #[unstable(feature = "core", since = "1.0.0")]
1063 pub fn wrapping_rem(self, rhs: $T) -> $T {
1064 self.overflowing_rem(rhs).0
1067 /// Wrapping (modular) negation. Computes `-self`,
1068 /// wrapping around at the boundary of the type.
1070 /// The only case where such wrapping can occur is when one
1071 /// negates `MIN` on a signed type (where `MIN` is the
1072 /// negative minimal value for the type); this is a positive
1073 /// value that is too large to represent in the type. In such
1074 /// a case, this function returns `MIN` itself.
1075 #[unstable(feature = "core", since = "1.0.0")]
1077 pub fn wrapping_neg(self) -> $T {
1078 self.overflowing_neg().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_shl(self, rhs: u32) -> $T {
1087 self.overflowing_shl(rhs).0
1090 /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
1091 /// where `mask` removes any high-order bits of `rhs` that
1092 /// would cause the shift to exceed the bitwidth of the type.
1093 #[unstable(feature = "core", since = "1.0.0")]
1095 pub fn wrapping_shr(self, rhs: u32) -> $T {
1096 self.overflowing_shr(rhs).0
1099 /// Raises self to the power of `exp`, using exponentiation by squaring.
1104 /// assert_eq!(2i32.pow(4), 16);
1106 #[stable(feature = "rust1", since = "1.0.0")]
1108 pub fn pow(self, mut exp: u32) -> $T {
1109 let mut base = self;
1110 let mut acc = <$T as One>::one();
1112 let mut prev_base = self;
1113 let mut base_oflo = false;
1117 // ensure overflow occurs in the same manner it
1118 // would have otherwise (i.e. signal any exception
1119 // it would have otherwise).
1120 acc = acc * (prev_base * prev_base);
1126 let (new_base, new_base_oflo) = base.overflowing_mul(base);
1128 base_oflo = new_base_oflo;
1134 /// Returns `true` iff `self == 2^k` for some `k`.
1135 #[stable(feature = "rust1", since = "1.0.0")]
1137 pub fn is_power_of_two(self) -> bool {
1138 (self.wrapping_sub(<$T as One>::one())) & self == <$T as Zero>::zero() &&
1139 !(self == <$T as Zero>::zero())
1142 /// Returns the smallest power of two greater than or equal to `self`.
1143 /// Unspecified behavior on overflow.
1144 #[stable(feature = "rust1", since = "1.0.0")]
1146 pub fn next_power_of_two(self) -> $T {
1147 let bits = size_of::<$T>() * 8;
1148 let one: $T = <$T as One>::one();
1149 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
1152 /// Returns the smallest power of two greater than or equal to `n`. If
1153 /// the next power of two is greater than the type's maximum value,
1154 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 pub fn checked_next_power_of_two(self) -> Option<$T> {
1157 let npot = self.next_power_of_two();
1169 uint_impl! { u8 = u8, 8,
1174 intrinsics::u8_add_with_overflow,
1175 intrinsics::u8_sub_with_overflow,
1176 intrinsics::u8_mul_with_overflow }
1181 uint_impl! { u16 = u16, 16,
1182 intrinsics::ctpop16,
1185 intrinsics::bswap16,
1186 intrinsics::u16_add_with_overflow,
1187 intrinsics::u16_sub_with_overflow,
1188 intrinsics::u16_mul_with_overflow }
1193 uint_impl! { u32 = u32, 32,
1194 intrinsics::ctpop32,
1197 intrinsics::bswap32,
1198 intrinsics::u32_add_with_overflow,
1199 intrinsics::u32_sub_with_overflow,
1200 intrinsics::u32_mul_with_overflow }
1206 uint_impl! { u64 = u64, 64,
1207 intrinsics::ctpop64,
1210 intrinsics::bswap64,
1211 intrinsics::u64_add_with_overflow,
1212 intrinsics::u64_sub_with_overflow,
1213 intrinsics::u64_mul_with_overflow }
1216 #[cfg(target_pointer_width = "32")]
1219 uint_impl! { usize = u32, 32,
1220 intrinsics::ctpop32,
1223 intrinsics::bswap32,
1224 intrinsics::u32_add_with_overflow,
1225 intrinsics::u32_sub_with_overflow,
1226 intrinsics::u32_mul_with_overflow }
1229 #[cfg(target_pointer_width = "64")]
1232 uint_impl! { usize = u64, 64,
1233 intrinsics::ctpop64,
1236 intrinsics::bswap64,
1237 intrinsics::u64_add_with_overflow,
1238 intrinsics::u64_sub_with_overflow,
1239 intrinsics::u64_mul_with_overflow }
1242 /// Used for representing the classification of floating point numbers
1243 #[derive(Copy, Clone, PartialEq, Debug)]
1244 #[stable(feature = "rust1", since = "1.0.0")]
1245 pub enum FpCategory {
1246 /// "Not a Number", often obtained by dividing by zero
1247 #[stable(feature = "rust1", since = "1.0.0")]
1250 /// Positive or negative infinity
1251 #[stable(feature = "rust1", since = "1.0.0")]
1254 /// Positive or negative zero
1255 #[stable(feature = "rust1", since = "1.0.0")]
1258 /// De-normalized floating point representation (less precise than `Normal`)
1259 #[stable(feature = "rust1", since = "1.0.0")]
1262 /// A regular floating point number
1263 #[stable(feature = "rust1", since = "1.0.0")]
1267 /// A built-in floating point number.
1270 /// Returns the NaN value.
1272 /// Returns the infinite value.
1273 fn infinity() -> Self;
1274 /// Returns the negative infinite value.
1275 fn neg_infinity() -> Self;
1277 fn neg_zero() -> Self;
1282 /// Parses the string `s` with the radix `r` as a float.
1283 fn from_str_radix(s: &str, r: u32) -> Result<Self, ParseFloatError>;
1285 /// Returns true if this value is NaN and false otherwise.
1286 fn is_nan(self) -> bool;
1287 /// Returns true if this value is positive infinity or negative infinity and
1288 /// false otherwise.
1289 fn is_infinite(self) -> bool;
1290 /// Returns true if this number is neither infinite nor NaN.
1291 fn is_finite(self) -> bool;
1292 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1293 fn is_normal(self) -> bool;
1294 /// Returns the category that this number falls into.
1295 fn classify(self) -> FpCategory;
1297 /// Returns the mantissa, exponent and sign as integers, respectively.
1298 fn integer_decode(self) -> (u64, i16, i8);
1300 /// Return the largest integer less than or equal to a number.
1301 fn floor(self) -> Self;
1302 /// Return the smallest integer greater than or equal to a number.
1303 fn ceil(self) -> Self;
1304 /// Return the nearest integer to a number. Round half-way cases away from
1306 fn round(self) -> Self;
1307 /// Return the integer part of a number.
1308 fn trunc(self) -> Self;
1309 /// Return the fractional part of a number.
1310 fn fract(self) -> Self;
1312 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1313 /// number is `Float::nan()`.
1314 fn abs(self) -> Self;
1315 /// Returns a number that represents the sign of `self`.
1317 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1318 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1319 /// - `Float::nan()` if the number is `Float::nan()`
1320 fn signum(self) -> Self;
1321 /// Returns `true` if `self` is positive, including `+0.0` and
1322 /// `Float::infinity()`.
1323 fn is_positive(self) -> bool;
1324 /// Returns `true` if `self` is negative, including `-0.0` and
1325 /// `Float::neg_infinity()`.
1326 fn is_negative(self) -> bool;
1328 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1329 /// error. This produces a more accurate result with better performance than
1330 /// a separate multiplication operation followed by an add.
1331 fn mul_add(self, a: Self, b: Self) -> Self;
1332 /// Take the reciprocal (inverse) of a number, `1/x`.
1333 fn recip(self) -> Self;
1335 /// Raise a number to an integer power.
1337 /// Using this function is generally faster than using `powf`
1338 fn powi(self, n: i32) -> Self;
1339 /// Raise a number to a floating point power.
1340 fn powf(self, n: Self) -> Self;
1342 /// Take the square root of a number.
1344 /// Returns NaN if `self` is a negative number.
1345 fn sqrt(self) -> Self;
1346 /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1347 fn rsqrt(self) -> Self;
1349 /// Returns `e^(self)`, (the exponential function).
1350 fn exp(self) -> Self;
1351 /// Returns 2 raised to the power of the number, `2^(self)`.
1352 fn exp2(self) -> Self;
1353 /// Returns the natural logarithm of the number.
1354 fn ln(self) -> Self;
1355 /// Returns the logarithm of the number with respect to an arbitrary base.
1356 fn log(self, base: Self) -> Self;
1357 /// Returns the base 2 logarithm of the number.
1358 fn log2(self) -> Self;
1359 /// Returns the base 10 logarithm of the number.
1360 fn log10(self) -> Self;
1362 /// Convert radians to degrees.
1363 fn to_degrees(self) -> Self;
1364 /// Convert degrees to radians.
1365 fn to_radians(self) -> Self;
1368 macro_rules! from_str_float_impl {
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl FromStr for $T {
1372 type Err = ParseFloatError;
1374 /// Converts a string in base 10 to a float.
1375 /// Accepts an optional decimal exponent.
1377 /// This function accepts strings such as
1380 /// * '+3.14', equivalent to '3.14'
1382 /// * '2.5E10', or equivalently, '2.5e10'
1384 /// * '.' (understood as 0)
1386 /// * '.5', or, equivalently, '0.5'
1387 /// * '+inf', 'inf', '-inf', 'NaN'
1389 /// Leading and trailing whitespace represent an error.
1393 /// * src - A string
1397 /// `Err(ParseFloatError)` if the string did not represent a valid
1398 /// number. Otherwise, `Ok(n)` where `n` is the floating-point
1399 /// number represented by `src`.
1401 #[allow(deprecated)]
1402 fn from_str(src: &str) -> Result<$T, ParseFloatError> {
1403 $T::from_str_radix(src, 10)
1408 from_str_float_impl!(f32);
1409 from_str_float_impl!(f64);
1411 macro_rules! from_str_radix_int_impl {
1412 ($($T:ident)*) => {$(
1413 #[stable(feature = "rust1", since = "1.0.0")]
1414 #[allow(deprecated)]
1415 impl FromStr for $T {
1416 type Err = ParseIntError;
1417 fn from_str(src: &str) -> Result<$T, ParseIntError> {
1418 from_str_radix(src, 10)
1423 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
1426 trait FromStrRadixHelper: PartialOrd + Copy {
1427 fn min_value() -> Self;
1428 fn from_u32(u: u32) -> Self;
1429 fn checked_mul(&self, other: u32) -> Option<Self>;
1430 fn checked_sub(&self, other: u32) -> Option<Self>;
1431 fn checked_add(&self, other: u32) -> Option<Self>;
1435 ($($t:ident)*) => ($(impl FromStrRadixHelper for $t {
1436 fn min_value() -> Self { <$t>::min_value() }
1437 fn from_u32(u: u32) -> Self { u as $t }
1438 fn checked_mul(&self, other: u32) -> Option<Self> {
1439 <$t>::checked_mul(*self, other as $t)
1441 fn checked_sub(&self, other: u32) -> Option<Self> {
1442 <$t>::checked_sub(*self, other as $t)
1444 fn checked_add(&self, other: u32) -> Option<Self> {
1445 <$t>::checked_add(*self, other as $t)
1449 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1451 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
1452 -> Result<T, ParseIntError> {
1453 use self::IntErrorKind::*;
1454 use self::ParseIntError as PIE;
1455 assert!(radix >= 2 && radix <= 36,
1456 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1459 let is_signed_ty = T::from_u32(0) > T::min_value();
1461 match src.slice_shift_char() {
1462 Some(('-', "")) => Err(PIE { kind: Empty }),
1463 Some(('-', src)) if is_signed_ty => {
1464 // The number is negative
1465 let mut result = T::from_u32(0);
1466 for c in src.chars() {
1467 let x = match c.to_digit(radix) {
1469 None => return Err(PIE { kind: InvalidDigit }),
1471 result = match result.checked_mul(radix) {
1472 Some(result) => result,
1473 None => return Err(PIE { kind: Underflow }),
1475 result = match result.checked_sub(x) {
1476 Some(result) => result,
1477 None => return Err(PIE { kind: Underflow }),
1483 // The number is signed
1484 let mut result = T::from_u32(0);
1485 for c in src.chars() {
1486 let x = match c.to_digit(radix) {
1488 None => return Err(PIE { kind: InvalidDigit }),
1490 result = match result.checked_mul(radix) {
1491 Some(result) => result,
1492 None => return Err(PIE { kind: Overflow }),
1494 result = match result.checked_add(x) {
1495 Some(result) => result,
1496 None => return Err(PIE { kind: Overflow }),
1501 None => Err(ParseIntError { kind: Empty }),
1505 /// An error which can be returned when parsing an integer.
1506 #[derive(Debug, Clone, PartialEq)]
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 pub struct ParseIntError { kind: IntErrorKind }
1510 #[derive(Debug, Clone, PartialEq)]
1518 impl ParseIntError {
1519 #[unstable(feature = "core", reason = "available through Error trait")]
1520 pub fn description(&self) -> &str {
1522 IntErrorKind::Empty => "cannot parse integer from empty string",
1523 IntErrorKind::InvalidDigit => "invalid digit found in string",
1524 IntErrorKind::Overflow => "number too large to fit in target type",
1525 IntErrorKind::Underflow => "number too small to fit in target type",
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 impl fmt::Display for ParseIntError {
1532 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1533 self.description().fmt(f)
1537 /// An error which can be returned when parsing a float.
1538 #[derive(Debug, Clone, PartialEq)]
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 pub struct ParseFloatError {
1542 pub __kind: FloatErrorKind
1545 #[derive(Debug, Clone, PartialEq)]
1546 pub enum FloatErrorKind {
1551 impl ParseFloatError {
1553 pub fn __description(&self) -> &str {
1555 FloatErrorKind::Empty => "cannot parse float from empty string",
1556 FloatErrorKind::Invalid => "invalid float literal",
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl fmt::Display for ParseFloatError {
1563 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1564 self.__description().fmt(f)