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 //! Numeric traits and functions for generic mathematics
13 #![allow(missing_doc)]
16 use {int, i8, i16, i32, i64};
17 use {uint, u8, u16, u32, u64};
20 use cmp::{PartialEq, PartialOrd};
23 use ops::{Add, Sub, Mul, Div, Rem, Neg};
24 use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
25 use option::{Option, Some, None};
27 /// The base trait for numeric types
28 pub trait Num: PartialEq + Zero + One
36 macro_rules! trait_impl(
37 ($name:ident for $($t:ty)*) => ($(
42 trait_impl!(Num for uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
44 /// Simultaneous division and remainder
46 pub fn div_rem<T: Div<T, T> + Rem<T, T>>(x: T, y: T) -> (T, T) {
50 /// Defines an additive identity element for `Self`.
54 /// This trait can be automatically be derived using `#[deriving(Zero)]`
55 /// attribute. If you choose to use this, make sure that the laws outlined in
56 /// the documentation for `Zero::zero` still hold.
57 pub trait Zero: Add<Self, Self> {
58 /// Returns the additive identity element of `Self`, `0`.
63 /// a + 0 = a ∀ a ∈ Self
64 /// 0 + a = a ∀ a ∈ Self
69 /// This function should return the same result at all times regardless of
70 /// external mutable state, for example values stored in TLS or in
72 // FIXME (#5527): This should be an associated constant
75 /// Returns `true` if `self` is equal to the additive identity.
76 fn is_zero(&self) -> bool;
79 macro_rules! zero_impl(
83 fn zero() -> $t { $v }
85 fn is_zero(&self) -> bool { *self == $v }
90 macro_rules! zero_float_impl(
94 fn zero() -> $t { $v }
97 fn is_zero(&self) -> bool { *self == $v || *self == -$v }
104 zero_impl!(u16, 0u16)
105 zero_impl!(u32, 0u32)
106 zero_impl!(u64, 0u64)
110 zero_impl!(i16, 0i16)
111 zero_impl!(i32, 0i32)
112 zero_impl!(i64, 0i64)
114 zero_float_impl!(f32, 0.0f32)
115 zero_float_impl!(f64, 0.0f64)
117 /// Returns the additive identity, `0`.
118 #[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() }
120 /// Defines a multiplicative identity element for `Self`.
121 pub trait One: Mul<Self, Self> {
122 /// Returns the multiplicative identity element of `Self`, `1`.
127 /// a * 1 = a ∀ a ∈ Self
128 /// 1 * a = a ∀ a ∈ Self
133 /// This function should return the same result at all times regardless of
134 /// external mutable state, for example values stored in TLS or in
136 // FIXME (#5527): This should be an associated constant
140 macro_rules! one_impl(
141 ($t:ty, $v:expr) => {
144 fn one() -> $t { $v }
161 one_impl!(f32, 1.0f32)
162 one_impl!(f64, 1.0f64)
164 /// Returns the multiplicative identity, `1`.
165 #[inline(always)] pub fn one<T: One>() -> T { One::one() }
167 /// Useful functions for signed numbers (i.e. numbers that can be negative).
168 pub trait Signed: Num + Neg<Self> {
169 /// Computes the absolute value.
171 /// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`.
172 fn abs(&self) -> Self;
174 /// The positive difference of two numbers.
176 /// Returns `zero` if the number is less than or equal to `other`, otherwise the difference
177 /// between `self` and `other` is returned.
178 fn abs_sub(&self, other: &Self) -> Self;
180 /// Returns the sign of the number.
182 /// For `f32` and `f64`:
184 /// * `1.0` if the number is positive, `+0.0` or `INFINITY`
185 /// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
186 /// * `NaN` if the number is `NaN`
190 /// * `0` if the number is zero
191 /// * `1` if the number is positive
192 /// * `-1` if the number is negative
193 fn signum(&self) -> Self;
195 /// Returns true if the number is positive and false if the number is zero or negative.
196 fn is_positive(&self) -> bool;
198 /// Returns true if the number is negative and false if the number is zero or positive.
199 fn is_negative(&self) -> bool;
202 macro_rules! signed_impl(
206 fn abs(&self) -> $t {
207 if self.is_negative() { -*self } else { *self }
211 fn abs_sub(&self, other: &$t) -> $t {
212 if *self <= *other { 0 } else { *self - *other }
216 fn signum(&self) -> $t {
225 fn is_positive(&self) -> bool { *self > 0 }
228 fn is_negative(&self) -> bool { *self < 0 }
233 signed_impl!(int i8 i16 i32 i64)
235 macro_rules! signed_float_impl(
236 ($t:ty, $nan:expr, $inf:expr, $neg_inf:expr, $fabs:path, $fcopysign:path, $fdim:ident) => {
238 /// Computes the absolute value. Returns `NAN` if the number is `NAN`.
240 fn abs(&self) -> $t {
241 unsafe { $fabs(*self) }
244 /// The positive difference of two numbers. Returns `0.0` if the number is
245 /// less than or equal to `other`, otherwise the difference between`self`
246 /// and `other` is returned.
248 fn abs_sub(&self, other: &$t) -> $t {
249 extern { fn $fdim(a: $t, b: $t) -> $t; }
250 unsafe { $fdim(*self, *other) }
255 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
256 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
257 /// - `NAN` if the number is NaN
259 fn signum(&self) -> $t {
260 if self != self { $nan } else {
261 unsafe { $fcopysign(1.0, *self) }
265 /// Returns `true` if the number is positive, including `+0.0` and `INFINITY`
267 fn is_positive(&self) -> bool { *self > 0.0 || (1.0 / *self) == $inf }
269 /// Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY`
271 fn is_negative(&self) -> bool { *self < 0.0 || (1.0 / *self) == $neg_inf }
276 signed_float_impl!(f32, f32::NAN, f32::INFINITY, f32::NEG_INFINITY,
277 intrinsics::fabsf32, intrinsics::copysignf32, fdimf)
278 signed_float_impl!(f64, f64::NAN, f64::INFINITY, f64::NEG_INFINITY,
279 intrinsics::fabsf64, intrinsics::copysignf64, fdim)
281 /// Computes the absolute value.
283 /// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`
285 pub fn abs<T: Signed>(value: T) -> T {
289 /// The positive difference of two numbers.
291 /// Returns `zero` if the number is less than or equal to `other`,
292 /// otherwise the difference between `self` and `other` is returned.
294 pub fn abs_sub<T: Signed>(x: T, y: T) -> T {
298 /// Returns the sign of the number.
300 /// For `f32` and `f64`:
302 /// * `1.0` if the number is positive, `+0.0` or `INFINITY`
303 /// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
304 /// * `NaN` if the number is `NaN`
308 /// * `0` if the number is zero
309 /// * `1` if the number is positive
310 /// * `-1` if the number is negative
311 #[inline(always)] pub fn signum<T: Signed>(value: T) -> T { value.signum() }
313 /// A trait for values which cannot be negative
314 pub trait Unsigned: Num {}
316 trait_impl!(Unsigned for uint u8 u16 u32 u64)
318 /// Raises a value to the power of exp, using exponentiation by squaring.
325 /// assert_eq!(num::pow(2, 4), 16);
328 pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
331 let mut acc = one::<T>();
343 /// Numbers which have upper and lower bounds
345 // FIXME (#5527): These should be associated constants
346 /// returns the smallest finite number this type can represent
347 fn min_value() -> Self;
348 /// returns the largest finite number this type can represent
349 fn max_value() -> Self;
352 macro_rules! bounded_impl(
353 ($t:ty, $min:expr, $max:expr) => {
354 impl Bounded for $t {
356 fn min_value() -> $t { $min }
359 fn max_value() -> $t { $max }
364 bounded_impl!(uint, uint::MIN, uint::MAX)
365 bounded_impl!(u8, u8::MIN, u8::MAX)
366 bounded_impl!(u16, u16::MIN, u16::MAX)
367 bounded_impl!(u32, u32::MIN, u32::MAX)
368 bounded_impl!(u64, u64::MIN, u64::MAX)
370 bounded_impl!(int, int::MIN, int::MAX)
371 bounded_impl!(i8, i8::MIN, i8::MAX)
372 bounded_impl!(i16, i16::MIN, i16::MAX)
373 bounded_impl!(i32, i32::MIN, i32::MAX)
374 bounded_impl!(i64, i64::MIN, i64::MAX)
376 bounded_impl!(f32, f32::MIN_VALUE, f32::MAX_VALUE)
377 bounded_impl!(f64, f64::MIN_VALUE, f64::MAX_VALUE)
379 /// Numbers with a fixed binary representation.
380 pub trait Bitwise: Bounded
387 /// Returns the number of ones in the binary representation of the number.
392 /// use std::num::Bitwise;
394 /// let n = 0b01001100u8;
395 /// assert_eq!(n.count_ones(), 3);
397 fn count_ones(&self) -> Self;
399 /// Returns the number of zeros in the binary representation of the number.
404 /// use std::num::Bitwise;
406 /// let n = 0b01001100u8;
407 /// assert_eq!(n.count_zeros(), 5);
410 fn count_zeros(&self) -> Self {
411 (!*self).count_ones()
414 /// Returns the number of leading zeros in the in the binary representation
420 /// use std::num::Bitwise;
422 /// let n = 0b0101000u16;
423 /// assert_eq!(n.leading_zeros(), 10);
425 fn leading_zeros(&self) -> Self;
427 /// Returns the number of trailing zeros in the in the binary representation
433 /// use std::num::Bitwise;
435 /// let n = 0b0101000u16;
436 /// assert_eq!(n.trailing_zeros(), 3);
438 fn trailing_zeros(&self) -> Self;
440 /// Shifts the bits to the left by a specified amount amount, `r`, wrapping
441 /// the truncated bits to the end of the resulting value.
446 /// use std::num::Bitwise;
448 /// let n = 0x0123456789ABCDEFu64;
449 /// let m = 0x3456789ABCDEF012u64;
450 /// assert_eq!(n.rotate_left(12), m);
452 fn rotate_left(&self, r: uint) -> Self;
454 /// Shifts the bits to the right by a specified amount amount, `r`, wrapping
455 /// the truncated bits to the beginning of the resulting value.
460 /// use std::num::Bitwise;
462 /// let n = 0x0123456789ABCDEFu64;
463 /// let m = 0xDEF0123456789ABCu64;
464 /// assert_eq!(n.rotate_right(12), m);
466 fn rotate_right(&self, r: uint) -> Self;
469 macro_rules! bitwise_impl {
470 ($t:ty, $bits:expr, $co:path, $lz:path, $tz:path) => {
471 impl Bitwise for $t {
473 fn count_ones(&self) -> $t { unsafe { $co(*self) } }
476 fn leading_zeros(&self) -> $t { unsafe { $lz(*self) } }
479 fn trailing_zeros(&self) -> $t { unsafe { $tz(*self) } }
482 fn rotate_left(&self, r: uint) -> $t {
483 // Protect against undefined behaviour for overlong bit shifts
485 (*self << r) | (*self >> ($bits - r))
489 fn rotate_right(&self, r: uint) -> $t {
490 // Protect against undefined behaviour for overlong bit shifts
492 (*self >> r) | (*self << ($bits - r))
498 macro_rules! bitwise_cast_impl {
499 ($t:ty, $t_cast:ty, $bits:expr, $co:path, $lz:path, $tz:path) => {
500 impl Bitwise for $t {
502 fn count_ones(&self) -> $t { unsafe { $co(*self as $t_cast) as $t } }
505 fn leading_zeros(&self) -> $t { unsafe { $lz(*self as $t_cast) as $t } }
508 fn trailing_zeros(&self) -> $t { unsafe { $tz(*self as $t_cast) as $t } }
511 fn rotate_left(&self, r: uint) -> $t {
512 // cast to prevent the sign bit from being corrupted
513 (*self as $t_cast).rotate_left(r) as $t
517 fn rotate_right(&self, r: uint) -> $t {
518 // cast to prevent the sign bit from being corrupted
519 (*self as $t_cast).rotate_right(r) as $t
525 #[cfg(target_word_size = "32")]
526 bitwise_cast_impl!(uint, u32, 32, intrinsics::ctpop32, intrinsics::ctlz32, intrinsics::cttz32)
527 #[cfg(target_word_size = "64")]
528 bitwise_cast_impl!(uint, u64, 64, intrinsics::ctpop64, intrinsics::ctlz64, intrinsics::cttz64)
530 bitwise_impl!(u8, 8, intrinsics::ctpop8, intrinsics::ctlz8, intrinsics::cttz8)
531 bitwise_impl!(u16, 16, intrinsics::ctpop16, intrinsics::ctlz16, intrinsics::cttz16)
532 bitwise_impl!(u32, 32, intrinsics::ctpop32, intrinsics::ctlz32, intrinsics::cttz32)
533 bitwise_impl!(u64, 64, intrinsics::ctpop64, intrinsics::ctlz64, intrinsics::cttz64)
535 #[cfg(target_word_size = "32")]
536 bitwise_cast_impl!(int, u32, 32, intrinsics::ctpop32, intrinsics::ctlz32, intrinsics::cttz32)
537 #[cfg(target_word_size = "64")]
538 bitwise_cast_impl!(int, u64, 64, intrinsics::ctpop64, intrinsics::ctlz64, intrinsics::cttz64)
540 bitwise_cast_impl!(i8, u8, 8, intrinsics::ctpop8, intrinsics::ctlz8, intrinsics::cttz8)
541 bitwise_cast_impl!(i16, u16, 16, intrinsics::ctpop16, intrinsics::ctlz16, intrinsics::cttz16)
542 bitwise_cast_impl!(i32, u32, 32, intrinsics::ctpop32, intrinsics::ctlz32, intrinsics::cttz32)
543 bitwise_cast_impl!(i64, u64, 64, intrinsics::ctpop64, intrinsics::ctlz64, intrinsics::cttz64)
545 /// Specifies the available operations common to all of Rust's core numeric primitives.
546 /// These may not always make sense from a purely mathematical point of view, but
547 /// may be useful for systems programming.
548 pub trait Primitive: Copy
555 trait_impl!(Primitive for uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
557 /// A collection of traits relevant to primitive signed and unsigned integers
558 pub trait Int: Primitive
565 trait_impl!(Int for uint u8 u16 u32 u64 int i8 i16 i32 i64)
567 /// Returns the smallest power of 2 greater than or equal to `n`.
569 pub fn next_power_of_two<T: Unsigned + Int>(n: T) -> T {
570 let halfbits: T = cast(size_of::<T>() * 4).unwrap();
571 let mut tmp: T = n - one();
572 let mut shift: T = one();
573 while shift <= halfbits {
574 tmp = tmp | (tmp >> shift);
575 shift = shift << one();
580 // Returns `true` iff `n == 2^k` for some k.
582 pub fn is_power_of_two<T: Unsigned + Int>(n: T) -> bool {
583 (n - one()) & n == zero()
586 /// Returns the smallest power of 2 greater than or equal to `n`. If the next
587 /// power of two is greater than the type's maximum value, `None` is returned,
588 /// otherwise the power of 2 is wrapped in `Some`.
590 pub fn checked_next_power_of_two<T: Unsigned + Int>(n: T) -> Option<T> {
591 let halfbits: T = cast(size_of::<T>() * 4).unwrap();
592 let mut tmp: T = n - one();
593 let mut shift: T = one();
594 while shift <= halfbits {
595 tmp = tmp | (tmp >> shift);
596 shift = shift << one();
598 tmp.checked_add(&one())
601 /// A generic trait for converting a value to a number.
602 pub trait ToPrimitive {
603 /// Converts the value of `self` to an `int`.
605 fn to_int(&self) -> Option<int> {
606 self.to_i64().and_then(|x| x.to_int())
609 /// Converts the value of `self` to an `i8`.
611 fn to_i8(&self) -> Option<i8> {
612 self.to_i64().and_then(|x| x.to_i8())
615 /// Converts the value of `self` to an `i16`.
617 fn to_i16(&self) -> Option<i16> {
618 self.to_i64().and_then(|x| x.to_i16())
621 /// Converts the value of `self` to an `i32`.
623 fn to_i32(&self) -> Option<i32> {
624 self.to_i64().and_then(|x| x.to_i32())
627 /// Converts the value of `self` to an `i64`.
628 fn to_i64(&self) -> Option<i64>;
630 /// Converts the value of `self` to an `uint`.
632 fn to_uint(&self) -> Option<uint> {
633 self.to_u64().and_then(|x| x.to_uint())
636 /// Converts the value of `self` to an `u8`.
638 fn to_u8(&self) -> Option<u8> {
639 self.to_u64().and_then(|x| x.to_u8())
642 /// Converts the value of `self` to an `u16`.
644 fn to_u16(&self) -> Option<u16> {
645 self.to_u64().and_then(|x| x.to_u16())
648 /// Converts the value of `self` to an `u32`.
650 fn to_u32(&self) -> Option<u32> {
651 self.to_u64().and_then(|x| x.to_u32())
654 /// Converts the value of `self` to an `u64`.
656 fn to_u64(&self) -> Option<u64>;
658 /// Converts the value of `self` to an `f32`.
660 fn to_f32(&self) -> Option<f32> {
661 self.to_f64().and_then(|x| x.to_f32())
664 /// Converts the value of `self` to an `f64`.
666 fn to_f64(&self) -> Option<f64> {
667 self.to_i64().and_then(|x| x.to_f64())
671 macro_rules! impl_to_primitive_int_to_int(
672 ($SrcT:ty, $DstT:ty) => (
674 if size_of::<$SrcT>() <= size_of::<$DstT>() {
677 let n = *self as i64;
678 let min_value: $DstT = Bounded::min_value();
679 let max_value: $DstT = Bounded::max_value();
680 if min_value as i64 <= n && n <= max_value as i64 {
690 macro_rules! impl_to_primitive_int_to_uint(
691 ($SrcT:ty, $DstT:ty) => (
693 let zero: $SrcT = Zero::zero();
694 let max_value: $DstT = Bounded::max_value();
695 if zero <= *self && *self as u64 <= max_value as u64 {
704 macro_rules! impl_to_primitive_int(
706 impl ToPrimitive for $T {
708 fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int) }
710 fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8) }
712 fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16) }
714 fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32) }
716 fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64) }
719 fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint) }
721 fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8) }
723 fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16) }
725 fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32) }
727 fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64) }
730 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
732 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
737 impl_to_primitive_int!(int)
738 impl_to_primitive_int!(i8)
739 impl_to_primitive_int!(i16)
740 impl_to_primitive_int!(i32)
741 impl_to_primitive_int!(i64)
743 macro_rules! impl_to_primitive_uint_to_int(
746 let max_value: $DstT = Bounded::max_value();
747 if *self as u64 <= max_value as u64 {
756 macro_rules! impl_to_primitive_uint_to_uint(
757 ($SrcT:ty, $DstT:ty) => (
759 if size_of::<$SrcT>() <= size_of::<$DstT>() {
762 let zero: $SrcT = Zero::zero();
763 let max_value: $DstT = Bounded::max_value();
764 if zero <= *self && *self as u64 <= max_value as u64 {
774 macro_rules! impl_to_primitive_uint(
776 impl ToPrimitive for $T {
778 fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int) }
780 fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8) }
782 fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16) }
784 fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32) }
786 fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64) }
789 fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint) }
791 fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8) }
793 fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16) }
795 fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32) }
797 fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64) }
800 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
802 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
807 impl_to_primitive_uint!(uint)
808 impl_to_primitive_uint!(u8)
809 impl_to_primitive_uint!(u16)
810 impl_to_primitive_uint!(u32)
811 impl_to_primitive_uint!(u64)
813 macro_rules! impl_to_primitive_float_to_float(
814 ($SrcT:ty, $DstT:ty) => (
815 if size_of::<$SrcT>() <= size_of::<$DstT>() {
818 let n = *self as f64;
819 let max_value: $SrcT = Bounded::max_value();
820 if -max_value as f64 <= n && n <= max_value as f64 {
829 macro_rules! impl_to_primitive_float(
831 impl ToPrimitive for $T {
833 fn to_int(&self) -> Option<int> { Some(*self as int) }
835 fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
837 fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
839 fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
841 fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
844 fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
846 fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
848 fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
850 fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
852 fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
855 fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32) }
857 fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64) }
862 impl_to_primitive_float!(f32)
863 impl_to_primitive_float!(f64)
865 /// A generic trait for converting a number to a value.
866 pub trait FromPrimitive {
867 /// Convert an `int` to return an optional value of this type. If the
868 /// value cannot be represented by this value, the `None` is returned.
870 fn from_int(n: int) -> Option<Self> {
871 FromPrimitive::from_i64(n as i64)
874 /// Convert an `i8` to return an optional value of this type. If the
875 /// type cannot be represented by this value, the `None` is returned.
877 fn from_i8(n: i8) -> Option<Self> {
878 FromPrimitive::from_i64(n as i64)
881 /// Convert an `i16` to return an optional value of this type. If the
882 /// type cannot be represented by this value, the `None` is returned.
884 fn from_i16(n: i16) -> Option<Self> {
885 FromPrimitive::from_i64(n as i64)
888 /// Convert an `i32` to return an optional value of this type. If the
889 /// type cannot be represented by this value, the `None` is returned.
891 fn from_i32(n: i32) -> Option<Self> {
892 FromPrimitive::from_i64(n as i64)
895 /// Convert an `i64` to return an optional value of this type. If the
896 /// type cannot be represented by this value, the `None` is returned.
897 fn from_i64(n: i64) -> Option<Self>;
899 /// Convert an `uint` to return an optional value of this type. If the
900 /// type cannot be represented by this value, the `None` is returned.
902 fn from_uint(n: uint) -> Option<Self> {
903 FromPrimitive::from_u64(n as u64)
906 /// Convert an `u8` to return an optional value of this type. If the
907 /// type cannot be represented by this value, the `None` is returned.
909 fn from_u8(n: u8) -> Option<Self> {
910 FromPrimitive::from_u64(n as u64)
913 /// Convert an `u16` to return an optional value of this type. If the
914 /// type cannot be represented by this value, the `None` is returned.
916 fn from_u16(n: u16) -> Option<Self> {
917 FromPrimitive::from_u64(n as u64)
920 /// Convert an `u32` to return an optional value of this type. If the
921 /// type cannot be represented by this value, the `None` is returned.
923 fn from_u32(n: u32) -> Option<Self> {
924 FromPrimitive::from_u64(n as u64)
927 /// Convert an `u64` to return an optional value of this type. If the
928 /// type cannot be represented by this value, the `None` is returned.
929 fn from_u64(n: u64) -> Option<Self>;
931 /// Convert a `f32` to return an optional value of this type. If the
932 /// type cannot be represented by this value, the `None` is returned.
934 fn from_f32(n: f32) -> Option<Self> {
935 FromPrimitive::from_f64(n as f64)
938 /// Convert a `f64` to return an optional value of this type. If the
939 /// type cannot be represented by this value, the `None` is returned.
941 fn from_f64(n: f64) -> Option<Self> {
942 FromPrimitive::from_i64(n as i64)
946 /// A utility function that just calls `FromPrimitive::from_int`.
947 pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
948 FromPrimitive::from_int(n)
951 /// A utility function that just calls `FromPrimitive::from_i8`.
952 pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> {
953 FromPrimitive::from_i8(n)
956 /// A utility function that just calls `FromPrimitive::from_i16`.
957 pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> {
958 FromPrimitive::from_i16(n)
961 /// A utility function that just calls `FromPrimitive::from_i32`.
962 pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> {
963 FromPrimitive::from_i32(n)
966 /// A utility function that just calls `FromPrimitive::from_i64`.
967 pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
968 FromPrimitive::from_i64(n)
971 /// A utility function that just calls `FromPrimitive::from_uint`.
972 pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
973 FromPrimitive::from_uint(n)
976 /// A utility function that just calls `FromPrimitive::from_u8`.
977 pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> {
978 FromPrimitive::from_u8(n)
981 /// A utility function that just calls `FromPrimitive::from_u16`.
982 pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> {
983 FromPrimitive::from_u16(n)
986 /// A utility function that just calls `FromPrimitive::from_u32`.
987 pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> {
988 FromPrimitive::from_u32(n)
991 /// A utility function that just calls `FromPrimitive::from_u64`.
992 pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> {
993 FromPrimitive::from_u64(n)
996 /// A utility function that just calls `FromPrimitive::from_f32`.
997 pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> {
998 FromPrimitive::from_f32(n)
1001 /// A utility function that just calls `FromPrimitive::from_f64`.
1002 pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {
1003 FromPrimitive::from_f64(n)
1006 macro_rules! impl_from_primitive(
1007 ($T:ty, $to_ty:expr) => (
1008 impl FromPrimitive for $T {
1009 #[inline] fn from_int(n: int) -> Option<$T> { $to_ty }
1010 #[inline] fn from_i8(n: i8) -> Option<$T> { $to_ty }
1011 #[inline] fn from_i16(n: i16) -> Option<$T> { $to_ty }
1012 #[inline] fn from_i32(n: i32) -> Option<$T> { $to_ty }
1013 #[inline] fn from_i64(n: i64) -> Option<$T> { $to_ty }
1015 #[inline] fn from_uint(n: uint) -> Option<$T> { $to_ty }
1016 #[inline] fn from_u8(n: u8) -> Option<$T> { $to_ty }
1017 #[inline] fn from_u16(n: u16) -> Option<$T> { $to_ty }
1018 #[inline] fn from_u32(n: u32) -> Option<$T> { $to_ty }
1019 #[inline] fn from_u64(n: u64) -> Option<$T> { $to_ty }
1021 #[inline] fn from_f32(n: f32) -> Option<$T> { $to_ty }
1022 #[inline] fn from_f64(n: f64) -> Option<$T> { $to_ty }
1027 impl_from_primitive!(int, n.to_int())
1028 impl_from_primitive!(i8, n.to_i8())
1029 impl_from_primitive!(i16, n.to_i16())
1030 impl_from_primitive!(i32, n.to_i32())
1031 impl_from_primitive!(i64, n.to_i64())
1032 impl_from_primitive!(uint, n.to_uint())
1033 impl_from_primitive!(u8, n.to_u8())
1034 impl_from_primitive!(u16, n.to_u16())
1035 impl_from_primitive!(u32, n.to_u32())
1036 impl_from_primitive!(u64, n.to_u64())
1037 impl_from_primitive!(f32, n.to_f32())
1038 impl_from_primitive!(f64, n.to_f64())
1040 /// Cast from one machine scalar to another.
1047 /// let twenty: f32 = num::cast(0x14).unwrap();
1048 /// assert_eq!(twenty, 20f32);
1052 pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
1056 /// An interface for casting between machine scalars.
1057 pub trait NumCast: ToPrimitive {
1058 /// Creates a number from another value that can be converted into a primitive via the
1059 /// `ToPrimitive` trait.
1060 fn from<T: ToPrimitive>(n: T) -> Option<Self>;
1063 macro_rules! impl_num_cast(
1064 ($T:ty, $conv:ident) => (
1065 impl NumCast for $T {
1067 fn from<N: ToPrimitive>(n: N) -> Option<$T> {
1068 // `$conv` could be generated using `concat_idents!`, but that
1069 // macro seems to be broken at the moment
1076 impl_num_cast!(u8, to_u8)
1077 impl_num_cast!(u16, to_u16)
1078 impl_num_cast!(u32, to_u32)
1079 impl_num_cast!(u64, to_u64)
1080 impl_num_cast!(uint, to_uint)
1081 impl_num_cast!(i8, to_i8)
1082 impl_num_cast!(i16, to_i16)
1083 impl_num_cast!(i32, to_i32)
1084 impl_num_cast!(i64, to_i64)
1085 impl_num_cast!(int, to_int)
1086 impl_num_cast!(f32, to_f32)
1087 impl_num_cast!(f64, to_f64)
1089 /// Saturating math operations
1090 pub trait Saturating {
1091 /// Saturating addition operator.
1092 /// Returns a+b, saturating at the numeric bounds instead of overflowing.
1093 fn saturating_add(self, v: Self) -> Self;
1095 /// Saturating subtraction operator.
1096 /// Returns a-b, saturating at the numeric bounds instead of overflowing.
1097 fn saturating_sub(self, v: Self) -> Self;
1100 impl<T: CheckedAdd + CheckedSub + Zero + PartialOrd + Bounded> Saturating for T {
1102 fn saturating_add(self, v: T) -> T {
1103 match self.checked_add(&v) {
1105 None => if v >= Zero::zero() {
1106 Bounded::max_value()
1108 Bounded::min_value()
1114 fn saturating_sub(self, v: T) -> T {
1115 match self.checked_sub(&v) {
1117 None => if v >= Zero::zero() {
1118 Bounded::min_value()
1120 Bounded::max_value()
1126 /// Performs addition that returns `None` instead of wrapping around on overflow.
1127 pub trait CheckedAdd: Add<Self, Self> {
1128 /// Adds two numbers, checking for overflow. If overflow happens, `None` is returned.
1129 fn checked_add(&self, v: &Self) -> Option<Self>;
1132 macro_rules! checked_impl(
1133 ($trait_name:ident, $method:ident, $t:ty, $op:path) => {
1134 impl $trait_name for $t {
1136 fn $method(&self, v: &$t) -> Option<$t> {
1138 let (x, y) = $op(*self, *v);
1139 if y { None } else { Some(x) }
1145 macro_rules! checked_cast_impl(
1146 ($trait_name:ident, $method:ident, $t:ty, $cast:ty, $op:path) => {
1147 impl $trait_name for $t {
1149 fn $method(&self, v: &$t) -> Option<$t> {
1151 let (x, y) = $op(*self as $cast, *v as $cast);
1152 if y { None } else { Some(x as $t) }
1159 #[cfg(target_word_size = "32")]
1160 checked_cast_impl!(CheckedAdd, checked_add, uint, u32, intrinsics::u32_add_with_overflow)
1161 #[cfg(target_word_size = "64")]
1162 checked_cast_impl!(CheckedAdd, checked_add, uint, u64, intrinsics::u64_add_with_overflow)
1164 checked_impl!(CheckedAdd, checked_add, u8, intrinsics::u8_add_with_overflow)
1165 checked_impl!(CheckedAdd, checked_add, u16, intrinsics::u16_add_with_overflow)
1166 checked_impl!(CheckedAdd, checked_add, u32, intrinsics::u32_add_with_overflow)
1167 checked_impl!(CheckedAdd, checked_add, u64, intrinsics::u64_add_with_overflow)
1169 #[cfg(target_word_size = "32")]
1170 checked_cast_impl!(CheckedAdd, checked_add, int, i32, intrinsics::i32_add_with_overflow)
1171 #[cfg(target_word_size = "64")]
1172 checked_cast_impl!(CheckedAdd, checked_add, int, i64, intrinsics::i64_add_with_overflow)
1174 checked_impl!(CheckedAdd, checked_add, i8, intrinsics::i8_add_with_overflow)
1175 checked_impl!(CheckedAdd, checked_add, i16, intrinsics::i16_add_with_overflow)
1176 checked_impl!(CheckedAdd, checked_add, i32, intrinsics::i32_add_with_overflow)
1177 checked_impl!(CheckedAdd, checked_add, i64, intrinsics::i64_add_with_overflow)
1179 /// Performs subtraction that returns `None` instead of wrapping around on underflow.
1180 pub trait CheckedSub: Sub<Self, Self> {
1181 /// Subtracts two numbers, checking for underflow. If underflow happens, `None` is returned.
1182 fn checked_sub(&self, v: &Self) -> Option<Self>;
1185 #[cfg(target_word_size = "32")]
1186 checked_cast_impl!(CheckedSub, checked_sub, uint, u32, intrinsics::u32_sub_with_overflow)
1187 #[cfg(target_word_size = "64")]
1188 checked_cast_impl!(CheckedSub, checked_sub, uint, u64, intrinsics::u64_sub_with_overflow)
1190 checked_impl!(CheckedSub, checked_sub, u8, intrinsics::u8_sub_with_overflow)
1191 checked_impl!(CheckedSub, checked_sub, u16, intrinsics::u16_sub_with_overflow)
1192 checked_impl!(CheckedSub, checked_sub, u32, intrinsics::u32_sub_with_overflow)
1193 checked_impl!(CheckedSub, checked_sub, u64, intrinsics::u64_sub_with_overflow)
1195 #[cfg(target_word_size = "32")]
1196 checked_cast_impl!(CheckedSub, checked_sub, int, i32, intrinsics::i32_sub_with_overflow)
1197 #[cfg(target_word_size = "64")]
1198 checked_cast_impl!(CheckedSub, checked_sub, int, i64, intrinsics::i64_sub_with_overflow)
1200 checked_impl!(CheckedSub, checked_sub, i8, intrinsics::i8_sub_with_overflow)
1201 checked_impl!(CheckedSub, checked_sub, i16, intrinsics::i16_sub_with_overflow)
1202 checked_impl!(CheckedSub, checked_sub, i32, intrinsics::i32_sub_with_overflow)
1203 checked_impl!(CheckedSub, checked_sub, i64, intrinsics::i64_sub_with_overflow)
1205 /// Performs multiplication that returns `None` instead of wrapping around on underflow or
1207 pub trait CheckedMul: Mul<Self, Self> {
1208 /// Multiplies two numbers, checking for underflow or overflow. If underflow or overflow
1209 /// happens, `None` is returned.
1210 fn checked_mul(&self, v: &Self) -> Option<Self>;
1213 #[cfg(target_word_size = "32")]
1214 checked_cast_impl!(CheckedMul, checked_mul, uint, u32, intrinsics::u32_mul_with_overflow)
1215 #[cfg(target_word_size = "64")]
1216 checked_cast_impl!(CheckedMul, checked_mul, uint, u64, intrinsics::u64_mul_with_overflow)
1218 checked_impl!(CheckedMul, checked_mul, u8, intrinsics::u8_mul_with_overflow)
1219 checked_impl!(CheckedMul, checked_mul, u16, intrinsics::u16_mul_with_overflow)
1220 checked_impl!(CheckedMul, checked_mul, u32, intrinsics::u32_mul_with_overflow)
1221 checked_impl!(CheckedMul, checked_mul, u64, intrinsics::u64_mul_with_overflow)
1223 #[cfg(target_word_size = "32")]
1224 checked_cast_impl!(CheckedMul, checked_mul, int, i32, intrinsics::i32_mul_with_overflow)
1225 #[cfg(target_word_size = "64")]
1226 checked_cast_impl!(CheckedMul, checked_mul, int, i64, intrinsics::i64_mul_with_overflow)
1228 checked_impl!(CheckedMul, checked_mul, i8, intrinsics::i8_mul_with_overflow)
1229 checked_impl!(CheckedMul, checked_mul, i16, intrinsics::i16_mul_with_overflow)
1230 checked_impl!(CheckedMul, checked_mul, i32, intrinsics::i32_mul_with_overflow)
1231 checked_impl!(CheckedMul, checked_mul, i64, intrinsics::i64_mul_with_overflow)
1233 /// Performs division that returns `None` instead of wrapping around on underflow or overflow.
1234 pub trait CheckedDiv: Div<Self, Self> {
1235 /// Divides two numbers, checking for underflow or overflow. If underflow or overflow happens,
1236 /// `None` is returned.
1237 fn checked_div(&self, v: &Self) -> Option<Self>;
1240 macro_rules! checkeddiv_int_impl(
1241 ($t:ty, $min:expr) => {
1242 impl CheckedDiv for $t {
1244 fn checked_div(&self, v: &$t) -> Option<$t> {
1245 if *v == 0 || (*self == $min && *v == -1) {
1255 checkeddiv_int_impl!(int, int::MIN)
1256 checkeddiv_int_impl!(i8, i8::MIN)
1257 checkeddiv_int_impl!(i16, i16::MIN)
1258 checkeddiv_int_impl!(i32, i32::MIN)
1259 checkeddiv_int_impl!(i64, i64::MIN)
1261 macro_rules! checkeddiv_uint_impl(
1263 impl CheckedDiv for $t {
1265 fn checked_div(&self, v: &$t) -> Option<$t> {
1276 checkeddiv_uint_impl!(uint u8 u16 u32 u64)
1278 /// Helper function for testing numeric operations
1280 pub fn test_num<T:Num + NumCast + ::std::fmt::Show>(ten: T, two: T) {
1281 assert_eq!(ten.add(&two), cast(12).unwrap());
1282 assert_eq!(ten.sub(&two), cast(8).unwrap());
1283 assert_eq!(ten.mul(&two), cast(20).unwrap());
1284 assert_eq!(ten.div(&two), cast(5).unwrap());
1285 assert_eq!(ten.rem(&two), cast(0).unwrap());
1287 assert_eq!(ten.add(&two), ten + two);
1288 assert_eq!(ten.sub(&two), ten - two);
1289 assert_eq!(ten.mul(&two), ten * two);
1290 assert_eq!(ten.div(&two), ten / two);
1291 assert_eq!(ten.rem(&two), ten % two);
1294 /// Used for representing the classification of floating point numbers
1295 #[deriving(PartialEq, Show)]
1296 pub enum FPCategory {
1297 /// "Not a Number", often obtained by dividing by zero
1299 /// Positive or negative infinity
1301 /// Positive or negative zero
1303 /// De-normalized floating point representation (less precise than `FPNormal`)
1305 /// A regular floating point number
1309 /// Operations on primitive floating point numbers.
1310 // FIXME(#5527): In a future version of Rust, many of these functions will
1311 // become constants.
1313 // FIXME(#8888): Several of these functions have a parameter named
1314 // `unused_self`. Removing it requires #8888 to be fixed.
1315 pub trait Float: Signed + Primitive {
1316 /// Returns the NaN value.
1318 /// Returns the infinite value.
1319 fn infinity() -> Self;
1320 /// Returns the negative infinite value.
1321 fn neg_infinity() -> Self;
1323 fn neg_zero() -> Self;
1325 /// Returns true if this value is NaN and false otherwise.
1326 fn is_nan(self) -> bool;
1327 /// Returns true if this value is positive infinity or negative infinity and
1328 /// false otherwise.
1329 fn is_infinite(self) -> bool;
1330 /// Returns true if this number is neither infinite nor NaN.
1331 fn is_finite(self) -> bool;
1332 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1333 fn is_normal(self) -> bool;
1334 /// Returns the category that this number falls into.
1335 fn classify(self) -> FPCategory;
1337 // FIXME (#5527): These should be associated constants
1339 /// Returns the number of binary digits of mantissa that this type supports.
1340 fn mantissa_digits(unused_self: Option<Self>) -> uint;
1341 /// Returns the number of base-10 digits of precision that this type supports.
1342 fn digits(unused_self: Option<Self>) -> uint;
1343 /// Returns the difference between 1.0 and the smallest representable number larger than 1.0.
1344 fn epsilon() -> Self;
1345 /// Returns the minimum binary exponent that this type can represent.
1346 fn min_exp(unused_self: Option<Self>) -> int;
1347 /// Returns the maximum binary exponent that this type can represent.
1348 fn max_exp(unused_self: Option<Self>) -> int;
1349 /// Returns the minimum base-10 exponent that this type can represent.
1350 fn min_10_exp(unused_self: Option<Self>) -> int;
1351 /// Returns the maximum base-10 exponent that this type can represent.
1352 fn max_10_exp(unused_self: Option<Self>) -> int;
1353 /// Returns the smallest normalized positive number that this type can represent.
1354 fn min_pos_value(unused_self: Option<Self>) -> Self;
1356 /// Returns the mantissa, exponent and sign as integers, respectively.
1357 fn integer_decode(self) -> (u64, i16, i8);
1359 /// Return the largest integer less than or equal to a number.
1360 fn floor(self) -> Self;
1361 /// Return the smallest integer greater than or equal to a number.
1362 fn ceil(self) -> Self;
1363 /// Return the nearest integer to a number. Round half-way cases away from
1365 fn round(self) -> Self;
1366 /// Return the integer part of a number.
1367 fn trunc(self) -> Self;
1368 /// Return the fractional part of a number.
1369 fn fract(self) -> Self;
1371 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1372 /// error. This produces a more accurate result with better performance than
1373 /// a separate multiplication operation followed by an add.
1374 fn mul_add(self, a: Self, b: Self) -> Self;
1375 /// Take the reciprocal (inverse) of a number, `1/x`.
1376 fn recip(self) -> Self;
1378 /// Raise a number to an integer power.
1380 /// Using this function is generally faster than using `powf`
1381 fn powi(self, n: i32) -> Self;
1382 /// Raise a number to a floating point power.
1383 fn powf(self, n: Self) -> Self;
1387 /// 1.0 / sqrt(2.0).
1388 fn frac_1_sqrt2() -> Self;
1390 /// Take the square root of a number.
1391 fn sqrt(self) -> Self;
1392 /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1393 fn rsqrt(self) -> Self;
1395 // FIXME (#5527): These should be associated constants
1397 /// Archimedes' constant.
1400 fn two_pi() -> Self;
1402 fn frac_pi_2() -> Self;
1404 fn frac_pi_3() -> Self;
1406 fn frac_pi_4() -> Self;
1408 fn frac_pi_6() -> Self;
1410 fn frac_pi_8() -> Self;
1412 fn frac_1_pi() -> Self;
1414 fn frac_2_pi() -> Self;
1416 fn frac_2_sqrtpi() -> Self;
1421 fn log2_e() -> Self;
1423 fn log10_e() -> Self;
1429 /// Returns `e^(self)`, (the exponential function).
1430 fn exp(self) -> Self;
1431 /// Returns 2 raised to the power of the number, `2^(self)`.
1432 fn exp2(self) -> Self;
1433 /// Returns the natural logarithm of the number.
1434 fn ln(self) -> Self;
1435 /// Returns the logarithm of the number with respect to an arbitrary base.
1436 fn log(self, base: Self) -> Self;
1437 /// Returns the base 2 logarithm of the number.
1438 fn log2(self) -> Self;
1439 /// Returns the base 10 logarithm of the number.
1440 fn log10(self) -> Self;
1442 /// Convert radians to degrees.
1443 fn to_degrees(self) -> Self;
1444 /// Convert degrees to radians.
1445 fn to_radians(self) -> Self;