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 use {int, i8, i16, i32, i64};
19 use {uint, u8, u16, u32, u64};
23 use cmp::{PartialEq, Eq};
24 use cmp::{PartialOrd, Ord};
26 use iter::IteratorExt;
29 use ops::{Add, Sub, Mul, Div, Rem, Neg};
30 use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
32 use option::Option::{Some, None};
33 use str::{FromStr, from_str, StrExt};
35 /// Simultaneous division and remainder
37 #[deprecated = "use division and remainder directly"]
38 pub fn div_rem<T: Clone + Div<Output=T> + Rem<Output=T>>(x: T, y: T) -> (T, T) {
39 (x.clone() / y.clone(), x % y)
42 /// Raises a `base` to the power of `exp`, using exponentiation by squaring.
44 #[deprecated = "Use Int::pow() instead, as in 2i.pow(4)"]
45 pub fn pow<T: Int>(base: T, exp: uint) -> T {
49 /// A built-in signed or unsigned integer.
50 #[unstable = "recently settled as part of numerics reform"]
65 + Shl<uint, Output=Self>
66 + Shr<uint, Output=Self>
68 /// Returns the `0` value of this integer type.
69 // FIXME (#5527): Should be an associated constant
72 /// Returns the `1` value of this integer type.
73 // FIXME (#5527): Should be an associated constant
76 /// Returns the smallest value that can be represented by this integer type.
77 // FIXME (#5527): Should be and associated constant
78 fn min_value() -> Self;
80 /// Returns the largest value that can be represented by this integer type.
81 // FIXME (#5527): Should be and associated constant
82 fn max_value() -> Self;
84 /// Returns the number of ones in the binary representation of `self`.
89 /// use std::num::Int;
91 /// let n = 0b01001100u8;
93 /// assert_eq!(n.count_ones(), 3);
95 fn count_ones(self) -> uint;
97 /// Returns the number of zeros in the binary representation of `self`.
102 /// use std::num::Int;
104 /// let n = 0b01001100u8;
106 /// assert_eq!(n.count_zeros(), 5);
109 fn count_zeros(self) -> uint {
113 /// Returns the number of leading zeros in the binary representation
119 /// use std::num::Int;
121 /// let n = 0b0101000u16;
123 /// assert_eq!(n.leading_zeros(), 10);
125 fn leading_zeros(self) -> uint;
127 /// Returns the number of trailing zeros in the binary representation
133 /// use std::num::Int;
135 /// let n = 0b0101000u16;
137 /// assert_eq!(n.trailing_zeros(), 3);
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 fn rotate_left(self, n: uint) -> Self;
156 /// Shifts the bits to the right by a specified amount amount, `n`, wrapping
157 /// the truncated bits to the beginning of the resulting integer.
162 /// use std::num::Int;
164 /// let n = 0x0123456789ABCDEFu64;
165 /// let m = 0xDEF0123456789ABCu64;
167 /// assert_eq!(n.rotate_right(12), m);
169 fn rotate_right(self, n: uint) -> Self;
171 /// Reverses the byte order of the integer.
176 /// use std::num::Int;
178 /// let n = 0x0123456789ABCDEFu64;
179 /// let m = 0xEFCDAB8967452301u64;
181 /// assert_eq!(n.swap_bytes(), m);
183 fn swap_bytes(self) -> Self;
185 /// Convert an integer from big endian to the target's endianness.
187 /// On big endian this is a no-op. On little endian the bytes are swapped.
192 /// use std::num::Int;
194 /// let n = 0x0123456789ABCDEFu64;
196 /// if cfg!(target_endian = "big") {
197 /// assert_eq!(Int::from_be(n), n)
199 /// assert_eq!(Int::from_be(n), n.swap_bytes())
203 fn from_be(x: Self) -> Self {
204 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
207 /// Convert an integer from little endian to the target's endianness.
209 /// On little endian this is a no-op. On big endian the bytes are swapped.
214 /// use std::num::Int;
216 /// let n = 0x0123456789ABCDEFu64;
218 /// if cfg!(target_endian = "little") {
219 /// assert_eq!(Int::from_le(n), n)
221 /// assert_eq!(Int::from_le(n), n.swap_bytes())
225 fn from_le(x: Self) -> Self {
226 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
229 /// Convert `self` to big endian from the target's endianness.
231 /// On big endian this is a no-op. On little endian the bytes are swapped.
236 /// use std::num::Int;
238 /// let n = 0x0123456789ABCDEFu64;
240 /// if cfg!(target_endian = "big") {
241 /// assert_eq!(n.to_be(), n)
243 /// assert_eq!(n.to_be(), n.swap_bytes())
247 fn to_be(self) -> Self { // or not to be?
248 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
251 /// Convert `self` to little endian from the target's endianness.
253 /// On little endian this is a no-op. On big endian the bytes are swapped.
258 /// use std::num::Int;
260 /// let n = 0x0123456789ABCDEFu64;
262 /// if cfg!(target_endian = "little") {
263 /// assert_eq!(n.to_le(), n)
265 /// assert_eq!(n.to_le(), n.swap_bytes())
269 fn to_le(self) -> Self {
270 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
273 /// Checked integer addition. Computes `self + other`, returning `None` if
274 /// overflow occurred.
279 /// use std::num::Int;
281 /// assert_eq!(5u16.checked_add(65530), Some(65535));
282 /// assert_eq!(6u16.checked_add(65530), None);
284 fn checked_add(self, other: Self) -> Option<Self>;
286 /// Checked integer subtraction. Computes `self - other`, returning `None`
287 /// if underflow occurred.
292 /// use std::num::Int;
294 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
295 /// assert_eq!((-128i8).checked_sub(1), None);
297 fn checked_sub(self, other: Self) -> Option<Self>;
299 /// Checked integer multiplication. Computes `self * other`, returning
300 /// `None` if underflow or overflow occurred.
305 /// use std::num::Int;
307 /// assert_eq!(5u8.checked_mul(51), Some(255));
308 /// assert_eq!(5u8.checked_mul(52), None);
310 fn checked_mul(self, other: Self) -> Option<Self>;
312 /// Checked integer division. Computes `self / other`, returning `None` if
313 /// `other == 0` or the operation results in underflow or overflow.
318 /// use std::num::Int;
320 /// assert_eq!((-127i8).checked_div(-1), Some(127));
321 /// assert_eq!((-128i8).checked_div(-1), None);
322 /// assert_eq!((1i8).checked_div(0), None);
325 fn checked_div(self, other: Self) -> Option<Self>;
327 /// Saturating integer addition. Computes `self + other`, saturating at
328 /// the numeric bounds instead of overflowing.
330 fn saturating_add(self, other: Self) -> Self {
331 match self.checked_add(other) {
333 None if other >= Int::zero() => Int::max_value(),
334 None => Int::min_value(),
338 /// Saturating integer subtraction. Computes `self - other`, saturating at
339 /// the numeric bounds instead of overflowing.
341 fn saturating_sub(self, other: Self) -> Self {
342 match self.checked_sub(other) {
344 None if other >= Int::zero() => Int::min_value(),
345 None => Int::max_value(),
349 /// Raises self to the power of `exp`, using exponentiation by squaring.
354 /// use std::num::Int;
356 /// assert_eq!(2i.pow(4), 16);
359 fn pow(self, mut exp: uint) -> Self {
361 let mut acc: Self = Int::one();
373 macro_rules! checked_op {
374 ($T:ty, $U:ty, $op:path, $x:expr, $y:expr) => {{
375 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
376 if overflowed { None } else { Some(result as $T) }
380 macro_rules! uint_impl {
381 ($T:ty = $ActualT:ty, $BITS:expr,
386 $add_with_overflow:path,
387 $sub_with_overflow:path,
388 $mul_with_overflow:path) => {
389 #[unstable = "trait is unstable"]
392 fn zero() -> $T { 0 }
398 fn min_value() -> $T { 0 }
401 fn max_value() -> $T { -1 }
404 fn count_ones(self) -> uint { unsafe { $ctpop(self as $ActualT) as uint } }
407 fn leading_zeros(self) -> uint { unsafe { $ctlz(self as $ActualT) as uint } }
410 fn trailing_zeros(self) -> uint { unsafe { $cttz(self as $ActualT) as uint } }
413 fn rotate_left(self, n: uint) -> $T {
414 // Protect against undefined behaviour for over-long bit shifts
416 (self << n) | (self >> (($BITS - n) % $BITS))
420 fn rotate_right(self, n: uint) -> $T {
421 // Protect against undefined behaviour for over-long bit shifts
423 (self >> n) | (self << (($BITS - n) % $BITS))
427 fn swap_bytes(self) -> $T { unsafe { $bswap(self as $ActualT) as $T } }
430 fn checked_add(self, other: $T) -> Option<$T> {
431 checked_op!($T, $ActualT, $add_with_overflow, self, other)
435 fn checked_sub(self, other: $T) -> Option<$T> {
436 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
440 fn checked_mul(self, other: $T) -> Option<$T> {
441 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
445 fn checked_div(self, v: $T) -> Option<$T> {
455 /// Swapping a single byte is a no-op. This is marked as `unsafe` for
456 /// consistency with the other `bswap` intrinsics.
457 unsafe fn bswap8(x: u8) -> u8 { x }
459 uint_impl! { u8 = u8, 8,
464 intrinsics::u8_add_with_overflow,
465 intrinsics::u8_sub_with_overflow,
466 intrinsics::u8_mul_with_overflow }
468 uint_impl! { u16 = u16, 16,
473 intrinsics::u16_add_with_overflow,
474 intrinsics::u16_sub_with_overflow,
475 intrinsics::u16_mul_with_overflow }
477 uint_impl! { u32 = u32, 32,
482 intrinsics::u32_add_with_overflow,
483 intrinsics::u32_sub_with_overflow,
484 intrinsics::u32_mul_with_overflow }
486 uint_impl! { u64 = u64, 64,
491 intrinsics::u64_add_with_overflow,
492 intrinsics::u64_sub_with_overflow,
493 intrinsics::u64_mul_with_overflow }
495 #[cfg(target_word_size = "32")]
496 uint_impl! { uint = u32, 32,
501 intrinsics::u32_add_with_overflow,
502 intrinsics::u32_sub_with_overflow,
503 intrinsics::u32_mul_with_overflow }
505 #[cfg(target_word_size = "64")]
506 uint_impl! { uint = u64, 64,
511 intrinsics::u64_add_with_overflow,
512 intrinsics::u64_sub_with_overflow,
513 intrinsics::u64_mul_with_overflow }
515 macro_rules! int_impl {
516 ($T:ty = $ActualT:ty, $UnsignedT:ty, $BITS:expr,
517 $add_with_overflow:path,
518 $sub_with_overflow:path,
519 $mul_with_overflow:path) => {
520 #[unstable = "trait is unstable"]
523 fn zero() -> $T { 0 }
529 fn min_value() -> $T { (-1 as $T) << ($BITS - 1) }
532 fn max_value() -> $T { let min: $T = Int::min_value(); !min }
535 fn count_ones(self) -> uint { (self as $UnsignedT).count_ones() }
538 fn leading_zeros(self) -> uint { (self as $UnsignedT).leading_zeros() }
541 fn trailing_zeros(self) -> uint { (self as $UnsignedT).trailing_zeros() }
544 fn rotate_left(self, n: uint) -> $T { (self as $UnsignedT).rotate_left(n) as $T }
547 fn rotate_right(self, n: uint) -> $T { (self as $UnsignedT).rotate_right(n) as $T }
550 fn swap_bytes(self) -> $T { (self as $UnsignedT).swap_bytes() as $T }
553 fn checked_add(self, other: $T) -> Option<$T> {
554 checked_op!($T, $ActualT, $add_with_overflow, self, other)
558 fn checked_sub(self, other: $T) -> Option<$T> {
559 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
563 fn checked_mul(self, other: $T) -> Option<$T> {
564 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
568 fn checked_div(self, v: $T) -> Option<$T> {
571 -1 if self == Int::min_value()
580 int_impl! { i8 = i8, u8, 8,
581 intrinsics::i8_add_with_overflow,
582 intrinsics::i8_sub_with_overflow,
583 intrinsics::i8_mul_with_overflow }
585 int_impl! { i16 = i16, u16, 16,
586 intrinsics::i16_add_with_overflow,
587 intrinsics::i16_sub_with_overflow,
588 intrinsics::i16_mul_with_overflow }
590 int_impl! { i32 = i32, u32, 32,
591 intrinsics::i32_add_with_overflow,
592 intrinsics::i32_sub_with_overflow,
593 intrinsics::i32_mul_with_overflow }
595 int_impl! { i64 = i64, u64, 64,
596 intrinsics::i64_add_with_overflow,
597 intrinsics::i64_sub_with_overflow,
598 intrinsics::i64_mul_with_overflow }
600 #[cfg(target_word_size = "32")]
601 int_impl! { int = i32, u32, 32,
602 intrinsics::i32_add_with_overflow,
603 intrinsics::i32_sub_with_overflow,
604 intrinsics::i32_mul_with_overflow }
606 #[cfg(target_word_size = "64")]
607 int_impl! { int = i64, u64, 64,
608 intrinsics::i64_add_with_overflow,
609 intrinsics::i64_sub_with_overflow,
610 intrinsics::i64_mul_with_overflow }
612 /// A built-in two's complement integer.
613 #[unstable = "recently settled as part of numerics reform"]
618 /// Computes the absolute value of `self`. `Int::min_value()` will be
619 /// returned if the number is `Int::min_value()`.
620 fn abs(self) -> Self;
622 /// Returns a number representing sign of `self`.
624 /// - `0` if the number is zero
625 /// - `1` if the number is positive
626 /// - `-1` if the number is negative
627 fn signum(self) -> Self;
629 /// Returns `true` if `self` is positive and `false` if the number
630 /// is zero or negative.
631 fn is_positive(self) -> bool;
633 /// Returns `true` if `self` is negative and `false` if the number
634 /// is zero or positive.
635 fn is_negative(self) -> bool;
638 macro_rules! signed_int_impl {
640 impl SignedInt for $T {
643 if self.is_negative() { -self } else { self }
647 fn signum(self) -> $T {
656 fn is_positive(self) -> bool { self > 0 }
659 fn is_negative(self) -> bool { self < 0 }
664 signed_int_impl! { i8 }
665 signed_int_impl! { i16 }
666 signed_int_impl! { i32 }
667 signed_int_impl! { i64 }
668 signed_int_impl! { int }
670 /// A built-in unsigned integer.
671 #[unstable = "recently settled as part of numerics reform"]
672 pub trait UnsignedInt: Int {
673 /// Returns `true` iff `self == 2^k` for some `k`.
675 fn is_power_of_two(self) -> bool {
676 (self - Int::one()) & self == Int::zero() && !(self == Int::zero())
679 /// Returns the smallest power of two greater than or equal to `self`.
680 /// Unspecified behavior on overflow.
682 fn next_power_of_two(self) -> Self {
683 let bits = size_of::<Self>() * 8;
684 let one: Self = Int::one();
685 one << ((bits - (self - one).leading_zeros()) % bits)
688 /// Returns the smallest power of two greater than or equal to `n`. If the
689 /// next power of two is greater than the type's maximum value, `None` is
690 /// returned, otherwise the power of two is wrapped in `Some`.
691 fn checked_next_power_of_two(self) -> Option<Self> {
692 let npot = self.next_power_of_two();
701 #[unstable = "trait is unstable"]
702 impl UnsignedInt for uint {}
704 #[unstable = "trait is unstable"]
705 impl UnsignedInt for u8 {}
707 #[unstable = "trait is unstable"]
708 impl UnsignedInt for u16 {}
710 #[unstable = "trait is unstable"]
711 impl UnsignedInt for u32 {}
713 #[unstable = "trait is unstable"]
714 impl UnsignedInt for u64 {}
716 /// A generic trait for converting a value to a number.
717 #[experimental = "trait is likely to be removed"]
718 pub trait ToPrimitive {
719 /// Converts the value of `self` to an `int`.
721 fn to_int(&self) -> Option<int> {
722 self.to_i64().and_then(|x| x.to_int())
725 /// Converts the value of `self` to an `i8`.
727 fn to_i8(&self) -> Option<i8> {
728 self.to_i64().and_then(|x| x.to_i8())
731 /// Converts the value of `self` to an `i16`.
733 fn to_i16(&self) -> Option<i16> {
734 self.to_i64().and_then(|x| x.to_i16())
737 /// Converts the value of `self` to an `i32`.
739 fn to_i32(&self) -> Option<i32> {
740 self.to_i64().and_then(|x| x.to_i32())
743 /// Converts the value of `self` to an `i64`.
744 fn to_i64(&self) -> Option<i64>;
746 /// Converts the value of `self` to an `uint`.
748 fn to_uint(&self) -> Option<uint> {
749 self.to_u64().and_then(|x| x.to_uint())
752 /// Converts the value of `self` to an `u8`.
754 fn to_u8(&self) -> Option<u8> {
755 self.to_u64().and_then(|x| x.to_u8())
758 /// Converts the value of `self` to an `u16`.
760 fn to_u16(&self) -> Option<u16> {
761 self.to_u64().and_then(|x| x.to_u16())
764 /// Converts the value of `self` to an `u32`.
766 fn to_u32(&self) -> Option<u32> {
767 self.to_u64().and_then(|x| x.to_u32())
770 /// Converts the value of `self` to an `u64`.
772 fn to_u64(&self) -> Option<u64>;
774 /// Converts the value of `self` to an `f32`.
776 fn to_f32(&self) -> Option<f32> {
777 self.to_f64().and_then(|x| x.to_f32())
780 /// Converts the value of `self` to an `f64`.
782 fn to_f64(&self) -> Option<f64> {
783 self.to_i64().and_then(|x| x.to_f64())
787 macro_rules! impl_to_primitive_int_to_int {
788 ($SrcT:ty, $DstT:ty, $slf:expr) => (
790 if size_of::<$SrcT>() <= size_of::<$DstT>() {
794 let min_value: $DstT = Int::min_value();
795 let max_value: $DstT = Int::max_value();
796 if min_value as i64 <= n && n <= max_value as i64 {
806 macro_rules! impl_to_primitive_int_to_uint {
807 ($SrcT:ty, $DstT:ty, $slf:expr) => (
809 let zero: $SrcT = Int::zero();
810 let max_value: $DstT = Int::max_value();
811 if zero <= $slf && $slf as u64 <= max_value as u64 {
820 macro_rules! impl_to_primitive_int {
822 impl ToPrimitive for $T {
824 fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int, *self) }
826 fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) }
828 fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) }
830 fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32, *self) }
832 fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self) }
835 fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint, *self) }
837 fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) }
839 fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) }
841 fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32, *self) }
843 fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64, *self) }
846 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
848 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
853 impl_to_primitive_int! { int }
854 impl_to_primitive_int! { i8 }
855 impl_to_primitive_int! { i16 }
856 impl_to_primitive_int! { i32 }
857 impl_to_primitive_int! { i64 }
859 macro_rules! impl_to_primitive_uint_to_int {
860 ($DstT:ty, $slf:expr) => (
862 let max_value: $DstT = Int::max_value();
863 if $slf as u64 <= max_value as u64 {
872 macro_rules! impl_to_primitive_uint_to_uint {
873 ($SrcT:ty, $DstT:ty, $slf:expr) => (
875 if size_of::<$SrcT>() <= size_of::<$DstT>() {
878 let zero: $SrcT = Int::zero();
879 let max_value: $DstT = Int::max_value();
880 if zero <= $slf && $slf as u64 <= max_value as u64 {
890 macro_rules! impl_to_primitive_uint {
892 impl ToPrimitive for $T {
894 fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int, *self) }
896 fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) }
898 fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) }
900 fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32, *self) }
902 fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) }
905 fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint, *self) }
907 fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) }
909 fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) }
911 fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32, *self) }
913 fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64, *self) }
916 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
918 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
923 impl_to_primitive_uint! { uint }
924 impl_to_primitive_uint! { u8 }
925 impl_to_primitive_uint! { u16 }
926 impl_to_primitive_uint! { u32 }
927 impl_to_primitive_uint! { u64 }
929 macro_rules! impl_to_primitive_float_to_float {
930 ($SrcT:ty, $DstT:ty, $slf:expr) => (
931 if size_of::<$SrcT>() <= size_of::<$DstT>() {
935 let max_value: $SrcT = Float::max_value();
936 if -max_value as f64 <= n && n <= max_value as f64 {
945 macro_rules! impl_to_primitive_float {
947 impl ToPrimitive for $T {
949 fn to_int(&self) -> Option<int> { Some(*self as int) }
951 fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
953 fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
955 fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
957 fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
960 fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
962 fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
964 fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
966 fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
968 fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
971 fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32, *self) }
973 fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64, *self) }
978 impl_to_primitive_float! { f32 }
979 impl_to_primitive_float! { f64 }
981 /// A generic trait for converting a number to a value.
982 #[experimental = "trait is likely to be removed"]
983 pub trait FromPrimitive : ::kinds::Sized {
984 /// Convert an `int` to return an optional value of this type. If the
985 /// value cannot be represented by this value, the `None` is returned.
987 fn from_int(n: int) -> Option<Self> {
988 FromPrimitive::from_i64(n as i64)
991 /// Convert an `i8` to return an optional value of this type. If the
992 /// type cannot be represented by this value, the `None` is returned.
994 fn from_i8(n: i8) -> Option<Self> {
995 FromPrimitive::from_i64(n as i64)
998 /// Convert an `i16` 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_i16(n: i16) -> Option<Self> {
1002 FromPrimitive::from_i64(n as i64)
1005 /// Convert an `i32` 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_i32(n: i32) -> Option<Self> {
1009 FromPrimitive::from_i64(n as i64)
1012 /// Convert an `i64` to return an optional value of this type. If the
1013 /// type cannot be represented by this value, the `None` is returned.
1014 fn from_i64(n: i64) -> Option<Self>;
1016 /// Convert an `uint` to return an optional value of this type. If the
1017 /// type cannot be represented by this value, the `None` is returned.
1019 fn from_uint(n: uint) -> Option<Self> {
1020 FromPrimitive::from_u64(n as u64)
1023 /// Convert an `u8` 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_u8(n: u8) -> Option<Self> {
1027 FromPrimitive::from_u64(n as u64)
1030 /// Convert an `u16` 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_u16(n: u16) -> Option<Self> {
1034 FromPrimitive::from_u64(n as u64)
1037 /// Convert an `u32` 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_u32(n: u32) -> Option<Self> {
1041 FromPrimitive::from_u64(n as u64)
1044 /// Convert an `u64` to return an optional value of this type. If the
1045 /// type cannot be represented by this value, the `None` is returned.
1046 fn from_u64(n: u64) -> Option<Self>;
1048 /// Convert a `f32` to return an optional value of this type. If the
1049 /// type cannot be represented by this value, the `None` is returned.
1051 fn from_f32(n: f32) -> Option<Self> {
1052 FromPrimitive::from_f64(n as f64)
1055 /// Convert a `f64` 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_f64(n: f64) -> Option<Self> {
1059 FromPrimitive::from_i64(n as i64)
1063 /// A utility function that just calls `FromPrimitive::from_int`.
1064 #[experimental = "likely to be removed"]
1065 pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
1066 FromPrimitive::from_int(n)
1069 /// A utility function that just calls `FromPrimitive::from_i8`.
1070 #[experimental = "likely to be removed"]
1071 pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> {
1072 FromPrimitive::from_i8(n)
1075 /// A utility function that just calls `FromPrimitive::from_i16`.
1076 #[experimental = "likely to be removed"]
1077 pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> {
1078 FromPrimitive::from_i16(n)
1081 /// A utility function that just calls `FromPrimitive::from_i32`.
1082 #[experimental = "likely to be removed"]
1083 pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> {
1084 FromPrimitive::from_i32(n)
1087 /// A utility function that just calls `FromPrimitive::from_i64`.
1088 #[experimental = "likely to be removed"]
1089 pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
1090 FromPrimitive::from_i64(n)
1093 /// A utility function that just calls `FromPrimitive::from_uint`.
1094 #[experimental = "likely to be removed"]
1095 pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
1096 FromPrimitive::from_uint(n)
1099 /// A utility function that just calls `FromPrimitive::from_u8`.
1100 #[experimental = "likely to be removed"]
1101 pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> {
1102 FromPrimitive::from_u8(n)
1105 /// A utility function that just calls `FromPrimitive::from_u16`.
1106 #[experimental = "likely to be removed"]
1107 pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> {
1108 FromPrimitive::from_u16(n)
1111 /// A utility function that just calls `FromPrimitive::from_u32`.
1112 #[experimental = "likely to be removed"]
1113 pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> {
1114 FromPrimitive::from_u32(n)
1117 /// A utility function that just calls `FromPrimitive::from_u64`.
1118 #[experimental = "likely to be removed"]
1119 pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> {
1120 FromPrimitive::from_u64(n)
1123 /// A utility function that just calls `FromPrimitive::from_f32`.
1124 #[experimental = "likely to be removed"]
1125 pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> {
1126 FromPrimitive::from_f32(n)
1129 /// A utility function that just calls `FromPrimitive::from_f64`.
1130 #[experimental = "likely to be removed"]
1131 pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {
1132 FromPrimitive::from_f64(n)
1135 macro_rules! impl_from_primitive {
1136 ($T:ty, $to_ty:ident) => (
1137 impl FromPrimitive for $T {
1138 #[inline] fn from_int(n: int) -> Option<$T> { n.$to_ty() }
1139 #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() }
1140 #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() }
1141 #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() }
1142 #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() }
1144 #[inline] fn from_uint(n: uint) -> Option<$T> { n.$to_ty() }
1145 #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() }
1146 #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() }
1147 #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() }
1148 #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() }
1150 #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() }
1151 #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() }
1156 impl_from_primitive! { int, to_int }
1157 impl_from_primitive! { i8, to_i8 }
1158 impl_from_primitive! { i16, to_i16 }
1159 impl_from_primitive! { i32, to_i32 }
1160 impl_from_primitive! { i64, to_i64 }
1161 impl_from_primitive! { uint, to_uint }
1162 impl_from_primitive! { u8, to_u8 }
1163 impl_from_primitive! { u16, to_u16 }
1164 impl_from_primitive! { u32, to_u32 }
1165 impl_from_primitive! { u64, to_u64 }
1166 impl_from_primitive! { f32, to_f32 }
1167 impl_from_primitive! { f64, to_f64 }
1169 /// Cast from one machine scalar to another.
1176 /// let twenty: f32 = num::cast(0x14i).unwrap();
1177 /// assert_eq!(twenty, 20f32);
1181 #[experimental = "likely to be removed"]
1182 pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
1186 /// An interface for casting between machine scalars.
1187 #[experimental = "trait is likely to be removed"]
1188 pub trait NumCast: ToPrimitive {
1189 /// Creates a number from another value that can be converted into a primitive via the
1190 /// `ToPrimitive` trait.
1191 fn from<T: ToPrimitive>(n: T) -> Option<Self>;
1194 macro_rules! impl_num_cast {
1195 ($T:ty, $conv:ident) => (
1196 impl NumCast for $T {
1198 fn from<N: ToPrimitive>(n: N) -> Option<$T> {
1199 // `$conv` could be generated using `concat_idents!`, but that
1200 // macro seems to be broken at the moment
1207 impl_num_cast! { u8, to_u8 }
1208 impl_num_cast! { u16, to_u16 }
1209 impl_num_cast! { u32, to_u32 }
1210 impl_num_cast! { u64, to_u64 }
1211 impl_num_cast! { uint, to_uint }
1212 impl_num_cast! { i8, to_i8 }
1213 impl_num_cast! { i16, to_i16 }
1214 impl_num_cast! { i32, to_i32 }
1215 impl_num_cast! { i64, to_i64 }
1216 impl_num_cast! { int, to_int }
1217 impl_num_cast! { f32, to_f32 }
1218 impl_num_cast! { f64, to_f64 }
1220 /// Used for representing the classification of floating point numbers
1221 #[deriving(Copy, PartialEq, Show)]
1222 #[unstable = "may be renamed"]
1223 pub enum FpCategory {
1224 /// "Not a Number", often obtained by dividing by zero
1226 /// Positive or negative infinity
1228 /// Positive or negative zero
1230 /// De-normalized floating point representation (less precise than `Normal`)
1232 /// A regular floating point number
1236 /// A built-in floating point number.
1237 // FIXME(#5527): In a future version of Rust, many of these functions will
1238 // become constants.
1240 // FIXME(#8888): Several of these functions have a parameter named
1241 // `unused_self`. Removing it requires #8888 to be fixed.
1242 #[unstable = "recently settled as part of numerics reform"]
1255 /// Returns the NaN value.
1257 /// Returns the infinite value.
1258 fn infinity() -> Self;
1259 /// Returns the negative infinite value.
1260 fn neg_infinity() -> Self;
1261 /// Returns the `0` value.
1264 fn neg_zero() -> Self;
1265 /// Returns the `1` value.
1268 /// Returns true if this value is NaN and false otherwise.
1269 fn is_nan(self) -> bool;
1270 /// Returns true if this value is positive infinity or negative infinity and
1271 /// false otherwise.
1272 fn is_infinite(self) -> bool;
1273 /// Returns true if this number is neither infinite nor NaN.
1274 fn is_finite(self) -> bool;
1275 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1276 fn is_normal(self) -> bool;
1277 /// Returns the category that this number falls into.
1278 fn classify(self) -> FpCategory;
1280 // FIXME (#5527): These should be associated constants
1282 /// Returns the number of binary digits of mantissa that this type supports.
1283 fn mantissa_digits(unused_self: Option<Self>) -> uint;
1284 /// Returns the number of base-10 digits of precision that this type supports.
1285 fn digits(unused_self: Option<Self>) -> uint;
1286 /// Returns the difference between 1.0 and the smallest representable number larger than 1.0.
1287 fn epsilon() -> Self;
1288 /// Returns the minimum binary exponent that this type can represent.
1289 fn min_exp(unused_self: Option<Self>) -> int;
1290 /// Returns the maximum binary exponent that this type can represent.
1291 fn max_exp(unused_self: Option<Self>) -> int;
1292 /// Returns the minimum base-10 exponent that this type can represent.
1293 fn min_10_exp(unused_self: Option<Self>) -> int;
1294 /// Returns the maximum base-10 exponent that this type can represent.
1295 fn max_10_exp(unused_self: Option<Self>) -> int;
1296 /// Returns the smallest finite value that this type can represent.
1297 fn min_value() -> Self;
1298 /// Returns the smallest normalized positive number that this type can represent.
1299 fn min_pos_value(unused_self: Option<Self>) -> Self;
1300 /// Returns the largest finite value that this type can represent.
1301 fn max_value() -> Self;
1303 /// Returns the mantissa, exponent and sign as integers, respectively.
1304 fn integer_decode(self) -> (u64, i16, i8);
1306 /// Return the largest integer less than or equal to a number.
1307 fn floor(self) -> Self;
1308 /// Return the smallest integer greater than or equal to a number.
1309 fn ceil(self) -> Self;
1310 /// Return the nearest integer to a number. Round half-way cases away from
1312 fn round(self) -> Self;
1313 /// Return the integer part of a number.
1314 fn trunc(self) -> Self;
1315 /// Return the fractional part of a number.
1316 fn fract(self) -> Self;
1318 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1319 /// number is `Float::nan()`.
1320 fn abs(self) -> Self;
1321 /// Returns a number that represents the sign of `self`.
1323 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1324 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1325 /// - `Float::nan()` if the number is `Float::nan()`
1326 fn signum(self) -> Self;
1327 /// Returns `true` if `self` is positive, including `+0.0` and
1328 /// `Float::infinity()`.
1329 fn is_positive(self) -> bool;
1330 /// Returns `true` if `self` is negative, including `-0.0` and
1331 /// `Float::neg_infinity()`.
1332 fn is_negative(self) -> bool;
1334 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1335 /// error. This produces a more accurate result with better performance than
1336 /// a separate multiplication operation followed by an add.
1337 fn mul_add(self, a: Self, b: Self) -> Self;
1338 /// Take the reciprocal (inverse) of a number, `1/x`.
1339 fn recip(self) -> Self;
1341 /// Raise a number to an integer power.
1343 /// Using this function is generally faster than using `powf`
1344 fn powi(self, n: i32) -> Self;
1345 /// Raise a number to a floating point power.
1346 fn powf(self, n: Self) -> Self;
1350 /// 1.0 / sqrt(2.0).
1351 fn frac_1_sqrt2() -> Self;
1353 /// Take the square root of a number.
1355 /// Returns NaN if `self` is a negative number.
1356 fn sqrt(self) -> Self;
1357 /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1358 fn rsqrt(self) -> Self;
1360 /// Archimedes' constant.
1361 #[deprecated = "use f32::consts or f64::consts instead"]
1364 #[deprecated = "use f32::consts or f64::consts instead"]
1365 fn two_pi() -> Self;
1367 #[deprecated = "use f32::consts or f64::consts instead"]
1368 fn frac_pi_2() -> Self;
1370 #[deprecated = "use f32::consts or f64::consts instead"]
1371 fn frac_pi_3() -> Self;
1373 #[deprecated = "use f32::consts or f64::consts instead"]
1374 fn frac_pi_4() -> Self;
1376 #[deprecated = "use f32::consts or f64::consts instead"]
1377 fn frac_pi_6() -> Self;
1379 #[deprecated = "use f32::consts or f64::consts instead"]
1380 fn frac_pi_8() -> Self;
1382 #[deprecated = "use f32::consts or f64::consts instead"]
1383 fn frac_1_pi() -> Self;
1385 #[deprecated = "use f32::consts or f64::consts instead"]
1386 fn frac_2_pi() -> Self;
1388 #[deprecated = "use f32::consts or f64::consts instead"]
1389 fn frac_2_sqrtpi() -> Self;
1392 #[deprecated = "use f32::consts or f64::consts instead"]
1395 #[deprecated = "use f32::consts or f64::consts instead"]
1396 fn log2_e() -> Self;
1398 #[deprecated = "use f32::consts or f64::consts instead"]
1399 fn log10_e() -> Self;
1401 #[deprecated = "use f32::consts or f64::consts instead"]
1404 #[deprecated = "use f32::consts or f64::consts instead"]
1407 /// Returns `e^(self)`, (the exponential function).
1408 fn exp(self) -> Self;
1409 /// Returns 2 raised to the power of the number, `2^(self)`.
1410 fn exp2(self) -> Self;
1411 /// Returns the natural logarithm of the number.
1412 fn ln(self) -> Self;
1413 /// Returns the logarithm of the number with respect to an arbitrary base.
1414 fn log(self, base: Self) -> Self;
1415 /// Returns the base 2 logarithm of the number.
1416 fn log2(self) -> Self;
1417 /// Returns the base 10 logarithm of the number.
1418 fn log10(self) -> Self;
1420 /// Convert radians to degrees.
1421 fn to_degrees(self) -> Self;
1422 /// Convert degrees to radians.
1423 fn to_radians(self) -> Self;
1426 /// A generic trait for converting a string with a radix (base) to a value
1427 #[experimental = "might need to return Result"]
1428 pub trait FromStrRadix {
1429 fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
1432 /// A utility function that just calls FromStrRadix::from_str_radix.
1433 #[experimental = "might need to return Result"]
1434 pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint) -> Option<T> {
1435 FromStrRadix::from_str_radix(str, radix)
1438 macro_rules! from_str_radix_float_impl {
1440 #[experimental = "might need to return Result"]
1441 impl FromStr for $T {
1442 /// Convert a string in base 10 to a float.
1443 /// Accepts an optional decimal exponent.
1445 /// This function accepts strings such as
1448 /// * '+3.14', equivalent to '3.14'
1450 /// * '2.5E10', or equivalently, '2.5e10'
1452 /// * '.' (understood as 0)
1454 /// * '.5', or, equivalently, '0.5'
1455 /// * '+inf', 'inf', '-inf', 'NaN'
1457 /// Leading and trailing whitespace represent an error.
1461 /// * src - A string
1465 /// `None` if the string did not represent a valid number. Otherwise,
1466 /// `Some(n)` where `n` is the floating-point number represented by `src`.
1468 fn from_str(src: &str) -> Option<$T> {
1469 from_str_radix(src, 10)
1473 #[experimental = "might need to return Result"]
1474 impl FromStrRadix for $T {
1475 /// Convert a string in a given base to a float.
1477 /// Due to possible conflicts, this function does **not** accept
1478 /// the special values `inf`, `-inf`, `+inf` and `NaN`, **nor**
1479 /// does it recognize exponents of any kind.
1481 /// Leading and trailing whitespace represent an error.
1485 /// * src - A string
1486 /// * radix - The base to use. Must lie in the range [2 .. 36]
1490 /// `None` if the string did not represent a valid number. Otherwise,
1491 /// `Some(n)` where `n` is the floating-point number represented by `src`.
1492 fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
1493 assert!(radix >= 2 && radix <= 36,
1494 "from_str_radix_float: must lie in the range `[2, 36]` - found {}",
1499 "inf" => return Some(Float::infinity()),
1500 "-inf" => return Some(Float::neg_infinity()),
1501 "NaN" => return Some(Float::nan()),
1505 let (is_positive, src) = match src.slice_shift_char() {
1506 None => return None,
1507 Some(('-', "")) => return None,
1508 Some(('-', src)) => (false, src),
1509 Some((_, _)) => (true, src),
1512 // The significand to accumulate
1513 let mut sig = if is_positive { 0.0 } else { -0.0 };
1514 // Necessary to detect overflow
1515 let mut prev_sig = sig;
1516 let mut cs = src.chars().enumerate();
1517 // Exponent prefix and exponent index offset
1518 let mut exp_info = None::<(char, uint)>;
1520 // Parse the integer part of the significand
1522 match c.to_digit(radix) {
1524 // shift significand one digit left
1525 sig = sig * (radix as $T);
1527 // add/subtract current digit depending on sign
1529 sig = sig + ((digit as int) as $T);
1531 sig = sig - ((digit as int) as $T);
1534 // Detect overflow by comparing to last value, except
1535 // if we've not seen any non-zero digits.
1536 if prev_sig != 0.0 {
1537 if is_positive && sig <= prev_sig
1538 { return Some(Float::infinity()); }
1539 if !is_positive && sig >= prev_sig
1540 { return Some(Float::neg_infinity()); }
1542 // Detect overflow by reversing the shift-and-add process
1543 if is_positive && (prev_sig != (sig - digit as $T) / radix as $T)
1544 { return Some(Float::infinity()); }
1545 if !is_positive && (prev_sig != (sig + digit as $T) / radix as $T)
1546 { return Some(Float::neg_infinity()); }
1551 'e' | 'E' | 'p' | 'P' => {
1552 exp_info = Some((c, i + 1));
1553 break; // start of exponent
1556 break; // start of fractional part
1565 // If we are not yet at the exponent parse the fractional
1566 // part of the significand
1567 if exp_info.is_none() {
1568 let mut power = 1.0;
1570 match c.to_digit(radix) {
1572 // Decrease power one order of magnitude
1573 power = power / (radix as $T);
1574 // add/subtract current digit depending on sign
1575 sig = if is_positive {
1576 sig + (digit as $T) * power
1578 sig - (digit as $T) * power
1580 // Detect overflow by comparing to last value
1581 if is_positive && sig < prev_sig
1582 { return Some(Float::infinity()); }
1583 if !is_positive && sig > prev_sig
1584 { return Some(Float::neg_infinity()); }
1588 'e' | 'E' | 'p' | 'P' => {
1589 exp_info = Some((c, i + 1));
1590 break; // start of exponent
1593 return None; // invalid number
1600 // Parse and calculate the exponent
1601 let exp = match exp_info {
1602 Some((c, offset)) => {
1603 let base = match c {
1604 'E' | 'e' if radix == 10 => 10u as $T,
1605 'P' | 'p' if radix == 16 => 2u as $T,
1609 // Parse the exponent as decimal integer
1610 let src = src[offset..];
1611 let (is_positive, exp) = match src.slice_shift_char() {
1612 Some(('-', src)) => (false, from_str::<uint>(src)),
1613 Some(('+', src)) => (true, from_str::<uint>(src)),
1614 Some((_, _)) => (true, from_str::<uint>(src)),
1615 None => return None,
1618 match (is_positive, exp) {
1619 (true, Some(exp)) => base.powi(exp as i32),
1620 (false, Some(exp)) => 1.0 / base.powi(exp as i32),
1621 (_, None) => return None,
1624 None => 1.0, // no exponent
1632 from_str_radix_float_impl! { f32 }
1633 from_str_radix_float_impl! { f64 }
1635 macro_rules! from_str_radix_int_impl {
1637 #[experimental = "might need to return Result"]
1638 impl FromStr for $T {
1640 fn from_str(src: &str) -> Option<$T> {
1641 from_str_radix(src, 10)
1645 #[experimental = "might need to return Result"]
1646 impl FromStrRadix for $T {
1647 fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
1648 assert!(radix >= 2 && radix <= 36,
1649 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1652 let is_signed_ty = (0 as $T) > Int::min_value();
1654 match src.slice_shift_char() {
1655 Some(('-', src)) if is_signed_ty => {
1656 // The number is negative
1658 for c in src.chars() {
1659 let x = match c.to_digit(radix) {
1661 None => return None,
1663 result = match result.checked_mul(radix as $T) {
1664 Some(result) => result,
1665 None => return None,
1667 result = match result.checked_sub(x as $T) {
1668 Some(result) => result,
1669 None => return None,
1675 // The number is signed
1677 for c in src.chars() {
1678 let x = match c.to_digit(radix) {
1680 None => return None,
1682 result = match result.checked_mul(radix as $T) {
1683 Some(result) => result,
1684 None => return None,
1686 result = match result.checked_add(x as $T) {
1687 Some(result) => result,
1688 None => return None,
1699 from_str_radix_int_impl! { int }
1700 from_str_radix_int_impl! { i8 }
1701 from_str_radix_int_impl! { i16 }
1702 from_str_radix_int_impl! { i32 }
1703 from_str_radix_int_impl! { i64 }
1704 from_str_radix_int_impl! { uint }
1705 from_str_radix_int_impl! { u8 }
1706 from_str_radix_int_impl! { u16 }
1707 from_str_radix_int_impl! { u32 }
1708 from_str_radix_int_impl! { u64 }
1712 macro_rules! trait_impl {
1713 ($name:ident for $($t:ty)*) => {
1714 $(#[allow(deprecated)] impl $name for $t {})*
1718 #[deprecated = "Generalised numbers are no longer supported"]
1719 #[allow(deprecated)]
1720 pub trait Num: PartialEq + Zero + One
1726 + Rem<Output=Self> {}
1727 trait_impl! { Num for uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 }
1729 #[deprecated = "Generalised unsigned numbers are no longer supported"]
1730 #[allow(deprecated)]
1731 pub trait Unsigned: Num {}
1732 trait_impl! { Unsigned for uint u8 u16 u32 u64 }
1734 #[deprecated = "Use `Float` or `Int`"]
1735 #[allow(deprecated)]
1736 pub trait Primitive: Copy + Clone + Num + NumCast + PartialOrd {}
1737 trait_impl! { Primitive for uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 }
1739 #[deprecated = "The generic `Zero` trait will be removed soon."]
1740 pub trait Zero: Add<Output=Self> {
1741 #[deprecated = "Use `Int::zero()` or `Float::zero()`."]
1743 #[deprecated = "Use `x == Int::zero()` or `x == Float::zero()`."]
1744 fn is_zero(&self) -> bool;
1746 #[deprecated = "Use `Int::zero()` or `Float::zero()`."]
1747 #[allow(deprecated)]
1748 pub fn zero<T: Zero>() -> T { Zero::zero() }
1749 macro_rules! zero_impl {
1750 ($t:ty, $v:expr) => {
1752 fn zero() -> $t { $v }
1753 fn is_zero(&self) -> bool { *self == $v }
1757 zero_impl! { uint, 0u }
1758 zero_impl! { u8, 0u8 }
1759 zero_impl! { u16, 0u16 }
1760 zero_impl! { u32, 0u32 }
1761 zero_impl! { u64, 0u64 }
1762 zero_impl! { int, 0i }
1763 zero_impl! { i8, 0i8 }
1764 zero_impl! { i16, 0i16 }
1765 zero_impl! { i32, 0i32 }
1766 zero_impl! { i64, 0i64 }
1767 zero_impl! { f32, 0.0f32 }
1768 zero_impl! { f64, 0.0f64 }
1770 #[deprecated = "The generic `One` trait will be removed soon."]
1771 pub trait One: Mul<Output=Self> {
1772 #[deprecated = "Use `Int::one()` or `Float::one()`."]
1775 #[deprecated = "Use `Int::one()` or `Float::one()`."]
1776 #[allow(deprecated)]
1777 pub fn one<T: One>() -> T { One::one() }
1778 macro_rules! one_impl {
1779 ($t:ty, $v:expr) => {
1781 fn one() -> $t { $v }
1785 one_impl! { uint, 1u }
1786 one_impl! { u8, 1u8 }
1787 one_impl! { u16, 1u16 }
1788 one_impl! { u32, 1u32 }
1789 one_impl! { u64, 1u64 }
1790 one_impl! { int, 1i }
1791 one_impl! { i8, 1i8 }
1792 one_impl! { i16, 1i16 }
1793 one_impl! { i32, 1i32 }
1794 one_impl! { i64, 1i64 }
1795 one_impl! { f32, 1.0f32 }
1796 one_impl! { f64, 1.0f64 }
1798 #[deprecated = "Use `UnsignedInt::next_power_of_two`"]
1799 pub fn next_power_of_two<T: UnsignedInt>(n: T) -> T {
1800 n.next_power_of_two()
1802 #[deprecated = "Use `UnsignedInt::is_power_of_two`"]
1803 pub fn is_power_of_two<T: UnsignedInt>(n: T) -> bool {
1806 #[deprecated = "Use `UnsignedInt::checked_next_power_of_two`"]
1807 pub fn checked_next_power_of_two<T: UnsignedInt>(n: T) -> Option<T> {
1808 n.checked_next_power_of_two()
1811 #[deprecated = "Generalised bounded values are no longer supported"]
1813 #[deprecated = "Use `Int::min_value` or `Float::min_value`"]
1814 fn min_value() -> Self;
1815 #[deprecated = "Use `Int::max_value` or `Float::max_value`"]
1816 fn max_value() -> Self;
1818 macro_rules! bounded_impl {
1819 ($T:ty, $min:expr, $max:expr) => {
1820 impl Bounded for $T {
1822 fn min_value() -> $T { $min }
1825 fn max_value() -> $T { $max }
1829 bounded_impl! { uint, uint::MIN, uint::MAX }
1830 bounded_impl! { u8, u8::MIN, u8::MAX }
1831 bounded_impl! { u16, u16::MIN, u16::MAX }
1832 bounded_impl! { u32, u32::MIN, u32::MAX }
1833 bounded_impl! { u64, u64::MIN, u64::MAX }
1834 bounded_impl! { int, int::MIN, int::MAX }
1835 bounded_impl! { i8, i8::MIN, i8::MAX }
1836 bounded_impl! { i16, i16::MIN, i16::MAX }
1837 bounded_impl! { i32, i32::MIN, i32::MAX }
1838 bounded_impl! { i64, i64::MIN, i64::MAX }
1839 bounded_impl! { f32, f32::MIN_VALUE, f32::MAX_VALUE }
1840 bounded_impl! { f64, f64::MIN_VALUE, f64::MAX_VALUE }