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.
15 #![stable(feature = "rust1", since = "1.0.0")]
16 #![allow(missing_docs)]
20 use cmp::{PartialEq, Eq, PartialOrd, Ord};
24 use iter::IteratorExt;
27 use ops::{Add, Sub, Mul, Div, Rem, Neg};
28 use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
29 use option::Option::{self, Some, None};
30 use result::Result::{self, Ok, Err};
31 use str::{FromStr, StrExt};
33 /// A built-in signed or unsigned integer.
34 #[stable(feature = "rust1", since = "1.0.0")]
49 + Shl<uint, Output=Self>
50 + Shr<uint, Output=Self>
52 /// Returns the `0` value of this integer type.
53 // FIXME (#5527): Should be an associated constant
54 #[unstable(feature = "core",
55 reason = "unsure about its place in the world")]
58 /// Returns the `1` value of this integer type.
59 // FIXME (#5527): Should be an associated constant
60 #[unstable(feature = "core",
61 reason = "unsure about its place in the world")]
64 /// Returns the smallest value that can be represented by this integer type.
65 // FIXME (#5527): Should be and associated constant
66 #[unstable(feature = "core",
67 reason = "unsure about its place in the world")]
68 fn min_value() -> Self;
70 /// Returns the largest value that can be represented by this integer type.
71 // FIXME (#5527): Should be and associated constant
72 #[unstable(feature = "core",
73 reason = "unsure about its place in the world")]
74 fn max_value() -> Self;
76 /// Returns the number of ones in the binary representation of `self`.
81 /// use std::num::Int;
83 /// let n = 0b01001100u8;
85 /// assert_eq!(n.count_ones(), 3);
87 #[unstable(feature = "core",
88 reason = "pending integer conventions")]
89 fn count_ones(self) -> uint;
91 /// Returns the number of zeros in the binary representation of `self`.
96 /// use std::num::Int;
98 /// let n = 0b01001100u8;
100 /// assert_eq!(n.count_zeros(), 5);
102 #[unstable(feature = "core",
103 reason = "pending integer conventions")]
105 fn count_zeros(self) -> uint {
109 /// Returns the number of leading zeros in the binary representation
115 /// use std::num::Int;
117 /// let n = 0b0101000u16;
119 /// assert_eq!(n.leading_zeros(), 10);
121 #[unstable(feature = "core",
122 reason = "pending integer conventions")]
123 fn leading_zeros(self) -> uint;
125 /// Returns the number of trailing zeros in the binary representation
131 /// use std::num::Int;
133 /// let n = 0b0101000u16;
135 /// assert_eq!(n.trailing_zeros(), 3);
137 #[unstable(feature = "core",
138 reason = "pending integer conventions")]
139 fn trailing_zeros(self) -> uint;
141 /// Shifts the bits to the left by a specified amount amount, `n`, wrapping
142 /// the truncated bits to the end of the resulting integer.
147 /// use std::num::Int;
149 /// let n = 0x0123456789ABCDEFu64;
150 /// let m = 0x3456789ABCDEF012u64;
152 /// assert_eq!(n.rotate_left(12), m);
154 #[unstable(feature = "core",
155 reason = "pending integer conventions")]
156 fn rotate_left(self, n: uint) -> Self;
158 /// Shifts the bits to the right by a specified amount amount, `n`, wrapping
159 /// the truncated bits to the beginning of the resulting integer.
164 /// use std::num::Int;
166 /// let n = 0x0123456789ABCDEFu64;
167 /// let m = 0xDEF0123456789ABCu64;
169 /// assert_eq!(n.rotate_right(12), m);
171 #[unstable(feature = "core",
172 reason = "pending integer conventions")]
173 fn rotate_right(self, n: uint) -> Self;
175 /// Reverses the byte order of the integer.
180 /// use std::num::Int;
182 /// let n = 0x0123456789ABCDEFu64;
183 /// let m = 0xEFCDAB8967452301u64;
185 /// assert_eq!(n.swap_bytes(), m);
187 #[stable(feature = "rust1", since = "1.0.0")]
188 fn swap_bytes(self) -> Self;
190 /// Convert an integer from big endian to the target's endianness.
192 /// On big endian this is a no-op. On little endian the bytes are swapped.
197 /// use std::num::Int;
199 /// let n = 0x0123456789ABCDEFu64;
201 /// if cfg!(target_endian = "big") {
202 /// assert_eq!(Int::from_be(n), n)
204 /// assert_eq!(Int::from_be(n), n.swap_bytes())
207 #[stable(feature = "rust1", since = "1.0.0")]
209 fn from_be(x: Self) -> Self {
210 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
213 /// Convert an integer from little endian to the target's endianness.
215 /// On little endian this is a no-op. On big endian the bytes are swapped.
220 /// use std::num::Int;
222 /// let n = 0x0123456789ABCDEFu64;
224 /// if cfg!(target_endian = "little") {
225 /// assert_eq!(Int::from_le(n), n)
227 /// assert_eq!(Int::from_le(n), n.swap_bytes())
230 #[stable(feature = "rust1", since = "1.0.0")]
232 fn from_le(x: Self) -> Self {
233 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
236 /// Convert `self` to big endian from the target's endianness.
238 /// On big endian this is a no-op. On little endian the bytes are swapped.
243 /// use std::num::Int;
245 /// let n = 0x0123456789ABCDEFu64;
247 /// if cfg!(target_endian = "big") {
248 /// assert_eq!(n.to_be(), n)
250 /// assert_eq!(n.to_be(), n.swap_bytes())
253 #[stable(feature = "rust1", since = "1.0.0")]
255 fn to_be(self) -> Self { // or not to be?
256 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
259 /// Convert `self` to little endian from the target's endianness.
261 /// On little endian this is a no-op. On big endian the bytes are swapped.
266 /// use std::num::Int;
268 /// let n = 0x0123456789ABCDEFu64;
270 /// if cfg!(target_endian = "little") {
271 /// assert_eq!(n.to_le(), n)
273 /// assert_eq!(n.to_le(), n.swap_bytes())
276 #[stable(feature = "rust1", since = "1.0.0")]
278 fn to_le(self) -> Self {
279 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
282 /// Checked integer addition. Computes `self + other`, returning `None` if
283 /// overflow occurred.
288 /// use std::num::Int;
290 /// assert_eq!(5u16.checked_add(65530), Some(65535));
291 /// assert_eq!(6u16.checked_add(65530), None);
293 #[stable(feature = "rust1", since = "1.0.0")]
294 fn checked_add(self, other: Self) -> Option<Self>;
296 /// Checked integer subtraction. Computes `self - other`, returning `None`
297 /// if underflow occurred.
302 /// use std::num::Int;
304 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
305 /// assert_eq!((-128i8).checked_sub(1), None);
307 #[stable(feature = "rust1", since = "1.0.0")]
308 fn checked_sub(self, other: Self) -> Option<Self>;
310 /// Checked integer multiplication. Computes `self * other`, returning
311 /// `None` if underflow or overflow occurred.
316 /// use std::num::Int;
318 /// assert_eq!(5u8.checked_mul(51), Some(255));
319 /// assert_eq!(5u8.checked_mul(52), None);
321 #[stable(feature = "rust1", since = "1.0.0")]
322 fn checked_mul(self, other: Self) -> Option<Self>;
324 /// Checked integer division. Computes `self / other`, returning `None` if
325 /// `other == 0` or the operation results in underflow or overflow.
330 /// use std::num::Int;
332 /// assert_eq!((-127i8).checked_div(-1), Some(127));
333 /// assert_eq!((-128i8).checked_div(-1), None);
334 /// assert_eq!((1i8).checked_div(0), None);
336 #[stable(feature = "rust1", since = "1.0.0")]
337 fn checked_div(self, other: Self) -> Option<Self>;
339 /// Saturating integer addition. Computes `self + other`, saturating at
340 /// the numeric bounds instead of overflowing.
341 #[stable(feature = "rust1", since = "1.0.0")]
343 fn saturating_add(self, other: Self) -> Self {
344 match self.checked_add(other) {
346 None if other >= Int::zero() => Int::max_value(),
347 None => Int::min_value(),
351 /// Saturating integer subtraction. Computes `self - other`, saturating at
352 /// the numeric bounds instead of overflowing.
353 #[stable(feature = "rust1", since = "1.0.0")]
355 fn saturating_sub(self, other: Self) -> Self {
356 match self.checked_sub(other) {
358 None if other >= Int::zero() => Int::min_value(),
359 None => Int::max_value(),
363 /// Raises self to the power of `exp`, using exponentiation by squaring.
368 /// use std::num::Int;
370 /// assert_eq!(2.pow(4), 16);
372 #[unstable(feature = "core",
373 reason = "pending integer conventions")]
375 fn pow(self, mut exp: uint) -> Self {
377 let mut acc: Self = Int::one();
389 macro_rules! checked_op {
390 ($T:ty, $U:ty, $op:path, $x:expr, $y:expr) => {{
391 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
392 if overflowed { None } else { Some(result as $T) }
396 macro_rules! uint_impl {
397 ($T:ty = $ActualT:ty, $BITS:expr,
402 $add_with_overflow:path,
403 $sub_with_overflow:path,
404 $mul_with_overflow:path) => {
405 #[stable(feature = "rust1", since = "1.0.0")]
408 fn zero() -> $T { 0 }
414 fn min_value() -> $T { 0 }
417 fn max_value() -> $T { -1 }
420 fn count_ones(self) -> uint { unsafe { $ctpop(self as $ActualT) as uint } }
423 fn leading_zeros(self) -> uint { unsafe { $ctlz(self as $ActualT) as uint } }
426 fn trailing_zeros(self) -> uint { unsafe { $cttz(self as $ActualT) as uint } }
429 fn rotate_left(self, n: uint) -> $T {
430 // Protect against undefined behaviour for over-long bit shifts
432 (self << n) | (self >> (($BITS - n) % $BITS))
436 fn rotate_right(self, n: uint) -> $T {
437 // Protect against undefined behaviour for over-long bit shifts
439 (self >> n) | (self << (($BITS - n) % $BITS))
443 fn swap_bytes(self) -> $T { unsafe { $bswap(self as $ActualT) as $T } }
446 fn checked_add(self, other: $T) -> Option<$T> {
447 checked_op!($T, $ActualT, $add_with_overflow, self, other)
451 fn checked_sub(self, other: $T) -> Option<$T> {
452 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
456 fn checked_mul(self, other: $T) -> Option<$T> {
457 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
461 fn checked_div(self, v: $T) -> Option<$T> {
471 /// Swapping a single byte is a no-op. This is marked as `unsafe` for
472 /// consistency with the other `bswap` intrinsics.
473 unsafe fn bswap8(x: u8) -> u8 { x }
475 uint_impl! { u8 = u8, 8,
480 intrinsics::u8_add_with_overflow,
481 intrinsics::u8_sub_with_overflow,
482 intrinsics::u8_mul_with_overflow }
484 uint_impl! { u16 = u16, 16,
489 intrinsics::u16_add_with_overflow,
490 intrinsics::u16_sub_with_overflow,
491 intrinsics::u16_mul_with_overflow }
493 uint_impl! { u32 = u32, 32,
498 intrinsics::u32_add_with_overflow,
499 intrinsics::u32_sub_with_overflow,
500 intrinsics::u32_mul_with_overflow }
502 uint_impl! { u64 = u64, 64,
507 intrinsics::u64_add_with_overflow,
508 intrinsics::u64_sub_with_overflow,
509 intrinsics::u64_mul_with_overflow }
511 #[cfg(target_pointer_width = "32")]
512 uint_impl! { uint = u32, 32,
517 intrinsics::u32_add_with_overflow,
518 intrinsics::u32_sub_with_overflow,
519 intrinsics::u32_mul_with_overflow }
521 #[cfg(target_pointer_width = "64")]
522 uint_impl! { uint = u64, 64,
527 intrinsics::u64_add_with_overflow,
528 intrinsics::u64_sub_with_overflow,
529 intrinsics::u64_mul_with_overflow }
531 macro_rules! int_impl {
532 ($T:ty = $ActualT:ty, $UnsignedT:ty, $BITS:expr,
533 $add_with_overflow:path,
534 $sub_with_overflow:path,
535 $mul_with_overflow:path) => {
536 #[stable(feature = "rust1", since = "1.0.0")]
539 fn zero() -> $T { 0 }
545 fn min_value() -> $T { (-1 as $T) << ($BITS - 1) }
548 fn max_value() -> $T { let min: $T = Int::min_value(); !min }
551 fn count_ones(self) -> uint { (self as $UnsignedT).count_ones() }
554 fn leading_zeros(self) -> uint { (self as $UnsignedT).leading_zeros() }
557 fn trailing_zeros(self) -> uint { (self as $UnsignedT).trailing_zeros() }
560 fn rotate_left(self, n: uint) -> $T { (self as $UnsignedT).rotate_left(n) as $T }
563 fn rotate_right(self, n: uint) -> $T { (self as $UnsignedT).rotate_right(n) as $T }
566 fn swap_bytes(self) -> $T { (self as $UnsignedT).swap_bytes() as $T }
569 fn checked_add(self, other: $T) -> Option<$T> {
570 checked_op!($T, $ActualT, $add_with_overflow, self, other)
574 fn checked_sub(self, other: $T) -> Option<$T> {
575 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
579 fn checked_mul(self, other: $T) -> Option<$T> {
580 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
584 fn checked_div(self, v: $T) -> Option<$T> {
587 -1 if self == Int::min_value()
596 int_impl! { i8 = i8, u8, 8,
597 intrinsics::i8_add_with_overflow,
598 intrinsics::i8_sub_with_overflow,
599 intrinsics::i8_mul_with_overflow }
601 int_impl! { i16 = i16, u16, 16,
602 intrinsics::i16_add_with_overflow,
603 intrinsics::i16_sub_with_overflow,
604 intrinsics::i16_mul_with_overflow }
606 int_impl! { i32 = i32, u32, 32,
607 intrinsics::i32_add_with_overflow,
608 intrinsics::i32_sub_with_overflow,
609 intrinsics::i32_mul_with_overflow }
611 int_impl! { i64 = i64, u64, 64,
612 intrinsics::i64_add_with_overflow,
613 intrinsics::i64_sub_with_overflow,
614 intrinsics::i64_mul_with_overflow }
616 #[cfg(target_pointer_width = "32")]
617 int_impl! { int = i32, u32, 32,
618 intrinsics::i32_add_with_overflow,
619 intrinsics::i32_sub_with_overflow,
620 intrinsics::i32_mul_with_overflow }
622 #[cfg(target_pointer_width = "64")]
623 int_impl! { int = i64, u64, 64,
624 intrinsics::i64_add_with_overflow,
625 intrinsics::i64_sub_with_overflow,
626 intrinsics::i64_mul_with_overflow }
628 /// A built-in two's complement integer.
629 #[stable(feature = "rust1", since = "1.0.0")]
634 /// Computes the absolute value of `self`. `Int::min_value()` will be
635 /// returned if the number is `Int::min_value()`.
636 #[unstable(feature = "core", reason = "overflow in debug builds?")]
637 fn abs(self) -> Self;
639 /// Returns a number representing sign of `self`.
641 /// - `0` if the number is zero
642 /// - `1` if the number is positive
643 /// - `-1` if the number is negative
644 #[stable(feature = "rust1", since = "1.0.0")]
645 fn signum(self) -> Self;
647 /// Returns `true` if `self` is positive and `false` if the number
648 /// is zero or negative.
649 #[stable(feature = "rust1", since = "1.0.0")]
650 fn is_positive(self) -> bool;
652 /// Returns `true` if `self` is negative and `false` if the number
653 /// is zero or positive.
654 #[stable(feature = "rust1", since = "1.0.0")]
655 fn is_negative(self) -> bool;
658 macro_rules! signed_int_impl {
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl SignedInt for $T {
664 if self.is_negative() { -self } else { self }
668 fn signum(self) -> $T {
677 fn is_positive(self) -> bool { self > 0 }
680 fn is_negative(self) -> bool { self < 0 }
685 signed_int_impl! { i8 }
686 signed_int_impl! { i16 }
687 signed_int_impl! { i32 }
688 signed_int_impl! { i64 }
689 signed_int_impl! { int }
691 /// A built-in unsigned integer.
692 #[stable(feature = "rust1", since = "1.0.0")]
693 pub trait UnsignedInt: Int {
694 /// Returns `true` iff `self == 2^k` for some `k`.
695 #[stable(feature = "rust1", since = "1.0.0")]
697 fn is_power_of_two(self) -> bool {
698 (self - Int::one()) & self == Int::zero() && !(self == Int::zero())
701 /// Returns the smallest power of two greater than or equal to `self`.
702 /// Unspecified behavior on overflow.
703 #[stable(feature = "rust1", since = "1.0.0")]
705 fn next_power_of_two(self) -> Self {
706 let bits = size_of::<Self>() * 8;
707 let one: Self = Int::one();
708 one << ((bits - (self - one).leading_zeros()) % bits)
711 /// Returns the smallest power of two greater than or equal to `n`. If the
712 /// next power of two is greater than the type's maximum value, `None` is
713 /// returned, otherwise the power of two is wrapped in `Some`.
714 #[stable(feature = "rust1", since = "1.0.0")]
715 fn checked_next_power_of_two(self) -> Option<Self> {
716 let npot = self.next_power_of_two();
725 #[stable(feature = "rust1", since = "1.0.0")]
726 impl UnsignedInt for uint {}
728 #[stable(feature = "rust1", since = "1.0.0")]
729 impl UnsignedInt for u8 {}
731 #[stable(feature = "rust1", since = "1.0.0")]
732 impl UnsignedInt for u16 {}
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl UnsignedInt for u32 {}
737 #[stable(feature = "rust1", since = "1.0.0")]
738 impl UnsignedInt for u64 {}
740 /// A generic trait for converting a value to a number.
741 #[unstable(feature = "core", reason = "trait is likely to be removed")]
742 pub trait ToPrimitive {
743 /// Converts the value of `self` to an `int`.
745 fn to_int(&self) -> Option<int> {
746 self.to_i64().and_then(|x| x.to_int())
749 /// Converts the value of `self` to an `i8`.
751 fn to_i8(&self) -> Option<i8> {
752 self.to_i64().and_then(|x| x.to_i8())
755 /// Converts the value of `self` to an `i16`.
757 fn to_i16(&self) -> Option<i16> {
758 self.to_i64().and_then(|x| x.to_i16())
761 /// Converts the value of `self` to an `i32`.
763 fn to_i32(&self) -> Option<i32> {
764 self.to_i64().and_then(|x| x.to_i32())
767 /// Converts the value of `self` to an `i64`.
768 fn to_i64(&self) -> Option<i64>;
770 /// Converts the value of `self` to an `uint`.
772 fn to_uint(&self) -> Option<uint> {
773 self.to_u64().and_then(|x| x.to_uint())
776 /// Converts the value of `self` to an `u8`.
778 fn to_u8(&self) -> Option<u8> {
779 self.to_u64().and_then(|x| x.to_u8())
782 /// Converts the value of `self` to an `u16`.
784 fn to_u16(&self) -> Option<u16> {
785 self.to_u64().and_then(|x| x.to_u16())
788 /// Converts the value of `self` to an `u32`.
790 fn to_u32(&self) -> Option<u32> {
791 self.to_u64().and_then(|x| x.to_u32())
794 /// Converts the value of `self` to an `u64`.
796 fn to_u64(&self) -> Option<u64>;
798 /// Converts the value of `self` to an `f32`.
800 fn to_f32(&self) -> Option<f32> {
801 self.to_f64().and_then(|x| x.to_f32())
804 /// Converts the value of `self` to an `f64`.
806 fn to_f64(&self) -> Option<f64> {
807 self.to_i64().and_then(|x| x.to_f64())
811 macro_rules! impl_to_primitive_int_to_int {
812 ($SrcT:ty, $DstT:ty, $slf:expr) => (
814 if size_of::<$SrcT>() <= size_of::<$DstT>() {
818 let min_value: $DstT = Int::min_value();
819 let max_value: $DstT = Int::max_value();
820 if min_value as i64 <= n && n <= max_value as i64 {
830 macro_rules! impl_to_primitive_int_to_uint {
831 ($SrcT:ty, $DstT:ty, $slf:expr) => (
833 let zero: $SrcT = Int::zero();
834 let max_value: $DstT = Int::max_value();
835 if zero <= $slf && $slf as u64 <= max_value as u64 {
844 macro_rules! impl_to_primitive_int {
846 impl ToPrimitive for $T {
848 fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int, *self) }
850 fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) }
852 fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) }
854 fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32, *self) }
856 fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self) }
859 fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint, *self) }
861 fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) }
863 fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) }
865 fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32, *self) }
867 fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64, *self) }
870 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
872 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
877 impl_to_primitive_int! { int }
878 impl_to_primitive_int! { i8 }
879 impl_to_primitive_int! { i16 }
880 impl_to_primitive_int! { i32 }
881 impl_to_primitive_int! { i64 }
883 macro_rules! impl_to_primitive_uint_to_int {
884 ($DstT:ty, $slf:expr) => (
886 let max_value: $DstT = Int::max_value();
887 if $slf as u64 <= max_value as u64 {
896 macro_rules! impl_to_primitive_uint_to_uint {
897 ($SrcT:ty, $DstT:ty, $slf:expr) => (
899 if size_of::<$SrcT>() <= size_of::<$DstT>() {
902 let zero: $SrcT = Int::zero();
903 let max_value: $DstT = Int::max_value();
904 if zero <= $slf && $slf as u64 <= max_value as u64 {
914 macro_rules! impl_to_primitive_uint {
916 impl ToPrimitive for $T {
918 fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int, *self) }
920 fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) }
922 fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) }
924 fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32, *self) }
926 fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) }
929 fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint, *self) }
931 fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) }
933 fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) }
935 fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32, *self) }
937 fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64, *self) }
940 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
942 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
947 impl_to_primitive_uint! { uint }
948 impl_to_primitive_uint! { u8 }
949 impl_to_primitive_uint! { u16 }
950 impl_to_primitive_uint! { u32 }
951 impl_to_primitive_uint! { u64 }
953 macro_rules! impl_to_primitive_float_to_float {
954 ($SrcT:ident, $DstT:ident, $slf:expr) => (
955 if size_of::<$SrcT>() <= size_of::<$DstT>() {
959 let max_value: $SrcT = ::$SrcT::MAX_VALUE;
960 if -max_value as f64 <= n && n <= max_value as f64 {
969 macro_rules! impl_to_primitive_float {
971 impl ToPrimitive for $T {
973 fn to_int(&self) -> Option<int> { Some(*self as int) }
975 fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
977 fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
979 fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
981 fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
984 fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
986 fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
988 fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
990 fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
992 fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
995 fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32, *self) }
997 fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64, *self) }
1002 impl_to_primitive_float! { f32 }
1003 impl_to_primitive_float! { f64 }
1005 /// A generic trait for converting a number to a value.
1006 #[unstable(feature = "core", reason = "trait is likely to be removed")]
1007 pub trait FromPrimitive : ::marker::Sized {
1008 /// Convert an `int` to return an optional value of this type. If the
1009 /// value cannot be represented by this value, the `None` is returned.
1011 fn from_int(n: int) -> Option<Self> {
1012 FromPrimitive::from_i64(n as i64)
1015 /// Convert an `i8` to return an optional value of this type. If the
1016 /// type cannot be represented by this value, the `None` is returned.
1018 fn from_i8(n: i8) -> Option<Self> {
1019 FromPrimitive::from_i64(n as i64)
1022 /// Convert an `i16` to return an optional value of this type. If the
1023 /// type cannot be represented by this value, the `None` is returned.
1025 fn from_i16(n: i16) -> Option<Self> {
1026 FromPrimitive::from_i64(n as i64)
1029 /// Convert an `i32` to return an optional value of this type. If the
1030 /// type cannot be represented by this value, the `None` is returned.
1032 fn from_i32(n: i32) -> Option<Self> {
1033 FromPrimitive::from_i64(n as i64)
1036 /// Convert an `i64` to return an optional value of this type. If the
1037 /// type cannot be represented by this value, the `None` is returned.
1038 fn from_i64(n: i64) -> Option<Self>;
1040 /// Convert an `uint` to return an optional value of this type. If the
1041 /// type cannot be represented by this value, the `None` is returned.
1043 fn from_uint(n: uint) -> Option<Self> {
1044 FromPrimitive::from_u64(n as u64)
1047 /// Convert an `u8` to return an optional value of this type. If the
1048 /// type cannot be represented by this value, the `None` is returned.
1050 fn from_u8(n: u8) -> Option<Self> {
1051 FromPrimitive::from_u64(n as u64)
1054 /// Convert an `u16` to return an optional value of this type. If the
1055 /// type cannot be represented by this value, the `None` is returned.
1057 fn from_u16(n: u16) -> Option<Self> {
1058 FromPrimitive::from_u64(n as u64)
1061 /// Convert an `u32` to return an optional value of this type. If the
1062 /// type cannot be represented by this value, the `None` is returned.
1064 fn from_u32(n: u32) -> Option<Self> {
1065 FromPrimitive::from_u64(n as u64)
1068 /// Convert an `u64` to return an optional value of this type. If the
1069 /// type cannot be represented by this value, the `None` is returned.
1070 fn from_u64(n: u64) -> Option<Self>;
1072 /// Convert a `f32` to return an optional value of this type. If the
1073 /// type cannot be represented by this value, the `None` is returned.
1075 fn from_f32(n: f32) -> Option<Self> {
1076 FromPrimitive::from_f64(n as f64)
1079 /// Convert a `f64` to return an optional value of this type. If the
1080 /// type cannot be represented by this value, the `None` is returned.
1082 fn from_f64(n: f64) -> Option<Self> {
1083 FromPrimitive::from_i64(n as i64)
1087 /// A utility function that just calls `FromPrimitive::from_int`.
1088 #[unstable(feature = "core", reason = "likely to be removed")]
1089 pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
1090 FromPrimitive::from_int(n)
1093 /// A utility function that just calls `FromPrimitive::from_i8`.
1094 #[unstable(feature = "core", reason = "likely to be removed")]
1095 pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> {
1096 FromPrimitive::from_i8(n)
1099 /// A utility function that just calls `FromPrimitive::from_i16`.
1100 #[unstable(feature = "core", reason = "likely to be removed")]
1101 pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> {
1102 FromPrimitive::from_i16(n)
1105 /// A utility function that just calls `FromPrimitive::from_i32`.
1106 #[unstable(feature = "core", reason = "likely to be removed")]
1107 pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> {
1108 FromPrimitive::from_i32(n)
1111 /// A utility function that just calls `FromPrimitive::from_i64`.
1112 #[unstable(feature = "core", reason = "likely to be removed")]
1113 pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
1114 FromPrimitive::from_i64(n)
1117 /// A utility function that just calls `FromPrimitive::from_uint`.
1118 #[unstable(feature = "core", reason = "likely to be removed")]
1119 pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
1120 FromPrimitive::from_uint(n)
1123 /// A utility function that just calls `FromPrimitive::from_u8`.
1124 #[unstable(feature = "core", reason = "likely to be removed")]
1125 pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> {
1126 FromPrimitive::from_u8(n)
1129 /// A utility function that just calls `FromPrimitive::from_u16`.
1130 #[unstable(feature = "core", reason = "likely to be removed")]
1131 pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> {
1132 FromPrimitive::from_u16(n)
1135 /// A utility function that just calls `FromPrimitive::from_u32`.
1136 #[unstable(feature = "core", reason = "likely to be removed")]
1137 pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> {
1138 FromPrimitive::from_u32(n)
1141 /// A utility function that just calls `FromPrimitive::from_u64`.
1142 #[unstable(feature = "core", reason = "likely to be removed")]
1143 pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> {
1144 FromPrimitive::from_u64(n)
1147 /// A utility function that just calls `FromPrimitive::from_f32`.
1148 #[unstable(feature = "core", reason = "likely to be removed")]
1149 pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> {
1150 FromPrimitive::from_f32(n)
1153 /// A utility function that just calls `FromPrimitive::from_f64`.
1154 #[unstable(feature = "core", reason = "likely to be removed")]
1155 pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {
1156 FromPrimitive::from_f64(n)
1159 macro_rules! impl_from_primitive {
1160 ($T:ty, $to_ty:ident) => (
1161 impl FromPrimitive for $T {
1162 #[inline] fn from_int(n: int) -> Option<$T> { n.$to_ty() }
1163 #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() }
1164 #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() }
1165 #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() }
1166 #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() }
1168 #[inline] fn from_uint(n: uint) -> Option<$T> { n.$to_ty() }
1169 #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() }
1170 #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() }
1171 #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() }
1172 #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() }
1174 #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() }
1175 #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() }
1180 impl_from_primitive! { int, to_int }
1181 impl_from_primitive! { i8, to_i8 }
1182 impl_from_primitive! { i16, to_i16 }
1183 impl_from_primitive! { i32, to_i32 }
1184 impl_from_primitive! { i64, to_i64 }
1185 impl_from_primitive! { uint, to_uint }
1186 impl_from_primitive! { u8, to_u8 }
1187 impl_from_primitive! { u16, to_u16 }
1188 impl_from_primitive! { u32, to_u32 }
1189 impl_from_primitive! { u64, to_u64 }
1190 impl_from_primitive! { f32, to_f32 }
1191 impl_from_primitive! { f64, to_f64 }
1193 /// Cast from one machine scalar to another.
1200 /// let twenty: f32 = num::cast(0x14).unwrap();
1201 /// assert_eq!(twenty, 20f32);
1205 #[unstable(feature = "core", reason = "likely to be removed")]
1206 pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
1210 /// An interface for casting between machine scalars.
1211 #[unstable(feature = "core", reason = "trait is likely to be removed")]
1212 pub trait NumCast: ToPrimitive {
1213 /// Creates a number from another value that can be converted into a primitive via the
1214 /// `ToPrimitive` trait.
1215 fn from<T: ToPrimitive>(n: T) -> Option<Self>;
1218 macro_rules! impl_num_cast {
1219 ($T:ty, $conv:ident) => (
1220 impl NumCast for $T {
1222 fn from<N: ToPrimitive>(n: N) -> Option<$T> {
1223 // `$conv` could be generated using `concat_idents!`, but that
1224 // macro seems to be broken at the moment
1231 impl_num_cast! { u8, to_u8 }
1232 impl_num_cast! { u16, to_u16 }
1233 impl_num_cast! { u32, to_u32 }
1234 impl_num_cast! { u64, to_u64 }
1235 impl_num_cast! { uint, to_uint }
1236 impl_num_cast! { i8, to_i8 }
1237 impl_num_cast! { i16, to_i16 }
1238 impl_num_cast! { i32, to_i32 }
1239 impl_num_cast! { i64, to_i64 }
1240 impl_num_cast! { int, to_int }
1241 impl_num_cast! { f32, to_f32 }
1242 impl_num_cast! { f64, to_f64 }
1244 /// Used for representing the classification of floating point numbers
1245 #[derive(Copy, PartialEq, Debug)]
1246 #[unstable(feature = "core", reason = "may be renamed")]
1247 pub enum FpCategory {
1248 /// "Not a Number", often obtained by dividing by zero
1250 /// Positive or negative infinity
1252 /// Positive or negative zero
1254 /// De-normalized floating point representation (less precise than `Normal`)
1256 /// A regular floating point number
1260 /// A built-in floating point number.
1261 // FIXME(#5527): In a future version of Rust, many of these functions will
1262 // become constants.
1264 // FIXME(#8888): Several of these functions have a parameter named
1265 // `unused_self`. Removing it requires #8888 to be fixed.
1266 #[unstable(feature = "core",
1267 reason = "distribution of methods between core/std is unclear")]
1280 /// Returns the NaN value.
1282 /// Returns the infinite value.
1283 fn infinity() -> Self;
1284 /// Returns the negative infinite value.
1285 fn neg_infinity() -> Self;
1286 /// Returns the `0` value.
1289 fn neg_zero() -> Self;
1290 /// Returns the `1` value.
1293 // FIXME (#5527): These should be associated constants
1295 /// Returns the number of binary digits of mantissa that this type supports.
1296 #[unstable(feature = "core")]
1297 #[deprecated(since = "1.0.0",
1298 reason = "use `std::f32::MANTISSA_DIGITS` or \
1299 `std::f64::MANTISSA_DIGITS` as appropriate")]
1300 fn mantissa_digits(unused_self: Option<Self>) -> uint;
1301 /// Returns the number of base-10 digits of precision that this type supports.
1302 #[unstable(feature = "core")]
1303 #[deprecated(since = "1.0.0",
1304 reason = "use `std::f32::DIGITS` or `std::f64::DIGITS` as appropriate")]
1305 fn digits(unused_self: Option<Self>) -> uint;
1306 /// Returns the difference between 1.0 and the smallest representable number larger than 1.0.
1307 #[unstable(feature = "core")]
1308 #[deprecated(since = "1.0.0",
1309 reason = "use `std::f32::EPSILON` or `std::f64::EPSILON` as appropriate")]
1310 fn epsilon() -> Self;
1311 /// Returns the minimum binary exponent that this type can represent.
1312 #[unstable(feature = "core")]
1313 #[deprecated(since = "1.0.0",
1314 reason = "use `std::f32::MIN_EXP` or `std::f64::MIN_EXP` as appropriate")]
1315 fn min_exp(unused_self: Option<Self>) -> int;
1316 /// Returns the maximum binary exponent that this type can represent.
1317 #[unstable(feature = "core")]
1318 #[deprecated(since = "1.0.0",
1319 reason = "use `std::f32::MAX_EXP` or `std::f64::MAX_EXP` as appropriate")]
1320 fn max_exp(unused_self: Option<Self>) -> int;
1321 /// Returns the minimum base-10 exponent that this type can represent.
1322 #[unstable(feature = "core")]
1323 #[deprecated(since = "1.0.0",
1324 reason = "use `std::f32::MIN_10_EXP` or `std::f64::MIN_10_EXP` as appropriate")]
1325 fn min_10_exp(unused_self: Option<Self>) -> int;
1326 /// Returns the maximum base-10 exponent that this type can represent.
1327 #[unstable(feature = "core")]
1328 #[deprecated(since = "1.0.0",
1329 reason = "use `std::f32::MAX_10_EXP` or `std::f64::MAX_10_EXP` as appropriate")]
1330 fn max_10_exp(unused_self: Option<Self>) -> int;
1331 /// Returns the smallest finite value that this type can represent.
1332 #[unstable(feature = "core")]
1333 #[deprecated(since = "1.0.0",
1334 reason = "use `std::f32::MIN_VALUE` or `std::f64::MIN_VALUE` as appropriate")]
1335 fn min_value() -> Self;
1336 /// Returns the smallest normalized positive number that this type can represent.
1337 #[unstable(feature = "core")]
1338 #[deprecated(since = "1.0.0",
1339 reason = "use `std::f32::MIN_POS_VALUE` or \
1340 `std::f64::MIN_POS_VALUE` as appropriate")]
1341 fn min_pos_value(unused_self: Option<Self>) -> Self;
1342 /// Returns the largest finite value that this type can represent.
1343 #[unstable(feature = "core")]
1344 #[deprecated(since = "1.0.0",
1345 reason = "use `std::f32::MAX_VALUE` or `std::f64::MAX_VALUE` as appropriate")]
1346 fn max_value() -> Self;
1348 /// Returns true if this value is NaN and false otherwise.
1349 fn is_nan(self) -> bool;
1350 /// Returns true if this value is positive infinity or negative infinity and
1351 /// false otherwise.
1352 fn is_infinite(self) -> bool;
1353 /// Returns true if this number is neither infinite nor NaN.
1354 fn is_finite(self) -> bool;
1355 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1356 fn is_normal(self) -> bool;
1357 /// Returns the category that this number falls into.
1358 fn classify(self) -> FpCategory;
1360 /// Returns the mantissa, exponent and sign as integers, respectively.
1361 fn integer_decode(self) -> (u64, i16, i8);
1363 /// Return the largest integer less than or equal to a number.
1364 fn floor(self) -> Self;
1365 /// Return the smallest integer greater than or equal to a number.
1366 fn ceil(self) -> Self;
1367 /// Return the nearest integer to a number. Round half-way cases away from
1369 fn round(self) -> Self;
1370 /// Return the integer part of a number.
1371 fn trunc(self) -> Self;
1372 /// Return the fractional part of a number.
1373 fn fract(self) -> Self;
1375 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1376 /// number is `Float::nan()`.
1377 fn abs(self) -> Self;
1378 /// Returns a number that represents the sign of `self`.
1380 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1381 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1382 /// - `Float::nan()` if the number is `Float::nan()`
1383 fn signum(self) -> Self;
1384 /// Returns `true` if `self` is positive, including `+0.0` and
1385 /// `Float::infinity()`.
1386 fn is_positive(self) -> bool;
1387 /// Returns `true` if `self` is negative, including `-0.0` and
1388 /// `Float::neg_infinity()`.
1389 fn is_negative(self) -> bool;
1391 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1392 /// error. This produces a more accurate result with better performance than
1393 /// a separate multiplication operation followed by an add.
1394 fn mul_add(self, a: Self, b: Self) -> Self;
1395 /// Take the reciprocal (inverse) of a number, `1/x`.
1396 fn recip(self) -> Self;
1398 /// Raise a number to an integer power.
1400 /// Using this function is generally faster than using `powf`
1401 fn powi(self, n: i32) -> Self;
1402 /// Raise a number to a floating point power.
1403 fn powf(self, n: Self) -> Self;
1405 /// Take the square root of a number.
1407 /// Returns NaN if `self` is a negative number.
1408 fn sqrt(self) -> Self;
1409 /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1410 fn rsqrt(self) -> Self;
1412 /// Returns `e^(self)`, (the exponential function).
1413 fn exp(self) -> Self;
1414 /// Returns 2 raised to the power of the number, `2^(self)`.
1415 fn exp2(self) -> Self;
1416 /// Returns the natural logarithm of the number.
1417 fn ln(self) -> Self;
1418 /// Returns the logarithm of the number with respect to an arbitrary base.
1419 fn log(self, base: Self) -> Self;
1420 /// Returns the base 2 logarithm of the number.
1421 fn log2(self) -> Self;
1422 /// Returns the base 10 logarithm of the number.
1423 fn log10(self) -> Self;
1425 /// Convert radians to degrees.
1426 fn to_degrees(self) -> Self;
1427 /// Convert degrees to radians.
1428 fn to_radians(self) -> Self;
1431 /// A generic trait for converting a string with a radix (base) to a value
1432 #[unstable(feature = "core", reason = "needs reevaluation")]
1433 pub trait FromStrRadix {
1435 fn from_str_radix(str: &str, radix: uint) -> Result<Self, Self::Err>;
1438 /// A utility function that just calls FromStrRadix::from_str_radix.
1439 #[unstable(feature = "core", reason = "needs reevaluation")]
1440 pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint)
1441 -> Result<T, T::Err> {
1442 FromStrRadix::from_str_radix(str, radix)
1445 macro_rules! from_str_radix_float_impl {
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 impl FromStr for $T {
1449 type Err = ParseFloatError;
1451 /// Convert a string in base 10 to a float.
1452 /// Accepts an optional decimal exponent.
1454 /// This function accepts strings such as
1457 /// * '+3.14', equivalent to '3.14'
1459 /// * '2.5E10', or equivalently, '2.5e10'
1461 /// * '.' (understood as 0)
1463 /// * '.5', or, equivalently, '0.5'
1464 /// * '+inf', 'inf', '-inf', 'NaN'
1466 /// Leading and trailing whitespace represent an error.
1470 /// * src - A string
1474 /// `None` if the string did not represent a valid number. Otherwise,
1475 /// `Some(n)` where `n` is the floating-point number represented by `src`.
1477 fn from_str(src: &str) -> Result<$T, ParseFloatError> {
1478 from_str_radix(src, 10)
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 impl FromStrRadix for $T {
1484 type Err = ParseFloatError;
1486 /// Convert a string in a given base to a float.
1488 /// Due to possible conflicts, this function does **not** accept
1489 /// the special values `inf`, `-inf`, `+inf` and `NaN`, **nor**
1490 /// does it recognize exponents of any kind.
1492 /// Leading and trailing whitespace represent an error.
1496 /// * src - A string
1497 /// * radix - The base to use. Must lie in the range [2 .. 36]
1501 /// `None` if the string did not represent a valid number.
1502 /// Otherwise, `Some(n)` where `n` is the floating-point number
1503 /// represented by `src`.
1504 fn from_str_radix(src: &str, radix: uint)
1505 -> Result<$T, ParseFloatError> {
1506 use self::FloatErrorKind::*;
1507 use self::ParseFloatError as PFE;
1508 assert!(radix >= 2 && radix <= 36,
1509 "from_str_radix_float: must lie in the range `[2, 36]` - found {}",
1514 "inf" => return Ok(Float::infinity()),
1515 "-inf" => return Ok(Float::neg_infinity()),
1516 "NaN" => return Ok(Float::nan()),
1520 let (is_positive, src) = match src.slice_shift_char() {
1521 None => return Err(PFE { kind: Empty }),
1522 Some(('-', "")) => return Err(PFE { kind: Empty }),
1523 Some(('-', src)) => (false, src),
1524 Some((_, _)) => (true, src),
1527 // The significand to accumulate
1528 let mut sig = if is_positive { 0.0 } else { -0.0 };
1529 // Necessary to detect overflow
1530 let mut prev_sig = sig;
1531 let mut cs = src.chars().enumerate();
1532 // Exponent prefix and exponent index offset
1533 let mut exp_info = None::<(char, uint)>;
1535 // Parse the integer part of the significand
1536 for (i, c) in cs.by_ref() {
1537 match c.to_digit(radix) {
1539 // shift significand one digit left
1540 sig = sig * (radix as $T);
1542 // add/subtract current digit depending on sign
1544 sig = sig + ((digit as int) as $T);
1546 sig = sig - ((digit as int) as $T);
1549 // Detect overflow by comparing to last value, except
1550 // if we've not seen any non-zero digits.
1551 if prev_sig != 0.0 {
1552 if is_positive && sig <= prev_sig
1553 { return Ok(Float::infinity()); }
1554 if !is_positive && sig >= prev_sig
1555 { return Ok(Float::neg_infinity()); }
1557 // Detect overflow by reversing the shift-and-add process
1558 if is_positive && (prev_sig != (sig - digit as $T) / radix as $T)
1559 { return Ok(Float::infinity()); }
1560 if !is_positive && (prev_sig != (sig + digit as $T) / radix as $T)
1561 { return Ok(Float::neg_infinity()); }
1566 'e' | 'E' | 'p' | 'P' => {
1567 exp_info = Some((c, i + 1));
1568 break; // start of exponent
1571 break; // start of fractional part
1574 return Err(PFE { kind: Invalid });
1580 // If we are not yet at the exponent parse the fractional
1581 // part of the significand
1582 if exp_info.is_none() {
1583 let mut power = 1.0;
1584 for (i, c) in cs.by_ref() {
1585 match c.to_digit(radix) {
1587 // Decrease power one order of magnitude
1588 power = power / (radix as $T);
1589 // add/subtract current digit depending on sign
1590 sig = if is_positive {
1591 sig + (digit as $T) * power
1593 sig - (digit as $T) * power
1595 // Detect overflow by comparing to last value
1596 if is_positive && sig < prev_sig
1597 { return Ok(Float::infinity()); }
1598 if !is_positive && sig > prev_sig
1599 { return Ok(Float::neg_infinity()); }
1603 'e' | 'E' | 'p' | 'P' => {
1604 exp_info = Some((c, i + 1));
1605 break; // start of exponent
1608 return Err(PFE { kind: Invalid });
1615 // Parse and calculate the exponent
1616 let exp = match exp_info {
1617 Some((c, offset)) => {
1618 let base = match c {
1619 'E' | 'e' if radix == 10 => 10.0,
1620 'P' | 'p' if radix == 16 => 2.0,
1621 _ => return Err(PFE { kind: Invalid }),
1624 // Parse the exponent as decimal integer
1625 let src = &src[offset..];
1626 let (is_positive, exp) = match src.slice_shift_char() {
1627 Some(('-', src)) => (false, src.parse::<uint>()),
1628 Some(('+', src)) => (true, src.parse::<uint>()),
1629 Some((_, _)) => (true, src.parse::<uint>()),
1630 None => return Err(PFE { kind: Invalid }),
1633 match (is_positive, exp) {
1634 (true, Ok(exp)) => base.powi(exp as i32),
1635 (false, Ok(exp)) => 1.0 / base.powi(exp as i32),
1636 (_, Err(_)) => return Err(PFE { kind: Invalid }),
1639 None => 1.0, // no exponent
1647 from_str_radix_float_impl! { f32 }
1648 from_str_radix_float_impl! { f64 }
1650 macro_rules! from_str_radix_int_impl {
1652 #[stable(feature = "rust1", since = "1.0.0")]
1653 impl FromStr for $T {
1654 type Err = ParseIntError;
1656 fn from_str(src: &str) -> Result<$T, ParseIntError> {
1657 from_str_radix(src, 10)
1661 #[stable(feature = "rust1", since = "1.0.0")]
1662 impl FromStrRadix for $T {
1663 type Err = ParseIntError;
1664 fn from_str_radix(src: &str, radix: uint)
1665 -> Result<$T, ParseIntError> {
1666 use self::IntErrorKind::*;
1667 use self::ParseIntError as PIE;
1668 assert!(radix >= 2 && radix <= 36,
1669 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1672 let is_signed_ty = (0 as $T) > Int::min_value();
1674 match src.slice_shift_char() {
1675 Some(('-', src)) if is_signed_ty => {
1676 // The number is negative
1678 for c in src.chars() {
1679 let x = match c.to_digit(radix) {
1681 None => return Err(PIE { kind: InvalidDigit }),
1683 result = match result.checked_mul(radix as $T) {
1684 Some(result) => result,
1685 None => return Err(PIE { kind: Underflow }),
1687 result = match result.checked_sub(x as $T) {
1688 Some(result) => result,
1689 None => return Err(PIE { kind: Underflow }),
1695 // The number is signed
1697 for c in src.chars() {
1698 let x = match c.to_digit(radix) {
1700 None => return Err(PIE { kind: InvalidDigit }),
1702 result = match result.checked_mul(radix as $T) {
1703 Some(result) => result,
1704 None => return Err(PIE { kind: Overflow }),
1706 result = match result.checked_add(x as $T) {
1707 Some(result) => result,
1708 None => return Err(PIE { kind: Overflow }),
1713 None => Err(ParseIntError { kind: Empty }),
1719 from_str_radix_int_impl! { int }
1720 from_str_radix_int_impl! { i8 }
1721 from_str_radix_int_impl! { i16 }
1722 from_str_radix_int_impl! { i32 }
1723 from_str_radix_int_impl! { i64 }
1724 from_str_radix_int_impl! { uint }
1725 from_str_radix_int_impl! { u8 }
1726 from_str_radix_int_impl! { u16 }
1727 from_str_radix_int_impl! { u32 }
1728 from_str_radix_int_impl! { u64 }
1730 /// An error which can be returned when parsing an integer.
1731 #[derive(Debug, Clone, PartialEq)]
1732 #[stable(feature = "rust1", since = "1.0.0")]
1733 pub struct ParseIntError { kind: IntErrorKind }
1735 #[derive(Debug, Clone, PartialEq)]
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 impl fmt::Display for ParseIntError {
1745 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1746 self.description().fmt(f)
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 impl Error for ParseIntError {
1752 fn description(&self) -> &str {
1754 IntErrorKind::Empty => "cannot parse integer from empty string",
1755 IntErrorKind::InvalidDigit => "invalid digit found in string",
1756 IntErrorKind::Overflow => "number too large to fit in target type",
1757 IntErrorKind::Underflow => "number too small to fit in target type",
1762 /// An error which can be returned when parsing a float.
1763 #[derive(Debug, Clone, PartialEq)]
1764 #[stable(feature = "rust1", since = "1.0.0")]
1765 pub struct ParseFloatError { kind: FloatErrorKind }
1767 #[derive(Debug, Clone, PartialEq)]
1768 enum FloatErrorKind {
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 impl fmt::Display for ParseFloatError {
1775 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1776 self.description().fmt(f)
1780 #[stable(feature = "rust1", since = "1.0.0")]
1781 impl Error for ParseFloatError {
1782 fn description(&self) -> &str {
1784 FloatErrorKind::Empty => "cannot parse float from empty string",
1785 FloatErrorKind::Invalid => "invalid float literal",