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)]
18 pub use self::FPCategory::*;
20 use {int, i8, i16, i32, i64};
21 use {uint, u8, u16, u32, u64};
25 use cmp::{PartialEq, Eq};
26 use cmp::{PartialOrd, Ord};
28 use iter::IteratorExt;
31 use ops::{Add, Sub, Mul, Div, Rem, Neg};
32 use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
34 use option::Option::{Some, None};
35 use str::{FromStr, from_str, StrPrelude};
37 /// Simultaneous division and remainder
39 #[deprecated = "use division and remainder directly"]
40 pub fn div_rem<T: Div<T, T> + Rem<T, T>>(x: T, y: T) -> (T, T) {
44 /// Raises a `base` to the power of `exp`, using exponentiation by squaring.
46 #[deprecated = "Use Int::pow() instead, as in 2i.pow(4)"]
47 pub fn pow<T: Int>(base: T, exp: uint) -> T {
51 /// A built-in signed or unsigned integer.
52 #[unstable = "recently settled as part of numerics reform"]
70 /// Returns the `0` value of this integer type.
71 // FIXME (#5527): Should be an associated constant
74 /// Returns the `1` value of this integer type.
75 // FIXME (#5527): Should be an associated constant
78 /// Returns the smallest value that can be represented by this integer type.
79 // FIXME (#5527): Should be and associated constant
80 fn min_value() -> Self;
82 /// Returns the largest value that can be represented by this integer type.
83 // FIXME (#5527): Should be and associated constant
84 fn max_value() -> Self;
86 /// Returns the number of ones in the binary representation of `self`.
91 /// use std::num::Int;
93 /// let n = 0b01001100u8;
95 /// assert_eq!(n.count_ones(), 3);
97 fn count_ones(self) -> uint;
99 /// Returns the number of zeros in the binary representation of `self`.
104 /// use std::num::Int;
106 /// let n = 0b01001100u8;
108 /// assert_eq!(n.count_zeros(), 5);
111 fn count_zeros(self) -> uint {
115 /// Returns the number of leading zeros in the binary representation
121 /// use std::num::Int;
123 /// let n = 0b0101000u16;
125 /// assert_eq!(n.leading_zeros(), 10);
127 fn leading_zeros(self) -> uint;
129 /// Returns the number of trailing zeros in the binary representation
135 /// use std::num::Int;
137 /// let n = 0b0101000u16;
139 /// assert_eq!(n.trailing_zeros(), 3);
141 fn trailing_zeros(self) -> uint;
143 /// Shifts the bits to the left by a specified amount amount, `n`, wrapping
144 /// the truncated bits to the end of the resulting integer.
149 /// use std::num::Int;
151 /// let n = 0x0123456789ABCDEFu64;
152 /// let m = 0x3456789ABCDEF012u64;
154 /// assert_eq!(n.rotate_left(12), m);
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 fn rotate_right(self, n: uint) -> Self;
173 /// Reverses the byte order of the integer.
178 /// use std::num::Int;
180 /// let n = 0x0123456789ABCDEFu64;
181 /// let m = 0xEFCDAB8967452301u64;
183 /// assert_eq!(n.swap_bytes(), m);
185 fn swap_bytes(self) -> Self;
187 /// Convert an integer from big endian to the target's endianness.
189 /// On big endian this is a no-op. On little endian the bytes are swapped.
194 /// use std::num::Int;
196 /// let n = 0x0123456789ABCDEFu64;
198 /// if cfg!(target_endian = "big") {
199 /// assert_eq!(Int::from_be(n), n)
201 /// assert_eq!(Int::from_be(n), n.swap_bytes())
205 fn from_be(x: Self) -> Self {
206 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
209 /// Convert an integer from little endian to the target's endianness.
211 /// On little endian this is a no-op. On big endian the bytes are swapped.
216 /// use std::num::Int;
218 /// let n = 0x0123456789ABCDEFu64;
220 /// if cfg!(target_endian = "little") {
221 /// assert_eq!(Int::from_le(n), n)
223 /// assert_eq!(Int::from_le(n), n.swap_bytes())
227 fn from_le(x: Self) -> Self {
228 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
231 /// Convert `self` to big endian from the target's endianness.
233 /// On big endian this is a no-op. On little endian the bytes are swapped.
238 /// use std::num::Int;
240 /// let n = 0x0123456789ABCDEFu64;
242 /// if cfg!(target_endian = "big") {
243 /// assert_eq!(n.to_be(), n)
245 /// assert_eq!(n.to_be(), n.swap_bytes())
249 fn to_be(self) -> Self { // or not to be?
250 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
253 /// Convert `self` to little endian from the target's endianness.
255 /// On little endian this is a no-op. On big endian the bytes are swapped.
260 /// use std::num::Int;
262 /// let n = 0x0123456789ABCDEFu64;
264 /// if cfg!(target_endian = "little") {
265 /// assert_eq!(n.to_le(), n)
267 /// assert_eq!(n.to_le(), n.swap_bytes())
271 fn to_le(self) -> Self {
272 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
275 /// Checked integer addition. Computes `self + other`, returning `None` if
276 /// overflow occurred.
281 /// use std::num::Int;
283 /// assert_eq!(5u16.checked_add(65530), Some(65535));
284 /// assert_eq!(6u16.checked_add(65530), None);
286 fn checked_add(self, other: Self) -> Option<Self>;
288 /// Checked integer subtraction. Computes `self - other`, returning `None`
289 /// if underflow occurred.
294 /// use std::num::Int;
296 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
297 /// assert_eq!((-128i8).checked_sub(1), None);
299 fn checked_sub(self, other: Self) -> Option<Self>;
301 /// Checked integer multiplication. Computes `self * other`, returning
302 /// `None` if underflow or overflow occurred.
307 /// use std::num::Int;
309 /// assert_eq!(5u8.checked_mul(51), Some(255));
310 /// assert_eq!(5u8.checked_mul(52), None);
312 fn checked_mul(self, other: Self) -> Option<Self>;
314 /// Checked integer division. Computes `self / other`, returning `None` if
315 /// `other == 0` or the operation results in underflow or overflow.
320 /// use std::num::Int;
322 /// assert_eq!((-127i8).checked_div(-1), Some(127));
323 /// assert_eq!((-128i8).checked_div(-1), None);
324 /// assert_eq!((1i8).checked_div(0), None);
327 fn checked_div(self, other: Self) -> Option<Self>;
329 /// Saturating integer addition. Computes `self + other`, saturating at
330 /// 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.
343 fn saturating_sub(self, other: Self) -> Self {
344 match self.checked_sub(other) {
346 None if other >= Int::zero() => Int::min_value(),
347 None => Int::max_value(),
351 /// Raises self to the power of `exp`, using exponentiation by squaring.
356 /// use std::num::Int;
358 /// assert_eq!(2i.pow(4), 16);
361 fn pow(self, mut exp: uint) -> Self {
363 let mut acc: Self = Int::one();
375 macro_rules! checked_op {
376 ($T:ty, $U:ty, $op:path, $x:expr, $y:expr) => {{
377 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
378 if overflowed { None } else { Some(result as $T) }
382 macro_rules! uint_impl {
383 ($T:ty = $ActualT:ty, $BITS:expr,
388 $add_with_overflow:path,
389 $sub_with_overflow:path,
390 $mul_with_overflow:path) => {
391 #[unstable = "trait is unstable"]
394 fn zero() -> $T { 0 }
400 fn min_value() -> $T { 0 }
403 fn max_value() -> $T { -1 }
406 fn count_ones(self) -> uint { unsafe { $ctpop(self as $ActualT) as uint } }
409 fn leading_zeros(self) -> uint { unsafe { $ctlz(self as $ActualT) as uint } }
412 fn trailing_zeros(self) -> uint { unsafe { $cttz(self as $ActualT) as uint } }
415 fn rotate_left(self, n: uint) -> $T {
416 // Protect against undefined behaviour for over-long bit shifts
418 (self << n) | (self >> (($BITS - n) % $BITS))
422 fn rotate_right(self, n: uint) -> $T {
423 // Protect against undefined behaviour for over-long bit shifts
425 (self >> n) | (self << (($BITS - n) % $BITS))
429 fn swap_bytes(self) -> $T { unsafe { $bswap(self as $ActualT) as $T } }
432 fn checked_add(self, other: $T) -> Option<$T> {
433 checked_op!($T, $ActualT, $add_with_overflow, self, other)
437 fn checked_sub(self, other: $T) -> Option<$T> {
438 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
442 fn checked_mul(self, other: $T) -> Option<$T> {
443 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
447 fn checked_div(self, v: $T) -> Option<$T> {
457 /// Swapping a single byte is a no-op. This is marked as `unsafe` for
458 /// consistency with the other `bswap` intrinsics.
459 unsafe fn bswap8(x: u8) -> u8 { x }
461 uint_impl!(u8 = u8, 8,
466 intrinsics::u8_add_with_overflow,
467 intrinsics::u8_sub_with_overflow,
468 intrinsics::u8_mul_with_overflow)
470 uint_impl!(u16 = u16, 16,
475 intrinsics::u16_add_with_overflow,
476 intrinsics::u16_sub_with_overflow,
477 intrinsics::u16_mul_with_overflow)
479 uint_impl!(u32 = u32, 32,
484 intrinsics::u32_add_with_overflow,
485 intrinsics::u32_sub_with_overflow,
486 intrinsics::u32_mul_with_overflow)
488 uint_impl!(u64 = u64, 64,
493 intrinsics::u64_add_with_overflow,
494 intrinsics::u64_sub_with_overflow,
495 intrinsics::u64_mul_with_overflow)
497 #[cfg(target_word_size = "32")]
498 uint_impl!(uint = u32, 32,
503 intrinsics::u32_add_with_overflow,
504 intrinsics::u32_sub_with_overflow,
505 intrinsics::u32_mul_with_overflow)
507 #[cfg(target_word_size = "64")]
508 uint_impl!(uint = u64, 64,
513 intrinsics::u64_add_with_overflow,
514 intrinsics::u64_sub_with_overflow,
515 intrinsics::u64_mul_with_overflow)
517 macro_rules! int_impl {
518 ($T:ty = $ActualT:ty, $UnsignedT:ty, $BITS:expr,
519 $add_with_overflow:path,
520 $sub_with_overflow:path,
521 $mul_with_overflow:path) => {
522 #[unstable = "trait is unstable"]
525 fn zero() -> $T { 0 }
531 fn min_value() -> $T { (-1 as $T) << ($BITS - 1) }
534 fn max_value() -> $T { let min: $T = Int::min_value(); !min }
537 fn count_ones(self) -> uint { (self as $UnsignedT).count_ones() }
540 fn leading_zeros(self) -> uint { (self as $UnsignedT).leading_zeros() }
543 fn trailing_zeros(self) -> uint { (self as $UnsignedT).trailing_zeros() }
546 fn rotate_left(self, n: uint) -> $T { (self as $UnsignedT).rotate_left(n) as $T }
549 fn rotate_right(self, n: uint) -> $T { (self as $UnsignedT).rotate_right(n) as $T }
552 fn swap_bytes(self) -> $T { (self as $UnsignedT).swap_bytes() as $T }
555 fn checked_add(self, other: $T) -> Option<$T> {
556 checked_op!($T, $ActualT, $add_with_overflow, self, other)
560 fn checked_sub(self, other: $T) -> Option<$T> {
561 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
565 fn checked_mul(self, other: $T) -> Option<$T> {
566 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
570 fn checked_div(self, v: $T) -> Option<$T> {
573 -1 if self == Int::min_value()
582 int_impl!(i8 = i8, u8, 8,
583 intrinsics::i8_add_with_overflow,
584 intrinsics::i8_sub_with_overflow,
585 intrinsics::i8_mul_with_overflow)
587 int_impl!(i16 = i16, u16, 16,
588 intrinsics::i16_add_with_overflow,
589 intrinsics::i16_sub_with_overflow,
590 intrinsics::i16_mul_with_overflow)
592 int_impl!(i32 = i32, u32, 32,
593 intrinsics::i32_add_with_overflow,
594 intrinsics::i32_sub_with_overflow,
595 intrinsics::i32_mul_with_overflow)
597 int_impl!(i64 = i64, u64, 64,
598 intrinsics::i64_add_with_overflow,
599 intrinsics::i64_sub_with_overflow,
600 intrinsics::i64_mul_with_overflow)
602 #[cfg(target_word_size = "32")]
603 int_impl!(int = i32, u32, 32,
604 intrinsics::i32_add_with_overflow,
605 intrinsics::i32_sub_with_overflow,
606 intrinsics::i32_mul_with_overflow)
608 #[cfg(target_word_size = "64")]
609 int_impl!(int = i64, u64, 64,
610 intrinsics::i64_add_with_overflow,
611 intrinsics::i64_sub_with_overflow,
612 intrinsics::i64_mul_with_overflow)
614 /// A built-in two's complement integer.
615 #[unstable = "recently settled as part of numerics reform"]
620 /// Computes the absolute value of `self`. `Int::min_value()` will be
621 /// returned if the number is `Int::min_value()`.
622 fn abs(self) -> Self;
624 /// Returns a number representing sign of `self`.
626 /// - `0` if the number is zero
627 /// - `1` if the number is positive
628 /// - `-1` if the number is negative
629 fn signum(self) -> Self;
631 /// Returns `true` if `self` is positive and `false` if the number
632 /// is zero or negative.
633 fn is_positive(self) -> bool;
635 /// Returns `true` if `self` is negative and `false` if the number
636 /// is zero or positive.
637 fn is_negative(self) -> bool;
640 macro_rules! signed_int_impl {
642 impl SignedInt for $T {
645 if self.is_negative() { -self } else { self }
649 fn signum(self) -> $T {
658 fn is_positive(self) -> bool { self > 0 }
661 fn is_negative(self) -> bool { self < 0 }
667 signed_int_impl!(i16)
668 signed_int_impl!(i32)
669 signed_int_impl!(i64)
670 signed_int_impl!(int)
672 /// A built-in unsigned integer.
673 #[unstable = "recently settled as part of numerics reform"]
674 pub trait UnsignedInt: Int {
675 /// Returns `true` iff `self == 2^k` for some `k`.
676 fn is_power_of_two(self) -> bool {
677 (self - Int::one()) & self == Int::zero()
680 /// Returns the smallest power of two greater than or equal to `self`.
682 fn next_power_of_two(self) -> Self {
683 let halfbits = size_of::<Self>() * 4;
684 let mut tmp = self - Int::one();
686 while shift <= halfbits {
687 tmp = tmp | (tmp >> shift);
693 /// Returns the smallest power of two greater than or equal to `n`. If the
694 /// next power of two is greater than the type's maximum value, `None` is
695 /// returned, otherwise the power of two is wrapped in `Some`.
696 fn checked_next_power_of_two(self) -> Option<Self> {
697 let halfbits = size_of::<Self>() * 4;
698 let mut tmp = self - Int::one();
700 while shift <= halfbits {
701 tmp = tmp | (tmp >> shift);
704 tmp.checked_add(Int::one())
708 #[unstable = "trait is unstable"]
709 impl UnsignedInt for uint {}
711 #[unstable = "trait is unstable"]
712 impl UnsignedInt for u8 {}
714 #[unstable = "trait is unstable"]
715 impl UnsignedInt for u16 {}
717 #[unstable = "trait is unstable"]
718 impl UnsignedInt for u32 {}
720 #[unstable = "trait is unstable"]
721 impl UnsignedInt for u64 {}
723 /// A generic trait for converting a value to a number.
724 #[experimental = "trait is likely to be removed"]
725 pub trait ToPrimitive {
726 /// Converts the value of `self` to an `int`.
728 fn to_int(&self) -> Option<int> {
729 self.to_i64().and_then(|x| x.to_int())
732 /// Converts the value of `self` to an `i8`.
734 fn to_i8(&self) -> Option<i8> {
735 self.to_i64().and_then(|x| x.to_i8())
738 /// Converts the value of `self` to an `i16`.
740 fn to_i16(&self) -> Option<i16> {
741 self.to_i64().and_then(|x| x.to_i16())
744 /// Converts the value of `self` to an `i32`.
746 fn to_i32(&self) -> Option<i32> {
747 self.to_i64().and_then(|x| x.to_i32())
750 /// Converts the value of `self` to an `i64`.
751 fn to_i64(&self) -> Option<i64>;
753 /// Converts the value of `self` to an `uint`.
755 fn to_uint(&self) -> Option<uint> {
756 self.to_u64().and_then(|x| x.to_uint())
759 /// Converts the value of `self` to an `u8`.
761 fn to_u8(&self) -> Option<u8> {
762 self.to_u64().and_then(|x| x.to_u8())
765 /// Converts the value of `self` to an `u16`.
767 fn to_u16(&self) -> Option<u16> {
768 self.to_u64().and_then(|x| x.to_u16())
771 /// Converts the value of `self` to an `u32`.
773 fn to_u32(&self) -> Option<u32> {
774 self.to_u64().and_then(|x| x.to_u32())
777 /// Converts the value of `self` to an `u64`.
779 fn to_u64(&self) -> Option<u64>;
781 /// Converts the value of `self` to an `f32`.
783 fn to_f32(&self) -> Option<f32> {
784 self.to_f64().and_then(|x| x.to_f32())
787 /// Converts the value of `self` to an `f64`.
789 fn to_f64(&self) -> Option<f64> {
790 self.to_i64().and_then(|x| x.to_f64())
794 macro_rules! impl_to_primitive_int_to_int(
795 ($SrcT:ty, $DstT:ty, $slf:expr) => (
797 if size_of::<$SrcT>() <= size_of::<$DstT>() {
801 let min_value: $DstT = Int::min_value();
802 let max_value: $DstT = Int::max_value();
803 if min_value as i64 <= n && n <= max_value as i64 {
813 macro_rules! impl_to_primitive_int_to_uint(
814 ($SrcT:ty, $DstT:ty, $slf:expr) => (
816 let zero: $SrcT = Int::zero();
817 let max_value: $DstT = Int::max_value();
818 if zero <= $slf && $slf as u64 <= max_value as u64 {
827 macro_rules! impl_to_primitive_int(
829 impl ToPrimitive for $T {
831 fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int, *self) }
833 fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) }
835 fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) }
837 fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32, *self) }
839 fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self) }
842 fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint, *self) }
844 fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) }
846 fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) }
848 fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32, *self) }
850 fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64, *self) }
853 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
855 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
860 impl_to_primitive_int!(int)
861 impl_to_primitive_int!(i8)
862 impl_to_primitive_int!(i16)
863 impl_to_primitive_int!(i32)
864 impl_to_primitive_int!(i64)
866 macro_rules! impl_to_primitive_uint_to_int(
867 ($DstT:ty, $slf:expr) => (
869 let max_value: $DstT = Int::max_value();
870 if $slf as u64 <= max_value as u64 {
879 macro_rules! impl_to_primitive_uint_to_uint(
880 ($SrcT:ty, $DstT:ty, $slf:expr) => (
882 if size_of::<$SrcT>() <= size_of::<$DstT>() {
885 let zero: $SrcT = Int::zero();
886 let max_value: $DstT = Int::max_value();
887 if zero <= $slf && $slf as u64 <= max_value as u64 {
897 macro_rules! impl_to_primitive_uint(
899 impl ToPrimitive for $T {
901 fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int, *self) }
903 fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) }
905 fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) }
907 fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32, *self) }
909 fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) }
912 fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint, *self) }
914 fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) }
916 fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) }
918 fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32, *self) }
920 fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64, *self) }
923 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
925 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
930 impl_to_primitive_uint!(uint)
931 impl_to_primitive_uint!(u8)
932 impl_to_primitive_uint!(u16)
933 impl_to_primitive_uint!(u32)
934 impl_to_primitive_uint!(u64)
936 macro_rules! impl_to_primitive_float_to_float(
937 ($SrcT:ty, $DstT:ty, $slf:expr) => (
938 if size_of::<$SrcT>() <= size_of::<$DstT>() {
942 let max_value: $SrcT = Float::max_value();
943 if -max_value as f64 <= n && n <= max_value as f64 {
952 macro_rules! impl_to_primitive_float(
954 impl ToPrimitive for $T {
956 fn to_int(&self) -> Option<int> { Some(*self as int) }
958 fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
960 fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
962 fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
964 fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
967 fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
969 fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
971 fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
973 fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
975 fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
978 fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32, *self) }
980 fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64, *self) }
985 impl_to_primitive_float!(f32)
986 impl_to_primitive_float!(f64)
988 /// A generic trait for converting a number to a value.
989 #[experimental = "trait is likely to be removed"]
990 pub trait FromPrimitive {
991 /// Convert an `int` to return an optional value of this type. If the
992 /// value cannot be represented by this value, the `None` is returned.
994 fn from_int(n: int) -> Option<Self> {
995 FromPrimitive::from_i64(n as i64)
998 /// Convert an `i8` to return an optional value of this type. If the
999 /// type cannot be represented by this value, the `None` is returned.
1001 fn from_i8(n: i8) -> Option<Self> {
1002 FromPrimitive::from_i64(n as i64)
1005 /// Convert an `i16` to return an optional value of this type. If the
1006 /// type cannot be represented by this value, the `None` is returned.
1008 fn from_i16(n: i16) -> Option<Self> {
1009 FromPrimitive::from_i64(n as i64)
1012 /// Convert an `i32` to return an optional value of this type. If the
1013 /// type cannot be represented by this value, the `None` is returned.
1015 fn from_i32(n: i32) -> Option<Self> {
1016 FromPrimitive::from_i64(n as i64)
1019 /// Convert an `i64` to return an optional value of this type. If the
1020 /// type cannot be represented by this value, the `None` is returned.
1021 fn from_i64(n: i64) -> Option<Self>;
1023 /// Convert an `uint` to return an optional value of this type. If the
1024 /// type cannot be represented by this value, the `None` is returned.
1026 fn from_uint(n: uint) -> Option<Self> {
1027 FromPrimitive::from_u64(n as u64)
1030 /// Convert an `u8` to return an optional value of this type. If the
1031 /// type cannot be represented by this value, the `None` is returned.
1033 fn from_u8(n: u8) -> Option<Self> {
1034 FromPrimitive::from_u64(n as u64)
1037 /// Convert an `u16` to return an optional value of this type. If the
1038 /// type cannot be represented by this value, the `None` is returned.
1040 fn from_u16(n: u16) -> Option<Self> {
1041 FromPrimitive::from_u64(n as u64)
1044 /// Convert an `u32` to return an optional value of this type. If the
1045 /// type cannot be represented by this value, the `None` is returned.
1047 fn from_u32(n: u32) -> Option<Self> {
1048 FromPrimitive::from_u64(n as u64)
1051 /// Convert an `u64` to return an optional value of this type. If the
1052 /// type cannot be represented by this value, the `None` is returned.
1053 fn from_u64(n: u64) -> Option<Self>;
1055 /// Convert a `f32` to return an optional value of this type. If the
1056 /// type cannot be represented by this value, the `None` is returned.
1058 fn from_f32(n: f32) -> Option<Self> {
1059 FromPrimitive::from_f64(n as f64)
1062 /// Convert a `f64` to return an optional value of this type. If the
1063 /// type cannot be represented by this value, the `None` is returned.
1065 fn from_f64(n: f64) -> Option<Self> {
1066 FromPrimitive::from_i64(n as i64)
1070 /// A utility function that just calls `FromPrimitive::from_int`.
1071 #[experimental = "likely to be removed"]
1072 pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
1073 FromPrimitive::from_int(n)
1076 /// A utility function that just calls `FromPrimitive::from_i8`.
1077 #[experimental = "likely to be removed"]
1078 pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> {
1079 FromPrimitive::from_i8(n)
1082 /// A utility function that just calls `FromPrimitive::from_i16`.
1083 #[experimental = "likely to be removed"]
1084 pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> {
1085 FromPrimitive::from_i16(n)
1088 /// A utility function that just calls `FromPrimitive::from_i32`.
1089 #[experimental = "likely to be removed"]
1090 pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> {
1091 FromPrimitive::from_i32(n)
1094 /// A utility function that just calls `FromPrimitive::from_i64`.
1095 #[experimental = "likely to be removed"]
1096 pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
1097 FromPrimitive::from_i64(n)
1100 /// A utility function that just calls `FromPrimitive::from_uint`.
1101 #[experimental = "likely to be removed"]
1102 pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
1103 FromPrimitive::from_uint(n)
1106 /// A utility function that just calls `FromPrimitive::from_u8`.
1107 #[experimental = "likely to be removed"]
1108 pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> {
1109 FromPrimitive::from_u8(n)
1112 /// A utility function that just calls `FromPrimitive::from_u16`.
1113 #[experimental = "likely to be removed"]
1114 pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> {
1115 FromPrimitive::from_u16(n)
1118 /// A utility function that just calls `FromPrimitive::from_u32`.
1119 #[experimental = "likely to be removed"]
1120 pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> {
1121 FromPrimitive::from_u32(n)
1124 /// A utility function that just calls `FromPrimitive::from_u64`.
1125 #[experimental = "likely to be removed"]
1126 pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> {
1127 FromPrimitive::from_u64(n)
1130 /// A utility function that just calls `FromPrimitive::from_f32`.
1131 #[experimental = "likely to be removed"]
1132 pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> {
1133 FromPrimitive::from_f32(n)
1136 /// A utility function that just calls `FromPrimitive::from_f64`.
1137 #[experimental = "likely to be removed"]
1138 pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {
1139 FromPrimitive::from_f64(n)
1142 macro_rules! impl_from_primitive(
1143 ($T:ty, $to_ty:ident) => (
1144 impl FromPrimitive for $T {
1145 #[inline] fn from_int(n: int) -> Option<$T> { n.$to_ty() }
1146 #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() }
1147 #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() }
1148 #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() }
1149 #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() }
1151 #[inline] fn from_uint(n: uint) -> Option<$T> { n.$to_ty() }
1152 #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() }
1153 #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() }
1154 #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() }
1155 #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() }
1157 #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() }
1158 #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() }
1163 impl_from_primitive!(int, to_int)
1164 impl_from_primitive!(i8, to_i8)
1165 impl_from_primitive!(i16, to_i16)
1166 impl_from_primitive!(i32, to_i32)
1167 impl_from_primitive!(i64, to_i64)
1168 impl_from_primitive!(uint, to_uint)
1169 impl_from_primitive!(u8, to_u8)
1170 impl_from_primitive!(u16, to_u16)
1171 impl_from_primitive!(u32, to_u32)
1172 impl_from_primitive!(u64, to_u64)
1173 impl_from_primitive!(f32, to_f32)
1174 impl_from_primitive!(f64, to_f64)
1176 /// Cast from one machine scalar to another.
1183 /// let twenty: f32 = num::cast(0x14i).unwrap();
1184 /// assert_eq!(twenty, 20f32);
1188 #[experimental = "likely to be removed"]
1189 pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
1193 /// An interface for casting between machine scalars.
1194 #[experimental = "trait is likely to be removed"]
1195 pub trait NumCast: ToPrimitive {
1196 /// Creates a number from another value that can be converted into a primitive via the
1197 /// `ToPrimitive` trait.
1198 fn from<T: ToPrimitive>(n: T) -> Option<Self>;
1201 macro_rules! impl_num_cast(
1202 ($T:ty, $conv:ident) => (
1203 impl NumCast for $T {
1205 fn from<N: ToPrimitive>(n: N) -> Option<$T> {
1206 // `$conv` could be generated using `concat_idents!`, but that
1207 // macro seems to be broken at the moment
1214 impl_num_cast!(u8, to_u8)
1215 impl_num_cast!(u16, to_u16)
1216 impl_num_cast!(u32, to_u32)
1217 impl_num_cast!(u64, to_u64)
1218 impl_num_cast!(uint, to_uint)
1219 impl_num_cast!(i8, to_i8)
1220 impl_num_cast!(i16, to_i16)
1221 impl_num_cast!(i32, to_i32)
1222 impl_num_cast!(i64, to_i64)
1223 impl_num_cast!(int, to_int)
1224 impl_num_cast!(f32, to_f32)
1225 impl_num_cast!(f64, to_f64)
1227 /// Used for representing the classification of floating point numbers
1228 #[deriving(PartialEq, Show)]
1229 #[unstable = "may be renamed"]
1230 pub enum FPCategory {
1231 /// "Not a Number", often obtained by dividing by zero
1233 /// Positive or negative infinity
1235 /// Positive or negative zero
1237 /// De-normalized floating point representation (less precise than `FPNormal`)
1239 /// A regular floating point number
1243 impl Copy for FPCategory {}
1245 /// A built-in floating point number.
1246 // FIXME(#5527): In a future version of Rust, many of these functions will
1247 // become constants.
1249 // FIXME(#8888): Several of these functions have a parameter named
1250 // `unused_self`. Removing it requires #8888 to be fixed.
1251 #[unstable = "recently settled as part of numerics reform"]
1264 /// Returns the NaN value.
1266 /// Returns the infinite value.
1267 fn infinity() -> Self;
1268 /// Returns the negative infinite value.
1269 fn neg_infinity() -> Self;
1270 /// Returns the `0` value.
1273 fn neg_zero() -> Self;
1274 /// Returns the `1` value.
1277 /// Returns true if this value is NaN and false otherwise.
1278 fn is_nan(self) -> bool;
1279 /// Returns true if this value is positive infinity or negative infinity and
1280 /// false otherwise.
1281 fn is_infinite(self) -> bool;
1282 /// Returns true if this number is neither infinite nor NaN.
1283 fn is_finite(self) -> bool;
1284 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1285 fn is_normal(self) -> bool;
1286 /// Returns the category that this number falls into.
1287 fn classify(self) -> FPCategory;
1289 // FIXME (#5527): These should be associated constants
1291 /// Returns the number of binary digits of mantissa that this type supports.
1292 fn mantissa_digits(unused_self: Option<Self>) -> uint;
1293 /// Returns the number of base-10 digits of precision that this type supports.
1294 fn digits(unused_self: Option<Self>) -> uint;
1295 /// Returns the difference between 1.0 and the smallest representable number larger than 1.0.
1296 fn epsilon() -> Self;
1297 /// Returns the minimum binary exponent that this type can represent.
1298 fn min_exp(unused_self: Option<Self>) -> int;
1299 /// Returns the maximum binary exponent that this type can represent.
1300 fn max_exp(unused_self: Option<Self>) -> int;
1301 /// Returns the minimum base-10 exponent that this type can represent.
1302 fn min_10_exp(unused_self: Option<Self>) -> int;
1303 /// Returns the maximum base-10 exponent that this type can represent.
1304 fn max_10_exp(unused_self: Option<Self>) -> int;
1305 /// Returns the smallest finite value that this type can represent.
1306 fn min_value() -> Self;
1307 /// Returns the smallest normalized positive number that this type can represent.
1308 fn min_pos_value(unused_self: Option<Self>) -> Self;
1309 /// Returns the largest finite value that this type can represent.
1310 fn max_value() -> Self;
1312 /// Returns the mantissa, exponent and sign as integers, respectively.
1313 fn integer_decode(self) -> (u64, i16, i8);
1315 /// Return the largest integer less than or equal to a number.
1316 fn floor(self) -> Self;
1317 /// Return the smallest integer greater than or equal to a number.
1318 fn ceil(self) -> Self;
1319 /// Return the nearest integer to a number. Round half-way cases away from
1321 fn round(self) -> Self;
1322 /// Return the integer part of a number.
1323 fn trunc(self) -> Self;
1324 /// Return the fractional part of a number.
1325 fn fract(self) -> Self;
1327 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1328 /// number is `Float::nan()`.
1329 fn abs(self) -> Self;
1330 /// Returns a number that represents the sign of `self`.
1332 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1333 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1334 /// - `Float::nan()` if the number is `Float::nan()`
1335 fn signum(self) -> Self;
1336 /// Returns `true` if `self` is positive, including `+0.0` and
1337 /// `Float::infinity()`.
1338 fn is_positive(self) -> bool;
1339 /// Returns `true` if `self` is negative, including `-0.0` and
1340 /// `Float::neg_infinity()`.
1341 fn is_negative(self) -> bool;
1343 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1344 /// error. This produces a more accurate result with better performance than
1345 /// a separate multiplication operation followed by an add.
1346 fn mul_add(self, a: Self, b: Self) -> Self;
1347 /// Take the reciprocal (inverse) of a number, `1/x`.
1348 fn recip(self) -> Self;
1350 /// Raise a number to an integer power.
1352 /// Using this function is generally faster than using `powf`
1353 fn powi(self, n: i32) -> Self;
1354 /// Raise a number to a floating point power.
1355 fn powf(self, n: Self) -> Self;
1359 /// 1.0 / sqrt(2.0).
1360 fn frac_1_sqrt2() -> Self;
1362 /// Take the square root of a number.
1364 /// Returns NaN if `self` is a negative number.
1365 fn sqrt(self) -> Self;
1366 /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1367 fn rsqrt(self) -> Self;
1369 /// Archimedes' constant.
1370 #[deprecated = "use f32::consts or f64::consts instead"]
1373 #[deprecated = "use f32::consts or f64::consts instead"]
1374 fn two_pi() -> Self;
1376 #[deprecated = "use f32::consts or f64::consts instead"]
1377 fn frac_pi_2() -> Self;
1379 #[deprecated = "use f32::consts or f64::consts instead"]
1380 fn frac_pi_3() -> Self;
1382 #[deprecated = "use f32::consts or f64::consts instead"]
1383 fn frac_pi_4() -> Self;
1385 #[deprecated = "use f32::consts or f64::consts instead"]
1386 fn frac_pi_6() -> Self;
1388 #[deprecated = "use f32::consts or f64::consts instead"]
1389 fn frac_pi_8() -> Self;
1391 #[deprecated = "use f32::consts or f64::consts instead"]
1392 fn frac_1_pi() -> Self;
1394 #[deprecated = "use f32::consts or f64::consts instead"]
1395 fn frac_2_pi() -> Self;
1397 #[deprecated = "use f32::consts or f64::consts instead"]
1398 fn frac_2_sqrtpi() -> Self;
1401 #[deprecated = "use f32::consts or f64::consts instead"]
1404 #[deprecated = "use f32::consts or f64::consts instead"]
1405 fn log2_e() -> Self;
1407 #[deprecated = "use f32::consts or f64::consts instead"]
1408 fn log10_e() -> Self;
1410 #[deprecated = "use f32::consts or f64::consts instead"]
1413 #[deprecated = "use f32::consts or f64::consts instead"]
1416 /// Returns `e^(self)`, (the exponential function).
1417 fn exp(self) -> Self;
1418 /// Returns 2 raised to the power of the number, `2^(self)`.
1419 fn exp2(self) -> Self;
1420 /// Returns the natural logarithm of the number.
1421 fn ln(self) -> Self;
1422 /// Returns the logarithm of the number with respect to an arbitrary base.
1423 fn log(self, base: Self) -> Self;
1424 /// Returns the base 2 logarithm of the number.
1425 fn log2(self) -> Self;
1426 /// Returns the base 10 logarithm of the number.
1427 fn log10(self) -> Self;
1429 /// Convert radians to degrees.
1430 fn to_degrees(self) -> Self;
1431 /// Convert degrees to radians.
1432 fn to_radians(self) -> Self;
1435 /// A generic trait for converting a string with a radix (base) to a value
1436 #[experimental = "might need to return Result"]
1437 pub trait FromStrRadix {
1438 fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
1441 /// A utility function that just calls FromStrRadix::from_str_radix.
1442 #[experimental = "might need to return Result"]
1443 pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint) -> Option<T> {
1444 FromStrRadix::from_str_radix(str, radix)
1447 macro_rules! from_str_radix_float_impl {
1449 #[experimental = "might need to return Result"]
1450 impl FromStr for $T {
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) -> Option<$T> {
1478 from_str_radix(src, 10)
1482 #[experimental = "might need to return Result"]
1483 impl FromStrRadix for $T {
1484 /// Convert a string in a given base to a float.
1486 /// Due to possible conflicts, this function does **not** accept
1487 /// the special values `inf`, `-inf`, `+inf` and `NaN`, **nor**
1488 /// does it recognize exponents of any kind.
1490 /// Leading and trailing whitespace represent an error.
1494 /// * src - A string
1495 /// * radix - The base to use. Must lie in the range [2 .. 36]
1499 /// `None` if the string did not represent a valid number. Otherwise,
1500 /// `Some(n)` where `n` is the floating-point number represented by `src`.
1501 fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
1502 assert!(radix >= 2 && radix <= 36,
1503 "from_str_radix_float: must lie in the range `[2, 36]` - found {}",
1508 "inf" => return Some(Float::infinity()),
1509 "-inf" => return Some(Float::neg_infinity()),
1510 "NaN" => return Some(Float::nan()),
1514 let (is_positive, src) = match src.slice_shift_char() {
1515 None => return None,
1516 Some(('-', "")) => return None,
1517 Some(('-', src)) => (false, src),
1518 Some((_, _)) => (true, src),
1521 // The significand to accumulate
1522 let mut sig = if is_positive { 0.0 } else { -0.0 };
1523 // Necessary to detect overflow
1524 let mut prev_sig = sig;
1525 let mut cs = src.chars().enumerate();
1526 // Exponent prefix and exponent index offset
1527 let mut exp_info = None::<(char, uint)>;
1529 // Parse the integer part of the significand
1531 match c.to_digit(radix) {
1533 // shift significand one digit left
1534 sig = sig * (radix as $T);
1536 // add/subtract current digit depending on sign
1538 sig = sig + ((digit as int) as $T);
1540 sig = sig - ((digit as int) as $T);
1543 // Detect overflow by comparing to last value, except
1544 // if we've not seen any non-zero digits.
1545 if prev_sig != 0.0 {
1546 if is_positive && sig <= prev_sig
1547 { return Some(Float::infinity()); }
1548 if !is_positive && sig >= prev_sig
1549 { return Some(Float::neg_infinity()); }
1551 // Detect overflow by reversing the shift-and-add process
1552 if is_positive && (prev_sig != (sig - digit as $T) / radix as $T)
1553 { return Some(Float::infinity()); }
1554 if !is_positive && (prev_sig != (sig + digit as $T) / radix as $T)
1555 { return Some(Float::neg_infinity()); }
1560 'e' | 'E' | 'p' | 'P' => {
1561 exp_info = Some((c, i + 1));
1562 break; // start of exponent
1565 break; // start of fractional part
1574 // If we are not yet at the exponent parse the fractional
1575 // part of the significand
1576 if exp_info.is_none() {
1577 let mut power = 1.0;
1579 match c.to_digit(radix) {
1581 // Decrease power one order of magnitude
1582 power = power / (radix as $T);
1583 // add/subtract current digit depending on sign
1584 sig = if is_positive {
1585 sig + (digit as $T) * power
1587 sig - (digit as $T) * power
1589 // Detect overflow by comparing to last value
1590 if is_positive && sig < prev_sig
1591 { return Some(Float::infinity()); }
1592 if !is_positive && sig > prev_sig
1593 { return Some(Float::neg_infinity()); }
1597 'e' | 'E' | 'p' | 'P' => {
1598 exp_info = Some((c, i + 1));
1599 break; // start of exponent
1602 return None; // invalid number
1609 // Parse and calculate the exponent
1610 let exp = match exp_info {
1611 Some((c, offset)) => {
1612 let base = match c {
1613 'E' | 'e' if radix == 10 => 10u as $T,
1614 'P' | 'p' if radix == 16 => 2u as $T,
1618 // Parse the exponent as decimal integer
1619 let src = src[offset..];
1620 let (is_positive, exp) = match src.slice_shift_char() {
1621 Some(('-', src)) => (false, from_str::<uint>(src)),
1622 Some(('+', src)) => (true, from_str::<uint>(src)),
1623 Some((_, _)) => (true, from_str::<uint>(src)),
1624 None => return None,
1627 match (is_positive, exp) {
1628 (true, Some(exp)) => base.powi(exp as i32),
1629 (false, Some(exp)) => 1.0 / base.powi(exp as i32),
1630 (_, None) => return None,
1633 None => 1.0, // no exponent
1641 from_str_radix_float_impl!(f32)
1642 from_str_radix_float_impl!(f64)
1644 macro_rules! from_str_radix_int_impl {
1646 #[experimental = "might need to return Result"]
1647 impl FromStr for $T {
1649 fn from_str(src: &str) -> Option<$T> {
1650 from_str_radix(src, 10)
1654 #[experimental = "might need to return Result"]
1655 impl FromStrRadix for $T {
1656 fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
1657 assert!(radix >= 2 && radix <= 36,
1658 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1661 let is_signed_ty = (0 as $T) > Int::min_value();
1663 match src.slice_shift_char() {
1664 Some(('-', src)) if is_signed_ty => {
1665 // The number is negative
1667 for c in src.chars() {
1668 let x = match c.to_digit(radix) {
1670 None => return None,
1672 result = match result.checked_mul(radix as $T) {
1673 Some(result) => result,
1674 None => return None,
1676 result = match result.checked_sub(x as $T) {
1677 Some(result) => result,
1678 None => return None,
1684 // The number is signed
1686 for c in src.chars() {
1687 let x = match c.to_digit(radix) {
1689 None => return None,
1691 result = match result.checked_mul(radix as $T) {
1692 Some(result) => result,
1693 None => return None,
1695 result = match result.checked_add(x as $T) {
1696 Some(result) => result,
1697 None => return None,
1708 from_str_radix_int_impl!(int)
1709 from_str_radix_int_impl!(i8)
1710 from_str_radix_int_impl!(i16)
1711 from_str_radix_int_impl!(i32)
1712 from_str_radix_int_impl!(i64)
1713 from_str_radix_int_impl!(uint)
1714 from_str_radix_int_impl!(u8)
1715 from_str_radix_int_impl!(u16)
1716 from_str_radix_int_impl!(u32)
1717 from_str_radix_int_impl!(u64)
1721 macro_rules! trait_impl {
1722 ($name:ident for $($t:ty)*) => {
1723 $(#[allow(deprecated)] impl $name for $t {})*
1727 #[deprecated = "Generalised numbers are no longer supported"]
1728 #[allow(deprecated)]
1729 pub trait Num: PartialEq + Zero + One
1736 trait_impl!(Num for uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
1738 #[deprecated = "Generalised unsigned numbers are no longer supported"]
1739 #[allow(deprecated)]
1740 pub trait Unsigned: Num {}
1741 trait_impl!(Unsigned for uint u8 u16 u32 u64)
1743 #[deprecated = "Use `Float` or `Int`"]
1744 #[allow(deprecated)]
1745 pub trait Primitive: Copy + Clone + Num + NumCast + PartialOrd {}
1746 trait_impl!(Primitive for uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
1748 #[deprecated = "The generic `Zero` trait will be removed soon."]
1749 pub trait Zero: Add<Self, Self> {
1750 #[deprecated = "Use `Int::zero()` or `Float::zero()`."]
1752 #[deprecated = "Use `x == Int::zero()` or `x == Float::zero()`."]
1753 fn is_zero(&self) -> bool;
1755 #[deprecated = "Use `Int::zero()` or `Float::zero()`."]
1756 #[allow(deprecated)]
1757 pub fn zero<T: Zero>() -> T { Zero::zero() }
1758 macro_rules! zero_impl {
1759 ($t:ty, $v:expr) => {
1761 fn zero() -> $t { $v }
1762 fn is_zero(&self) -> bool { *self == $v }
1766 zero_impl!(uint, 0u)
1768 zero_impl!(u16, 0u16)
1769 zero_impl!(u32, 0u32)
1770 zero_impl!(u64, 0u64)
1773 zero_impl!(i16, 0i16)
1774 zero_impl!(i32, 0i32)
1775 zero_impl!(i64, 0i64)
1776 zero_impl!(f32, 0.0f32)
1777 zero_impl!(f64, 0.0f64)
1779 #[deprecated = "The generic `One` trait will be removed soon."]
1780 pub trait One: Mul<Self, Self> {
1781 #[deprecated = "Use `Int::one()` or `Float::one()`."]
1784 #[deprecated = "Use `Int::one()` or `Float::one()`."]
1785 #[allow(deprecated)]
1786 pub fn one<T: One>() -> T { One::one() }
1787 macro_rules! one_impl {
1788 ($t:ty, $v:expr) => {
1790 fn one() -> $t { $v }
1796 one_impl!(u16, 1u16)
1797 one_impl!(u32, 1u32)
1798 one_impl!(u64, 1u64)
1801 one_impl!(i16, 1i16)
1802 one_impl!(i32, 1i32)
1803 one_impl!(i64, 1i64)
1804 one_impl!(f32, 1.0f32)
1805 one_impl!(f64, 1.0f64)
1807 #[deprecated = "Use `UnsignedInt::next_power_of_two`"]
1808 pub fn next_power_of_two<T: UnsignedInt>(n: T) -> T {
1809 n.next_power_of_two()
1811 #[deprecated = "Use `UnsignedInt::is_power_of_two`"]
1812 pub fn is_power_of_two<T: UnsignedInt>(n: T) -> bool {
1815 #[deprecated = "Use `UnsignedInt::checked_next_power_of_two`"]
1816 pub fn checked_next_power_of_two<T: UnsignedInt>(n: T) -> Option<T> {
1817 n.checked_next_power_of_two()
1820 #[deprecated = "Generalised bounded values are no longer supported"]
1822 #[deprecated = "Use `Int::min_value` or `Float::min_value`"]
1823 fn min_value() -> Self;
1824 #[deprecated = "Use `Int::max_value` or `Float::max_value`"]
1825 fn max_value() -> Self;
1827 macro_rules! bounded_impl {
1828 ($T:ty, $min:expr, $max:expr) => {
1829 impl Bounded for $T {
1831 fn min_value() -> $T { $min }
1834 fn max_value() -> $T { $max }
1838 bounded_impl!(uint, uint::MIN, uint::MAX)
1839 bounded_impl!(u8, u8::MIN, u8::MAX)
1840 bounded_impl!(u16, u16::MIN, u16::MAX)
1841 bounded_impl!(u32, u32::MIN, u32::MAX)
1842 bounded_impl!(u64, u64::MIN, u64::MAX)
1843 bounded_impl!(int, int::MIN, int::MAX)
1844 bounded_impl!(i8, i8::MIN, i8::MAX)
1845 bounded_impl!(i16, i16::MIN, i16::MAX)
1846 bounded_impl!(i32, i32::MIN, i32::MAX)
1847 bounded_impl!(i64, i64::MIN, i64::MAX)
1848 bounded_impl!(f32, f32::MIN_VALUE, f32::MAX_VALUE)
1849 bounded_impl!(f64, f64::MIN_VALUE, f64::MAX_VALUE)