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};
23 use marker::{Copy, Sized};
25 use option::Option::{self, Some, None};
26 use result::Result::{self, Ok, Err};
27 use str::{FromStr, StrExt};
30 /// Provides intentionally-wrapped arithmetic on `T`.
32 /// Operations like `+` on `u32` values is intended to never overflow,
33 /// and in some debug configurations overflow is detected and results
34 /// in a panic. While most arithmetic falls into this category, some
35 /// code explicitly expects and relies upon modular arithmetic (e.g.,
38 /// Wrapping arithmetic can be achieved either through methods like
39 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
40 /// all standard arithmetic operations on the underlying value are
41 /// intended to have wrapping semantics.
42 #[stable(feature = "rust1", since = "1.0.0")]
43 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default)]
44 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
48 // All these modules are technically private and only exposed for libcoretest:
54 /// Types that have a "zero" value.
56 /// This trait is intended for use in conjunction with `Add`, as an identity:
57 /// `x + T::zero() == x`.
58 #[unstable(feature = "zero_one",
59 reason = "unsure of placement, wants to use associated constants",
61 pub trait Zero: Sized {
62 /// The "zero" (usually, additive identity) for this type.
66 /// Types that have a "one" value.
68 /// This trait is intended for use in conjunction with `Mul`, as an identity:
69 /// `x * T::one() == x`.
70 #[unstable(feature = "zero_one",
71 reason = "unsure of placement, wants to use associated constants",
73 pub trait One: Sized {
74 /// The "one" (usually, multiplicative identity) for this type.
78 macro_rules! zero_one_impl {
82 fn zero() -> Self { 0 }
86 fn one() -> Self { 1 }
90 zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
92 macro_rules! zero_one_impl_float {
96 fn zero() -> Self { 0.0 }
100 fn one() -> Self { 1.0 }
104 zero_one_impl_float! { f32 f64 }
106 // Just for stage0; a byte swap on a byte is a no-op
107 // Delete this once it becomes unused
109 unsafe fn bswap8(x: u8) -> u8 { x }
111 macro_rules! checked_op {
112 ($U:ty, $op:path, $x:expr, $y:expr) => {{
113 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
114 if overflowed { None } else { Some(result as Self) }
118 // `Int` + `SignedInt` implemented for signed integers
119 macro_rules! int_impl {
120 ($ActualT:ty, $UnsignedT:ty, $BITS:expr,
121 $add_with_overflow:path,
122 $sub_with_overflow:path,
123 $mul_with_overflow:path) => {
124 /// Returns the smallest value that can be represented by this integer type.
125 #[stable(feature = "rust1", since = "1.0.0")]
127 pub fn min_value() -> Self {
128 (-1 as Self) << ($BITS - 1)
131 /// Returns the largest value that can be represented by this integer type.
132 #[stable(feature = "rust1", since = "1.0.0")]
134 pub fn max_value() -> Self {
135 let min = Self::min_value(); !min
138 /// Converts a string slice in a given base to an integer.
140 /// Leading and trailing whitespace represent an error.
145 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
149 from_str_radix(src, radix)
152 /// Returns the number of ones in the binary representation of `self`.
157 /// let n = 0b01001100u8;
159 /// assert_eq!(n.count_ones(), 3);
161 #[stable(feature = "rust1", since = "1.0.0")]
163 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
165 /// Returns the number of zeros in the binary representation of `self`.
170 /// let n = 0b01001100u8;
172 /// assert_eq!(n.count_zeros(), 5);
174 #[stable(feature = "rust1", since = "1.0.0")]
176 pub fn count_zeros(self) -> u32 {
180 /// Returns the number of leading zeros in the binary representation
186 /// let n = 0b0101000u16;
188 /// assert_eq!(n.leading_zeros(), 10);
190 #[stable(feature = "rust1", since = "1.0.0")]
192 pub fn leading_zeros(self) -> u32 {
193 (self as $UnsignedT).leading_zeros()
196 /// Returns the number of trailing zeros in the binary representation
202 /// let n = 0b0101000u16;
204 /// assert_eq!(n.trailing_zeros(), 3);
206 #[stable(feature = "rust1", since = "1.0.0")]
208 pub fn trailing_zeros(self) -> u32 {
209 (self as $UnsignedT).trailing_zeros()
212 /// Shifts the bits to the left by a specified amount, `n`,
213 /// wrapping the truncated bits to the end of the resulting integer.
218 /// let n = 0x0123456789ABCDEFu64;
219 /// let m = 0x3456789ABCDEF012u64;
221 /// assert_eq!(n.rotate_left(12), m);
223 #[stable(feature = "rust1", since = "1.0.0")]
225 pub fn rotate_left(self, n: u32) -> Self {
226 (self as $UnsignedT).rotate_left(n) as Self
229 /// Shifts the bits to the right by a specified amount, `n`,
230 /// wrapping the truncated bits to the beginning of the resulting
236 /// let n = 0x0123456789ABCDEFu64;
237 /// let m = 0xDEF0123456789ABCu64;
239 /// assert_eq!(n.rotate_right(12), m);
241 #[stable(feature = "rust1", since = "1.0.0")]
243 pub fn rotate_right(self, n: u32) -> Self {
244 (self as $UnsignedT).rotate_right(n) as Self
247 /// Reverses the byte order of the integer.
252 /// let n = 0x0123456789ABCDEFu64;
253 /// let m = 0xEFCDAB8967452301u64;
255 /// assert_eq!(n.swap_bytes(), m);
257 #[stable(feature = "rust1", since = "1.0.0")]
259 pub fn swap_bytes(self) -> Self {
260 (self as $UnsignedT).swap_bytes() as Self
263 /// Converts an integer from big endian to the target's endianness.
265 /// On big endian this is a no-op. On little endian the bytes are
271 /// let n = 0x0123456789ABCDEFu64;
273 /// if cfg!(target_endian = "big") {
274 /// assert_eq!(u64::from_be(n), n)
276 /// assert_eq!(u64::from_be(n), n.swap_bytes())
279 #[stable(feature = "rust1", since = "1.0.0")]
281 pub fn from_be(x: Self) -> Self {
282 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
285 /// Converts an integer from little endian to the target's endianness.
287 /// On little endian this is a no-op. On big endian the bytes are
293 /// let n = 0x0123456789ABCDEFu64;
295 /// if cfg!(target_endian = "little") {
296 /// assert_eq!(u64::from_le(n), n)
298 /// assert_eq!(u64::from_le(n), n.swap_bytes())
301 #[stable(feature = "rust1", since = "1.0.0")]
303 pub fn from_le(x: Self) -> Self {
304 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
307 /// Converts `self` to big endian from the target's endianness.
309 /// On big endian this is a no-op. On little endian the bytes are
315 /// let n = 0x0123456789ABCDEFu64;
317 /// if cfg!(target_endian = "big") {
318 /// assert_eq!(n.to_be(), n)
320 /// assert_eq!(n.to_be(), n.swap_bytes())
323 #[stable(feature = "rust1", since = "1.0.0")]
325 pub fn to_be(self) -> Self { // or not to be?
326 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
329 /// Converts `self` to little endian from the target's endianness.
331 /// On little endian this is a no-op. On big endian the bytes are
337 /// let n = 0x0123456789ABCDEFu64;
339 /// if cfg!(target_endian = "little") {
340 /// assert_eq!(n.to_le(), n)
342 /// assert_eq!(n.to_le(), n.swap_bytes())
345 #[stable(feature = "rust1", since = "1.0.0")]
347 pub fn to_le(self) -> Self {
348 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
351 /// Checked integer addition. Computes `self + other`, returning `None`
352 /// if overflow occurred.
357 /// assert_eq!(5u16.checked_add(65530), Some(65535));
358 /// assert_eq!(6u16.checked_add(65530), None);
360 #[stable(feature = "rust1", since = "1.0.0")]
362 pub fn checked_add(self, other: Self) -> Option<Self> {
363 checked_op!($ActualT, $add_with_overflow, self, other)
366 /// Checked integer subtraction. Computes `self - other`, returning
367 /// `None` if underflow occurred.
372 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
373 /// assert_eq!((-128i8).checked_sub(1), None);
375 #[stable(feature = "rust1", since = "1.0.0")]
377 pub fn checked_sub(self, other: Self) -> Option<Self> {
378 checked_op!($ActualT, $sub_with_overflow, self, other)
381 /// Checked integer multiplication. Computes `self * other`, returning
382 /// `None` if underflow or overflow occurred.
387 /// assert_eq!(5u8.checked_mul(51), Some(255));
388 /// assert_eq!(5u8.checked_mul(52), None);
390 #[stable(feature = "rust1", since = "1.0.0")]
392 pub fn checked_mul(self, other: Self) -> Option<Self> {
393 checked_op!($ActualT, $mul_with_overflow, self, other)
396 /// Checked integer division. Computes `self / other`, returning `None`
397 /// if `other == 0` or the operation results in underflow or overflow.
402 /// assert_eq!((-127i8).checked_div(-1), Some(127));
403 /// assert_eq!((-128i8).checked_div(-1), None);
404 /// assert_eq!((1i8).checked_div(0), None);
406 #[stable(feature = "rust1", since = "1.0.0")]
408 pub fn checked_div(self, other: Self) -> Option<Self> {
411 -1 if self == Self::min_value()
413 other => Some(self / other),
417 /// Saturating integer addition. Computes `self + other`, saturating at
418 /// the numeric bounds instead of overflowing.
419 #[stable(feature = "rust1", since = "1.0.0")]
421 pub fn saturating_add(self, other: Self) -> Self {
422 match self.checked_add(other) {
424 None if other >= Self::zero() => Self::max_value(),
425 None => Self::min_value(),
429 /// Saturating integer subtraction. Computes `self - other`, saturating
430 /// at the numeric bounds instead of overflowing.
431 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn saturating_sub(self, other: Self) -> Self {
434 match self.checked_sub(other) {
436 None if other >= Self::zero() => Self::min_value(),
437 None => Self::max_value(),
441 /// Wrapping (modular) addition. Computes `self + other`,
442 /// wrapping around at the boundary of the type.
443 #[stable(feature = "rust1", since = "1.0.0")]
445 pub fn wrapping_add(self, rhs: Self) -> Self {
447 intrinsics::overflowing_add(self, rhs)
451 /// Wrapping (modular) subtraction. Computes `self - other`,
452 /// wrapping around at the boundary of the type.
453 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn wrapping_sub(self, rhs: Self) -> Self {
457 intrinsics::overflowing_sub(self, rhs)
461 /// Wrapping (modular) multiplication. Computes `self *
462 /// other`, wrapping around at the boundary of the type.
463 #[stable(feature = "rust1", since = "1.0.0")]
465 pub fn wrapping_mul(self, rhs: Self) -> Self {
467 intrinsics::overflowing_mul(self, rhs)
471 /// Wrapping (modular) division. Computes `self / other`,
472 /// wrapping around at the boundary of the type.
474 /// The only case where such wrapping can occur is when one
475 /// divides `MIN / -1` on a signed type (where `MIN` is the
476 /// negative minimal value for the type); this is equivalent
477 /// to `-MIN`, a positive value that is too large to represent
478 /// in the type. In such a case, this function returns `MIN`
480 #[stable(feature = "num_wrapping", since = "1.2.0")]
482 pub fn wrapping_div(self, rhs: Self) -> Self {
483 self.overflowing_div(rhs).0
486 /// Wrapping (modular) remainder. Computes `self % other`,
487 /// wrapping around at the boundary of the type.
489 /// Such wrap-around never actually occurs mathematically;
490 /// implementation artifacts make `x % y` invalid for `MIN /
491 /// -1` on a signed type (where `MIN` is the negative
492 /// minimal value). In such a case, this function returns `0`.
493 #[stable(feature = "num_wrapping", since = "1.2.0")]
495 pub fn wrapping_rem(self, rhs: Self) -> Self {
496 self.overflowing_rem(rhs).0
499 /// Wrapping (modular) negation. Computes `-self`,
500 /// wrapping around at the boundary of the type.
502 /// The only case where such wrapping can occur is when one
503 /// negates `MIN` on a signed type (where `MIN` is the
504 /// negative minimal value for the type); this is a positive
505 /// value that is too large to represent in the type. In such
506 /// a case, this function returns `MIN` itself.
507 #[stable(feature = "num_wrapping", since = "1.2.0")]
509 pub fn wrapping_neg(self) -> Self {
510 self.overflowing_neg().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 #[stable(feature = "num_wrapping", since = "1.2.0")]
518 pub fn wrapping_shl(self, rhs: u32) -> Self {
519 self.overflowing_shl(rhs).0
522 /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
523 /// where `mask` removes any high-order bits of `rhs` that
524 /// would cause the shift to exceed the bitwidth of the type.
525 #[stable(feature = "num_wrapping", since = "1.2.0")]
527 pub fn wrapping_shr(self, rhs: u32) -> Self {
528 self.overflowing_shr(rhs).0
531 /// Raises self to the power of `exp`, using exponentiation by squaring.
536 /// let x: i32 = 2; // or any other integer type
538 /// assert_eq!(x.pow(4), 16);
540 #[stable(feature = "rust1", since = "1.0.0")]
542 pub fn pow(self, mut exp: u32) -> Self {
544 let mut acc = Self::one();
554 // Deal with the final bit of the exponent separately, since
555 // squaring the base afterwards is not necessary and may cause a
556 // needless overflow.
564 /// Computes the absolute value of `self`.
566 /// # Overflow behavior
568 /// The absolute value of `i32::min_value()` cannot be represented as an
569 /// `i32`, and attempting to calculate it will cause an overflow. This
570 /// means that code in debug mode will trigger a panic on this case and
571 /// optimized code will return `i32::min_value()` without a panic.
572 #[stable(feature = "rust1", since = "1.0.0")]
574 pub fn abs(self) -> Self {
575 if self.is_negative() {
576 // Note that the #[inline] above means that the overflow
577 // semantics of this negation depend on the crate we're being
585 /// Returns a number representing sign of `self`.
587 /// - `0` if the number is zero
588 /// - `1` if the number is positive
589 /// - `-1` if the number is negative
590 #[stable(feature = "rust1", since = "1.0.0")]
592 pub fn signum(self) -> Self {
600 /// Returns `true` if `self` is positive and `false` if the number
601 /// is zero or negative.
602 #[stable(feature = "rust1", since = "1.0.0")]
604 pub fn is_positive(self) -> bool { self > 0 }
606 /// Returns `true` if `self` is negative and `false` if the number
607 /// is zero or positive.
608 #[stable(feature = "rust1", since = "1.0.0")]
610 pub fn is_negative(self) -> bool { self < 0 }
617 int_impl! { i8, u8, 8,
618 intrinsics::i8_add_with_overflow,
619 intrinsics::i8_sub_with_overflow,
620 intrinsics::i8_mul_with_overflow }
625 int_impl! { i8, u8, 8,
626 intrinsics::add_with_overflow,
627 intrinsics::sub_with_overflow,
628 intrinsics::mul_with_overflow }
634 int_impl! { i16, u16, 16,
635 intrinsics::i16_add_with_overflow,
636 intrinsics::i16_sub_with_overflow,
637 intrinsics::i16_mul_with_overflow }
642 int_impl! { i16, u16, 16,
643 intrinsics::add_with_overflow,
644 intrinsics::sub_with_overflow,
645 intrinsics::mul_with_overflow }
651 int_impl! { i32, u32, 32,
652 intrinsics::i32_add_with_overflow,
653 intrinsics::i32_sub_with_overflow,
654 intrinsics::i32_mul_with_overflow }
659 int_impl! { i32, u32, 32,
660 intrinsics::add_with_overflow,
661 intrinsics::sub_with_overflow,
662 intrinsics::mul_with_overflow }
668 int_impl! { i64, u64, 64,
669 intrinsics::i64_add_with_overflow,
670 intrinsics::i64_sub_with_overflow,
671 intrinsics::i64_mul_with_overflow }
676 int_impl! { i64, u64, 64,
677 intrinsics::add_with_overflow,
678 intrinsics::sub_with_overflow,
679 intrinsics::mul_with_overflow }
682 #[cfg(target_pointer_width = "32")]
686 int_impl! { i32, u32, 32,
687 intrinsics::i32_add_with_overflow,
688 intrinsics::i32_sub_with_overflow,
689 intrinsics::i32_mul_with_overflow }
691 #[cfg(target_pointer_width = "32")]
695 int_impl! { i32, u32, 32,
696 intrinsics::add_with_overflow,
697 intrinsics::sub_with_overflow,
698 intrinsics::mul_with_overflow }
701 #[cfg(target_pointer_width = "64")]
705 int_impl! { i64, u64, 64,
706 intrinsics::i64_add_with_overflow,
707 intrinsics::i64_sub_with_overflow,
708 intrinsics::i64_mul_with_overflow }
710 #[cfg(target_pointer_width = "64")]
714 int_impl! { i64, u64, 64,
715 intrinsics::add_with_overflow,
716 intrinsics::sub_with_overflow,
717 intrinsics::mul_with_overflow }
720 // `Int` + `UnsignedInt` implemented for signed integers
721 macro_rules! uint_impl {
722 ($ActualT:ty, $BITS:expr,
727 $add_with_overflow:path,
728 $sub_with_overflow:path,
729 $mul_with_overflow:path) => {
730 /// Returns the smallest value that can be represented by this integer type.
731 #[stable(feature = "rust1", since = "1.0.0")]
733 pub fn min_value() -> Self { 0 }
735 /// Returns the largest value that can be represented by this integer type.
736 #[stable(feature = "rust1", since = "1.0.0")]
738 pub fn max_value() -> Self { !0 }
740 /// Converts a string slice in a given base to an integer.
742 /// Leading and trailing whitespace represent an error.
746 /// * src - A string slice
747 /// * radix - The base to use. Must lie in the range [2 .. 36]
751 /// `Err(ParseIntError)` if the string did not represent a valid number.
752 /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
753 #[stable(feature = "rust1", since = "1.0.0")]
754 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
755 from_str_radix(src, radix)
758 /// Returns the number of ones in the binary representation of `self`.
763 /// let n = 0b01001100u8;
765 /// assert_eq!(n.count_ones(), 3);
767 #[stable(feature = "rust1", since = "1.0.0")]
769 pub fn count_ones(self) -> u32 {
770 unsafe { $ctpop(self as $ActualT) as u32 }
773 /// Returns the number of zeros in the binary representation of `self`.
778 /// let n = 0b01001100u8;
780 /// assert_eq!(n.count_zeros(), 5);
782 #[stable(feature = "rust1", since = "1.0.0")]
784 pub fn count_zeros(self) -> u32 {
788 /// Returns the number of leading zeros in the binary representation
794 /// let n = 0b0101000u16;
796 /// assert_eq!(n.leading_zeros(), 10);
798 #[stable(feature = "rust1", since = "1.0.0")]
800 pub fn leading_zeros(self) -> u32 {
801 unsafe { $ctlz(self as $ActualT) as u32 }
804 #[stable(feature = "rust1", since = "1.0.0")]
807 pub fn trailing_zeros(self) -> u32 {
808 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
809 // emits two conditional moves on x86_64. By promoting the value to
810 // u16 and setting bit 8, we get better code without any conditional
812 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
813 // pending, remove this workaround once LLVM generates better code
817 intrinsics::cttz16(self as u16 | 0x100) as u32
819 $cttz(self as $ActualT) as u32
823 /// Returns the number of trailing zeros in the binary representation
829 /// let n = 0b0101000u16;
831 /// assert_eq!(n.trailing_zeros(), 3);
833 #[stable(feature = "rust1", since = "1.0.0")]
836 pub fn trailing_zeros(self) -> u32 {
837 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
838 // emits two conditional moves on x86_64. By promoting the value to
839 // u16 and setting bit 8, we get better code without any conditional
841 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
842 // pending, remove this workaround once LLVM generates better code
846 intrinsics::cttz(self as u16 | 0x100) as u32
848 intrinsics::cttz(self) as u32
853 /// Shifts the bits to the left by a specified amount, `n`,
854 /// wrapping the truncated bits to the end of the resulting integer.
859 /// let n = 0x0123456789ABCDEFu64;
860 /// let m = 0x3456789ABCDEF012u64;
862 /// assert_eq!(n.rotate_left(12), m);
864 #[stable(feature = "rust1", since = "1.0.0")]
866 pub fn rotate_left(self, n: u32) -> Self {
867 // Protect against undefined behaviour for over-long bit shifts
869 (self << n) | (self >> (($BITS - n) % $BITS))
872 /// Shifts the bits to the right by a specified amount, `n`,
873 /// wrapping the truncated bits to the beginning of the resulting
879 /// let n = 0x0123456789ABCDEFu64;
880 /// let m = 0xDEF0123456789ABCu64;
882 /// assert_eq!(n.rotate_right(12), m);
884 #[stable(feature = "rust1", since = "1.0.0")]
886 pub fn rotate_right(self, n: u32) -> Self {
887 // Protect against undefined behaviour for over-long bit shifts
889 (self >> n) | (self << (($BITS - n) % $BITS))
892 /// Reverses the byte order of the integer.
897 /// let n = 0x0123456789ABCDEFu64;
898 /// let m = 0xEFCDAB8967452301u64;
900 /// assert_eq!(n.swap_bytes(), m);
902 #[stable(feature = "rust1", since = "1.0.0")]
904 pub fn swap_bytes(self) -> Self {
905 unsafe { $bswap(self as $ActualT) as Self }
908 /// Converts an integer from big endian to the target's endianness.
910 /// On big endian this is a no-op. On little endian the bytes are
916 /// let n = 0x0123456789ABCDEFu64;
918 /// if cfg!(target_endian = "big") {
919 /// assert_eq!(u64::from_be(n), n)
921 /// assert_eq!(u64::from_be(n), n.swap_bytes())
924 #[stable(feature = "rust1", since = "1.0.0")]
926 pub fn from_be(x: Self) -> Self {
927 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
930 /// Converts an integer from little endian to the target's endianness.
932 /// On little endian this is a no-op. On big endian the bytes are
938 /// let n = 0x0123456789ABCDEFu64;
940 /// if cfg!(target_endian = "little") {
941 /// assert_eq!(u64::from_le(n), n)
943 /// assert_eq!(u64::from_le(n), n.swap_bytes())
946 #[stable(feature = "rust1", since = "1.0.0")]
948 pub fn from_le(x: Self) -> Self {
949 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
952 /// Converts `self` to big endian from the target's endianness.
954 /// On big endian this is a no-op. On little endian the bytes are
960 /// let n = 0x0123456789ABCDEFu64;
962 /// if cfg!(target_endian = "big") {
963 /// assert_eq!(n.to_be(), n)
965 /// assert_eq!(n.to_be(), n.swap_bytes())
968 #[stable(feature = "rust1", since = "1.0.0")]
970 pub fn to_be(self) -> Self { // or not to be?
971 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
974 /// Converts `self` to little endian from the target's endianness.
976 /// On little endian this is a no-op. On big endian the bytes are
982 /// let n = 0x0123456789ABCDEFu64;
984 /// if cfg!(target_endian = "little") {
985 /// assert_eq!(n.to_le(), n)
987 /// assert_eq!(n.to_le(), n.swap_bytes())
990 #[stable(feature = "rust1", since = "1.0.0")]
992 pub fn to_le(self) -> Self {
993 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
996 /// Checked integer addition. Computes `self + other`, returning `None`
997 /// if overflow occurred.
1002 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1003 /// assert_eq!(6u16.checked_add(65530), None);
1005 #[stable(feature = "rust1", since = "1.0.0")]
1007 pub fn checked_add(self, other: Self) -> Option<Self> {
1008 checked_op!($ActualT, $add_with_overflow, self, other)
1011 /// Checked integer subtraction. Computes `self - other`, returning
1012 /// `None` if underflow occurred.
1017 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
1018 /// assert_eq!((-128i8).checked_sub(1), None);
1020 #[stable(feature = "rust1", since = "1.0.0")]
1022 pub fn checked_sub(self, other: Self) -> Option<Self> {
1023 checked_op!($ActualT, $sub_with_overflow, self, other)
1026 /// Checked integer multiplication. Computes `self * other`, returning
1027 /// `None` if underflow or overflow occurred.
1032 /// assert_eq!(5u8.checked_mul(51), Some(255));
1033 /// assert_eq!(5u8.checked_mul(52), None);
1035 #[stable(feature = "rust1", since = "1.0.0")]
1037 pub fn checked_mul(self, other: Self) -> Option<Self> {
1038 checked_op!($ActualT, $mul_with_overflow, self, other)
1041 /// Checked integer division. Computes `self / other`, returning `None`
1042 /// if `other == 0` or the operation results in underflow or overflow.
1047 /// assert_eq!((-127i8).checked_div(-1), Some(127));
1048 /// assert_eq!((-128i8).checked_div(-1), None);
1049 /// assert_eq!((1i8).checked_div(0), None);
1051 #[stable(feature = "rust1", since = "1.0.0")]
1053 pub fn checked_div(self, other: Self) -> Option<Self> {
1056 other => Some(self / other),
1060 /// Saturating integer addition. Computes `self + other`, saturating at
1061 /// the numeric bounds instead of overflowing.
1062 #[stable(feature = "rust1", since = "1.0.0")]
1064 pub fn saturating_add(self, other: Self) -> Self {
1065 match self.checked_add(other) {
1067 None if other >= Self::zero() => Self::max_value(),
1068 None => Self::min_value(),
1072 /// Saturating integer subtraction. Computes `self - other`, saturating
1073 /// at the numeric bounds instead of overflowing.
1074 #[stable(feature = "rust1", since = "1.0.0")]
1076 pub fn saturating_sub(self, other: Self) -> Self {
1077 match self.checked_sub(other) {
1079 None if other >= Self::zero() => Self::min_value(),
1080 None => Self::max_value(),
1084 /// Wrapping (modular) addition. Computes `self + other`,
1085 /// wrapping around at the boundary of the type.
1086 #[stable(feature = "rust1", since = "1.0.0")]
1088 pub fn wrapping_add(self, rhs: Self) -> Self {
1090 intrinsics::overflowing_add(self, rhs)
1094 /// Wrapping (modular) subtraction. Computes `self - other`,
1095 /// wrapping around at the boundary of the type.
1096 #[stable(feature = "rust1", since = "1.0.0")]
1098 pub fn wrapping_sub(self, rhs: Self) -> Self {
1100 intrinsics::overflowing_sub(self, rhs)
1104 /// Wrapping (modular) multiplication. Computes `self *
1105 /// other`, wrapping around at the boundary of the type.
1106 #[stable(feature = "rust1", since = "1.0.0")]
1108 pub fn wrapping_mul(self, rhs: Self) -> Self {
1110 intrinsics::overflowing_mul(self, rhs)
1114 /// Wrapping (modular) division. Computes `self / other`,
1115 /// wrapping around at the boundary of the type.
1117 /// The only case where such wrapping can occur is when one
1118 /// divides `MIN / -1` on a signed type (where `MIN` is the
1119 /// negative minimal value for the type); this is equivalent
1120 /// to `-MIN`, a positive value that is too large to represent
1121 /// in the type. In such a case, this function returns `MIN`
1123 #[stable(feature = "num_wrapping", since = "1.2.0")]
1125 pub fn wrapping_div(self, rhs: Self) -> Self {
1126 self.overflowing_div(rhs).0
1129 /// Wrapping (modular) remainder. Computes `self % other`,
1130 /// wrapping around at the boundary of the type.
1132 /// Such wrap-around never actually occurs mathematically;
1133 /// implementation artifacts make `x % y` invalid for `MIN /
1134 /// -1` on a signed type (where `MIN` is the negative
1135 /// minimal value). In such a case, this function returns `0`.
1136 #[stable(feature = "num_wrapping", since = "1.2.0")]
1138 pub fn wrapping_rem(self, rhs: Self) -> Self {
1139 self.overflowing_rem(rhs).0
1142 /// Wrapping (modular) negation. Computes `-self`,
1143 /// wrapping around at the boundary of the type.
1145 /// The only case where such wrapping can occur is when one
1146 /// negates `MIN` on a signed type (where `MIN` is the
1147 /// negative minimal value for the type); this is a positive
1148 /// value that is too large to represent in the type. In such
1149 /// a case, this function returns `MIN` itself.
1150 #[stable(feature = "num_wrapping", since = "1.2.0")]
1152 pub fn wrapping_neg(self) -> Self {
1153 self.overflowing_neg().0
1156 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1157 /// where `mask` removes any high-order bits of `rhs` that
1158 /// would cause the shift to exceed the bitwidth of the type.
1159 #[stable(feature = "num_wrapping", since = "1.2.0")]
1161 pub fn wrapping_shl(self, rhs: u32) -> Self {
1162 self.overflowing_shl(rhs).0
1165 /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
1166 /// where `mask` removes any high-order bits of `rhs` that
1167 /// would cause the shift to exceed the bitwidth of the type.
1168 #[stable(feature = "num_wrapping", since = "1.2.0")]
1170 pub fn wrapping_shr(self, rhs: u32) -> Self {
1171 self.overflowing_shr(rhs).0
1174 /// Raises self to the power of `exp`, using exponentiation by squaring.
1179 /// assert_eq!(2i32.pow(4), 16);
1181 #[stable(feature = "rust1", since = "1.0.0")]
1183 pub fn pow(self, mut exp: u32) -> Self {
1184 let mut base = self;
1185 let mut acc = Self::one();
1187 let mut prev_base = self;
1188 let mut base_oflo = false;
1192 // ensure overflow occurs in the same manner it
1193 // would have otherwise (i.e. signal any exception
1194 // it would have otherwise).
1195 acc = acc * (prev_base * prev_base);
1201 let (new_base, new_base_oflo) = base.overflowing_mul(base);
1203 base_oflo = new_base_oflo;
1209 /// Returns `true` if and only if `self == 2^k` for some `k`.
1210 #[stable(feature = "rust1", since = "1.0.0")]
1212 pub fn is_power_of_two(self) -> bool {
1213 (self.wrapping_sub(Self::one())) & self == Self::zero() &&
1214 !(self == Self::zero())
1217 /// Returns the smallest power of two greater than or equal to `self`.
1218 /// Unspecified behavior on overflow.
1219 #[stable(feature = "rust1", since = "1.0.0")]
1221 pub fn next_power_of_two(self) -> Self {
1222 let bits = size_of::<Self>() * 8;
1223 let one: Self = Self::one();
1224 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
1227 /// Returns the smallest power of two greater than or equal to `n`. If
1228 /// the next power of two is greater than the type's maximum value,
1229 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 pub fn checked_next_power_of_two(self) -> Option<Self> {
1232 let npot = self.next_power_of_two();
1250 intrinsics::u8_add_with_overflow,
1251 intrinsics::u8_sub_with_overflow,
1252 intrinsics::u8_mul_with_overflow }
1262 intrinsics::add_with_overflow,
1263 intrinsics::sub_with_overflow,
1264 intrinsics::mul_with_overflow }
1270 uint_impl! { u16, 16,
1271 intrinsics::ctpop16,
1274 intrinsics::bswap16,
1275 intrinsics::u16_add_with_overflow,
1276 intrinsics::u16_sub_with_overflow,
1277 intrinsics::u16_mul_with_overflow }
1282 uint_impl! { u16, 16,
1287 intrinsics::add_with_overflow,
1288 intrinsics::sub_with_overflow,
1289 intrinsics::mul_with_overflow }
1295 uint_impl! { u32, 32,
1296 intrinsics::ctpop32,
1299 intrinsics::bswap32,
1300 intrinsics::u32_add_with_overflow,
1301 intrinsics::u32_sub_with_overflow,
1302 intrinsics::u32_mul_with_overflow }
1307 uint_impl! { u32, 32,
1312 intrinsics::add_with_overflow,
1313 intrinsics::sub_with_overflow,
1314 intrinsics::mul_with_overflow }
1320 uint_impl! { u64, 64,
1321 intrinsics::ctpop64,
1324 intrinsics::bswap64,
1325 intrinsics::u64_add_with_overflow,
1326 intrinsics::u64_sub_with_overflow,
1327 intrinsics::u64_mul_with_overflow }
1332 uint_impl! { u64, 64,
1337 intrinsics::add_with_overflow,
1338 intrinsics::sub_with_overflow,
1339 intrinsics::mul_with_overflow }
1342 #[cfg(target_pointer_width = "32")]
1346 uint_impl! { u32, 32,
1347 intrinsics::ctpop32,
1350 intrinsics::bswap32,
1351 intrinsics::u32_add_with_overflow,
1352 intrinsics::u32_sub_with_overflow,
1353 intrinsics::u32_mul_with_overflow }
1355 #[cfg(target_pointer_width = "32")]
1359 uint_impl! { u32, 32,
1364 intrinsics::add_with_overflow,
1365 intrinsics::sub_with_overflow,
1366 intrinsics::mul_with_overflow }
1369 #[cfg(target_pointer_width = "64")]
1373 uint_impl! { u64, 64,
1374 intrinsics::ctpop64,
1377 intrinsics::bswap64,
1378 intrinsics::u64_add_with_overflow,
1379 intrinsics::u64_sub_with_overflow,
1380 intrinsics::u64_mul_with_overflow }
1382 #[cfg(target_pointer_width = "64")]
1386 uint_impl! { u64, 64,
1391 intrinsics::add_with_overflow,
1392 intrinsics::sub_with_overflow,
1393 intrinsics::mul_with_overflow }
1396 /// Used for representing the classification of floating point numbers
1397 #[derive(Copy, Clone, PartialEq, Debug)]
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 pub enum FpCategory {
1400 /// "Not a Number", often obtained by dividing by zero
1401 #[stable(feature = "rust1", since = "1.0.0")]
1404 /// Positive or negative infinity
1405 #[stable(feature = "rust1", since = "1.0.0")]
1408 /// Positive or negative zero
1409 #[stable(feature = "rust1", since = "1.0.0")]
1412 /// De-normalized floating point representation (less precise than `Normal`)
1413 #[stable(feature = "rust1", since = "1.0.0")]
1416 /// A regular floating point number
1417 #[stable(feature = "rust1", since = "1.0.0")]
1421 /// A built-in floating point number.
1423 #[unstable(feature = "core_float",
1424 reason = "stable interface is via `impl f{32,64}` in later crates",
1426 pub trait Float: Sized {
1427 /// Returns the NaN value.
1429 /// Returns the infinite value.
1430 fn infinity() -> Self;
1431 /// Returns the negative infinite value.
1432 fn neg_infinity() -> Self;
1434 fn neg_zero() -> Self;
1439 /// Parses the string `s` with the radix `r` as a float.
1440 fn from_str_radix(s: &str, r: u32) -> Result<Self, ParseFloatError>;
1442 /// Returns true if this value is NaN and false otherwise.
1443 fn is_nan(self) -> bool;
1444 /// Returns true if this value is positive infinity or negative infinity and
1445 /// false otherwise.
1446 fn is_infinite(self) -> bool;
1447 /// Returns true if this number is neither infinite nor NaN.
1448 fn is_finite(self) -> bool;
1449 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1450 fn is_normal(self) -> bool;
1451 /// Returns the category that this number falls into.
1452 fn classify(self) -> FpCategory;
1454 /// Returns the mantissa, exponent and sign as integers, respectively.
1455 fn integer_decode(self) -> (u64, i16, i8);
1457 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1458 /// number is `Float::nan()`.
1459 fn abs(self) -> Self;
1460 /// Returns a number that represents the sign of `self`.
1462 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1463 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1464 /// - `Float::nan()` if the number is `Float::nan()`
1465 fn signum(self) -> Self;
1466 /// Returns `true` if `self` is positive, including `+0.0` and
1467 /// `Float::infinity()`.
1468 fn is_positive(self) -> bool;
1469 /// Returns `true` if `self` is negative, including `-0.0` and
1470 /// `Float::neg_infinity()`.
1471 fn is_negative(self) -> bool;
1473 /// Take the reciprocal (inverse) of a number, `1/x`.
1474 fn recip(self) -> Self;
1476 /// Raise a number to an integer power.
1478 /// Using this function is generally faster than using `powf`
1479 fn powi(self, n: i32) -> Self;
1481 /// Convert radians to degrees.
1482 fn to_degrees(self) -> Self;
1483 /// Convert degrees to radians.
1484 fn to_radians(self) -> Self;
1487 macro_rules! from_str_radix_int_impl {
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 impl FromStr for $t {
1491 type Err = ParseIntError;
1492 fn from_str(src: &str) -> Result<Self, ParseIntError> {
1493 from_str_radix(src, 10)
1498 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
1501 trait FromStrRadixHelper: PartialOrd + Copy {
1502 fn min_value() -> Self;
1503 fn from_u32(u: u32) -> Self;
1504 fn checked_mul(&self, other: u32) -> Option<Self>;
1505 fn checked_sub(&self, other: u32) -> Option<Self>;
1506 fn checked_add(&self, other: u32) -> Option<Self>;
1510 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
1511 fn min_value() -> Self { Self::min_value() }
1512 fn from_u32(u: u32) -> Self { u as Self }
1513 fn checked_mul(&self, other: u32) -> Option<Self> {
1514 Self::checked_mul(*self, other as Self)
1516 fn checked_sub(&self, other: u32) -> Option<Self> {
1517 Self::checked_sub(*self, other as Self)
1519 fn checked_add(&self, other: u32) -> Option<Self> {
1520 Self::checked_add(*self, other as Self)
1524 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1526 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
1527 -> Result<T, ParseIntError> {
1528 use self::IntErrorKind::*;
1529 use self::ParseIntError as PIE;
1531 assert!(radix >= 2 && radix <= 36,
1532 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1536 return Err(PIE { kind: Empty });
1539 let is_signed_ty = T::from_u32(0) > T::min_value();
1541 // all valid digits are ascii, so we will just iterate over the utf8 bytes
1542 // and cast them to chars. .to_digit() will safely return None for anything
1543 // other than a valid ascii digit for the given radix, including the first-byte
1544 // of multi-byte sequences
1545 let src = src.as_bytes();
1547 let (is_positive, digits) = match src[0] {
1548 b'+' => (true, &src[1..]),
1549 b'-' if is_signed_ty => (false, &src[1..]),
1553 if digits.is_empty() {
1554 return Err(PIE { kind: Empty });
1557 let mut result = T::from_u32(0);
1559 // The number is positive
1561 let x = match (c as char).to_digit(radix) {
1563 None => return Err(PIE { kind: InvalidDigit }),
1565 result = match result.checked_mul(radix) {
1566 Some(result) => result,
1567 None => return Err(PIE { kind: Overflow }),
1569 result = match result.checked_add(x) {
1570 Some(result) => result,
1571 None => return Err(PIE { kind: Overflow }),
1575 // The number is negative
1577 let x = match (c as char).to_digit(radix) {
1579 None => return Err(PIE { kind: InvalidDigit }),
1581 result = match result.checked_mul(radix) {
1582 Some(result) => result,
1583 None => return Err(PIE { kind: Underflow }),
1585 result = match result.checked_sub(x) {
1586 Some(result) => result,
1587 None => return Err(PIE { kind: Underflow }),
1594 /// An error which can be returned when parsing an integer.
1595 #[derive(Debug, Clone, PartialEq)]
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 pub struct ParseIntError { kind: IntErrorKind }
1599 #[derive(Debug, Clone, PartialEq)]
1607 impl ParseIntError {
1608 #[unstable(feature = "int_error_internals",
1609 reason = "available through Error trait and this method should \
1610 not be exposed publicly",
1613 pub fn __description(&self) -> &str {
1615 IntErrorKind::Empty => "cannot parse integer from empty string",
1616 IntErrorKind::InvalidDigit => "invalid digit found in string",
1617 IntErrorKind::Overflow => "number too large to fit in target type",
1618 IntErrorKind::Underflow => "number too small to fit in target type",
1623 #[stable(feature = "rust1", since = "1.0.0")]
1624 impl fmt::Display for ParseIntError {
1625 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1626 self.__description().fmt(f)
1630 pub use num::dec2flt::ParseFloatError;
1632 // Conversion traits for primitive integer and float types
1633 // Conversions T -> T are covered by a blanket impl and therefore excluded
1634 // Some conversions from and to usize/isize are not implemented due to portability concerns
1635 macro_rules! impl_from {
1636 ($Small: ty, $Large: ty) => {
1637 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
1638 impl From<$Small> for $Large {
1639 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
1641 fn from(small: $Small) -> $Large {
1648 // Unsigned -> Unsigned
1649 impl_from! { u8, u16 }
1650 impl_from! { u8, u32 }
1651 impl_from! { u8, u64 }
1652 impl_from! { u8, usize }
1653 impl_from! { u16, u32 }
1654 impl_from! { u16, u64 }
1655 impl_from! { u32, u64 }
1658 impl_from! { i8, i16 }
1659 impl_from! { i8, i32 }
1660 impl_from! { i8, i64 }
1661 impl_from! { i8, isize }
1662 impl_from! { i16, i32 }
1663 impl_from! { i16, i64 }
1664 impl_from! { i32, i64 }
1666 // Unsigned -> Signed
1667 impl_from! { u8, i16 }
1668 impl_from! { u8, i32 }
1669 impl_from! { u8, i64 }
1670 impl_from! { u16, i32 }
1671 impl_from! { u16, i64 }
1672 impl_from! { u32, i64 }
1674 // Note: integers can only be represented with full precision in a float if
1675 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
1676 // Lossy float conversions are not implemented at this time.
1679 impl_from! { i8, f32 }
1680 impl_from! { i8, f64 }
1681 impl_from! { i16, f32 }
1682 impl_from! { i16, f64 }
1683 impl_from! { i32, f64 }
1685 // Unsigned -> Float
1686 impl_from! { u8, f32 }
1687 impl_from! { u8, f64 }
1688 impl_from! { u16, f32 }
1689 impl_from! { u16, f64 }
1690 impl_from! { u32, f64 }
1693 impl_from! { f32, f64 }