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 // ignore-lexer-test FIXME #15679
13 //! Numeric traits and functions for the built-in numeric types.
16 #![allow(missing_docs)]
20 use cmp::{PartialEq, Eq};
21 use cmp::{PartialOrd, Ord};
23 use iter::IteratorExt;
26 use ops::{Add, Sub, Mul, Div, Rem, Neg};
27 use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr, Index};
29 use option::Option::{Some, None};
30 use str::{FromStr, StrExt};
32 /// A built-in signed or unsigned integer.
48 + Shl<uint, Output=Self>
49 + Shr<uint, Output=Self>
51 /// Returns the `0` value of this integer type.
52 // FIXME (#5527): Should be an associated constant
53 #[unstable = "unsure about its place in the world"]
56 /// Returns the `1` value of this integer type.
57 // FIXME (#5527): Should be an associated constant
58 #[unstable = "unsure about its place in the world"]
61 /// Returns the smallest value that can be represented by this integer type.
62 // FIXME (#5527): Should be and associated constant
63 #[unstable = "unsure about its place in the world"]
64 fn min_value() -> Self;
66 /// Returns the largest value that can be represented by this integer type.
67 // FIXME (#5527): Should be and associated constant
68 #[unstable = "unsure about its place in the world"]
69 fn max_value() -> Self;
71 /// Returns the number of ones in the binary representation of `self`.
76 /// use std::num::Int;
78 /// let n = 0b01001100u8;
80 /// assert_eq!(n.count_ones(), 3);
82 #[unstable = "pending integer conventions"]
83 fn count_ones(self) -> uint;
85 /// Returns the number of zeros in the binary representation of `self`.
90 /// use std::num::Int;
92 /// let n = 0b01001100u8;
94 /// assert_eq!(n.count_zeros(), 5);
96 #[unstable = "pending integer conventions"]
98 fn count_zeros(self) -> uint {
102 /// Returns the number of leading zeros in the binary representation
108 /// use std::num::Int;
110 /// let n = 0b0101000u16;
112 /// assert_eq!(n.leading_zeros(), 10);
114 #[unstable = "pending integer conventions"]
115 fn leading_zeros(self) -> uint;
117 /// Returns the number of trailing zeros in the binary representation
123 /// use std::num::Int;
125 /// let n = 0b0101000u16;
127 /// assert_eq!(n.trailing_zeros(), 3);
129 #[unstable = "pending integer conventions"]
130 fn trailing_zeros(self) -> uint;
132 /// Shifts the bits to the left by a specified amount amount, `n`, wrapping
133 /// the truncated bits to the end of the resulting integer.
138 /// use std::num::Int;
140 /// let n = 0x0123456789ABCDEFu64;
141 /// let m = 0x3456789ABCDEF012u64;
143 /// assert_eq!(n.rotate_left(12), m);
145 #[unstable = "pending integer conventions"]
146 fn rotate_left(self, n: uint) -> Self;
148 /// Shifts the bits to the right by a specified amount amount, `n`, wrapping
149 /// the truncated bits to the beginning of the resulting integer.
154 /// use std::num::Int;
156 /// let n = 0x0123456789ABCDEFu64;
157 /// let m = 0xDEF0123456789ABCu64;
159 /// assert_eq!(n.rotate_right(12), m);
161 #[unstable = "pending integer conventions"]
162 fn rotate_right(self, n: uint) -> Self;
164 /// Reverses the byte order of the integer.
169 /// use std::num::Int;
171 /// let n = 0x0123456789ABCDEFu64;
172 /// let m = 0xEFCDAB8967452301u64;
174 /// assert_eq!(n.swap_bytes(), m);
177 fn swap_bytes(self) -> Self;
179 /// Convert an integer from big endian to the target's endianness.
181 /// On big endian this is a no-op. On little endian the bytes are swapped.
186 /// use std::num::Int;
188 /// let n = 0x0123456789ABCDEFu64;
190 /// if cfg!(target_endian = "big") {
191 /// assert_eq!(Int::from_be(n), n)
193 /// assert_eq!(Int::from_be(n), n.swap_bytes())
198 fn from_be(x: Self) -> Self {
199 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
202 /// Convert an integer from little endian to the target's endianness.
204 /// On little endian this is a no-op. On big endian the bytes are swapped.
209 /// use std::num::Int;
211 /// let n = 0x0123456789ABCDEFu64;
213 /// if cfg!(target_endian = "little") {
214 /// assert_eq!(Int::from_le(n), n)
216 /// assert_eq!(Int::from_le(n), n.swap_bytes())
221 fn from_le(x: Self) -> Self {
222 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
225 /// Convert `self` to big endian from the target's endianness.
227 /// On big endian this is a no-op. On little endian the bytes are swapped.
232 /// use std::num::Int;
234 /// let n = 0x0123456789ABCDEFu64;
236 /// if cfg!(target_endian = "big") {
237 /// assert_eq!(n.to_be(), n)
239 /// assert_eq!(n.to_be(), n.swap_bytes())
244 fn to_be(self) -> Self { // or not to be?
245 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
248 /// Convert `self` to little endian from the target's endianness.
250 /// On little endian this is a no-op. On big endian the bytes are swapped.
255 /// use std::num::Int;
257 /// let n = 0x0123456789ABCDEFu64;
259 /// if cfg!(target_endian = "little") {
260 /// assert_eq!(n.to_le(), n)
262 /// assert_eq!(n.to_le(), n.swap_bytes())
267 fn to_le(self) -> Self {
268 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
271 /// Checked integer addition. Computes `self + other`, returning `None` if
272 /// overflow occurred.
277 /// use std::num::Int;
279 /// assert_eq!(5u16.checked_add(65530), Some(65535));
280 /// assert_eq!(6u16.checked_add(65530), None);
283 fn checked_add(self, other: Self) -> Option<Self>;
285 /// Checked integer subtraction. Computes `self - other`, returning `None`
286 /// if underflow occurred.
291 /// use std::num::Int;
293 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
294 /// assert_eq!((-128i8).checked_sub(1), None);
297 fn checked_sub(self, other: Self) -> Option<Self>;
299 /// Checked integer multiplication. Computes `self * other`, returning
300 /// `None` if underflow or overflow occurred.
305 /// use std::num::Int;
307 /// assert_eq!(5u8.checked_mul(51), Some(255));
308 /// assert_eq!(5u8.checked_mul(52), None);
311 fn checked_mul(self, other: Self) -> Option<Self>;
313 /// Checked integer division. Computes `self / other`, returning `None` if
314 /// `other == 0` or the operation results in underflow or overflow.
319 /// use std::num::Int;
321 /// assert_eq!((-127i8).checked_div(-1), Some(127));
322 /// assert_eq!((-128i8).checked_div(-1), None);
323 /// assert_eq!((1i8).checked_div(0), None);
326 fn checked_div(self, other: Self) -> Option<Self>;
328 /// Saturating integer addition. Computes `self + other`, saturating at
329 /// the numeric bounds instead of overflowing.
332 fn saturating_add(self, other: Self) -> Self {
333 match self.checked_add(other) {
335 None if other >= Int::zero() => Int::max_value(),
336 None => Int::min_value(),
340 /// Saturating integer subtraction. Computes `self - other`, saturating at
341 /// the numeric bounds instead of overflowing.
344 fn saturating_sub(self, other: Self) -> Self {
345 match self.checked_sub(other) {
347 None if other >= Int::zero() => Int::min_value(),
348 None => Int::max_value(),
352 /// Raises self to the power of `exp`, using exponentiation by squaring.
357 /// use std::num::Int;
359 /// assert_eq!(2i.pow(4), 16);
361 #[unstable = "pending integer conventions"]
363 fn pow(self, mut exp: uint) -> Self {
365 let mut acc: Self = Int::one();
377 macro_rules! checked_op {
378 ($T:ty, $U:ty, $op:path, $x:expr, $y:expr) => {{
379 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
380 if overflowed { None } else { Some(result as $T) }
384 macro_rules! uint_impl {
385 ($T:ty = $ActualT:ty, $BITS:expr,
390 $add_with_overflow:path,
391 $sub_with_overflow:path,
392 $mul_with_overflow:path) => {
396 fn zero() -> $T { 0 }
402 fn min_value() -> $T { 0 }
405 fn max_value() -> $T { -1 }
408 fn count_ones(self) -> uint { unsafe { $ctpop(self as $ActualT) as uint } }
411 fn leading_zeros(self) -> uint { unsafe { $ctlz(self as $ActualT) as uint } }
414 fn trailing_zeros(self) -> uint { unsafe { $cttz(self as $ActualT) as uint } }
417 fn rotate_left(self, n: uint) -> $T {
418 // Protect against undefined behaviour for over-long bit shifts
420 (self << n) | (self >> (($BITS - n) % $BITS))
424 fn rotate_right(self, n: uint) -> $T {
425 // Protect against undefined behaviour for over-long bit shifts
427 (self >> n) | (self << (($BITS - n) % $BITS))
431 fn swap_bytes(self) -> $T { unsafe { $bswap(self as $ActualT) as $T } }
434 fn checked_add(self, other: $T) -> Option<$T> {
435 checked_op!($T, $ActualT, $add_with_overflow, self, other)
439 fn checked_sub(self, other: $T) -> Option<$T> {
440 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
444 fn checked_mul(self, other: $T) -> Option<$T> {
445 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
449 fn checked_div(self, v: $T) -> Option<$T> {
459 /// Swapping a single byte is a no-op. This is marked as `unsafe` for
460 /// consistency with the other `bswap` intrinsics.
461 unsafe fn bswap8(x: u8) -> u8 { x }
463 uint_impl! { u8 = u8, 8,
468 intrinsics::u8_add_with_overflow,
469 intrinsics::u8_sub_with_overflow,
470 intrinsics::u8_mul_with_overflow }
472 uint_impl! { u16 = u16, 16,
477 intrinsics::u16_add_with_overflow,
478 intrinsics::u16_sub_with_overflow,
479 intrinsics::u16_mul_with_overflow }
481 uint_impl! { u32 = u32, 32,
486 intrinsics::u32_add_with_overflow,
487 intrinsics::u32_sub_with_overflow,
488 intrinsics::u32_mul_with_overflow }
490 uint_impl! { u64 = u64, 64,
495 intrinsics::u64_add_with_overflow,
496 intrinsics::u64_sub_with_overflow,
497 intrinsics::u64_mul_with_overflow }
499 #[cfg(target_word_size = "32")]
500 uint_impl! { uint = u32, 32,
505 intrinsics::u32_add_with_overflow,
506 intrinsics::u32_sub_with_overflow,
507 intrinsics::u32_mul_with_overflow }
509 #[cfg(target_word_size = "64")]
510 uint_impl! { uint = u64, 64,
515 intrinsics::u64_add_with_overflow,
516 intrinsics::u64_sub_with_overflow,
517 intrinsics::u64_mul_with_overflow }
519 macro_rules! int_impl {
520 ($T:ty = $ActualT:ty, $UnsignedT:ty, $BITS:expr,
521 $add_with_overflow:path,
522 $sub_with_overflow:path,
523 $mul_with_overflow:path) => {
527 fn zero() -> $T { 0 }
533 fn min_value() -> $T { (-1 as $T) << ($BITS - 1) }
536 fn max_value() -> $T { let min: $T = Int::min_value(); !min }
539 fn count_ones(self) -> uint { (self as $UnsignedT).count_ones() }
542 fn leading_zeros(self) -> uint { (self as $UnsignedT).leading_zeros() }
545 fn trailing_zeros(self) -> uint { (self as $UnsignedT).trailing_zeros() }
548 fn rotate_left(self, n: uint) -> $T { (self as $UnsignedT).rotate_left(n) as $T }
551 fn rotate_right(self, n: uint) -> $T { (self as $UnsignedT).rotate_right(n) as $T }
554 fn swap_bytes(self) -> $T { (self as $UnsignedT).swap_bytes() as $T }
557 fn checked_add(self, other: $T) -> Option<$T> {
558 checked_op!($T, $ActualT, $add_with_overflow, self, other)
562 fn checked_sub(self, other: $T) -> Option<$T> {
563 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
567 fn checked_mul(self, other: $T) -> Option<$T> {
568 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
572 fn checked_div(self, v: $T) -> Option<$T> {
575 -1 if self == Int::min_value()
584 int_impl! { i8 = i8, u8, 8,
585 intrinsics::i8_add_with_overflow,
586 intrinsics::i8_sub_with_overflow,
587 intrinsics::i8_mul_with_overflow }
589 int_impl! { i16 = i16, u16, 16,
590 intrinsics::i16_add_with_overflow,
591 intrinsics::i16_sub_with_overflow,
592 intrinsics::i16_mul_with_overflow }
594 int_impl! { i32 = i32, u32, 32,
595 intrinsics::i32_add_with_overflow,
596 intrinsics::i32_sub_with_overflow,
597 intrinsics::i32_mul_with_overflow }
599 int_impl! { i64 = i64, u64, 64,
600 intrinsics::i64_add_with_overflow,
601 intrinsics::i64_sub_with_overflow,
602 intrinsics::i64_mul_with_overflow }
604 #[cfg(target_word_size = "32")]
605 int_impl! { int = i32, u32, 32,
606 intrinsics::i32_add_with_overflow,
607 intrinsics::i32_sub_with_overflow,
608 intrinsics::i32_mul_with_overflow }
610 #[cfg(target_word_size = "64")]
611 int_impl! { int = i64, u64, 64,
612 intrinsics::i64_add_with_overflow,
613 intrinsics::i64_sub_with_overflow,
614 intrinsics::i64_mul_with_overflow }
616 /// A built-in two's complement integer.
622 /// Computes the absolute value of `self`. `Int::min_value()` will be
623 /// returned if the number is `Int::min_value()`.
624 #[unstable = "overflow in debug builds?"]
625 fn abs(self) -> Self;
627 /// Returns a number representing sign of `self`.
629 /// - `0` if the number is zero
630 /// - `1` if the number is positive
631 /// - `-1` if the number is negative
633 fn signum(self) -> Self;
635 /// Returns `true` if `self` is positive and `false` if the number
636 /// is zero or negative.
638 fn is_positive(self) -> bool;
640 /// Returns `true` if `self` is negative and `false` if the number
641 /// is zero or positive.
643 fn is_negative(self) -> bool;
646 macro_rules! signed_int_impl {
649 impl SignedInt for $T {
652 if self.is_negative() { -self } else { self }
656 fn signum(self) -> $T {
665 fn is_positive(self) -> bool { self > 0 }
668 fn is_negative(self) -> bool { self < 0 }
673 signed_int_impl! { i8 }
674 signed_int_impl! { i16 }
675 signed_int_impl! { i32 }
676 signed_int_impl! { i64 }
677 signed_int_impl! { int }
679 /// A built-in unsigned integer.
681 pub trait UnsignedInt: Int {
682 /// Returns `true` iff `self == 2^k` for some `k`.
685 fn is_power_of_two(self) -> bool {
686 (self - Int::one()) & self == Int::zero() && !(self == Int::zero())
689 /// Returns the smallest power of two greater than or equal to `self`.
690 /// Unspecified behavior on overflow.
693 fn next_power_of_two(self) -> Self {
694 let bits = size_of::<Self>() * 8;
695 let one: Self = Int::one();
696 one << ((bits - (self - one).leading_zeros()) % bits)
699 /// Returns the smallest power of two greater than or equal to `n`. If the
700 /// next power of two is greater than the type's maximum value, `None` is
701 /// returned, otherwise the power of two is wrapped in `Some`.
703 fn checked_next_power_of_two(self) -> Option<Self> {
704 let npot = self.next_power_of_two();
714 impl UnsignedInt for uint {}
717 impl UnsignedInt for u8 {}
720 impl UnsignedInt for u16 {}
723 impl UnsignedInt for u32 {}
726 impl UnsignedInt for u64 {}
728 /// A generic trait for converting a value to a number.
729 #[experimental = "trait is likely to be removed"]
730 pub trait ToPrimitive {
731 /// Converts the value of `self` to an `int`.
733 fn to_int(&self) -> Option<int> {
734 self.to_i64().and_then(|x| x.to_int())
737 /// Converts the value of `self` to an `i8`.
739 fn to_i8(&self) -> Option<i8> {
740 self.to_i64().and_then(|x| x.to_i8())
743 /// Converts the value of `self` to an `i16`.
745 fn to_i16(&self) -> Option<i16> {
746 self.to_i64().and_then(|x| x.to_i16())
749 /// Converts the value of `self` to an `i32`.
751 fn to_i32(&self) -> Option<i32> {
752 self.to_i64().and_then(|x| x.to_i32())
755 /// Converts the value of `self` to an `i64`.
756 fn to_i64(&self) -> Option<i64>;
758 /// Converts the value of `self` to an `uint`.
760 fn to_uint(&self) -> Option<uint> {
761 self.to_u64().and_then(|x| x.to_uint())
764 /// Converts the value of `self` to an `u8`.
766 fn to_u8(&self) -> Option<u8> {
767 self.to_u64().and_then(|x| x.to_u8())
770 /// Converts the value of `self` to an `u16`.
772 fn to_u16(&self) -> Option<u16> {
773 self.to_u64().and_then(|x| x.to_u16())
776 /// Converts the value of `self` to an `u32`.
778 fn to_u32(&self) -> Option<u32> {
779 self.to_u64().and_then(|x| x.to_u32())
782 /// Converts the value of `self` to an `u64`.
784 fn to_u64(&self) -> Option<u64>;
786 /// Converts the value of `self` to an `f32`.
788 fn to_f32(&self) -> Option<f32> {
789 self.to_f64().and_then(|x| x.to_f32())
792 /// Converts the value of `self` to an `f64`.
794 fn to_f64(&self) -> Option<f64> {
795 self.to_i64().and_then(|x| x.to_f64())
799 macro_rules! impl_to_primitive_int_to_int {
800 ($SrcT:ty, $DstT:ty, $slf:expr) => (
802 if size_of::<$SrcT>() <= size_of::<$DstT>() {
806 let min_value: $DstT = Int::min_value();
807 let max_value: $DstT = Int::max_value();
808 if min_value as i64 <= n && n <= max_value as i64 {
818 macro_rules! impl_to_primitive_int_to_uint {
819 ($SrcT:ty, $DstT:ty, $slf:expr) => (
821 let zero: $SrcT = Int::zero();
822 let max_value: $DstT = Int::max_value();
823 if zero <= $slf && $slf as u64 <= max_value as u64 {
832 macro_rules! impl_to_primitive_int {
834 impl ToPrimitive for $T {
836 fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int, *self) }
838 fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) }
840 fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) }
842 fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32, *self) }
844 fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self) }
847 fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint, *self) }
849 fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) }
851 fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) }
853 fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32, *self) }
855 fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64, *self) }
858 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
860 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
865 impl_to_primitive_int! { int }
866 impl_to_primitive_int! { i8 }
867 impl_to_primitive_int! { i16 }
868 impl_to_primitive_int! { i32 }
869 impl_to_primitive_int! { i64 }
871 macro_rules! impl_to_primitive_uint_to_int {
872 ($DstT:ty, $slf:expr) => (
874 let max_value: $DstT = Int::max_value();
875 if $slf as u64 <= max_value as u64 {
884 macro_rules! impl_to_primitive_uint_to_uint {
885 ($SrcT:ty, $DstT:ty, $slf:expr) => (
887 if size_of::<$SrcT>() <= size_of::<$DstT>() {
890 let zero: $SrcT = Int::zero();
891 let max_value: $DstT = Int::max_value();
892 if zero <= $slf && $slf as u64 <= max_value as u64 {
902 macro_rules! impl_to_primitive_uint {
904 impl ToPrimitive for $T {
906 fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int, *self) }
908 fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) }
910 fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) }
912 fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32, *self) }
914 fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) }
917 fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint, *self) }
919 fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) }
921 fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) }
923 fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32, *self) }
925 fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64, *self) }
928 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
930 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
935 impl_to_primitive_uint! { uint }
936 impl_to_primitive_uint! { u8 }
937 impl_to_primitive_uint! { u16 }
938 impl_to_primitive_uint! { u32 }
939 impl_to_primitive_uint! { u64 }
941 macro_rules! impl_to_primitive_float_to_float {
942 ($SrcT:ident, $DstT:ident, $slf:expr) => (
943 if size_of::<$SrcT>() <= size_of::<$DstT>() {
947 let max_value: $SrcT = ::$SrcT::MAX_VALUE;
948 if -max_value as f64 <= n && n <= max_value as f64 {
957 macro_rules! impl_to_primitive_float {
959 impl ToPrimitive for $T {
961 fn to_int(&self) -> Option<int> { Some(*self as int) }
963 fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
965 fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
967 fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
969 fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
972 fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
974 fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
976 fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
978 fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
980 fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
983 fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32, *self) }
985 fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64, *self) }
990 impl_to_primitive_float! { f32 }
991 impl_to_primitive_float! { f64 }
993 /// A generic trait for converting a number to a value.
994 #[experimental = "trait is likely to be removed"]
995 pub trait FromPrimitive : ::marker::Sized {
996 /// Convert an `int` to return an optional value of this type. If the
997 /// value cannot be represented by this value, the `None` is returned.
999 fn from_int(n: int) -> Option<Self> {
1000 FromPrimitive::from_i64(n as i64)
1003 /// Convert an `i8` to return an optional value of this type. If the
1004 /// type cannot be represented by this value, the `None` is returned.
1006 fn from_i8(n: i8) -> Option<Self> {
1007 FromPrimitive::from_i64(n as i64)
1010 /// Convert an `i16` to return an optional value of this type. If the
1011 /// type cannot be represented by this value, the `None` is returned.
1013 fn from_i16(n: i16) -> Option<Self> {
1014 FromPrimitive::from_i64(n as i64)
1017 /// Convert an `i32` to return an optional value of this type. If the
1018 /// type cannot be represented by this value, the `None` is returned.
1020 fn from_i32(n: i32) -> Option<Self> {
1021 FromPrimitive::from_i64(n as i64)
1024 /// Convert an `i64` to return an optional value of this type. If the
1025 /// type cannot be represented by this value, the `None` is returned.
1026 fn from_i64(n: i64) -> Option<Self>;
1028 /// Convert an `uint` to return an optional value of this type. If the
1029 /// type cannot be represented by this value, the `None` is returned.
1031 fn from_uint(n: uint) -> Option<Self> {
1032 FromPrimitive::from_u64(n as u64)
1035 /// Convert an `u8` to return an optional value of this type. If the
1036 /// type cannot be represented by this value, the `None` is returned.
1038 fn from_u8(n: u8) -> Option<Self> {
1039 FromPrimitive::from_u64(n as u64)
1042 /// Convert an `u16` to return an optional value of this type. If the
1043 /// type cannot be represented by this value, the `None` is returned.
1045 fn from_u16(n: u16) -> Option<Self> {
1046 FromPrimitive::from_u64(n as u64)
1049 /// Convert an `u32` to return an optional value of this type. If the
1050 /// type cannot be represented by this value, the `None` is returned.
1052 fn from_u32(n: u32) -> Option<Self> {
1053 FromPrimitive::from_u64(n as u64)
1056 /// Convert an `u64` to return an optional value of this type. If the
1057 /// type cannot be represented by this value, the `None` is returned.
1058 fn from_u64(n: u64) -> Option<Self>;
1060 /// Convert a `f32` to return an optional value of this type. If the
1061 /// type cannot be represented by this value, the `None` is returned.
1063 fn from_f32(n: f32) -> Option<Self> {
1064 FromPrimitive::from_f64(n as f64)
1067 /// Convert a `f64` to return an optional value of this type. If the
1068 /// type cannot be represented by this value, the `None` is returned.
1070 fn from_f64(n: f64) -> Option<Self> {
1071 FromPrimitive::from_i64(n as i64)
1075 /// A utility function that just calls `FromPrimitive::from_int`.
1076 #[experimental = "likely to be removed"]
1077 pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
1078 FromPrimitive::from_int(n)
1081 /// A utility function that just calls `FromPrimitive::from_i8`.
1082 #[experimental = "likely to be removed"]
1083 pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> {
1084 FromPrimitive::from_i8(n)
1087 /// A utility function that just calls `FromPrimitive::from_i16`.
1088 #[experimental = "likely to be removed"]
1089 pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> {
1090 FromPrimitive::from_i16(n)
1093 /// A utility function that just calls `FromPrimitive::from_i32`.
1094 #[experimental = "likely to be removed"]
1095 pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> {
1096 FromPrimitive::from_i32(n)
1099 /// A utility function that just calls `FromPrimitive::from_i64`.
1100 #[experimental = "likely to be removed"]
1101 pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
1102 FromPrimitive::from_i64(n)
1105 /// A utility function that just calls `FromPrimitive::from_uint`.
1106 #[experimental = "likely to be removed"]
1107 pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
1108 FromPrimitive::from_uint(n)
1111 /// A utility function that just calls `FromPrimitive::from_u8`.
1112 #[experimental = "likely to be removed"]
1113 pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> {
1114 FromPrimitive::from_u8(n)
1117 /// A utility function that just calls `FromPrimitive::from_u16`.
1118 #[experimental = "likely to be removed"]
1119 pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> {
1120 FromPrimitive::from_u16(n)
1123 /// A utility function that just calls `FromPrimitive::from_u32`.
1124 #[experimental = "likely to be removed"]
1125 pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> {
1126 FromPrimitive::from_u32(n)
1129 /// A utility function that just calls `FromPrimitive::from_u64`.
1130 #[experimental = "likely to be removed"]
1131 pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> {
1132 FromPrimitive::from_u64(n)
1135 /// A utility function that just calls `FromPrimitive::from_f32`.
1136 #[experimental = "likely to be removed"]
1137 pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> {
1138 FromPrimitive::from_f32(n)
1141 /// A utility function that just calls `FromPrimitive::from_f64`.
1142 #[experimental = "likely to be removed"]
1143 pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {
1144 FromPrimitive::from_f64(n)
1147 macro_rules! impl_from_primitive {
1148 ($T:ty, $to_ty:ident) => (
1149 impl FromPrimitive for $T {
1150 #[inline] fn from_int(n: int) -> Option<$T> { n.$to_ty() }
1151 #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() }
1152 #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() }
1153 #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() }
1154 #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() }
1156 #[inline] fn from_uint(n: uint) -> Option<$T> { n.$to_ty() }
1157 #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() }
1158 #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() }
1159 #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() }
1160 #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() }
1162 #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() }
1163 #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() }
1168 impl_from_primitive! { int, to_int }
1169 impl_from_primitive! { i8, to_i8 }
1170 impl_from_primitive! { i16, to_i16 }
1171 impl_from_primitive! { i32, to_i32 }
1172 impl_from_primitive! { i64, to_i64 }
1173 impl_from_primitive! { uint, to_uint }
1174 impl_from_primitive! { u8, to_u8 }
1175 impl_from_primitive! { u16, to_u16 }
1176 impl_from_primitive! { u32, to_u32 }
1177 impl_from_primitive! { u64, to_u64 }
1178 impl_from_primitive! { f32, to_f32 }
1179 impl_from_primitive! { f64, to_f64 }
1181 /// Cast from one machine scalar to another.
1188 /// let twenty: f32 = num::cast(0x14i).unwrap();
1189 /// assert_eq!(twenty, 20f32);
1193 #[experimental = "likely to be removed"]
1194 pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
1198 /// An interface for casting between machine scalars.
1199 #[experimental = "trait is likely to be removed"]
1200 pub trait NumCast: ToPrimitive {
1201 /// Creates a number from another value that can be converted into a primitive via the
1202 /// `ToPrimitive` trait.
1203 fn from<T: ToPrimitive>(n: T) -> Option<Self>;
1206 macro_rules! impl_num_cast {
1207 ($T:ty, $conv:ident) => (
1208 impl NumCast for $T {
1210 fn from<N: ToPrimitive>(n: N) -> Option<$T> {
1211 // `$conv` could be generated using `concat_idents!`, but that
1212 // macro seems to be broken at the moment
1219 impl_num_cast! { u8, to_u8 }
1220 impl_num_cast! { u16, to_u16 }
1221 impl_num_cast! { u32, to_u32 }
1222 impl_num_cast! { u64, to_u64 }
1223 impl_num_cast! { uint, to_uint }
1224 impl_num_cast! { i8, to_i8 }
1225 impl_num_cast! { i16, to_i16 }
1226 impl_num_cast! { i32, to_i32 }
1227 impl_num_cast! { i64, to_i64 }
1228 impl_num_cast! { int, to_int }
1229 impl_num_cast! { f32, to_f32 }
1230 impl_num_cast! { f64, to_f64 }
1232 /// Used for representing the classification of floating point numbers
1233 #[derive(Copy, PartialEq, Show)]
1234 #[unstable = "may be renamed"]
1235 pub enum FpCategory {
1236 /// "Not a Number", often obtained by dividing by zero
1238 /// Positive or negative infinity
1240 /// Positive or negative zero
1242 /// De-normalized floating point representation (less precise than `Normal`)
1244 /// A regular floating point number
1248 /// A built-in floating point number.
1249 // FIXME(#5527): In a future version of Rust, many of these functions will
1250 // become constants.
1252 // FIXME(#8888): Several of these functions have a parameter named
1253 // `unused_self`. Removing it requires #8888 to be fixed.
1254 #[unstable = "distribution of methods between core/std is unclear"]
1267 /// Returns the NaN value.
1269 /// Returns the infinite value.
1270 fn infinity() -> Self;
1271 /// Returns the negative infinite value.
1272 fn neg_infinity() -> Self;
1273 /// Returns the `0` value.
1276 fn neg_zero() -> Self;
1277 /// Returns the `1` value.
1280 // FIXME (#5527): These should be associated constants
1282 /// Returns the number of binary digits of mantissa that this type supports.
1283 #[deprecated = "use `std::f32::MANTISSA_DIGITS` or `std::f64::MANTISSA_DIGITS` as appropriate"]
1284 fn mantissa_digits(unused_self: Option<Self>) -> uint;
1285 /// Returns the number of base-10 digits of precision that this type supports.
1286 #[deprecated = "use `std::f32::DIGITS` or `std::f64::DIGITS` as appropriate"]
1287 fn digits(unused_self: Option<Self>) -> uint;
1288 /// Returns the difference between 1.0 and the smallest representable number larger than 1.0.
1289 #[deprecated = "use `std::f32::EPSILON` or `std::f64::EPSILON` as appropriate"]
1290 fn epsilon() -> Self;
1291 /// Returns the minimum binary exponent that this type can represent.
1292 #[deprecated = "use `std::f32::MIN_EXP` or `std::f64::MIN_EXP` as appropriate"]
1293 fn min_exp(unused_self: Option<Self>) -> int;
1294 /// Returns the maximum binary exponent that this type can represent.
1295 #[deprecated = "use `std::f32::MAX_EXP` or `std::f64::MAX_EXP` as appropriate"]
1296 fn max_exp(unused_self: Option<Self>) -> int;
1297 /// Returns the minimum base-10 exponent that this type can represent.
1298 #[deprecated = "use `std::f32::MIN_10_EXP` or `std::f64::MIN_10_EXP` as appropriate"]
1299 fn min_10_exp(unused_self: Option<Self>) -> int;
1300 /// Returns the maximum base-10 exponent that this type can represent.
1301 #[deprecated = "use `std::f32::MAX_10_EXP` or `std::f64::MAX_10_EXP` as appropriate"]
1302 fn max_10_exp(unused_self: Option<Self>) -> int;
1303 /// Returns the smallest finite value that this type can represent.
1304 #[deprecated = "use `std::f32::MIN_VALUE` or `std::f64::MIN_VALUE` as appropriate"]
1305 fn min_value() -> Self;
1306 /// Returns the smallest normalized positive number that this type can represent.
1307 #[deprecated = "use `std::f32::MIN_POS_VALUE` or `std::f64::MIN_POS_VALUE` as appropriate"]
1308 fn min_pos_value(unused_self: Option<Self>) -> Self;
1309 /// Returns the largest finite value that this type can represent.
1310 #[deprecated = "use `std::f32::MAX_VALUE` or `std::f64::MAX_VALUE` as appropriate"]
1311 fn max_value() -> Self;
1313 /// Returns true if this value is NaN and false otherwise.
1314 fn is_nan(self) -> bool;
1315 /// Returns true if this value is positive infinity or negative infinity and
1316 /// false otherwise.
1317 fn is_infinite(self) -> bool;
1318 /// Returns true if this number is neither infinite nor NaN.
1319 fn is_finite(self) -> bool;
1320 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1321 fn is_normal(self) -> bool;
1322 /// Returns the category that this number falls into.
1323 fn classify(self) -> FpCategory;
1325 /// Returns the mantissa, exponent and sign as integers, respectively.
1326 fn integer_decode(self) -> (u64, i16, i8);
1328 /// Return the largest integer less than or equal to a number.
1329 fn floor(self) -> Self;
1330 /// Return the smallest integer greater than or equal to a number.
1331 fn ceil(self) -> Self;
1332 /// Return the nearest integer to a number. Round half-way cases away from
1334 fn round(self) -> Self;
1335 /// Return the integer part of a number.
1336 fn trunc(self) -> Self;
1337 /// Return the fractional part of a number.
1338 fn fract(self) -> Self;
1340 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1341 /// number is `Float::nan()`.
1342 fn abs(self) -> Self;
1343 /// Returns a number that represents the sign of `self`.
1345 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1346 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1347 /// - `Float::nan()` if the number is `Float::nan()`
1348 fn signum(self) -> Self;
1349 /// Returns `true` if `self` is positive, including `+0.0` and
1350 /// `Float::infinity()`.
1351 fn is_positive(self) -> bool;
1352 /// Returns `true` if `self` is negative, including `-0.0` and
1353 /// `Float::neg_infinity()`.
1354 fn is_negative(self) -> bool;
1356 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1357 /// error. This produces a more accurate result with better performance than
1358 /// a separate multiplication operation followed by an add.
1359 fn mul_add(self, a: Self, b: Self) -> Self;
1360 /// Take the reciprocal (inverse) of a number, `1/x`.
1361 fn recip(self) -> Self;
1363 /// Raise a number to an integer power.
1365 /// Using this function is generally faster than using `powf`
1366 fn powi(self, n: i32) -> Self;
1367 /// Raise a number to a floating point power.
1368 fn powf(self, n: Self) -> Self;
1370 /// Take the square root of a number.
1372 /// Returns NaN if `self` is a negative number.
1373 fn sqrt(self) -> Self;
1374 /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1375 fn rsqrt(self) -> Self;
1377 /// Returns `e^(self)`, (the exponential function).
1378 fn exp(self) -> Self;
1379 /// Returns 2 raised to the power of the number, `2^(self)`.
1380 fn exp2(self) -> Self;
1381 /// Returns the natural logarithm of the number.
1382 fn ln(self) -> Self;
1383 /// Returns the logarithm of the number with respect to an arbitrary base.
1384 fn log(self, base: Self) -> Self;
1385 /// Returns the base 2 logarithm of the number.
1386 fn log2(self) -> Self;
1387 /// Returns the base 10 logarithm of the number.
1388 fn log10(self) -> Self;
1390 /// Convert radians to degrees.
1391 fn to_degrees(self) -> Self;
1392 /// Convert degrees to radians.
1393 fn to_radians(self) -> Self;
1396 /// A generic trait for converting a string with a radix (base) to a value
1397 #[experimental = "might need to return Result"]
1398 pub trait FromStrRadix {
1399 fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
1402 /// A utility function that just calls FromStrRadix::from_str_radix.
1403 #[experimental = "might need to return Result"]
1404 pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint) -> Option<T> {
1405 FromStrRadix::from_str_radix(str, radix)
1408 macro_rules! from_str_radix_float_impl {
1410 #[experimental = "might need to return Result"]
1411 impl FromStr for $T {
1412 /// Convert a string in base 10 to a float.
1413 /// Accepts an optional decimal exponent.
1415 /// This function accepts strings such as
1418 /// * '+3.14', equivalent to '3.14'
1420 /// * '2.5E10', or equivalently, '2.5e10'
1422 /// * '.' (understood as 0)
1424 /// * '.5', or, equivalently, '0.5'
1425 /// * '+inf', 'inf', '-inf', 'NaN'
1427 /// Leading and trailing whitespace represent an error.
1431 /// * src - A string
1435 /// `None` if the string did not represent a valid number. Otherwise,
1436 /// `Some(n)` where `n` is the floating-point number represented by `src`.
1438 fn from_str(src: &str) -> Option<$T> {
1439 from_str_radix(src, 10)
1443 #[experimental = "might need to return Result"]
1444 impl FromStrRadix for $T {
1445 /// Convert a string in a given base to a float.
1447 /// Due to possible conflicts, this function does **not** accept
1448 /// the special values `inf`, `-inf`, `+inf` and `NaN`, **nor**
1449 /// does it recognize exponents of any kind.
1451 /// Leading and trailing whitespace represent an error.
1455 /// * src - A string
1456 /// * radix - The base to use. Must lie in the range [2 .. 36]
1460 /// `None` if the string did not represent a valid number. Otherwise,
1461 /// `Some(n)` where `n` is the floating-point number represented by `src`.
1462 fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
1463 assert!(radix >= 2 && radix <= 36,
1464 "from_str_radix_float: must lie in the range `[2, 36]` - found {}",
1469 "inf" => return Some(Float::infinity()),
1470 "-inf" => return Some(Float::neg_infinity()),
1471 "NaN" => return Some(Float::nan()),
1475 let (is_positive, src) = match src.slice_shift_char() {
1476 None => return None,
1477 Some(('-', "")) => return None,
1478 Some(('-', src)) => (false, src),
1479 Some((_, _)) => (true, src),
1482 // The significand to accumulate
1483 let mut sig = if is_positive { 0.0 } else { -0.0 };
1484 // Necessary to detect overflow
1485 let mut prev_sig = sig;
1486 let mut cs = src.chars().enumerate();
1487 // Exponent prefix and exponent index offset
1488 let mut exp_info = None::<(char, uint)>;
1490 // Parse the integer part of the significand
1492 match c.to_digit(radix) {
1494 // shift significand one digit left
1495 sig = sig * (radix as $T);
1497 // add/subtract current digit depending on sign
1499 sig = sig + ((digit as int) as $T);
1501 sig = sig - ((digit as int) as $T);
1504 // Detect overflow by comparing to last value, except
1505 // if we've not seen any non-zero digits.
1506 if prev_sig != 0.0 {
1507 if is_positive && sig <= prev_sig
1508 { return Some(Float::infinity()); }
1509 if !is_positive && sig >= prev_sig
1510 { return Some(Float::neg_infinity()); }
1512 // Detect overflow by reversing the shift-and-add process
1513 if is_positive && (prev_sig != (sig - digit as $T) / radix as $T)
1514 { return Some(Float::infinity()); }
1515 if !is_positive && (prev_sig != (sig + digit as $T) / radix as $T)
1516 { return Some(Float::neg_infinity()); }
1521 'e' | 'E' | 'p' | 'P' => {
1522 exp_info = Some((c, i + 1));
1523 break; // start of exponent
1526 break; // start of fractional part
1535 // If we are not yet at the exponent parse the fractional
1536 // part of the significand
1537 if exp_info.is_none() {
1538 let mut power = 1.0;
1540 match c.to_digit(radix) {
1542 // Decrease power one order of magnitude
1543 power = power / (radix as $T);
1544 // add/subtract current digit depending on sign
1545 sig = if is_positive {
1546 sig + (digit as $T) * power
1548 sig - (digit as $T) * power
1550 // Detect overflow by comparing to last value
1551 if is_positive && sig < prev_sig
1552 { return Some(Float::infinity()); }
1553 if !is_positive && sig > prev_sig
1554 { return Some(Float::neg_infinity()); }
1558 'e' | 'E' | 'p' | 'P' => {
1559 exp_info = Some((c, i + 1));
1560 break; // start of exponent
1563 return None; // invalid number
1570 // Parse and calculate the exponent
1571 let exp = match exp_info {
1572 Some((c, offset)) => {
1573 let base = match c {
1574 'E' | 'e' if radix == 10 => 10u as $T,
1575 'P' | 'p' if radix == 16 => 2u as $T,
1579 // Parse the exponent as decimal integer
1580 let src = src.index(&(offset..));
1581 let (is_positive, exp) = match src.slice_shift_char() {
1582 Some(('-', src)) => (false, src.parse::<uint>()),
1583 Some(('+', src)) => (true, src.parse::<uint>()),
1584 Some((_, _)) => (true, src.parse::<uint>()),
1585 None => return None,
1588 match (is_positive, exp) {
1589 (true, Some(exp)) => base.powi(exp as i32),
1590 (false, Some(exp)) => 1.0 / base.powi(exp as i32),
1591 (_, None) => return None,
1594 None => 1.0, // no exponent
1602 from_str_radix_float_impl! { f32 }
1603 from_str_radix_float_impl! { f64 }
1605 macro_rules! from_str_radix_int_impl {
1607 #[experimental = "might need to return Result"]
1608 impl FromStr for $T {
1610 fn from_str(src: &str) -> Option<$T> {
1611 from_str_radix(src, 10)
1615 #[experimental = "might need to return Result"]
1616 impl FromStrRadix for $T {
1617 fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
1618 assert!(radix >= 2 && radix <= 36,
1619 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1622 let is_signed_ty = (0 as $T) > Int::min_value();
1624 match src.slice_shift_char() {
1625 Some(('-', src)) if is_signed_ty => {
1626 // The number is negative
1628 for c in src.chars() {
1629 let x = match c.to_digit(radix) {
1631 None => return None,
1633 result = match result.checked_mul(radix as $T) {
1634 Some(result) => result,
1635 None => return None,
1637 result = match result.checked_sub(x as $T) {
1638 Some(result) => result,
1639 None => return None,
1645 // The number is signed
1647 for c in src.chars() {
1648 let x = match c.to_digit(radix) {
1650 None => return None,
1652 result = match result.checked_mul(radix as $T) {
1653 Some(result) => result,
1654 None => return None,
1656 result = match result.checked_add(x as $T) {
1657 Some(result) => result,
1658 None => return None,
1669 from_str_radix_int_impl! { int }
1670 from_str_radix_int_impl! { i8 }
1671 from_str_radix_int_impl! { i16 }
1672 from_str_radix_int_impl! { i32 }
1673 from_str_radix_int_impl! { i64 }
1674 from_str_radix_int_impl! { uint }
1675 from_str_radix_int_impl! { u8 }
1676 from_str_radix_int_impl! { u16 }
1677 from_str_radix_int_impl! { u32 }
1678 from_str_radix_int_impl! { u64 }