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 //! These are implemented for the primitive numeric types in `std::{u8, u16,
14 //! u32, u64, uint, i8, i16, i32, i64, int, f32, f64, float}`.
16 #![allow(missing_doc)]
22 use ops::{Add, Sub, Mul, Div, Rem, Neg};
23 use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
24 use option::{Option, Some, None};
25 use fmt::{Show, Binary, Octal, LowerHex, UpperHex};
29 /// The base trait for numeric types
30 pub trait Num: Eq + Zero + One
38 /// Simultaneous division and remainder
40 pub fn div_rem<T: Div<T, T> + Rem<T, T>>(x: T, y: T) -> (T, T) {
44 /// Defines an additive identity element for `Self`.
48 /// This trait can be automatically be derived using `#[deriving(Zero)]`
49 /// attribute. If you choose to use this, make sure that the laws outlined in
50 /// the documentation for `Zero::zero` still hold.
51 pub trait Zero: Add<Self, Self> {
52 /// Returns the additive identity element of `Self`, `0`.
57 /// a + 0 = a ∀ a ∈ Self
58 /// 0 + a = a ∀ a ∈ Self
63 /// This function should return the same result at all times regardless of
64 /// external mutable state, for example values stored in TLS or in
66 // FIXME (#5527): This should be an associated constant
69 /// Returns `true` if `self` is equal to the additive identity.
70 fn is_zero(&self) -> bool;
73 /// Returns the additive identity, `0`.
74 #[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() }
76 /// Defines a multiplicative identity element for `Self`.
77 pub trait One: Mul<Self, Self> {
78 /// Returns the multiplicative identity element of `Self`, `1`.
83 /// a * 1 = a ∀ a ∈ Self
84 /// 1 * a = a ∀ a ∈ Self
89 /// This function should return the same result at all times regardless of
90 /// external mutable state, for example values stored in TLS or in
92 // FIXME (#5527): This should be an associated constant
96 /// Returns the multiplicative identity, `1`.
97 #[inline(always)] pub fn one<T: One>() -> T { One::one() }
99 /// Useful functions for signed numbers (i.e. numbers that can be negative).
100 pub trait Signed: Num + Neg<Self> {
101 /// Computes the absolute value.
103 /// For float, f32, and f64, `NaN` will be returned if the number is `NaN`.
104 fn abs(&self) -> Self;
106 /// The positive difference of two numbers.
108 /// Returns `zero` if the number is less than or equal to `other`, otherwise the difference
109 /// between `self` and `other` is returned.
110 fn abs_sub(&self, other: &Self) -> Self;
112 /// Returns the sign of the number.
114 /// For `float`, `f32`, `f64`:
115 /// * `1.0` if the number is positive, `+0.0` or `INFINITY`
116 /// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
117 /// * `NaN` if the number is `NaN`
120 /// * `0` if the number is zero
121 /// * `1` if the number is positive
122 /// * `-1` if the number is negative
123 fn signum(&self) -> Self;
125 /// Returns true if the number is positive and false if the number is zero or negative.
126 fn is_positive(&self) -> bool;
128 /// Returns true if the number is negative and false if the number is zero or positive.
129 fn is_negative(&self) -> bool;
132 /// Computes the absolute value.
134 /// For float, f32, and f64, `NaN` will be returned if the number is `NaN`
136 pub fn abs<T: Signed>(value: T) -> T {
140 /// The positive difference of two numbers.
142 /// Returns `zero` if the number is less than or equal to `other`,
143 /// otherwise the difference between `self` and `other` is returned.
145 pub fn abs_sub<T: Signed>(x: T, y: T) -> T {
149 /// Returns the sign of the number.
151 /// For float, f32, f64:
152 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
153 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
154 /// - `NAN` if the number is `NAN`
157 /// - `0` if the number is zero
158 /// - `1` if the number is positive
159 /// - `-1` if the number is negative
160 #[inline(always)] pub fn signum<T: Signed>(value: T) -> T { value.signum() }
162 /// A trait for values which cannot be negative
163 pub trait Unsigned: Num {}
165 /// Raises a value to the power of exp, using exponentiation by squaring.
172 /// assert_eq!(num::pow(2, 4), 16);
175 pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
178 let mut acc = one::<T>();
190 /// Numbers which have upper and lower bounds
192 // FIXME (#5527): These should be associated constants
193 fn min_value() -> Self;
194 fn max_value() -> Self;
197 /// Numbers with a fixed binary representation.
198 pub trait Bitwise: Bounded
205 /// Returns the number of ones in the binary representation of the number.
210 /// use std::num::Bitwise;
212 /// let n = 0b01001100u8;
213 /// assert_eq!(n.count_ones(), 3);
215 fn count_ones(&self) -> Self;
217 /// Returns the number of zeros in the binary representation of the number.
222 /// use std::num::Bitwise;
224 /// let n = 0b01001100u8;
225 /// assert_eq!(n.count_zeros(), 5);
228 fn count_zeros(&self) -> Self {
229 (!*self).count_ones()
232 /// Returns the number of leading zeros in the in the binary representation
238 /// use std::num::Bitwise;
240 /// let n = 0b0101000u16;
241 /// assert_eq!(n.leading_zeros(), 10);
243 fn leading_zeros(&self) -> Self;
245 /// Returns the number of trailing zeros in the in the binary representation
251 /// use std::num::Bitwise;
253 /// let n = 0b0101000u16;
254 /// assert_eq!(n.trailing_zeros(), 3);
256 fn trailing_zeros(&self) -> Self;
259 /// Specifies the available operations common to all of Rust's core numeric primitives.
260 /// These may not always make sense from a purely mathematical point of view, but
261 /// may be useful for systems programming.
262 pub trait Primitive: Copy
269 /// A collection of traits relevant to primitive signed and unsigned integers
270 pub trait Int: Primitive
282 /// Returns the smallest power of 2 greater than or equal to `n`.
284 pub fn next_power_of_two<T: Unsigned + Int>(n: T) -> T {
285 let halfbits: T = cast(size_of::<T>() * 4).unwrap();
286 let mut tmp: T = n - one();
287 let mut shift: T = one();
288 while shift <= halfbits {
289 tmp = tmp | (tmp >> shift);
290 shift = shift << one();
295 // Returns `true` iff `n == 2^k` for some k.
297 pub fn is_power_of_two<T: Unsigned + Int>(n: T) -> bool {
298 (n - one()) & n == zero()
301 /// Returns the smallest power of 2 greater than or equal to `n`. If the next
302 /// power of two is greater than the type's maximum value, `None` is returned,
303 /// otherwise the power of 2 is wrapped in `Some`.
305 pub fn checked_next_power_of_two<T: Unsigned + Int>(n: T) -> Option<T> {
306 let halfbits: T = cast(size_of::<T>() * 4).unwrap();
307 let mut tmp: T = n - one();
308 let mut shift: T = one();
309 while shift <= halfbits {
310 tmp = tmp | (tmp >> shift);
311 shift = shift << one();
313 tmp.checked_add(&one())
316 /// Used for representing the classification of floating point numbers
317 #[deriving(Eq, Show)]
318 pub enum FPCategory {
319 /// "Not a Number", often obtained by dividing by zero
321 /// Positive or negative infinity
323 /// Positive or negative zero
325 /// De-normalized floating point representation (less precise than `FPNormal`)
327 /// A regular floating point number
331 /// Operations on primitive floating point numbers.
332 // FIXME(#5527): In a future version of Rust, many of these functions will
335 // FIXME(#8888): Several of these functions have a parameter named
336 // `unused_self`. Removing it requires #8888 to be fixed.
337 pub trait Float: Signed + Primitive {
338 /// Returns the NaN value.
340 /// Returns the infinite value.
341 fn infinity() -> Self;
342 /// Returns the negative infinite value.
343 fn neg_infinity() -> Self;
345 fn neg_zero() -> Self;
347 /// Returns true if this value is NaN and false otherwise.
348 fn is_nan(self) -> bool;
349 /// Returns true if this value is positive infinity or negative infinity and
351 fn is_infinite(self) -> bool;
352 /// Returns true if this number is neither infinite nor NaN.
353 fn is_finite(self) -> bool;
354 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
355 fn is_normal(self) -> bool;
356 /// Returns the category that this number falls into.
357 fn classify(self) -> FPCategory;
359 /// Returns the number of binary digits of mantissa that this type supports.
360 fn mantissa_digits(unused_self: Option<Self>) -> uint;
361 /// Returns the number of base-10 digits of precision that this type supports.
362 fn digits(unused_self: Option<Self>) -> uint;
363 /// Returns the difference between 1.0 and the smallest representable number larger than 1.0.
364 fn epsilon() -> Self;
365 /// Returns the minimum binary exponent that this type can represent.
366 fn min_exp(unused_self: Option<Self>) -> int;
367 /// Returns the maximum binary exponent that this type can represent.
368 fn max_exp(unused_self: Option<Self>) -> int;
369 /// Returns the minimum base-10 exponent that this type can represent.
370 fn min_10_exp(unused_self: Option<Self>) -> int;
371 /// Returns the maximum base-10 exponent that this type can represent.
372 fn max_10_exp(unused_self: Option<Self>) -> int;
374 /// Constructs a floating point number created by multiplying `x` by 2
375 /// raised to the power of `exp`.
376 fn ldexp(x: Self, exp: int) -> Self;
377 /// Breaks the number into a normalized fraction and a base-2 exponent,
380 /// * `self = x * pow(2, exp)`
382 /// * `0.5 <= abs(x) < 1.0`
383 fn frexp(self) -> (Self, int);
384 /// Returns the mantissa, exponent and sign as integers, respectively.
385 fn integer_decode(self) -> (u64, i16, i8);
387 /// Returns the next representable floating-point value in the direction of
389 fn next_after(self, other: Self) -> Self;
391 /// Return the largest integer less than or equal to a number.
392 fn floor(self) -> Self;
393 /// Return the smallest integer greater than or equal to a number.
394 fn ceil(self) -> Self;
395 /// Return the nearest integer to a number. Round half-way cases away from
397 fn round(self) -> Self;
398 /// Return the integer part of a number.
399 fn trunc(self) -> Self;
400 /// Return the fractional part of a number.
401 fn fract(self) -> Self;
403 /// Returns the maximum of the two numbers.
404 fn max(self, other: Self) -> Self;
405 /// Returns the minimum of the two numbers.
406 fn min(self, other: Self) -> Self;
408 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
409 /// error. This produces a more accurate result with better performance than
410 /// a separate multiplication operation followed by an add.
411 fn mul_add(self, a: Self, b: Self) -> Self;
412 /// Take the reciprocal (inverse) of a number, `1/x`.
413 fn recip(self) -> Self;
415 /// Raise a number to an integer power.
417 /// Using this function is generally faster than using `powf`
418 fn powi(self, n: i32) -> Self;
419 /// Raise a number to a floating point power.
420 fn powf(self, n: Self) -> Self;
425 fn frac_1_sqrt2() -> Self;
427 /// Take the square root of a number.
428 fn sqrt(self) -> Self;
429 /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
430 fn rsqrt(self) -> Self;
431 /// Take the cubic root of a number.
432 fn cbrt(self) -> Self;
433 /// Calculate the length of the hypotenuse of a right-angle triangle given
434 /// legs of length `x` and `y`.
435 fn hypot(self, other: Self) -> Self;
437 /// Archimedes' constant.
442 fn frac_pi_2() -> Self;
444 fn frac_pi_3() -> Self;
446 fn frac_pi_4() -> Self;
448 fn frac_pi_6() -> Self;
450 fn frac_pi_8() -> Self;
452 fn frac_1_pi() -> Self;
454 fn frac_2_pi() -> Self;
456 fn frac_2_sqrtpi() -> Self;
458 /// Computes the sine of a number (in radians).
459 fn sin(self) -> Self;
460 /// Computes the cosine of a number (in radians).
461 fn cos(self) -> Self;
462 /// Computes the tangent of a number (in radians).
463 fn tan(self) -> Self;
465 /// Computes the arcsine of a number. Return value is in radians in
466 /// the range [-pi/2, pi/2] or NaN if the number is outside the range
468 fn asin(self) -> Self;
469 /// Computes the arccosine of a number. Return value is in radians in
470 /// the range [0, pi] or NaN if the number is outside the range
472 fn acos(self) -> Self;
473 /// Computes the arctangent of a number. Return value is in radians in the
474 /// range [-pi/2, pi/2];
475 fn atan(self) -> Self;
476 /// Computes the four quadrant arctangent of a number, `y`, and another
477 /// number `x`. Return value is in radians in the range [-pi, pi].
478 fn atan2(self, other: Self) -> Self;
479 /// Simultaneously computes the sine and cosine of the number, `x`. Returns
480 /// `(sin(x), cos(x))`.
481 fn sin_cos(self) -> (Self, Self);
488 fn log10_e() -> Self;
494 /// Returns `e^(self)`, (the exponential function).
495 fn exp(self) -> Self;
496 /// Returns 2 raised to the power of the number, `2^(self)`.
497 fn exp2(self) -> Self;
498 /// Returns the exponential of the number, minus 1, in a way that is
499 /// accurate even if the number is close to zero.
500 fn exp_m1(self) -> Self;
501 /// Returns the natural logarithm of the number.
503 /// Returns the logarithm of the number with respect to an arbitrary base.
504 fn log(self, base: Self) -> Self;
505 /// Returns the base 2 logarithm of the number.
506 fn log2(self) -> Self;
507 /// Returns the base 10 logarithm of the number.
508 fn log10(self) -> Self;
509 /// Returns the natural logarithm of the number plus 1 (`ln(1+n)`) more
510 /// accurately than if the operations were performed separately.
511 fn ln_1p(self) -> Self;
513 /// Hyperbolic sine function.
514 fn sinh(self) -> Self;
515 /// Hyperbolic cosine function.
516 fn cosh(self) -> Self;
517 /// Hyperbolic tangent function.
518 fn tanh(self) -> Self;
519 /// Inverse hyperbolic sine function.
520 fn asinh(self) -> Self;
521 /// Inverse hyperbolic cosine function.
522 fn acosh(self) -> Self;
523 /// Inverse hyperbolic tangent function.
524 fn atanh(self) -> Self;
526 /// Convert radians to degrees.
527 fn to_degrees(self) -> Self;
528 /// Convert degrees to radians.
529 fn to_radians(self) -> Self;
532 /// A generic trait for converting a value to a number.
533 pub trait ToPrimitive {
534 /// Converts the value of `self` to an `int`.
536 fn to_int(&self) -> Option<int> {
537 self.to_i64().and_then(|x| x.to_int())
540 /// Converts the value of `self` to an `i8`.
542 fn to_i8(&self) -> Option<i8> {
543 self.to_i64().and_then(|x| x.to_i8())
546 /// Converts the value of `self` to an `i16`.
548 fn to_i16(&self) -> Option<i16> {
549 self.to_i64().and_then(|x| x.to_i16())
552 /// Converts the value of `self` to an `i32`.
554 fn to_i32(&self) -> Option<i32> {
555 self.to_i64().and_then(|x| x.to_i32())
558 /// Converts the value of `self` to an `i64`.
559 fn to_i64(&self) -> Option<i64>;
561 /// Converts the value of `self` to an `uint`.
563 fn to_uint(&self) -> Option<uint> {
564 self.to_u64().and_then(|x| x.to_uint())
567 /// Converts the value of `self` to an `u8`.
569 fn to_u8(&self) -> Option<u8> {
570 self.to_u64().and_then(|x| x.to_u8())
573 /// Converts the value of `self` to an `u16`.
575 fn to_u16(&self) -> Option<u16> {
576 self.to_u64().and_then(|x| x.to_u16())
579 /// Converts the value of `self` to an `u32`.
581 fn to_u32(&self) -> Option<u32> {
582 self.to_u64().and_then(|x| x.to_u32())
585 /// Converts the value of `self` to an `u64`.
587 fn to_u64(&self) -> Option<u64>;
589 /// Converts the value of `self` to an `f32`.
591 fn to_f32(&self) -> Option<f32> {
592 self.to_f64().and_then(|x| x.to_f32())
595 /// Converts the value of `self` to an `f64`.
597 fn to_f64(&self) -> Option<f64> {
598 self.to_i64().and_then(|x| x.to_f64())
602 macro_rules! impl_to_primitive_int_to_int(
603 ($SrcT:ty, $DstT:ty) => (
605 if size_of::<$SrcT>() <= size_of::<$DstT>() {
608 let n = *self as i64;
609 let min_value: $DstT = Bounded::min_value();
610 let max_value: $DstT = Bounded::max_value();
611 if min_value as i64 <= n && n <= max_value as i64 {
621 macro_rules! impl_to_primitive_int_to_uint(
622 ($SrcT:ty, $DstT:ty) => (
624 let zero: $SrcT = Zero::zero();
625 let max_value: $DstT = Bounded::max_value();
626 if zero <= *self && *self as u64 <= max_value as u64 {
635 macro_rules! impl_to_primitive_int(
637 impl ToPrimitive for $T {
639 fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int) }
641 fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8) }
643 fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16) }
645 fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32) }
647 fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64) }
650 fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint) }
652 fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8) }
654 fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16) }
656 fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32) }
658 fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64) }
661 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
663 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
668 impl_to_primitive_int!(int)
669 impl_to_primitive_int!(i8)
670 impl_to_primitive_int!(i16)
671 impl_to_primitive_int!(i32)
672 impl_to_primitive_int!(i64)
674 macro_rules! impl_to_primitive_uint_to_int(
677 let max_value: $DstT = Bounded::max_value();
678 if *self as u64 <= max_value as u64 {
687 macro_rules! impl_to_primitive_uint_to_uint(
688 ($SrcT:ty, $DstT:ty) => (
690 if size_of::<$SrcT>() <= size_of::<$DstT>() {
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 {
705 macro_rules! impl_to_primitive_uint(
707 impl ToPrimitive for $T {
709 fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int) }
711 fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8) }
713 fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16) }
715 fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32) }
717 fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64) }
720 fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint) }
722 fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8) }
724 fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16) }
726 fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32) }
728 fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64) }
731 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
733 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
738 impl_to_primitive_uint!(uint)
739 impl_to_primitive_uint!(u8)
740 impl_to_primitive_uint!(u16)
741 impl_to_primitive_uint!(u32)
742 impl_to_primitive_uint!(u64)
744 macro_rules! impl_to_primitive_float_to_float(
745 ($SrcT:ty, $DstT:ty) => (
746 if size_of::<$SrcT>() <= size_of::<$DstT>() {
749 let n = *self as f64;
750 let max_value: $SrcT = Bounded::max_value();
751 if -max_value as f64 <= n && n <= max_value as f64 {
760 macro_rules! impl_to_primitive_float(
762 impl ToPrimitive for $T {
764 fn to_int(&self) -> Option<int> { Some(*self as int) }
766 fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
768 fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
770 fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
772 fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
775 fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
777 fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
779 fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
781 fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
783 fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
786 fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32) }
788 fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64) }
793 impl_to_primitive_float!(f32)
794 impl_to_primitive_float!(f64)
796 /// A generic trait for converting a number to a value.
797 pub trait FromPrimitive {
798 /// Convert an `int` to return an optional value of this type. If the
799 /// value cannot be represented by this value, the `None` is returned.
801 fn from_int(n: int) -> Option<Self> {
802 FromPrimitive::from_i64(n as i64)
805 /// Convert an `i8` to return an optional value of this type. If the
806 /// type cannot be represented by this value, the `None` is returned.
808 fn from_i8(n: i8) -> Option<Self> {
809 FromPrimitive::from_i64(n as i64)
812 /// Convert an `i16` to return an optional value of this type. If the
813 /// type cannot be represented by this value, the `None` is returned.
815 fn from_i16(n: i16) -> Option<Self> {
816 FromPrimitive::from_i64(n as i64)
819 /// Convert an `i32` to return an optional value of this type. If the
820 /// type cannot be represented by this value, the `None` is returned.
822 fn from_i32(n: i32) -> Option<Self> {
823 FromPrimitive::from_i64(n as i64)
826 /// Convert an `i64` to return an optional value of this type. If the
827 /// type cannot be represented by this value, the `None` is returned.
828 fn from_i64(n: i64) -> Option<Self>;
830 /// Convert an `uint` to return an optional value of this type. If the
831 /// type cannot be represented by this value, the `None` is returned.
833 fn from_uint(n: uint) -> Option<Self> {
834 FromPrimitive::from_u64(n as u64)
837 /// Convert an `u8` to return an optional value of this type. If the
838 /// type cannot be represented by this value, the `None` is returned.
840 fn from_u8(n: u8) -> Option<Self> {
841 FromPrimitive::from_u64(n as u64)
844 /// Convert an `u16` to return an optional value of this type. If the
845 /// type cannot be represented by this value, the `None` is returned.
847 fn from_u16(n: u16) -> Option<Self> {
848 FromPrimitive::from_u64(n as u64)
851 /// Convert an `u32` to return an optional value of this type. If the
852 /// type cannot be represented by this value, the `None` is returned.
854 fn from_u32(n: u32) -> Option<Self> {
855 FromPrimitive::from_u64(n as u64)
858 /// Convert an `u64` to return an optional value of this type. If the
859 /// type cannot be represented by this value, the `None` is returned.
860 fn from_u64(n: u64) -> Option<Self>;
862 /// Convert a `f32` to return an optional value of this type. If the
863 /// type cannot be represented by this value, the `None` is returned.
865 fn from_f32(n: f32) -> Option<Self> {
866 FromPrimitive::from_f64(n as f64)
869 /// Convert a `f64` to return an optional value of this type. If the
870 /// type cannot be represented by this value, the `None` is returned.
872 fn from_f64(n: f64) -> Option<Self> {
873 FromPrimitive::from_i64(n as i64)
877 /// A utility function that just calls `FromPrimitive::from_int`.
878 pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
879 FromPrimitive::from_int(n)
882 /// A utility function that just calls `FromPrimitive::from_i8`.
883 pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> {
884 FromPrimitive::from_i8(n)
887 /// A utility function that just calls `FromPrimitive::from_i16`.
888 pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> {
889 FromPrimitive::from_i16(n)
892 /// A utility function that just calls `FromPrimitive::from_i32`.
893 pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> {
894 FromPrimitive::from_i32(n)
897 /// A utility function that just calls `FromPrimitive::from_i64`.
898 pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
899 FromPrimitive::from_i64(n)
902 /// A utility function that just calls `FromPrimitive::from_uint`.
903 pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
904 FromPrimitive::from_uint(n)
907 /// A utility function that just calls `FromPrimitive::from_u8`.
908 pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> {
909 FromPrimitive::from_u8(n)
912 /// A utility function that just calls `FromPrimitive::from_u16`.
913 pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> {
914 FromPrimitive::from_u16(n)
917 /// A utility function that just calls `FromPrimitive::from_u32`.
918 pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> {
919 FromPrimitive::from_u32(n)
922 /// A utility function that just calls `FromPrimitive::from_u64`.
923 pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> {
924 FromPrimitive::from_u64(n)
927 /// A utility function that just calls `FromPrimitive::from_f32`.
928 pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> {
929 FromPrimitive::from_f32(n)
932 /// A utility function that just calls `FromPrimitive::from_f64`.
933 pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {
934 FromPrimitive::from_f64(n)
937 macro_rules! impl_from_primitive(
938 ($T:ty, $to_ty:expr) => (
939 impl FromPrimitive for $T {
940 #[inline] fn from_int(n: int) -> Option<$T> { $to_ty }
941 #[inline] fn from_i8(n: i8) -> Option<$T> { $to_ty }
942 #[inline] fn from_i16(n: i16) -> Option<$T> { $to_ty }
943 #[inline] fn from_i32(n: i32) -> Option<$T> { $to_ty }
944 #[inline] fn from_i64(n: i64) -> Option<$T> { $to_ty }
946 #[inline] fn from_uint(n: uint) -> Option<$T> { $to_ty }
947 #[inline] fn from_u8(n: u8) -> Option<$T> { $to_ty }
948 #[inline] fn from_u16(n: u16) -> Option<$T> { $to_ty }
949 #[inline] fn from_u32(n: u32) -> Option<$T> { $to_ty }
950 #[inline] fn from_u64(n: u64) -> Option<$T> { $to_ty }
952 #[inline] fn from_f32(n: f32) -> Option<$T> { $to_ty }
953 #[inline] fn from_f64(n: f64) -> Option<$T> { $to_ty }
958 impl_from_primitive!(int, n.to_int())
959 impl_from_primitive!(i8, n.to_i8())
960 impl_from_primitive!(i16, n.to_i16())
961 impl_from_primitive!(i32, n.to_i32())
962 impl_from_primitive!(i64, n.to_i64())
963 impl_from_primitive!(uint, n.to_uint())
964 impl_from_primitive!(u8, n.to_u8())
965 impl_from_primitive!(u16, n.to_u16())
966 impl_from_primitive!(u32, n.to_u32())
967 impl_from_primitive!(u64, n.to_u64())
968 impl_from_primitive!(f32, n.to_f32())
969 impl_from_primitive!(f64, n.to_f64())
971 /// Cast from one machine scalar to another.
978 /// let twenty: f32 = num::cast(0x14).unwrap();
979 /// assert_eq!(twenty, 20f32);
983 pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
987 /// An interface for casting between machine scalars.
988 pub trait NumCast: ToPrimitive {
989 /// Creates a number from another value that can be converted into a primitive via the
990 /// `ToPrimitive` trait.
991 fn from<T: ToPrimitive>(n: T) -> Option<Self>;
994 macro_rules! impl_num_cast(
995 ($T:ty, $conv:ident) => (
996 impl NumCast for $T {
998 fn from<N: ToPrimitive>(n: N) -> Option<$T> {
999 // `$conv` could be generated using `concat_idents!`, but that
1000 // macro seems to be broken at the moment
1007 impl_num_cast!(u8, to_u8)
1008 impl_num_cast!(u16, to_u16)
1009 impl_num_cast!(u32, to_u32)
1010 impl_num_cast!(u64, to_u64)
1011 impl_num_cast!(uint, to_uint)
1012 impl_num_cast!(i8, to_i8)
1013 impl_num_cast!(i16, to_i16)
1014 impl_num_cast!(i32, to_i32)
1015 impl_num_cast!(i64, to_i64)
1016 impl_num_cast!(int, to_int)
1017 impl_num_cast!(f32, to_f32)
1018 impl_num_cast!(f64, to_f64)
1020 /// A generic trait for converting a value to a string with a radix (base)
1021 pub trait ToStrRadix {
1022 fn to_str_radix(&self, radix: uint) -> ~str;
1025 /// A generic trait for converting a string with a radix (base) to a value
1026 pub trait FromStrRadix {
1027 fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
1030 /// A utility function that just calls FromStrRadix::from_str_radix.
1031 pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint) -> Option<T> {
1032 FromStrRadix::from_str_radix(str, radix)
1035 /// Saturating math operations
1036 pub trait Saturating {
1037 /// Saturating addition operator.
1038 /// Returns a+b, saturating at the numeric bounds instead of overflowing.
1039 fn saturating_add(self, v: Self) -> Self;
1041 /// Saturating subtraction operator.
1042 /// Returns a-b, saturating at the numeric bounds instead of overflowing.
1043 fn saturating_sub(self, v: Self) -> Self;
1046 impl<T: CheckedAdd + CheckedSub + Zero + Ord + Bounded> Saturating for T {
1048 fn saturating_add(self, v: T) -> T {
1049 match self.checked_add(&v) {
1051 None => if v >= Zero::zero() {
1052 Bounded::max_value()
1054 Bounded::min_value()
1060 fn saturating_sub(self, v: T) -> T {
1061 match self.checked_sub(&v) {
1063 None => if v >= Zero::zero() {
1064 Bounded::min_value()
1066 Bounded::max_value()
1072 /// Performs addition that returns `None` instead of wrapping around on overflow.
1073 pub trait CheckedAdd: Add<Self, Self> {
1074 /// Adds two numbers, checking for overflow. If overflow happens, `None` is returned.
1075 fn checked_add(&self, v: &Self) -> Option<Self>;
1078 /// Performs subtraction that returns `None` instead of wrapping around on underflow.
1079 pub trait CheckedSub: Sub<Self, Self> {
1080 /// Subtracts two numbers, checking for underflow. If underflow happens, `None` is returned.
1081 fn checked_sub(&self, v: &Self) -> Option<Self>;
1084 /// Performs multiplication that returns `None` instead of wrapping around on underflow or
1086 pub trait CheckedMul: Mul<Self, Self> {
1087 /// Multiplies two numbers, checking for underflow or overflow. If underflow or overflow
1088 /// happens, `None` is returned.
1089 fn checked_mul(&self, v: &Self) -> Option<Self>;
1092 /// Performs division that returns `None` instead of wrapping around on underflow or overflow.
1093 pub trait CheckedDiv: Div<Self, Self> {
1094 /// Divides two numbers, checking for underflow or overflow. If underflow or overflow happens,
1095 /// `None` is returned.
1096 fn checked_div(&self, v: &Self) -> Option<Self>;
1099 /// Helper function for testing numeric operations
1101 pub fn test_num<T:Num + NumCast + Show>(ten: T, two: T) {
1102 assert_eq!(ten.add(&two), cast(12).unwrap());
1103 assert_eq!(ten.sub(&two), cast(8).unwrap());
1104 assert_eq!(ten.mul(&two), cast(20).unwrap());
1105 assert_eq!(ten.div(&two), cast(5).unwrap());
1106 assert_eq!(ten.rem(&two), cast(0).unwrap());
1108 assert_eq!(ten.add(&two), ten + two);
1109 assert_eq!(ten.sub(&two), ten - two);
1110 assert_eq!(ten.mul(&two), ten * two);
1111 assert_eq!(ten.div(&two), ten / two);
1112 assert_eq!(ten.rem(&two), ten % two);
1130 macro_rules! test_cast_20(
1134 assert_eq!(20u, _20.to_uint().unwrap());
1135 assert_eq!(20u8, _20.to_u8().unwrap());
1136 assert_eq!(20u16, _20.to_u16().unwrap());
1137 assert_eq!(20u32, _20.to_u32().unwrap());
1138 assert_eq!(20u64, _20.to_u64().unwrap());
1139 assert_eq!(20i, _20.to_int().unwrap());
1140 assert_eq!(20i8, _20.to_i8().unwrap());
1141 assert_eq!(20i16, _20.to_i16().unwrap());
1142 assert_eq!(20i32, _20.to_i32().unwrap());
1143 assert_eq!(20i64, _20.to_i64().unwrap());
1144 assert_eq!(20f32, _20.to_f32().unwrap());
1145 assert_eq!(20f64, _20.to_f64().unwrap());
1147 assert_eq!(_20, NumCast::from(20u).unwrap());
1148 assert_eq!(_20, NumCast::from(20u8).unwrap());
1149 assert_eq!(_20, NumCast::from(20u16).unwrap());
1150 assert_eq!(_20, NumCast::from(20u32).unwrap());
1151 assert_eq!(_20, NumCast::from(20u64).unwrap());
1152 assert_eq!(_20, NumCast::from(20i).unwrap());
1153 assert_eq!(_20, NumCast::from(20i8).unwrap());
1154 assert_eq!(_20, NumCast::from(20i16).unwrap());
1155 assert_eq!(_20, NumCast::from(20i32).unwrap());
1156 assert_eq!(_20, NumCast::from(20i64).unwrap());
1157 assert_eq!(_20, NumCast::from(20f32).unwrap());
1158 assert_eq!(_20, NumCast::from(20f64).unwrap());
1160 assert_eq!(_20, cast(20u).unwrap());
1161 assert_eq!(_20, cast(20u8).unwrap());
1162 assert_eq!(_20, cast(20u16).unwrap());
1163 assert_eq!(_20, cast(20u32).unwrap());
1164 assert_eq!(_20, cast(20u64).unwrap());
1165 assert_eq!(_20, cast(20i).unwrap());
1166 assert_eq!(_20, cast(20i8).unwrap());
1167 assert_eq!(_20, cast(20i16).unwrap());
1168 assert_eq!(_20, cast(20i32).unwrap());
1169 assert_eq!(_20, cast(20i64).unwrap());
1170 assert_eq!(_20, cast(20f32).unwrap());
1171 assert_eq!(_20, cast(20f64).unwrap());
1175 #[test] fn test_u8_cast() { test_cast_20!(20u8) }
1176 #[test] fn test_u16_cast() { test_cast_20!(20u16) }
1177 #[test] fn test_u32_cast() { test_cast_20!(20u32) }
1178 #[test] fn test_u64_cast() { test_cast_20!(20u64) }
1179 #[test] fn test_uint_cast() { test_cast_20!(20u) }
1180 #[test] fn test_i8_cast() { test_cast_20!(20i8) }
1181 #[test] fn test_i16_cast() { test_cast_20!(20i16) }
1182 #[test] fn test_i32_cast() { test_cast_20!(20i32) }
1183 #[test] fn test_i64_cast() { test_cast_20!(20i64) }
1184 #[test] fn test_int_cast() { test_cast_20!(20i) }
1185 #[test] fn test_f32_cast() { test_cast_20!(20f32) }
1186 #[test] fn test_f64_cast() { test_cast_20!(20f64) }
1189 fn test_cast_range_int_min() {
1190 assert_eq!(int::MIN.to_int(), Some(int::MIN as int));
1191 assert_eq!(int::MIN.to_i8(), None);
1192 assert_eq!(int::MIN.to_i16(), None);
1193 // int::MIN.to_i32() is word-size specific
1194 assert_eq!(int::MIN.to_i64(), Some(int::MIN as i64));
1195 assert_eq!(int::MIN.to_uint(), None);
1196 assert_eq!(int::MIN.to_u8(), None);
1197 assert_eq!(int::MIN.to_u16(), None);
1198 assert_eq!(int::MIN.to_u32(), None);
1199 assert_eq!(int::MIN.to_u64(), None);
1201 #[cfg(target_word_size = "32")]
1202 fn check_word_size() {
1203 assert_eq!(int::MIN.to_i32(), Some(int::MIN as i32));
1206 #[cfg(target_word_size = "64")]
1207 fn check_word_size() {
1208 assert_eq!(int::MIN.to_i32(), None);
1215 fn test_cast_range_i8_min() {
1216 assert_eq!(i8::MIN.to_int(), Some(i8::MIN as int));
1217 assert_eq!(i8::MIN.to_i8(), Some(i8::MIN as i8));
1218 assert_eq!(i8::MIN.to_i16(), Some(i8::MIN as i16));
1219 assert_eq!(i8::MIN.to_i32(), Some(i8::MIN as i32));
1220 assert_eq!(i8::MIN.to_i64(), Some(i8::MIN as i64));
1221 assert_eq!(i8::MIN.to_uint(), None);
1222 assert_eq!(i8::MIN.to_u8(), None);
1223 assert_eq!(i8::MIN.to_u16(), None);
1224 assert_eq!(i8::MIN.to_u32(), None);
1225 assert_eq!(i8::MIN.to_u64(), None);
1229 fn test_cast_range_i16_min() {
1230 assert_eq!(i16::MIN.to_int(), Some(i16::MIN as int));
1231 assert_eq!(i16::MIN.to_i8(), None);
1232 assert_eq!(i16::MIN.to_i16(), Some(i16::MIN as i16));
1233 assert_eq!(i16::MIN.to_i32(), Some(i16::MIN as i32));
1234 assert_eq!(i16::MIN.to_i64(), Some(i16::MIN as i64));
1235 assert_eq!(i16::MIN.to_uint(), None);
1236 assert_eq!(i16::MIN.to_u8(), None);
1237 assert_eq!(i16::MIN.to_u16(), None);
1238 assert_eq!(i16::MIN.to_u32(), None);
1239 assert_eq!(i16::MIN.to_u64(), None);
1243 fn test_cast_range_i32_min() {
1244 assert_eq!(i32::MIN.to_int(), Some(i32::MIN as int));
1245 assert_eq!(i32::MIN.to_i8(), None);
1246 assert_eq!(i32::MIN.to_i16(), None);
1247 assert_eq!(i32::MIN.to_i32(), Some(i32::MIN as i32));
1248 assert_eq!(i32::MIN.to_i64(), Some(i32::MIN as i64));
1249 assert_eq!(i32::MIN.to_uint(), None);
1250 assert_eq!(i32::MIN.to_u8(), None);
1251 assert_eq!(i32::MIN.to_u16(), None);
1252 assert_eq!(i32::MIN.to_u32(), None);
1253 assert_eq!(i32::MIN.to_u64(), None);
1257 fn test_cast_range_i64_min() {
1258 // i64::MIN.to_int() is word-size specific
1259 assert_eq!(i64::MIN.to_i8(), None);
1260 assert_eq!(i64::MIN.to_i16(), None);
1261 assert_eq!(i64::MIN.to_i32(), None);
1262 assert_eq!(i64::MIN.to_i64(), Some(i64::MIN as i64));
1263 assert_eq!(i64::MIN.to_uint(), None);
1264 assert_eq!(i64::MIN.to_u8(), None);
1265 assert_eq!(i64::MIN.to_u16(), None);
1266 assert_eq!(i64::MIN.to_u32(), None);
1267 assert_eq!(i64::MIN.to_u64(), None);
1269 #[cfg(target_word_size = "32")]
1270 fn check_word_size() {
1271 assert_eq!(i64::MIN.to_int(), None);
1274 #[cfg(target_word_size = "64")]
1275 fn check_word_size() {
1276 assert_eq!(i64::MIN.to_int(), Some(i64::MIN as int));
1283 fn test_cast_range_int_max() {
1284 assert_eq!(int::MAX.to_int(), Some(int::MAX as int));
1285 assert_eq!(int::MAX.to_i8(), None);
1286 assert_eq!(int::MAX.to_i16(), None);
1287 // int::MAX.to_i32() is word-size specific
1288 assert_eq!(int::MAX.to_i64(), Some(int::MAX as i64));
1289 assert_eq!(int::MAX.to_u8(), None);
1290 assert_eq!(int::MAX.to_u16(), None);
1291 // int::MAX.to_u32() is word-size specific
1292 assert_eq!(int::MAX.to_u64(), Some(int::MAX as u64));
1294 #[cfg(target_word_size = "32")]
1295 fn check_word_size() {
1296 assert_eq!(int::MAX.to_i32(), Some(int::MAX as i32));
1297 assert_eq!(int::MAX.to_u32(), Some(int::MAX as u32));
1300 #[cfg(target_word_size = "64")]
1301 fn check_word_size() {
1302 assert_eq!(int::MAX.to_i32(), None);
1303 assert_eq!(int::MAX.to_u32(), None);
1310 fn test_cast_range_i8_max() {
1311 assert_eq!(i8::MAX.to_int(), Some(i8::MAX as int));
1312 assert_eq!(i8::MAX.to_i8(), Some(i8::MAX as i8));
1313 assert_eq!(i8::MAX.to_i16(), Some(i8::MAX as i16));
1314 assert_eq!(i8::MAX.to_i32(), Some(i8::MAX as i32));
1315 assert_eq!(i8::MAX.to_i64(), Some(i8::MAX as i64));
1316 assert_eq!(i8::MAX.to_uint(), Some(i8::MAX as uint));
1317 assert_eq!(i8::MAX.to_u8(), Some(i8::MAX as u8));
1318 assert_eq!(i8::MAX.to_u16(), Some(i8::MAX as u16));
1319 assert_eq!(i8::MAX.to_u32(), Some(i8::MAX as u32));
1320 assert_eq!(i8::MAX.to_u64(), Some(i8::MAX as u64));
1324 fn test_cast_range_i16_max() {
1325 assert_eq!(i16::MAX.to_int(), Some(i16::MAX as int));
1326 assert_eq!(i16::MAX.to_i8(), None);
1327 assert_eq!(i16::MAX.to_i16(), Some(i16::MAX as i16));
1328 assert_eq!(i16::MAX.to_i32(), Some(i16::MAX as i32));
1329 assert_eq!(i16::MAX.to_i64(), Some(i16::MAX as i64));
1330 assert_eq!(i16::MAX.to_uint(), Some(i16::MAX as uint));
1331 assert_eq!(i16::MAX.to_u8(), None);
1332 assert_eq!(i16::MAX.to_u16(), Some(i16::MAX as u16));
1333 assert_eq!(i16::MAX.to_u32(), Some(i16::MAX as u32));
1334 assert_eq!(i16::MAX.to_u64(), Some(i16::MAX as u64));
1338 fn test_cast_range_i32_max() {
1339 assert_eq!(i32::MAX.to_int(), Some(i32::MAX as int));
1340 assert_eq!(i32::MAX.to_i8(), None);
1341 assert_eq!(i32::MAX.to_i16(), None);
1342 assert_eq!(i32::MAX.to_i32(), Some(i32::MAX as i32));
1343 assert_eq!(i32::MAX.to_i64(), Some(i32::MAX as i64));
1344 assert_eq!(i32::MAX.to_uint(), Some(i32::MAX as uint));
1345 assert_eq!(i32::MAX.to_u8(), None);
1346 assert_eq!(i32::MAX.to_u16(), None);
1347 assert_eq!(i32::MAX.to_u32(), Some(i32::MAX as u32));
1348 assert_eq!(i32::MAX.to_u64(), Some(i32::MAX as u64));
1352 fn test_cast_range_i64_max() {
1353 // i64::MAX.to_int() is word-size specific
1354 assert_eq!(i64::MAX.to_i8(), None);
1355 assert_eq!(i64::MAX.to_i16(), None);
1356 assert_eq!(i64::MAX.to_i32(), None);
1357 assert_eq!(i64::MAX.to_i64(), Some(i64::MAX as i64));
1358 // i64::MAX.to_uint() is word-size specific
1359 assert_eq!(i64::MAX.to_u8(), None);
1360 assert_eq!(i64::MAX.to_u16(), None);
1361 assert_eq!(i64::MAX.to_u32(), None);
1362 assert_eq!(i64::MAX.to_u64(), Some(i64::MAX as u64));
1364 #[cfg(target_word_size = "32")]
1365 fn check_word_size() {
1366 assert_eq!(i64::MAX.to_int(), None);
1367 assert_eq!(i64::MAX.to_uint(), None);
1370 #[cfg(target_word_size = "64")]
1371 fn check_word_size() {
1372 assert_eq!(i64::MAX.to_int(), Some(i64::MAX as int));
1373 assert_eq!(i64::MAX.to_uint(), Some(i64::MAX as uint));
1380 fn test_cast_range_uint_min() {
1381 assert_eq!(uint::MIN.to_int(), Some(uint::MIN as int));
1382 assert_eq!(uint::MIN.to_i8(), Some(uint::MIN as i8));
1383 assert_eq!(uint::MIN.to_i16(), Some(uint::MIN as i16));
1384 assert_eq!(uint::MIN.to_i32(), Some(uint::MIN as i32));
1385 assert_eq!(uint::MIN.to_i64(), Some(uint::MIN as i64));
1386 assert_eq!(uint::MIN.to_uint(), Some(uint::MIN as uint));
1387 assert_eq!(uint::MIN.to_u8(), Some(uint::MIN as u8));
1388 assert_eq!(uint::MIN.to_u16(), Some(uint::MIN as u16));
1389 assert_eq!(uint::MIN.to_u32(), Some(uint::MIN as u32));
1390 assert_eq!(uint::MIN.to_u64(), Some(uint::MIN as u64));
1394 fn test_cast_range_u8_min() {
1395 assert_eq!(u8::MIN.to_int(), Some(u8::MIN as int));
1396 assert_eq!(u8::MIN.to_i8(), Some(u8::MIN as i8));
1397 assert_eq!(u8::MIN.to_i16(), Some(u8::MIN as i16));
1398 assert_eq!(u8::MIN.to_i32(), Some(u8::MIN as i32));
1399 assert_eq!(u8::MIN.to_i64(), Some(u8::MIN as i64));
1400 assert_eq!(u8::MIN.to_uint(), Some(u8::MIN as uint));
1401 assert_eq!(u8::MIN.to_u8(), Some(u8::MIN as u8));
1402 assert_eq!(u8::MIN.to_u16(), Some(u8::MIN as u16));
1403 assert_eq!(u8::MIN.to_u32(), Some(u8::MIN as u32));
1404 assert_eq!(u8::MIN.to_u64(), Some(u8::MIN as u64));
1408 fn test_cast_range_u16_min() {
1409 assert_eq!(u16::MIN.to_int(), Some(u16::MIN as int));
1410 assert_eq!(u16::MIN.to_i8(), Some(u16::MIN as i8));
1411 assert_eq!(u16::MIN.to_i16(), Some(u16::MIN as i16));
1412 assert_eq!(u16::MIN.to_i32(), Some(u16::MIN as i32));
1413 assert_eq!(u16::MIN.to_i64(), Some(u16::MIN as i64));
1414 assert_eq!(u16::MIN.to_uint(), Some(u16::MIN as uint));
1415 assert_eq!(u16::MIN.to_u8(), Some(u16::MIN as u8));
1416 assert_eq!(u16::MIN.to_u16(), Some(u16::MIN as u16));
1417 assert_eq!(u16::MIN.to_u32(), Some(u16::MIN as u32));
1418 assert_eq!(u16::MIN.to_u64(), Some(u16::MIN as u64));
1422 fn test_cast_range_u32_min() {
1423 assert_eq!(u32::MIN.to_int(), Some(u32::MIN as int));
1424 assert_eq!(u32::MIN.to_i8(), Some(u32::MIN as i8));
1425 assert_eq!(u32::MIN.to_i16(), Some(u32::MIN as i16));
1426 assert_eq!(u32::MIN.to_i32(), Some(u32::MIN as i32));
1427 assert_eq!(u32::MIN.to_i64(), Some(u32::MIN as i64));
1428 assert_eq!(u32::MIN.to_uint(), Some(u32::MIN as uint));
1429 assert_eq!(u32::MIN.to_u8(), Some(u32::MIN as u8));
1430 assert_eq!(u32::MIN.to_u16(), Some(u32::MIN as u16));
1431 assert_eq!(u32::MIN.to_u32(), Some(u32::MIN as u32));
1432 assert_eq!(u32::MIN.to_u64(), Some(u32::MIN as u64));
1436 fn test_cast_range_u64_min() {
1437 assert_eq!(u64::MIN.to_int(), Some(u64::MIN as int));
1438 assert_eq!(u64::MIN.to_i8(), Some(u64::MIN as i8));
1439 assert_eq!(u64::MIN.to_i16(), Some(u64::MIN as i16));
1440 assert_eq!(u64::MIN.to_i32(), Some(u64::MIN as i32));
1441 assert_eq!(u64::MIN.to_i64(), Some(u64::MIN as i64));
1442 assert_eq!(u64::MIN.to_uint(), Some(u64::MIN as uint));
1443 assert_eq!(u64::MIN.to_u8(), Some(u64::MIN as u8));
1444 assert_eq!(u64::MIN.to_u16(), Some(u64::MIN as u16));
1445 assert_eq!(u64::MIN.to_u32(), Some(u64::MIN as u32));
1446 assert_eq!(u64::MIN.to_u64(), Some(u64::MIN as u64));
1450 fn test_cast_range_uint_max() {
1451 assert_eq!(uint::MAX.to_int(), None);
1452 assert_eq!(uint::MAX.to_i8(), None);
1453 assert_eq!(uint::MAX.to_i16(), None);
1454 assert_eq!(uint::MAX.to_i32(), None);
1455 // uint::MAX.to_i64() is word-size specific
1456 assert_eq!(uint::MAX.to_u8(), None);
1457 assert_eq!(uint::MAX.to_u16(), None);
1458 // uint::MAX.to_u32() is word-size specific
1459 assert_eq!(uint::MAX.to_u64(), Some(uint::MAX as u64));
1461 #[cfg(target_word_size = "32")]
1462 fn check_word_size() {
1463 assert_eq!(uint::MAX.to_u32(), Some(uint::MAX as u32));
1464 assert_eq!(uint::MAX.to_i64(), Some(uint::MAX as i64));
1467 #[cfg(target_word_size = "64")]
1468 fn check_word_size() {
1469 assert_eq!(uint::MAX.to_u32(), None);
1470 assert_eq!(uint::MAX.to_i64(), None);
1477 fn test_cast_range_u8_max() {
1478 assert_eq!(u8::MAX.to_int(), Some(u8::MAX as int));
1479 assert_eq!(u8::MAX.to_i8(), None);
1480 assert_eq!(u8::MAX.to_i16(), Some(u8::MAX as i16));
1481 assert_eq!(u8::MAX.to_i32(), Some(u8::MAX as i32));
1482 assert_eq!(u8::MAX.to_i64(), Some(u8::MAX as i64));
1483 assert_eq!(u8::MAX.to_uint(), Some(u8::MAX as uint));
1484 assert_eq!(u8::MAX.to_u8(), Some(u8::MAX as u8));
1485 assert_eq!(u8::MAX.to_u16(), Some(u8::MAX as u16));
1486 assert_eq!(u8::MAX.to_u32(), Some(u8::MAX as u32));
1487 assert_eq!(u8::MAX.to_u64(), Some(u8::MAX as u64));
1491 fn test_cast_range_u16_max() {
1492 assert_eq!(u16::MAX.to_int(), Some(u16::MAX as int));
1493 assert_eq!(u16::MAX.to_i8(), None);
1494 assert_eq!(u16::MAX.to_i16(), None);
1495 assert_eq!(u16::MAX.to_i32(), Some(u16::MAX as i32));
1496 assert_eq!(u16::MAX.to_i64(), Some(u16::MAX as i64));
1497 assert_eq!(u16::MAX.to_uint(), Some(u16::MAX as uint));
1498 assert_eq!(u16::MAX.to_u8(), None);
1499 assert_eq!(u16::MAX.to_u16(), Some(u16::MAX as u16));
1500 assert_eq!(u16::MAX.to_u32(), Some(u16::MAX as u32));
1501 assert_eq!(u16::MAX.to_u64(), Some(u16::MAX as u64));
1505 fn test_cast_range_u32_max() {
1506 // u32::MAX.to_int() is word-size specific
1507 assert_eq!(u32::MAX.to_i8(), None);
1508 assert_eq!(u32::MAX.to_i16(), None);
1509 assert_eq!(u32::MAX.to_i32(), None);
1510 assert_eq!(u32::MAX.to_i64(), Some(u32::MAX as i64));
1511 assert_eq!(u32::MAX.to_uint(), Some(u32::MAX as uint));
1512 assert_eq!(u32::MAX.to_u8(), None);
1513 assert_eq!(u32::MAX.to_u16(), None);
1514 assert_eq!(u32::MAX.to_u32(), Some(u32::MAX as u32));
1515 assert_eq!(u32::MAX.to_u64(), Some(u32::MAX as u64));
1517 #[cfg(target_word_size = "32")]
1518 fn check_word_size() {
1519 assert_eq!(u32::MAX.to_int(), None);
1522 #[cfg(target_word_size = "64")]
1523 fn check_word_size() {
1524 assert_eq!(u32::MAX.to_int(), Some(u32::MAX as int));
1531 fn test_cast_range_u64_max() {
1532 assert_eq!(u64::MAX.to_int(), None);
1533 assert_eq!(u64::MAX.to_i8(), None);
1534 assert_eq!(u64::MAX.to_i16(), None);
1535 assert_eq!(u64::MAX.to_i32(), None);
1536 assert_eq!(u64::MAX.to_i64(), None);
1537 // u64::MAX.to_uint() is word-size specific
1538 assert_eq!(u64::MAX.to_u8(), None);
1539 assert_eq!(u64::MAX.to_u16(), None);
1540 assert_eq!(u64::MAX.to_u32(), None);
1541 assert_eq!(u64::MAX.to_u64(), Some(u64::MAX as u64));
1543 #[cfg(target_word_size = "32")]
1544 fn check_word_size() {
1545 assert_eq!(u64::MAX.to_uint(), None);
1548 #[cfg(target_word_size = "64")]
1549 fn check_word_size() {
1550 assert_eq!(u64::MAX.to_uint(), Some(u64::MAX as uint));
1557 fn test_saturating_add_uint() {
1559 assert_eq!(3u.saturating_add(5u), 8u);
1560 assert_eq!(3u.saturating_add(MAX-1), MAX);
1561 assert_eq!(MAX.saturating_add(MAX), MAX);
1562 assert_eq!((MAX-2).saturating_add(1), MAX-1);
1566 fn test_saturating_sub_uint() {
1568 assert_eq!(5u.saturating_sub(3u), 2u);
1569 assert_eq!(3u.saturating_sub(5u), 0u);
1570 assert_eq!(0u.saturating_sub(1u), 0u);
1571 assert_eq!((MAX-1).saturating_sub(MAX), 0);
1575 fn test_saturating_add_int() {
1577 assert_eq!(3i.saturating_add(5i), 8i);
1578 assert_eq!(3i.saturating_add(MAX-1), MAX);
1579 assert_eq!(MAX.saturating_add(MAX), MAX);
1580 assert_eq!((MAX-2).saturating_add(1), MAX-1);
1581 assert_eq!(3i.saturating_add(-5i), -2i);
1582 assert_eq!(MIN.saturating_add(-1i), MIN);
1583 assert_eq!((-2i).saturating_add(-MAX), MIN);
1587 fn test_saturating_sub_int() {
1589 assert_eq!(3i.saturating_sub(5i), -2i);
1590 assert_eq!(MIN.saturating_sub(1i), MIN);
1591 assert_eq!((-2i).saturating_sub(MAX), MIN);
1592 assert_eq!(3i.saturating_sub(-5i), 8i);
1593 assert_eq!(3i.saturating_sub(-(MAX-1)), MAX);
1594 assert_eq!(MAX.saturating_sub(-MAX), MAX);
1595 assert_eq!((MAX-2).saturating_sub(-1), MAX-1);
1599 fn test_checked_add() {
1600 let five_less = uint::MAX - 5;
1601 assert_eq!(five_less.checked_add(&0), Some(uint::MAX - 5));
1602 assert_eq!(five_less.checked_add(&1), Some(uint::MAX - 4));
1603 assert_eq!(five_less.checked_add(&2), Some(uint::MAX - 3));
1604 assert_eq!(five_less.checked_add(&3), Some(uint::MAX - 2));
1605 assert_eq!(five_less.checked_add(&4), Some(uint::MAX - 1));
1606 assert_eq!(five_less.checked_add(&5), Some(uint::MAX));
1607 assert_eq!(five_less.checked_add(&6), None);
1608 assert_eq!(five_less.checked_add(&7), None);
1612 fn test_checked_sub() {
1613 assert_eq!(5u.checked_sub(&0), Some(5));
1614 assert_eq!(5u.checked_sub(&1), Some(4));
1615 assert_eq!(5u.checked_sub(&2), Some(3));
1616 assert_eq!(5u.checked_sub(&3), Some(2));
1617 assert_eq!(5u.checked_sub(&4), Some(1));
1618 assert_eq!(5u.checked_sub(&5), Some(0));
1619 assert_eq!(5u.checked_sub(&6), None);
1620 assert_eq!(5u.checked_sub(&7), None);
1624 fn test_checked_mul() {
1625 let third = uint::MAX / 3;
1626 assert_eq!(third.checked_mul(&0), Some(0));
1627 assert_eq!(third.checked_mul(&1), Some(third));
1628 assert_eq!(third.checked_mul(&2), Some(third * 2));
1629 assert_eq!(third.checked_mul(&3), Some(third * 3));
1630 assert_eq!(third.checked_mul(&4), None);
1633 macro_rules! test_next_power_of_two(
1634 ($test_name:ident, $T:ident) => (
1637 assert_eq!(next_power_of_two::<$T>(0), 0);
1638 let mut next_power = 1;
1639 for i in range::<$T>(1, 40) {
1640 assert_eq!(next_power_of_two(i), next_power);
1641 if i == next_power { next_power *= 2 }
1647 test_next_power_of_two!(test_next_power_of_two_u8, u8)
1648 test_next_power_of_two!(test_next_power_of_two_u16, u16)
1649 test_next_power_of_two!(test_next_power_of_two_u32, u32)
1650 test_next_power_of_two!(test_next_power_of_two_u64, u64)
1651 test_next_power_of_two!(test_next_power_of_two_uint, uint)
1653 macro_rules! test_checked_next_power_of_two(
1654 ($test_name:ident, $T:ident) => (
1657 assert_eq!(checked_next_power_of_two::<$T>(0), None);
1658 let mut next_power = 1;
1659 for i in range::<$T>(1, 40) {
1660 assert_eq!(checked_next_power_of_two(i), Some(next_power));
1661 if i == next_power { next_power *= 2 }
1663 assert!(checked_next_power_of_two::<$T>($T::MAX / 2).is_some());
1664 assert_eq!(checked_next_power_of_two::<$T>($T::MAX - 1), None);
1665 assert_eq!(checked_next_power_of_two::<$T>($T::MAX), None);
1670 test_checked_next_power_of_two!(test_checked_next_power_of_two_u8, u8)
1671 test_checked_next_power_of_two!(test_checked_next_power_of_two_u16, u16)
1672 test_checked_next_power_of_two!(test_checked_next_power_of_two_u32, u32)
1673 test_checked_next_power_of_two!(test_checked_next_power_of_two_u64, u64)
1674 test_checked_next_power_of_two!(test_checked_next_power_of_two_uint, uint)
1676 #[deriving(Eq, Show)]
1677 struct Value { x: int }
1679 impl ToPrimitive for Value {
1680 fn to_i64(&self) -> Option<i64> { self.x.to_i64() }
1681 fn to_u64(&self) -> Option<u64> { self.x.to_u64() }
1684 impl FromPrimitive for Value {
1685 fn from_i64(n: i64) -> Option<Value> { Some(Value { x: n as int }) }
1686 fn from_u64(n: u64) -> Option<Value> { Some(Value { x: n as int }) }
1690 fn test_to_primitive() {
1691 let value = Value { x: 5 };
1692 assert_eq!(value.to_int(), Some(5));
1693 assert_eq!(value.to_i8(), Some(5));
1694 assert_eq!(value.to_i16(), Some(5));
1695 assert_eq!(value.to_i32(), Some(5));
1696 assert_eq!(value.to_i64(), Some(5));
1697 assert_eq!(value.to_uint(), Some(5));
1698 assert_eq!(value.to_u8(), Some(5));
1699 assert_eq!(value.to_u16(), Some(5));
1700 assert_eq!(value.to_u32(), Some(5));
1701 assert_eq!(value.to_u64(), Some(5));
1702 assert_eq!(value.to_f32(), Some(5f32));
1703 assert_eq!(value.to_f64(), Some(5f64));
1707 fn test_from_primitive() {
1708 assert_eq!(from_int(5), Some(Value { x: 5 }));
1709 assert_eq!(from_i8(5), Some(Value { x: 5 }));
1710 assert_eq!(from_i16(5), Some(Value { x: 5 }));
1711 assert_eq!(from_i32(5), Some(Value { x: 5 }));
1712 assert_eq!(from_i64(5), Some(Value { x: 5 }));
1713 assert_eq!(from_uint(5), Some(Value { x: 5 }));
1714 assert_eq!(from_u8(5), Some(Value { x: 5 }));
1715 assert_eq!(from_u16(5), Some(Value { x: 5 }));
1716 assert_eq!(from_u32(5), Some(Value { x: 5 }));
1717 assert_eq!(from_u64(5), Some(Value { x: 5 }));
1718 assert_eq!(from_f32(5f32), Some(Value { x: 5 }));
1719 assert_eq!(from_f64(5f64), Some(Value { x: 5 }));
1724 fn naive_pow<T: One + Mul<T, T>>(base: T, exp: uint) -> T {
1725 range(0, exp).fold(one::<T>(), |acc, _| acc * base)
1727 macro_rules! assert_pow(
1728 (($num:expr, $exp:expr) => $expected:expr) => {{
1729 let result = pow($num, $exp);
1730 assert_eq!(result, $expected);
1731 assert_eq!(result, naive_pow($num, $exp));
1734 assert_pow!((3, 0 ) => 1);
1735 assert_pow!((5, 1 ) => 5);
1736 assert_pow!((-4, 2 ) => 16);
1737 assert_pow!((0.5, 5 ) => 0.03125);
1738 assert_pow!((8, 3 ) => 512);
1739 assert_pow!((8.0, 5 ) => 32768.0);
1740 assert_pow!((8.5, 5 ) => 44370.53125);
1741 assert_pow!((2u64, 50) => 1125899906842624);
1749 use self::test::Bencher;
1754 fn bench_pow_function(b: &mut Bencher) {
1755 let v = Vec::from_fn(1024, |n| n);
1756 b.iter(|| {v.iter().fold(0, |old, new| num::pow(old, *new));});