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};
29 use option::Option::{Some, None};
30 use str::{FromStr, StrExt};
32 /// A built-in signed or unsigned integer.
33 #[unstable = "recently settled as part of numerics reform"]
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
55 /// Returns the `1` value of this integer type.
56 // FIXME (#5527): Should be an associated constant
59 /// Returns the smallest value that can be represented by this integer type.
60 // FIXME (#5527): Should be and associated constant
61 fn min_value() -> Self;
63 /// Returns the largest value that can be represented by this integer type.
64 // FIXME (#5527): Should be and associated constant
65 fn max_value() -> Self;
67 /// Returns the number of ones in the binary representation of `self`.
72 /// use std::num::Int;
74 /// let n = 0b01001100u8;
76 /// assert_eq!(n.count_ones(), 3);
78 fn count_ones(self) -> uint;
80 /// Returns the number of zeros in the binary representation of `self`.
85 /// use std::num::Int;
87 /// let n = 0b01001100u8;
89 /// assert_eq!(n.count_zeros(), 5);
92 fn count_zeros(self) -> uint {
96 /// Returns the number of leading zeros in the binary representation
102 /// use std::num::Int;
104 /// let n = 0b0101000u16;
106 /// assert_eq!(n.leading_zeros(), 10);
108 fn leading_zeros(self) -> uint;
110 /// Returns the number of trailing zeros in the binary representation
116 /// use std::num::Int;
118 /// let n = 0b0101000u16;
120 /// assert_eq!(n.trailing_zeros(), 3);
122 fn trailing_zeros(self) -> uint;
124 /// Shifts the bits to the left by a specified amount amount, `n`, wrapping
125 /// the truncated bits to the end of the resulting integer.
130 /// use std::num::Int;
132 /// let n = 0x0123456789ABCDEFu64;
133 /// let m = 0x3456789ABCDEF012u64;
135 /// assert_eq!(n.rotate_left(12), m);
137 fn rotate_left(self, n: uint) -> Self;
139 /// Shifts the bits to the right by a specified amount amount, `n`, wrapping
140 /// the truncated bits to the beginning of the resulting integer.
145 /// use std::num::Int;
147 /// let n = 0x0123456789ABCDEFu64;
148 /// let m = 0xDEF0123456789ABCu64;
150 /// assert_eq!(n.rotate_right(12), m);
152 fn rotate_right(self, n: uint) -> Self;
154 /// Reverses the byte order of the integer.
159 /// use std::num::Int;
161 /// let n = 0x0123456789ABCDEFu64;
162 /// let m = 0xEFCDAB8967452301u64;
164 /// assert_eq!(n.swap_bytes(), m);
166 fn swap_bytes(self) -> Self;
168 /// Convert an integer from big endian to the target's endianness.
170 /// On big endian this is a no-op. On little endian the bytes are swapped.
175 /// use std::num::Int;
177 /// let n = 0x0123456789ABCDEFu64;
179 /// if cfg!(target_endian = "big") {
180 /// assert_eq!(Int::from_be(n), n)
182 /// assert_eq!(Int::from_be(n), n.swap_bytes())
186 fn from_be(x: Self) -> Self {
187 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
190 /// Convert an integer from little endian to the target's endianness.
192 /// On little endian this is a no-op. On big endian the bytes are swapped.
197 /// use std::num::Int;
199 /// let n = 0x0123456789ABCDEFu64;
201 /// if cfg!(target_endian = "little") {
202 /// assert_eq!(Int::from_le(n), n)
204 /// assert_eq!(Int::from_le(n), n.swap_bytes())
208 fn from_le(x: Self) -> Self {
209 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
212 /// Convert `self` to big endian from the target's endianness.
214 /// On big endian this is a no-op. On little endian the bytes are swapped.
219 /// use std::num::Int;
221 /// let n = 0x0123456789ABCDEFu64;
223 /// if cfg!(target_endian = "big") {
224 /// assert_eq!(n.to_be(), n)
226 /// assert_eq!(n.to_be(), n.swap_bytes())
230 fn to_be(self) -> Self { // or not to be?
231 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
234 /// Convert `self` to little endian from the target's endianness.
236 /// On little endian this is a no-op. On big endian the bytes are swapped.
241 /// use std::num::Int;
243 /// let n = 0x0123456789ABCDEFu64;
245 /// if cfg!(target_endian = "little") {
246 /// assert_eq!(n.to_le(), n)
248 /// assert_eq!(n.to_le(), n.swap_bytes())
252 fn to_le(self) -> Self {
253 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
256 /// Checked integer addition. Computes `self + other`, returning `None` if
257 /// overflow occurred.
262 /// use std::num::Int;
264 /// assert_eq!(5u16.checked_add(65530), Some(65535));
265 /// assert_eq!(6u16.checked_add(65530), None);
267 fn checked_add(self, other: Self) -> Option<Self>;
269 /// Checked integer subtraction. Computes `self - other`, returning `None`
270 /// if underflow occurred.
275 /// use std::num::Int;
277 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
278 /// assert_eq!((-128i8).checked_sub(1), None);
280 fn checked_sub(self, other: Self) -> Option<Self>;
282 /// Checked integer multiplication. Computes `self * other`, returning
283 /// `None` if underflow or overflow occurred.
288 /// use std::num::Int;
290 /// assert_eq!(5u8.checked_mul(51), Some(255));
291 /// assert_eq!(5u8.checked_mul(52), None);
293 fn checked_mul(self, other: Self) -> Option<Self>;
295 /// Checked integer division. Computes `self / other`, returning `None` if
296 /// `other == 0` or the operation results in underflow or overflow.
301 /// use std::num::Int;
303 /// assert_eq!((-127i8).checked_div(-1), Some(127));
304 /// assert_eq!((-128i8).checked_div(-1), None);
305 /// assert_eq!((1i8).checked_div(0), None);
308 fn checked_div(self, other: Self) -> Option<Self>;
310 /// Saturating integer addition. Computes `self + other`, saturating at
311 /// the numeric bounds instead of overflowing.
313 fn saturating_add(self, other: Self) -> Self {
314 match self.checked_add(other) {
316 None if other >= Int::zero() => Int::max_value(),
317 None => Int::min_value(),
321 /// Saturating integer subtraction. Computes `self - other`, saturating at
322 /// the numeric bounds instead of overflowing.
324 fn saturating_sub(self, other: Self) -> Self {
325 match self.checked_sub(other) {
327 None if other >= Int::zero() => Int::min_value(),
328 None => Int::max_value(),
332 /// Raises self to the power of `exp`, using exponentiation by squaring.
337 /// use std::num::Int;
339 /// assert_eq!(2i.pow(4), 16);
342 fn pow(self, mut exp: uint) -> Self {
344 let mut acc: Self = Int::one();
356 macro_rules! checked_op {
357 ($T:ty, $U:ty, $op:path, $x:expr, $y:expr) => {{
358 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
359 if overflowed { None } else { Some(result as $T) }
363 macro_rules! uint_impl {
364 ($T:ty = $ActualT:ty, $BITS:expr,
369 $add_with_overflow:path,
370 $sub_with_overflow:path,
371 $mul_with_overflow:path) => {
372 #[unstable = "trait is unstable"]
375 fn zero() -> $T { 0 }
381 fn min_value() -> $T { 0 }
384 fn max_value() -> $T { -1 }
387 fn count_ones(self) -> uint { unsafe { $ctpop(self as $ActualT) as uint } }
390 fn leading_zeros(self) -> uint { unsafe { $ctlz(self as $ActualT) as uint } }
393 fn trailing_zeros(self) -> uint { unsafe { $cttz(self as $ActualT) as uint } }
396 fn rotate_left(self, n: uint) -> $T {
397 // Protect against undefined behaviour for over-long bit shifts
399 (self << n) | (self >> (($BITS - n) % $BITS))
403 fn rotate_right(self, n: uint) -> $T {
404 // Protect against undefined behaviour for over-long bit shifts
406 (self >> n) | (self << (($BITS - n) % $BITS))
410 fn swap_bytes(self) -> $T { unsafe { $bswap(self as $ActualT) as $T } }
413 fn checked_add(self, other: $T) -> Option<$T> {
414 checked_op!($T, $ActualT, $add_with_overflow, self, other)
418 fn checked_sub(self, other: $T) -> Option<$T> {
419 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
423 fn checked_mul(self, other: $T) -> Option<$T> {
424 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
428 fn checked_div(self, v: $T) -> Option<$T> {
438 /// Swapping a single byte is a no-op. This is marked as `unsafe` for
439 /// consistency with the other `bswap` intrinsics.
440 unsafe fn bswap8(x: u8) -> u8 { x }
442 uint_impl! { u8 = u8, 8,
447 intrinsics::u8_add_with_overflow,
448 intrinsics::u8_sub_with_overflow,
449 intrinsics::u8_mul_with_overflow }
451 uint_impl! { u16 = u16, 16,
456 intrinsics::u16_add_with_overflow,
457 intrinsics::u16_sub_with_overflow,
458 intrinsics::u16_mul_with_overflow }
460 uint_impl! { u32 = u32, 32,
465 intrinsics::u32_add_with_overflow,
466 intrinsics::u32_sub_with_overflow,
467 intrinsics::u32_mul_with_overflow }
469 uint_impl! { u64 = u64, 64,
474 intrinsics::u64_add_with_overflow,
475 intrinsics::u64_sub_with_overflow,
476 intrinsics::u64_mul_with_overflow }
478 #[cfg(target_word_size = "32")]
479 uint_impl! { uint = u32, 32,
484 intrinsics::u32_add_with_overflow,
485 intrinsics::u32_sub_with_overflow,
486 intrinsics::u32_mul_with_overflow }
488 #[cfg(target_word_size = "64")]
489 uint_impl! { uint = u64, 64,
494 intrinsics::u64_add_with_overflow,
495 intrinsics::u64_sub_with_overflow,
496 intrinsics::u64_mul_with_overflow }
498 macro_rules! int_impl {
499 ($T:ty = $ActualT:ty, $UnsignedT:ty, $BITS:expr,
500 $add_with_overflow:path,
501 $sub_with_overflow:path,
502 $mul_with_overflow:path) => {
503 #[unstable = "trait is unstable"]
506 fn zero() -> $T { 0 }
512 fn min_value() -> $T { (-1 as $T) << ($BITS - 1) }
515 fn max_value() -> $T { let min: $T = Int::min_value(); !min }
518 fn count_ones(self) -> uint { (self as $UnsignedT).count_ones() }
521 fn leading_zeros(self) -> uint { (self as $UnsignedT).leading_zeros() }
524 fn trailing_zeros(self) -> uint { (self as $UnsignedT).trailing_zeros() }
527 fn rotate_left(self, n: uint) -> $T { (self as $UnsignedT).rotate_left(n) as $T }
530 fn rotate_right(self, n: uint) -> $T { (self as $UnsignedT).rotate_right(n) as $T }
533 fn swap_bytes(self) -> $T { (self as $UnsignedT).swap_bytes() as $T }
536 fn checked_add(self, other: $T) -> Option<$T> {
537 checked_op!($T, $ActualT, $add_with_overflow, self, other)
541 fn checked_sub(self, other: $T) -> Option<$T> {
542 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
546 fn checked_mul(self, other: $T) -> Option<$T> {
547 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
551 fn checked_div(self, v: $T) -> Option<$T> {
554 -1 if self == Int::min_value()
563 int_impl! { i8 = i8, u8, 8,
564 intrinsics::i8_add_with_overflow,
565 intrinsics::i8_sub_with_overflow,
566 intrinsics::i8_mul_with_overflow }
568 int_impl! { i16 = i16, u16, 16,
569 intrinsics::i16_add_with_overflow,
570 intrinsics::i16_sub_with_overflow,
571 intrinsics::i16_mul_with_overflow }
573 int_impl! { i32 = i32, u32, 32,
574 intrinsics::i32_add_with_overflow,
575 intrinsics::i32_sub_with_overflow,
576 intrinsics::i32_mul_with_overflow }
578 int_impl! { i64 = i64, u64, 64,
579 intrinsics::i64_add_with_overflow,
580 intrinsics::i64_sub_with_overflow,
581 intrinsics::i64_mul_with_overflow }
583 #[cfg(target_word_size = "32")]
584 int_impl! { int = i32, u32, 32,
585 intrinsics::i32_add_with_overflow,
586 intrinsics::i32_sub_with_overflow,
587 intrinsics::i32_mul_with_overflow }
589 #[cfg(target_word_size = "64")]
590 int_impl! { int = i64, u64, 64,
591 intrinsics::i64_add_with_overflow,
592 intrinsics::i64_sub_with_overflow,
593 intrinsics::i64_mul_with_overflow }
595 /// A built-in two's complement integer.
596 #[unstable = "recently settled as part of numerics reform"]
601 /// Computes the absolute value of `self`. `Int::min_value()` will be
602 /// returned if the number is `Int::min_value()`.
603 fn abs(self) -> Self;
605 /// Returns a number representing sign of `self`.
607 /// - `0` if the number is zero
608 /// - `1` if the number is positive
609 /// - `-1` if the number is negative
610 fn signum(self) -> Self;
612 /// Returns `true` if `self` is positive and `false` if the number
613 /// is zero or negative.
614 fn is_positive(self) -> bool;
616 /// Returns `true` if `self` is negative and `false` if the number
617 /// is zero or positive.
618 fn is_negative(self) -> bool;
621 macro_rules! signed_int_impl {
623 impl SignedInt for $T {
626 if self.is_negative() { -self } else { self }
630 fn signum(self) -> $T {
639 fn is_positive(self) -> bool { self > 0 }
642 fn is_negative(self) -> bool { self < 0 }
647 signed_int_impl! { i8 }
648 signed_int_impl! { i16 }
649 signed_int_impl! { i32 }
650 signed_int_impl! { i64 }
651 signed_int_impl! { int }
653 /// A built-in unsigned integer.
654 #[unstable = "recently settled as part of numerics reform"]
655 pub trait UnsignedInt: Int {
656 /// Returns `true` iff `self == 2^k` for some `k`.
658 fn is_power_of_two(self) -> bool {
659 (self - Int::one()) & self == Int::zero() && !(self == Int::zero())
662 /// Returns the smallest power of two greater than or equal to `self`.
663 /// Unspecified behavior on overflow.
665 fn next_power_of_two(self) -> Self {
666 let bits = size_of::<Self>() * 8;
667 let one: Self = Int::one();
668 one << ((bits - (self - one).leading_zeros()) % bits)
671 /// Returns the smallest power of two greater than or equal to `n`. If the
672 /// next power of two is greater than the type's maximum value, `None` is
673 /// returned, otherwise the power of two is wrapped in `Some`.
674 fn checked_next_power_of_two(self) -> Option<Self> {
675 let npot = self.next_power_of_two();
684 #[unstable = "trait is unstable"]
685 impl UnsignedInt for uint {}
687 #[unstable = "trait is unstable"]
688 impl UnsignedInt for u8 {}
690 #[unstable = "trait is unstable"]
691 impl UnsignedInt for u16 {}
693 #[unstable = "trait is unstable"]
694 impl UnsignedInt for u32 {}
696 #[unstable = "trait is unstable"]
697 impl UnsignedInt for u64 {}
699 /// A generic trait for converting a value to a number.
700 #[experimental = "trait is likely to be removed"]
701 pub trait ToPrimitive {
702 /// Converts the value of `self` to an `int`.
704 fn to_int(&self) -> Option<int> {
705 self.to_i64().and_then(|x| x.to_int())
708 /// Converts the value of `self` to an `i8`.
710 fn to_i8(&self) -> Option<i8> {
711 self.to_i64().and_then(|x| x.to_i8())
714 /// Converts the value of `self` to an `i16`.
716 fn to_i16(&self) -> Option<i16> {
717 self.to_i64().and_then(|x| x.to_i16())
720 /// Converts the value of `self` to an `i32`.
722 fn to_i32(&self) -> Option<i32> {
723 self.to_i64().and_then(|x| x.to_i32())
726 /// Converts the value of `self` to an `i64`.
727 fn to_i64(&self) -> Option<i64>;
729 /// Converts the value of `self` to an `uint`.
731 fn to_uint(&self) -> Option<uint> {
732 self.to_u64().and_then(|x| x.to_uint())
735 /// Converts the value of `self` to an `u8`.
737 fn to_u8(&self) -> Option<u8> {
738 self.to_u64().and_then(|x| x.to_u8())
741 /// Converts the value of `self` to an `u16`.
743 fn to_u16(&self) -> Option<u16> {
744 self.to_u64().and_then(|x| x.to_u16())
747 /// Converts the value of `self` to an `u32`.
749 fn to_u32(&self) -> Option<u32> {
750 self.to_u64().and_then(|x| x.to_u32())
753 /// Converts the value of `self` to an `u64`.
755 fn to_u64(&self) -> Option<u64>;
757 /// Converts the value of `self` to an `f32`.
759 fn to_f32(&self) -> Option<f32> {
760 self.to_f64().and_then(|x| x.to_f32())
763 /// Converts the value of `self` to an `f64`.
765 fn to_f64(&self) -> Option<f64> {
766 self.to_i64().and_then(|x| x.to_f64())
770 macro_rules! impl_to_primitive_int_to_int {
771 ($SrcT:ty, $DstT:ty, $slf:expr) => (
773 if size_of::<$SrcT>() <= size_of::<$DstT>() {
777 let min_value: $DstT = Int::min_value();
778 let max_value: $DstT = Int::max_value();
779 if min_value as i64 <= n && n <= max_value as i64 {
789 macro_rules! impl_to_primitive_int_to_uint {
790 ($SrcT:ty, $DstT:ty, $slf:expr) => (
792 let zero: $SrcT = Int::zero();
793 let max_value: $DstT = Int::max_value();
794 if zero <= $slf && $slf as u64 <= max_value as u64 {
803 macro_rules! impl_to_primitive_int {
805 impl ToPrimitive for $T {
807 fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int, *self) }
809 fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) }
811 fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) }
813 fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32, *self) }
815 fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self) }
818 fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint, *self) }
820 fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) }
822 fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) }
824 fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32, *self) }
826 fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64, *self) }
829 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
831 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
836 impl_to_primitive_int! { int }
837 impl_to_primitive_int! { i8 }
838 impl_to_primitive_int! { i16 }
839 impl_to_primitive_int! { i32 }
840 impl_to_primitive_int! { i64 }
842 macro_rules! impl_to_primitive_uint_to_int {
843 ($DstT:ty, $slf:expr) => (
845 let max_value: $DstT = Int::max_value();
846 if $slf as u64 <= max_value as u64 {
855 macro_rules! impl_to_primitive_uint_to_uint {
856 ($SrcT:ty, $DstT:ty, $slf:expr) => (
858 if size_of::<$SrcT>() <= size_of::<$DstT>() {
861 let zero: $SrcT = Int::zero();
862 let max_value: $DstT = Int::max_value();
863 if zero <= $slf && $slf as u64 <= max_value as u64 {
873 macro_rules! impl_to_primitive_uint {
875 impl ToPrimitive for $T {
877 fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int, *self) }
879 fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) }
881 fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) }
883 fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32, *self) }
885 fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) }
888 fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint, *self) }
890 fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) }
892 fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) }
894 fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32, *self) }
896 fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64, *self) }
899 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
901 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
906 impl_to_primitive_uint! { uint }
907 impl_to_primitive_uint! { u8 }
908 impl_to_primitive_uint! { u16 }
909 impl_to_primitive_uint! { u32 }
910 impl_to_primitive_uint! { u64 }
912 macro_rules! impl_to_primitive_float_to_float {
913 ($SrcT:ty, $DstT:ty, $slf:expr) => (
914 if size_of::<$SrcT>() <= size_of::<$DstT>() {
918 let max_value: $SrcT = Float::max_value();
919 if -max_value as f64 <= n && n <= max_value as f64 {
928 macro_rules! impl_to_primitive_float {
930 impl ToPrimitive for $T {
932 fn to_int(&self) -> Option<int> { Some(*self as int) }
934 fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
936 fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
938 fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
940 fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
943 fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
945 fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
947 fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
949 fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
951 fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
954 fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32, *self) }
956 fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64, *self) }
961 impl_to_primitive_float! { f32 }
962 impl_to_primitive_float! { f64 }
964 /// A generic trait for converting a number to a value.
965 #[experimental = "trait is likely to be removed"]
966 pub trait FromPrimitive : ::kinds::Sized {
967 /// Convert an `int` to return an optional value of this type. If the
968 /// value cannot be represented by this value, the `None` is returned.
970 fn from_int(n: int) -> Option<Self> {
971 FromPrimitive::from_i64(n as i64)
974 /// Convert an `i8` to return an optional value of this type. If the
975 /// type cannot be represented by this value, the `None` is returned.
977 fn from_i8(n: i8) -> Option<Self> {
978 FromPrimitive::from_i64(n as i64)
981 /// Convert an `i16` to return an optional value of this type. If the
982 /// type cannot be represented by this value, the `None` is returned.
984 fn from_i16(n: i16) -> Option<Self> {
985 FromPrimitive::from_i64(n as i64)
988 /// Convert an `i32` to return an optional value of this type. If the
989 /// type cannot be represented by this value, the `None` is returned.
991 fn from_i32(n: i32) -> Option<Self> {
992 FromPrimitive::from_i64(n as i64)
995 /// Convert an `i64` to return an optional value of this type. If the
996 /// type cannot be represented by this value, the `None` is returned.
997 fn from_i64(n: i64) -> Option<Self>;
999 /// Convert an `uint` to return an optional value of this type. If the
1000 /// type cannot be represented by this value, the `None` is returned.
1002 fn from_uint(n: uint) -> Option<Self> {
1003 FromPrimitive::from_u64(n as u64)
1006 /// Convert an `u8` to return an optional value of this type. If the
1007 /// type cannot be represented by this value, the `None` is returned.
1009 fn from_u8(n: u8) -> Option<Self> {
1010 FromPrimitive::from_u64(n as u64)
1013 /// Convert an `u16` to return an optional value of this type. If the
1014 /// type cannot be represented by this value, the `None` is returned.
1016 fn from_u16(n: u16) -> Option<Self> {
1017 FromPrimitive::from_u64(n as u64)
1020 /// Convert an `u32` to return an optional value of this type. If the
1021 /// type cannot be represented by this value, the `None` is returned.
1023 fn from_u32(n: u32) -> Option<Self> {
1024 FromPrimitive::from_u64(n as u64)
1027 /// Convert an `u64` to return an optional value of this type. If the
1028 /// type cannot be represented by this value, the `None` is returned.
1029 fn from_u64(n: u64) -> Option<Self>;
1031 /// Convert a `f32` to return an optional value of this type. If the
1032 /// type cannot be represented by this value, the `None` is returned.
1034 fn from_f32(n: f32) -> Option<Self> {
1035 FromPrimitive::from_f64(n as f64)
1038 /// Convert a `f64` to return an optional value of this type. If the
1039 /// type cannot be represented by this value, the `None` is returned.
1041 fn from_f64(n: f64) -> Option<Self> {
1042 FromPrimitive::from_i64(n as i64)
1046 /// A utility function that just calls `FromPrimitive::from_int`.
1047 #[experimental = "likely to be removed"]
1048 pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
1049 FromPrimitive::from_int(n)
1052 /// A utility function that just calls `FromPrimitive::from_i8`.
1053 #[experimental = "likely to be removed"]
1054 pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> {
1055 FromPrimitive::from_i8(n)
1058 /// A utility function that just calls `FromPrimitive::from_i16`.
1059 #[experimental = "likely to be removed"]
1060 pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> {
1061 FromPrimitive::from_i16(n)
1064 /// A utility function that just calls `FromPrimitive::from_i32`.
1065 #[experimental = "likely to be removed"]
1066 pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> {
1067 FromPrimitive::from_i32(n)
1070 /// A utility function that just calls `FromPrimitive::from_i64`.
1071 #[experimental = "likely to be removed"]
1072 pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
1073 FromPrimitive::from_i64(n)
1076 /// A utility function that just calls `FromPrimitive::from_uint`.
1077 #[experimental = "likely to be removed"]
1078 pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
1079 FromPrimitive::from_uint(n)
1082 /// A utility function that just calls `FromPrimitive::from_u8`.
1083 #[experimental = "likely to be removed"]
1084 pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> {
1085 FromPrimitive::from_u8(n)
1088 /// A utility function that just calls `FromPrimitive::from_u16`.
1089 #[experimental = "likely to be removed"]
1090 pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> {
1091 FromPrimitive::from_u16(n)
1094 /// A utility function that just calls `FromPrimitive::from_u32`.
1095 #[experimental = "likely to be removed"]
1096 pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> {
1097 FromPrimitive::from_u32(n)
1100 /// A utility function that just calls `FromPrimitive::from_u64`.
1101 #[experimental = "likely to be removed"]
1102 pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> {
1103 FromPrimitive::from_u64(n)
1106 /// A utility function that just calls `FromPrimitive::from_f32`.
1107 #[experimental = "likely to be removed"]
1108 pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> {
1109 FromPrimitive::from_f32(n)
1112 /// A utility function that just calls `FromPrimitive::from_f64`.
1113 #[experimental = "likely to be removed"]
1114 pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {
1115 FromPrimitive::from_f64(n)
1118 macro_rules! impl_from_primitive {
1119 ($T:ty, $to_ty:ident) => (
1120 impl FromPrimitive for $T {
1121 #[inline] fn from_int(n: int) -> Option<$T> { n.$to_ty() }
1122 #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() }
1123 #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() }
1124 #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() }
1125 #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() }
1127 #[inline] fn from_uint(n: uint) -> Option<$T> { n.$to_ty() }
1128 #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() }
1129 #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() }
1130 #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() }
1131 #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() }
1133 #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() }
1134 #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() }
1139 impl_from_primitive! { int, to_int }
1140 impl_from_primitive! { i8, to_i8 }
1141 impl_from_primitive! { i16, to_i16 }
1142 impl_from_primitive! { i32, to_i32 }
1143 impl_from_primitive! { i64, to_i64 }
1144 impl_from_primitive! { uint, to_uint }
1145 impl_from_primitive! { u8, to_u8 }
1146 impl_from_primitive! { u16, to_u16 }
1147 impl_from_primitive! { u32, to_u32 }
1148 impl_from_primitive! { u64, to_u64 }
1149 impl_from_primitive! { f32, to_f32 }
1150 impl_from_primitive! { f64, to_f64 }
1152 /// Cast from one machine scalar to another.
1159 /// let twenty: f32 = num::cast(0x14i).unwrap();
1160 /// assert_eq!(twenty, 20f32);
1164 #[experimental = "likely to be removed"]
1165 pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
1169 /// An interface for casting between machine scalars.
1170 #[experimental = "trait is likely to be removed"]
1171 pub trait NumCast: ToPrimitive {
1172 /// Creates a number from another value that can be converted into a primitive via the
1173 /// `ToPrimitive` trait.
1174 fn from<T: ToPrimitive>(n: T) -> Option<Self>;
1177 macro_rules! impl_num_cast {
1178 ($T:ty, $conv:ident) => (
1179 impl NumCast for $T {
1181 fn from<N: ToPrimitive>(n: N) -> Option<$T> {
1182 // `$conv` could be generated using `concat_idents!`, but that
1183 // macro seems to be broken at the moment
1190 impl_num_cast! { u8, to_u8 }
1191 impl_num_cast! { u16, to_u16 }
1192 impl_num_cast! { u32, to_u32 }
1193 impl_num_cast! { u64, to_u64 }
1194 impl_num_cast! { uint, to_uint }
1195 impl_num_cast! { i8, to_i8 }
1196 impl_num_cast! { i16, to_i16 }
1197 impl_num_cast! { i32, to_i32 }
1198 impl_num_cast! { i64, to_i64 }
1199 impl_num_cast! { int, to_int }
1200 impl_num_cast! { f32, to_f32 }
1201 impl_num_cast! { f64, to_f64 }
1203 /// Used for representing the classification of floating point numbers
1204 #[derive(Copy, PartialEq, Show)]
1205 #[unstable = "may be renamed"]
1206 pub enum FpCategory {
1207 /// "Not a Number", often obtained by dividing by zero
1209 /// Positive or negative infinity
1211 /// Positive or negative zero
1213 /// De-normalized floating point representation (less precise than `Normal`)
1215 /// A regular floating point number
1219 /// A built-in floating point number.
1220 // FIXME(#5527): In a future version of Rust, many of these functions will
1221 // become constants.
1223 // FIXME(#8888): Several of these functions have a parameter named
1224 // `unused_self`. Removing it requires #8888 to be fixed.
1225 #[unstable = "recently settled as part of numerics reform"]
1238 /// Returns the NaN value.
1240 /// Returns the infinite value.
1241 fn infinity() -> Self;
1242 /// Returns the negative infinite value.
1243 fn neg_infinity() -> Self;
1244 /// Returns the `0` value.
1247 fn neg_zero() -> Self;
1248 /// Returns the `1` value.
1251 /// Returns true if this value is NaN and false otherwise.
1252 fn is_nan(self) -> bool;
1253 /// Returns true if this value is positive infinity or negative infinity and
1254 /// false otherwise.
1255 fn is_infinite(self) -> bool;
1256 /// Returns true if this number is neither infinite nor NaN.
1257 fn is_finite(self) -> bool;
1258 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1259 fn is_normal(self) -> bool;
1260 /// Returns the category that this number falls into.
1261 fn classify(self) -> FpCategory;
1263 // FIXME (#5527): These should be associated constants
1265 /// Returns the number of binary digits of mantissa that this type supports.
1266 fn mantissa_digits(unused_self: Option<Self>) -> uint;
1267 /// Returns the number of base-10 digits of precision that this type supports.
1268 fn digits(unused_self: Option<Self>) -> uint;
1269 /// Returns the difference between 1.0 and the smallest representable number larger than 1.0.
1270 fn epsilon() -> Self;
1271 /// Returns the minimum binary exponent that this type can represent.
1272 fn min_exp(unused_self: Option<Self>) -> int;
1273 /// Returns the maximum binary exponent that this type can represent.
1274 fn max_exp(unused_self: Option<Self>) -> int;
1275 /// Returns the minimum base-10 exponent that this type can represent.
1276 fn min_10_exp(unused_self: Option<Self>) -> int;
1277 /// Returns the maximum base-10 exponent that this type can represent.
1278 fn max_10_exp(unused_self: Option<Self>) -> int;
1279 /// Returns the smallest finite value that this type can represent.
1280 fn min_value() -> Self;
1281 /// Returns the smallest normalized positive number that this type can represent.
1282 fn min_pos_value(unused_self: Option<Self>) -> Self;
1283 /// Returns the largest finite value that this type can represent.
1284 fn max_value() -> Self;
1286 /// Returns the mantissa, exponent and sign as integers, respectively.
1287 fn integer_decode(self) -> (u64, i16, i8);
1289 /// Return the largest integer less than or equal to a number.
1290 fn floor(self) -> Self;
1291 /// Return the smallest integer greater than or equal to a number.
1292 fn ceil(self) -> Self;
1293 /// Return the nearest integer to a number. Round half-way cases away from
1295 fn round(self) -> Self;
1296 /// Return the integer part of a number.
1297 fn trunc(self) -> Self;
1298 /// Return the fractional part of a number.
1299 fn fract(self) -> Self;
1301 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1302 /// number is `Float::nan()`.
1303 fn abs(self) -> Self;
1304 /// Returns a number that represents the sign of `self`.
1306 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1307 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1308 /// - `Float::nan()` if the number is `Float::nan()`
1309 fn signum(self) -> Self;
1310 /// Returns `true` if `self` is positive, including `+0.0` and
1311 /// `Float::infinity()`.
1312 fn is_positive(self) -> bool;
1313 /// Returns `true` if `self` is negative, including `-0.0` and
1314 /// `Float::neg_infinity()`.
1315 fn is_negative(self) -> bool;
1317 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1318 /// error. This produces a more accurate result with better performance than
1319 /// a separate multiplication operation followed by an add.
1320 fn mul_add(self, a: Self, b: Self) -> Self;
1321 /// Take the reciprocal (inverse) of a number, `1/x`.
1322 fn recip(self) -> Self;
1324 /// Raise a number to an integer power.
1326 /// Using this function is generally faster than using `powf`
1327 fn powi(self, n: i32) -> Self;
1328 /// Raise a number to a floating point power.
1329 fn powf(self, n: Self) -> Self;
1331 /// Take the square root of a number.
1333 /// Returns NaN if `self` is a negative number.
1334 fn sqrt(self) -> Self;
1335 /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1336 fn rsqrt(self) -> Self;
1338 /// Returns `e^(self)`, (the exponential function).
1339 fn exp(self) -> Self;
1340 /// Returns 2 raised to the power of the number, `2^(self)`.
1341 fn exp2(self) -> Self;
1342 /// Returns the natural logarithm of the number.
1343 fn ln(self) -> Self;
1344 /// Returns the logarithm of the number with respect to an arbitrary base.
1345 fn log(self, base: Self) -> Self;
1346 /// Returns the base 2 logarithm of the number.
1347 fn log2(self) -> Self;
1348 /// Returns the base 10 logarithm of the number.
1349 fn log10(self) -> Self;
1351 /// Convert radians to degrees.
1352 fn to_degrees(self) -> Self;
1353 /// Convert degrees to radians.
1354 fn to_radians(self) -> Self;
1357 /// A generic trait for converting a string with a radix (base) to a value
1358 #[experimental = "might need to return Result"]
1359 pub trait FromStrRadix {
1360 fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
1363 /// A utility function that just calls FromStrRadix::from_str_radix.
1364 #[experimental = "might need to return Result"]
1365 pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint) -> Option<T> {
1366 FromStrRadix::from_str_radix(str, radix)
1369 macro_rules! from_str_radix_float_impl {
1371 #[experimental = "might need to return Result"]
1372 impl FromStr for $T {
1373 /// Convert a string in base 10 to a float.
1374 /// Accepts an optional decimal exponent.
1376 /// This function accepts strings such as
1379 /// * '+3.14', equivalent to '3.14'
1381 /// * '2.5E10', or equivalently, '2.5e10'
1383 /// * '.' (understood as 0)
1385 /// * '.5', or, equivalently, '0.5'
1386 /// * '+inf', 'inf', '-inf', 'NaN'
1388 /// Leading and trailing whitespace represent an error.
1392 /// * src - A string
1396 /// `None` if the string did not represent a valid number. Otherwise,
1397 /// `Some(n)` where `n` is the floating-point number represented by `src`.
1399 fn from_str(src: &str) -> Option<$T> {
1400 from_str_radix(src, 10)
1404 #[experimental = "might need to return Result"]
1405 impl FromStrRadix for $T {
1406 /// Convert a string in a given base to a float.
1408 /// Due to possible conflicts, this function does **not** accept
1409 /// the special values `inf`, `-inf`, `+inf` and `NaN`, **nor**
1410 /// does it recognize exponents of any kind.
1412 /// Leading and trailing whitespace represent an error.
1416 /// * src - A string
1417 /// * radix - The base to use. Must lie in the range [2 .. 36]
1421 /// `None` if the string did not represent a valid number. Otherwise,
1422 /// `Some(n)` where `n` is the floating-point number represented by `src`.
1423 fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
1424 assert!(radix >= 2 && radix <= 36,
1425 "from_str_radix_float: must lie in the range `[2, 36]` - found {}",
1430 "inf" => return Some(Float::infinity()),
1431 "-inf" => return Some(Float::neg_infinity()),
1432 "NaN" => return Some(Float::nan()),
1436 let (is_positive, src) = match src.slice_shift_char() {
1437 None => return None,
1438 Some(('-', "")) => return None,
1439 Some(('-', src)) => (false, src),
1440 Some((_, _)) => (true, src),
1443 // The significand to accumulate
1444 let mut sig = if is_positive { 0.0 } else { -0.0 };
1445 // Necessary to detect overflow
1446 let mut prev_sig = sig;
1447 let mut cs = src.chars().enumerate();
1448 // Exponent prefix and exponent index offset
1449 let mut exp_info = None::<(char, uint)>;
1451 // Parse the integer part of the significand
1453 match c.to_digit(radix) {
1455 // shift significand one digit left
1456 sig = sig * (radix as $T);
1458 // add/subtract current digit depending on sign
1460 sig = sig + ((digit as int) as $T);
1462 sig = sig - ((digit as int) as $T);
1465 // Detect overflow by comparing to last value, except
1466 // if we've not seen any non-zero digits.
1467 if prev_sig != 0.0 {
1468 if is_positive && sig <= prev_sig
1469 { return Some(Float::infinity()); }
1470 if !is_positive && sig >= prev_sig
1471 { return Some(Float::neg_infinity()); }
1473 // Detect overflow by reversing the shift-and-add process
1474 if is_positive && (prev_sig != (sig - digit as $T) / radix as $T)
1475 { return Some(Float::infinity()); }
1476 if !is_positive && (prev_sig != (sig + digit as $T) / radix as $T)
1477 { return Some(Float::neg_infinity()); }
1482 'e' | 'E' | 'p' | 'P' => {
1483 exp_info = Some((c, i + 1));
1484 break; // start of exponent
1487 break; // start of fractional part
1496 // If we are not yet at the exponent parse the fractional
1497 // part of the significand
1498 if exp_info.is_none() {
1499 let mut power = 1.0;
1501 match c.to_digit(radix) {
1503 // Decrease power one order of magnitude
1504 power = power / (radix as $T);
1505 // add/subtract current digit depending on sign
1506 sig = if is_positive {
1507 sig + (digit as $T) * power
1509 sig - (digit as $T) * power
1511 // Detect overflow by comparing to last value
1512 if is_positive && sig < prev_sig
1513 { return Some(Float::infinity()); }
1514 if !is_positive && sig > prev_sig
1515 { return Some(Float::neg_infinity()); }
1519 'e' | 'E' | 'p' | 'P' => {
1520 exp_info = Some((c, i + 1));
1521 break; // start of exponent
1524 return None; // invalid number
1531 // Parse and calculate the exponent
1532 let exp = match exp_info {
1533 Some((c, offset)) => {
1534 let base = match c {
1535 'E' | 'e' if radix == 10 => 10u as $T,
1536 'P' | 'p' if radix == 16 => 2u as $T,
1540 // Parse the exponent as decimal integer
1541 let src = src[offset..];
1542 let (is_positive, exp) = match src.slice_shift_char() {
1543 Some(('-', src)) => (false, src.parse::<uint>()),
1544 Some(('+', src)) => (true, src.parse::<uint>()),
1545 Some((_, _)) => (true, src.parse::<uint>()),
1546 None => return None,
1549 match (is_positive, exp) {
1550 (true, Some(exp)) => base.powi(exp as i32),
1551 (false, Some(exp)) => 1.0 / base.powi(exp as i32),
1552 (_, None) => return None,
1555 None => 1.0, // no exponent
1563 from_str_radix_float_impl! { f32 }
1564 from_str_radix_float_impl! { f64 }
1566 macro_rules! from_str_radix_int_impl {
1568 #[experimental = "might need to return Result"]
1569 impl FromStr for $T {
1571 fn from_str(src: &str) -> Option<$T> {
1572 from_str_radix(src, 10)
1576 #[experimental = "might need to return Result"]
1577 impl FromStrRadix for $T {
1578 fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
1579 assert!(radix >= 2 && radix <= 36,
1580 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1583 let is_signed_ty = (0 as $T) > Int::min_value();
1585 match src.slice_shift_char() {
1586 Some(('-', src)) if is_signed_ty => {
1587 // The number is negative
1589 for c in src.chars() {
1590 let x = match c.to_digit(radix) {
1592 None => return None,
1594 result = match result.checked_mul(radix as $T) {
1595 Some(result) => result,
1596 None => return None,
1598 result = match result.checked_sub(x as $T) {
1599 Some(result) => result,
1600 None => return None,
1606 // The number is signed
1608 for c in src.chars() {
1609 let x = match c.to_digit(radix) {
1611 None => return None,
1613 result = match result.checked_mul(radix as $T) {
1614 Some(result) => result,
1615 None => return None,
1617 result = match result.checked_add(x as $T) {
1618 Some(result) => result,
1619 None => return None,
1630 from_str_radix_int_impl! { int }
1631 from_str_radix_int_impl! { i8 }
1632 from_str_radix_int_impl! { i16 }
1633 from_str_radix_int_impl! { i32 }
1634 from_str_radix_int_impl! { i64 }
1635 from_str_radix_int_impl! { uint }
1636 from_str_radix_int_impl! { u8 }
1637 from_str_radix_int_impl! { u16 }
1638 from_str_radix_int_impl! { u32 }
1639 from_str_radix_int_impl! { u64 }