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 pub trait Unsigned: Num {}
164 /// A collection of rounding operations.
166 /// Return the largest integer less than or equal to a number.
167 fn floor(&self) -> Self;
169 /// Return the smallest integer greater than or equal to a number.
170 fn ceil(&self) -> Self;
172 /// Return the nearest integer to a number. Round half-way cases away from
174 fn round(&self) -> Self;
176 /// Return the integer part of a number.
177 fn trunc(&self) -> Self;
179 /// Return the fractional part of a number.
180 fn fract(&self) -> Self;
183 /// Raises a value to the power of exp, using exponentiation by squaring.
190 /// assert_eq!(num::pow(2, 4), 16);
193 pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
196 let mut acc = one::<T>();
209 // FIXME (#5527): These should be associated constants
210 fn min_value() -> Self;
211 fn max_value() -> Self;
214 /// Numbers with a fixed binary representation.
215 pub trait Bitwise: Bounded
222 /// Returns the number of ones in the binary representation of the number.
227 /// use std::num::Bitwise;
229 /// let n = 0b01001100u8;
230 /// assert_eq!(n.count_ones(), 3);
232 fn count_ones(&self) -> Self;
234 /// Returns the number of zeros in the binary representation of the number.
239 /// use std::num::Bitwise;
241 /// let n = 0b01001100u8;
242 /// assert_eq!(n.count_zeros(), 5);
245 fn count_zeros(&self) -> Self {
246 (!*self).count_ones()
249 /// Returns the number of leading zeros in the in the binary representation
255 /// use std::num::Bitwise;
257 /// let n = 0b0101000u16;
258 /// assert_eq!(n.leading_zeros(), 10);
260 fn leading_zeros(&self) -> Self;
262 /// Returns the number of trailing zeros in the in the binary representation
268 /// use std::num::Bitwise;
270 /// let n = 0b0101000u16;
271 /// assert_eq!(n.trailing_zeros(), 3);
273 fn trailing_zeros(&self) -> Self;
276 /// Specifies the available operations common to all of Rust's core numeric primitives.
277 /// These may not always make sense from a purely mathematical point of view, but
278 /// may be useful for systems programming.
279 pub trait Primitive: Pod
286 /// A collection of traits relevant to primitive signed and unsigned integers
287 pub trait Int: Primitive
299 /// Returns the smallest power of 2 greater than or equal to `n`.
301 pub fn next_power_of_two<T: Unsigned + Int>(n: T) -> T {
302 let halfbits: T = cast(size_of::<T>() * 4).unwrap();
303 let mut tmp: T = n - one();
304 let mut shift: T = one();
305 while shift <= halfbits {
306 tmp = tmp | (tmp >> shift);
307 shift = shift << one();
312 /// Returns the smallest power of 2 greater than or equal to `n`. If the next
313 /// power of two is greater than the type's maximum value, `None` is returned,
314 /// otherwise the power of 2 is wrapped in `Some`.
316 pub fn checked_next_power_of_two<T: Unsigned + Int>(n: T) -> Option<T> {
317 let halfbits: T = cast(size_of::<T>() * 4).unwrap();
318 let mut tmp: T = n - one();
319 let mut shift: T = one();
320 while shift <= halfbits {
321 tmp = tmp | (tmp >> shift);
322 shift = shift << one();
324 tmp.checked_add(&one())
327 /// Used for representing the classification of floating point numbers
328 #[deriving(Eq, Show)]
329 pub enum FPCategory {
330 /// "Not a Number", often obtained by dividing by zero
332 /// Positive or negative infinity
334 /// Positive or negative zero
336 /// De-normalized floating point representation (less precise than `FPNormal`)
338 /// A regular floating point number
342 /// Operations on primitive floating point numbers.
344 /// TODO(#5527): In a future version of Rust, many of these functions will become constants.
346 /// FIXME(#8888): Several of these functions have a parameter named `unused_self`. Removing it
347 /// requires #8888 to be fixed.
348 pub trait Float: Signed + Round + Primitive {
349 /// Returns the maximum of the two numbers.
350 fn max(self, other: Self) -> Self;
351 /// Returns the minimum of the two numbers.
352 fn min(self, other: Self) -> Self;
354 /// Returns the NaN value.
357 /// Returns the infinite value.
358 fn infinity() -> Self;
360 /// Returns the negative infinite value.
361 fn neg_infinity() -> Self;
364 fn neg_zero() -> Self;
366 /// Returns true if this value is NaN and false otherwise.
367 fn is_nan(&self) -> bool;
369 /// Returns true if this value is positive infinity or negative infinity and false otherwise.
370 fn is_infinite(&self) -> bool;
372 /// Returns true if this number is neither infinite nor NaN.
373 fn is_finite(&self) -> bool;
375 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
376 fn is_normal(&self) -> bool;
378 /// Returns the category that this number falls into.
379 fn classify(&self) -> FPCategory;
381 /// Returns the number of binary digits of mantissa that this type supports.
382 fn mantissa_digits(unused_self: Option<Self>) -> uint;
384 /// Returns the number of binary digits of exponent that this type supports.
385 fn digits(unused_self: Option<Self>) -> uint;
387 /// Returns the smallest positive number that this type can represent.
388 fn epsilon() -> Self;
390 /// Returns the minimum binary exponent that this type can represent.
391 fn min_exp(unused_self: Option<Self>) -> int;
393 /// Returns the maximum binary exponent that this type can represent.
394 fn max_exp(unused_self: Option<Self>) -> int;
396 /// Returns the minimum base-10 exponent that this type can represent.
397 fn min_10_exp(unused_self: Option<Self>) -> int;
399 /// Returns the maximum base-10 exponent that this type can represent.
400 fn max_10_exp(unused_self: Option<Self>) -> int;
402 /// Constructs a floating point number created by multiplying `x` by 2 raised to the power of
404 fn ldexp(x: Self, exp: int) -> Self;
406 /// Breaks the number into a normalized fraction and a base-2 exponent, satisfying:
408 /// * `self = x * pow(2, exp)`
410 /// * `0.5 <= abs(x) < 1.0`
411 fn frexp(&self) -> (Self, int);
413 /// Returns the exponential of the number, minus 1, in a way that is accurate even if the
414 /// number is close to zero.
415 fn exp_m1(&self) -> Self;
417 /// Returns the natural logarithm of the number plus 1 (`ln(1+n)`) more accurately than if the
418 /// operations were performed separately.
419 fn ln_1p(&self) -> Self;
421 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding error. This produces a
422 /// more accurate result with better performance than a separate multiplication operation
423 /// followed by an add.
424 fn mul_add(&self, a: Self, b: Self) -> Self;
426 /// Returns the next representable floating-point value in the direction of `other`.
427 fn next_after(&self, other: Self) -> Self;
429 /// Returns the mantissa, exponent and sign as integers, respectively.
430 fn integer_decode(&self) -> (u64, i16, i8);
432 /// Archimedes' constant.
439 fn frac_pi_2() -> Self;
442 fn frac_pi_3() -> Self;
445 fn frac_pi_4() -> Self;
448 fn frac_pi_6() -> Self;
451 fn frac_pi_8() -> Self;
454 fn frac_1_pi() -> Self;
457 fn frac_2_pi() -> Self;
460 fn frac_2_sqrtpi() -> Self;
466 fn frac_1_sqrt2() -> Self;
475 fn log10_e() -> Self;
483 /// Take the reciprocal (inverse) of a number, `1/x`.
484 fn recip(&self) -> Self;
486 /// Raise a number to a power.
487 fn powf(&self, n: &Self) -> Self;
489 /// Take the square root of a number.
490 fn sqrt(&self) -> Self;
491 /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
492 fn rsqrt(&self) -> Self;
493 /// Take the cubic root of a number.
494 fn cbrt(&self) -> Self;
495 /// Calculate the length of the hypotenuse of a right-angle triangle given
496 /// legs of length `x` and `y`.
497 fn hypot(&self, other: &Self) -> Self;
499 /// Computes the sine of a number (in radians).
500 fn sin(&self) -> Self;
501 /// Computes the cosine of a number (in radians).
502 fn cos(&self) -> Self;
503 /// Computes the tangent of a number (in radians).
504 fn tan(&self) -> Self;
506 /// Computes the arcsine of a number. Return value is in radians in
507 /// the range [-pi/2, pi/2] or NaN if the number is outside the range
509 fn asin(&self) -> Self;
510 /// Computes the arccosine of a number. Return value is in radians in
511 /// the range [0, pi] or NaN if the number is outside the range
513 fn acos(&self) -> Self;
514 /// Computes the arctangent of a number. Return value is in radians in the
515 /// range [-pi/2, pi/2];
516 fn atan(&self) -> Self;
517 /// Computes the four quadrant arctangent of a number, `y`, and another
518 /// number `x`. Return value is in radians in the range [-pi, pi].
519 fn atan2(&self, other: &Self) -> Self;
520 /// Simultaneously computes the sine and cosine of the number, `x`. Returns
521 /// `(sin(x), cos(x))`.
522 fn sin_cos(&self) -> (Self, Self);
524 /// Returns `e^(self)`, (the exponential function).
525 fn exp(&self) -> Self;
526 /// Returns 2 raised to the power of the number, `2^(self)`.
527 fn exp2(&self) -> Self;
528 /// Returns the natural logarithm of the number.
529 fn ln(&self) -> Self;
530 /// Returns the logarithm of the number with respect to an arbitrary base.
531 fn log(&self, base: &Self) -> Self;
532 /// Returns the base 2 logarithm of the number.
533 fn log2(&self) -> Self;
534 /// Returns the base 10 logarithm of the number.
535 fn log10(&self) -> Self;
537 /// Hyperbolic sine function.
538 fn sinh(&self) -> Self;
539 /// Hyperbolic cosine function.
540 fn cosh(&self) -> Self;
541 /// Hyperbolic tangent function.
542 fn tanh(&self) -> Self;
543 /// Inverse hyperbolic sine function.
544 fn asinh(&self) -> Self;
545 /// Inverse hyperbolic cosine function.
546 fn acosh(&self) -> Self;
547 /// Inverse hyperbolic tangent function.
548 fn atanh(&self) -> Self;
550 /// Convert radians to degrees.
551 fn to_degrees(&self) -> Self;
552 /// Convert degrees to radians.
553 fn to_radians(&self) -> Self;
556 /// Returns the exponential of the number, minus `1`, `exp(n) - 1`, in a way
557 /// that is accurate even if the number is close to zero.
558 #[inline(always)] pub fn exp_m1<T: Float>(value: T) -> T { value.exp_m1() }
559 /// Returns the natural logarithm of the number plus `1`, `ln(n + 1)`, more
560 /// accurately than if the operations were performed separately.
561 #[inline(always)] pub fn ln_1p<T: Float>(value: T) -> T { value.ln_1p() }
562 /// Fused multiply-add. Computes `(a * b) + c` with only one rounding error.
564 /// This produces a more accurate result with better performance (on some
565 /// architectures) than a separate multiplication operation followed by an add.
566 #[inline(always)] pub fn mul_add<T: Float>(a: T, b: T, c: T) -> T { a.mul_add(b, c) }
568 /// Raise a number to a power.
575 /// let sixteen: f64 = num::powf(2.0, 4.0);
576 /// assert_eq!(sixteen, 16.0);
578 #[inline(always)] pub fn powf<T: Float>(value: T, n: T) -> T { value.powf(&n) }
579 /// Take the square root of a number.
580 #[inline(always)] pub fn sqrt<T: Float>(value: T) -> T { value.sqrt() }
581 /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
582 #[inline(always)] pub fn rsqrt<T: Float>(value: T) -> T { value.rsqrt() }
583 /// Take the cubic root of a number.
584 #[inline(always)] pub fn cbrt<T: Float>(value: T) -> T { value.cbrt() }
585 /// Calculate the length of the hypotenuse of a right-angle triangle given legs
586 /// of length `x` and `y`.
587 #[inline(always)] pub fn hypot<T: Float>(x: T, y: T) -> T { x.hypot(&y) }
589 #[inline(always)] pub fn sin<T: Float>(value: T) -> T { value.sin() }
591 #[inline(always)] pub fn cos<T: Float>(value: T) -> T { value.cos() }
592 /// Tangent function.
593 #[inline(always)] pub fn tan<T: Float>(value: T) -> T { value.tan() }
594 /// Compute the arcsine of the number.
595 #[inline(always)] pub fn asin<T: Float>(value: T) -> T { value.asin() }
596 /// Compute the arccosine of the number.
597 #[inline(always)] pub fn acos<T: Float>(value: T) -> T { value.acos() }
598 /// Compute the arctangent of the number.
599 #[inline(always)] pub fn atan<T: Float>(value: T) -> T { value.atan() }
600 /// Compute the arctangent with 2 arguments.
601 #[inline(always)] pub fn atan2<T: Float>(x: T, y: T) -> T { x.atan2(&y) }
602 /// Simultaneously computes the sine and cosine of the number.
603 #[inline(always)] pub fn sin_cos<T: Float>(value: T) -> (T, T) { value.sin_cos() }
604 /// Returns `e^(value)`, (the exponential function).
605 #[inline(always)] pub fn exp<T: Float>(value: T) -> T { value.exp() }
606 /// Returns 2 raised to the power of the number, `2^(value)`.
607 #[inline(always)] pub fn exp2<T: Float>(value: T) -> T { value.exp2() }
608 /// Returns the natural logarithm of the number.
609 #[inline(always)] pub fn ln<T: Float>(value: T) -> T { value.ln() }
610 /// Returns the logarithm of the number with respect to an arbitrary base.
611 #[inline(always)] pub fn log<T: Float>(value: T, base: T) -> T { value.log(&base) }
612 /// Returns the base 2 logarithm of the number.
613 #[inline(always)] pub fn log2<T: Float>(value: T) -> T { value.log2() }
614 /// Returns the base 10 logarithm of the number.
615 #[inline(always)] pub fn log10<T: Float>(value: T) -> T { value.log10() }
616 /// Hyperbolic sine function.
617 #[inline(always)] pub fn sinh<T: Float>(value: T) -> T { value.sinh() }
618 /// Hyperbolic cosine function.
619 #[inline(always)] pub fn cosh<T: Float>(value: T) -> T { value.cosh() }
620 /// Hyperbolic tangent function.
621 #[inline(always)] pub fn tanh<T: Float>(value: T) -> T { value.tanh() }
622 /// Inverse hyperbolic sine function.
623 #[inline(always)] pub fn asinh<T: Float>(value: T) -> T { value.asinh() }
624 /// Inverse hyperbolic cosine function.
625 #[inline(always)] pub fn acosh<T: Float>(value: T) -> T { value.acosh() }
626 /// Inverse hyperbolic tangent function.
627 #[inline(always)] pub fn atanh<T: Float>(value: T) -> T { value.atanh() }
629 /// A generic trait for converting a value to a number.
630 pub trait ToPrimitive {
631 /// Converts the value of `self` to an `int`.
633 fn to_int(&self) -> Option<int> {
634 self.to_i64().and_then(|x| x.to_int())
637 /// Converts the value of `self` to an `i8`.
639 fn to_i8(&self) -> Option<i8> {
640 self.to_i64().and_then(|x| x.to_i8())
643 /// Converts the value of `self` to an `i16`.
645 fn to_i16(&self) -> Option<i16> {
646 self.to_i64().and_then(|x| x.to_i16())
649 /// Converts the value of `self` to an `i32`.
651 fn to_i32(&self) -> Option<i32> {
652 self.to_i64().and_then(|x| x.to_i32())
655 /// Converts the value of `self` to an `i64`.
656 fn to_i64(&self) -> Option<i64>;
658 /// Converts the value of `self` to an `uint`.
660 fn to_uint(&self) -> Option<uint> {
661 self.to_u64().and_then(|x| x.to_uint())
664 /// Converts the value of `self` to an `u8`.
666 fn to_u8(&self) -> Option<u8> {
667 self.to_u64().and_then(|x| x.to_u8())
670 /// Converts the value of `self` to an `u16`.
672 fn to_u16(&self) -> Option<u16> {
673 self.to_u64().and_then(|x| x.to_u16())
676 /// Converts the value of `self` to an `u32`.
678 fn to_u32(&self) -> Option<u32> {
679 self.to_u64().and_then(|x| x.to_u32())
682 /// Converts the value of `self` to an `u64`.
684 fn to_u64(&self) -> Option<u64>;
686 /// Converts the value of `self` to an `f32`.
688 fn to_f32(&self) -> Option<f32> {
689 self.to_f64().and_then(|x| x.to_f32())
692 /// Converts the value of `self` to an `f64`.
694 fn to_f64(&self) -> Option<f64> {
695 self.to_i64().and_then(|x| x.to_f64())
699 macro_rules! impl_to_primitive_int_to_int(
700 ($SrcT:ty, $DstT:ty) => (
702 if size_of::<$SrcT>() <= size_of::<$DstT>() {
705 let n = *self as i64;
706 let min_value: $DstT = Bounded::min_value();
707 let max_value: $DstT = Bounded::max_value();
708 if min_value as i64 <= n && n <= max_value as i64 {
718 macro_rules! impl_to_primitive_int_to_uint(
719 ($SrcT:ty, $DstT:ty) => (
721 let zero: $SrcT = Zero::zero();
722 let max_value: $DstT = Bounded::max_value();
723 if zero <= *self && *self as u64 <= max_value as u64 {
732 macro_rules! impl_to_primitive_int(
734 impl ToPrimitive for $T {
736 fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int) }
738 fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8) }
740 fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16) }
742 fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32) }
744 fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64) }
747 fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint) }
749 fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8) }
751 fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16) }
753 fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32) }
755 fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64) }
758 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
760 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
765 impl_to_primitive_int!(int)
766 impl_to_primitive_int!(i8)
767 impl_to_primitive_int!(i16)
768 impl_to_primitive_int!(i32)
769 impl_to_primitive_int!(i64)
771 macro_rules! impl_to_primitive_uint_to_int(
774 let max_value: $DstT = Bounded::max_value();
775 if *self as u64 <= max_value as u64 {
784 macro_rules! impl_to_primitive_uint_to_uint(
785 ($SrcT:ty, $DstT:ty) => (
787 if size_of::<$SrcT>() <= size_of::<$DstT>() {
790 let zero: $SrcT = Zero::zero();
791 let max_value: $DstT = Bounded::max_value();
792 if zero <= *self && *self as u64 <= max_value as u64 {
802 macro_rules! impl_to_primitive_uint(
804 impl ToPrimitive for $T {
806 fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int) }
808 fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8) }
810 fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16) }
812 fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32) }
814 fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64) }
817 fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint) }
819 fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8) }
821 fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16) }
823 fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32) }
825 fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64) }
828 fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
830 fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
835 impl_to_primitive_uint!(uint)
836 impl_to_primitive_uint!(u8)
837 impl_to_primitive_uint!(u16)
838 impl_to_primitive_uint!(u32)
839 impl_to_primitive_uint!(u64)
841 macro_rules! impl_to_primitive_float_to_float(
842 ($SrcT:ty, $DstT:ty) => (
843 if size_of::<$SrcT>() <= size_of::<$DstT>() {
846 let n = *self as f64;
847 let max_value: $SrcT = Bounded::max_value();
848 if -max_value as f64 <= n && n <= max_value as f64 {
857 macro_rules! impl_to_primitive_float(
859 impl ToPrimitive for $T {
861 fn to_int(&self) -> Option<int> { Some(*self as int) }
863 fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
865 fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
867 fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
869 fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
872 fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
874 fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
876 fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
878 fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
880 fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
883 fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32) }
885 fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64) }
890 impl_to_primitive_float!(f32)
891 impl_to_primitive_float!(f64)
893 /// A generic trait for converting a number to a value.
894 pub trait FromPrimitive {
895 /// Convert an `int` to return an optional value of this type. If the
896 /// value cannot be represented by this value, the `None` is returned.
898 fn from_int(n: int) -> Option<Self> {
899 FromPrimitive::from_i64(n as i64)
902 /// Convert an `i8` to return an optional value of this type. If the
903 /// type cannot be represented by this value, the `None` is returned.
905 fn from_i8(n: i8) -> Option<Self> {
906 FromPrimitive::from_i64(n as i64)
909 /// Convert an `i16` to return an optional value of this type. If the
910 /// type cannot be represented by this value, the `None` is returned.
912 fn from_i16(n: i16) -> Option<Self> {
913 FromPrimitive::from_i64(n as i64)
916 /// Convert an `i32` to return an optional value of this type. If the
917 /// type cannot be represented by this value, the `None` is returned.
919 fn from_i32(n: i32) -> Option<Self> {
920 FromPrimitive::from_i64(n as i64)
923 /// Convert an `i64` to return an optional value of this type. If the
924 /// type cannot be represented by this value, the `None` is returned.
925 fn from_i64(n: i64) -> Option<Self>;
927 /// Convert an `uint` to return an optional value of this type. If the
928 /// type cannot be represented by this value, the `None` is returned.
930 fn from_uint(n: uint) -> Option<Self> {
931 FromPrimitive::from_u64(n as u64)
934 /// Convert an `u8` to return an optional value of this type. If the
935 /// type cannot be represented by this value, the `None` is returned.
937 fn from_u8(n: u8) -> Option<Self> {
938 FromPrimitive::from_u64(n as u64)
941 /// Convert an `u16` to return an optional value of this type. If the
942 /// type cannot be represented by this value, the `None` is returned.
944 fn from_u16(n: u16) -> Option<Self> {
945 FromPrimitive::from_u64(n as u64)
948 /// Convert an `u32` to return an optional value of this type. If the
949 /// type cannot be represented by this value, the `None` is returned.
951 fn from_u32(n: u32) -> Option<Self> {
952 FromPrimitive::from_u64(n as u64)
955 /// Convert an `u64` to return an optional value of this type. If the
956 /// type cannot be represented by this value, the `None` is returned.
957 fn from_u64(n: u64) -> Option<Self>;
959 /// Convert a `f32` to return an optional value of this type. If the
960 /// type cannot be represented by this value, the `None` is returned.
962 fn from_f32(n: f32) -> Option<Self> {
963 FromPrimitive::from_f64(n as f64)
966 /// Convert a `f64` to return an optional value of this type. If the
967 /// type cannot be represented by this value, the `None` is returned.
969 fn from_f64(n: f64) -> Option<Self> {
970 FromPrimitive::from_i64(n as i64)
974 /// A utility function that just calls `FromPrimitive::from_int`.
975 pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
976 FromPrimitive::from_int(n)
979 /// A utility function that just calls `FromPrimitive::from_i8`.
980 pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> {
981 FromPrimitive::from_i8(n)
984 /// A utility function that just calls `FromPrimitive::from_i16`.
985 pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> {
986 FromPrimitive::from_i16(n)
989 /// A utility function that just calls `FromPrimitive::from_i32`.
990 pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> {
991 FromPrimitive::from_i32(n)
994 /// A utility function that just calls `FromPrimitive::from_i64`.
995 pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
996 FromPrimitive::from_i64(n)
999 /// A utility function that just calls `FromPrimitive::from_uint`.
1000 pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
1001 FromPrimitive::from_uint(n)
1004 /// A utility function that just calls `FromPrimitive::from_u8`.
1005 pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> {
1006 FromPrimitive::from_u8(n)
1009 /// A utility function that just calls `FromPrimitive::from_u16`.
1010 pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> {
1011 FromPrimitive::from_u16(n)
1014 /// A utility function that just calls `FromPrimitive::from_u32`.
1015 pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> {
1016 FromPrimitive::from_u32(n)
1019 /// A utility function that just calls `FromPrimitive::from_u64`.
1020 pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> {
1021 FromPrimitive::from_u64(n)
1024 /// A utility function that just calls `FromPrimitive::from_f32`.
1025 pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> {
1026 FromPrimitive::from_f32(n)
1029 /// A utility function that just calls `FromPrimitive::from_f64`.
1030 pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {
1031 FromPrimitive::from_f64(n)
1034 macro_rules! impl_from_primitive(
1035 ($T:ty, $to_ty:expr) => (
1036 impl FromPrimitive for $T {
1037 #[inline] fn from_int(n: int) -> Option<$T> { $to_ty }
1038 #[inline] fn from_i8(n: i8) -> Option<$T> { $to_ty }
1039 #[inline] fn from_i16(n: i16) -> Option<$T> { $to_ty }
1040 #[inline] fn from_i32(n: i32) -> Option<$T> { $to_ty }
1041 #[inline] fn from_i64(n: i64) -> Option<$T> { $to_ty }
1043 #[inline] fn from_uint(n: uint) -> Option<$T> { $to_ty }
1044 #[inline] fn from_u8(n: u8) -> Option<$T> { $to_ty }
1045 #[inline] fn from_u16(n: u16) -> Option<$T> { $to_ty }
1046 #[inline] fn from_u32(n: u32) -> Option<$T> { $to_ty }
1047 #[inline] fn from_u64(n: u64) -> Option<$T> { $to_ty }
1049 #[inline] fn from_f32(n: f32) -> Option<$T> { $to_ty }
1050 #[inline] fn from_f64(n: f64) -> Option<$T> { $to_ty }
1055 impl_from_primitive!(int, n.to_int())
1056 impl_from_primitive!(i8, n.to_i8())
1057 impl_from_primitive!(i16, n.to_i16())
1058 impl_from_primitive!(i32, n.to_i32())
1059 impl_from_primitive!(i64, n.to_i64())
1060 impl_from_primitive!(uint, n.to_uint())
1061 impl_from_primitive!(u8, n.to_u8())
1062 impl_from_primitive!(u16, n.to_u16())
1063 impl_from_primitive!(u32, n.to_u32())
1064 impl_from_primitive!(u64, n.to_u64())
1065 impl_from_primitive!(f32, n.to_f32())
1066 impl_from_primitive!(f64, n.to_f64())
1068 /// Cast from one machine scalar to another.
1075 /// let twenty: f32 = num::cast(0x14).unwrap();
1076 /// assert_eq!(twenty, 20f32);
1080 pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
1084 /// An interface for casting between machine scalars.
1085 pub trait NumCast: ToPrimitive {
1086 /// Creates a number from another value that can be converted into a primitive via the
1087 /// `ToPrimitive` trait.
1088 fn from<T: ToPrimitive>(n: T) -> Option<Self>;
1091 macro_rules! impl_num_cast(
1092 ($T:ty, $conv:ident) => (
1093 impl NumCast for $T {
1095 fn from<N: ToPrimitive>(n: N) -> Option<$T> {
1096 // `$conv` could be generated using `concat_idents!`, but that
1097 // macro seems to be broken at the moment
1104 impl_num_cast!(u8, to_u8)
1105 impl_num_cast!(u16, to_u16)
1106 impl_num_cast!(u32, to_u32)
1107 impl_num_cast!(u64, to_u64)
1108 impl_num_cast!(uint, to_uint)
1109 impl_num_cast!(i8, to_i8)
1110 impl_num_cast!(i16, to_i16)
1111 impl_num_cast!(i32, to_i32)
1112 impl_num_cast!(i64, to_i64)
1113 impl_num_cast!(int, to_int)
1114 impl_num_cast!(f32, to_f32)
1115 impl_num_cast!(f64, to_f64)
1117 pub trait ToStrRadix {
1118 fn to_str_radix(&self, radix: uint) -> ~str;
1121 pub trait FromStrRadix {
1122 fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
1125 /// A utility function that just calls FromStrRadix::from_str_radix.
1126 pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint) -> Option<T> {
1127 FromStrRadix::from_str_radix(str, radix)
1130 /// Saturating math operations
1131 pub trait Saturating {
1132 /// Saturating addition operator.
1133 /// Returns a+b, saturating at the numeric bounds instead of overflowing.
1134 fn saturating_add(self, v: Self) -> Self;
1136 /// Saturating subtraction operator.
1137 /// Returns a-b, saturating at the numeric bounds instead of overflowing.
1138 fn saturating_sub(self, v: Self) -> Self;
1141 impl<T: CheckedAdd + CheckedSub + Zero + Ord + Bounded> Saturating for T {
1143 fn saturating_add(self, v: T) -> T {
1144 match self.checked_add(&v) {
1146 None => if v >= Zero::zero() {
1147 Bounded::max_value()
1149 Bounded::min_value()
1155 fn saturating_sub(self, v: T) -> T {
1156 match self.checked_sub(&v) {
1158 None => if v >= Zero::zero() {
1159 Bounded::min_value()
1161 Bounded::max_value()
1167 /// Performs addition that returns `None` instead of wrapping around on overflow.
1168 pub trait CheckedAdd: Add<Self, Self> {
1169 /// Adds two numbers, checking for overflow. If overflow happens, `None` is returned.
1170 fn checked_add(&self, v: &Self) -> Option<Self>;
1173 /// Performs subtraction that returns `None` instead of wrapping around on underflow.
1174 pub trait CheckedSub: Sub<Self, Self> {
1175 /// Subtracts two numbers, checking for underflow. If underflow happens, `None` is returned.
1176 fn checked_sub(&self, v: &Self) -> Option<Self>;
1179 /// Performs multiplication that returns `None` instead of wrapping around on underflow or
1181 pub trait CheckedMul: Mul<Self, Self> {
1182 /// Multiplies two numbers, checking for underflow or overflow. If underflow or overflow
1183 /// happens, `None` is returned.
1184 fn checked_mul(&self, v: &Self) -> Option<Self>;
1187 /// Performs division that returns `None` instead of wrapping around on underflow or overflow.
1188 pub trait CheckedDiv: Div<Self, Self> {
1189 /// Divides two numbers, checking for underflow or overflow. If underflow or overflow happens,
1190 /// `None` is returned.
1191 fn checked_div(&self, v: &Self) -> Option<Self>;
1194 /// Helper function for testing numeric operations
1196 pub fn test_num<T:Num + NumCast + Show>(ten: T, two: T) {
1197 assert_eq!(ten.add(&two), cast(12).unwrap());
1198 assert_eq!(ten.sub(&two), cast(8).unwrap());
1199 assert_eq!(ten.mul(&two), cast(20).unwrap());
1200 assert_eq!(ten.div(&two), cast(5).unwrap());
1201 assert_eq!(ten.rem(&two), cast(0).unwrap());
1203 assert_eq!(ten.add(&two), ten + two);
1204 assert_eq!(ten.sub(&two), ten - two);
1205 assert_eq!(ten.mul(&two), ten * two);
1206 assert_eq!(ten.div(&two), ten / two);
1207 assert_eq!(ten.rem(&two), ten % two);
1225 macro_rules! test_cast_20(
1229 assert_eq!(20u, _20.to_uint().unwrap());
1230 assert_eq!(20u8, _20.to_u8().unwrap());
1231 assert_eq!(20u16, _20.to_u16().unwrap());
1232 assert_eq!(20u32, _20.to_u32().unwrap());
1233 assert_eq!(20u64, _20.to_u64().unwrap());
1234 assert_eq!(20i, _20.to_int().unwrap());
1235 assert_eq!(20i8, _20.to_i8().unwrap());
1236 assert_eq!(20i16, _20.to_i16().unwrap());
1237 assert_eq!(20i32, _20.to_i32().unwrap());
1238 assert_eq!(20i64, _20.to_i64().unwrap());
1239 assert_eq!(20f32, _20.to_f32().unwrap());
1240 assert_eq!(20f64, _20.to_f64().unwrap());
1242 assert_eq!(_20, NumCast::from(20u).unwrap());
1243 assert_eq!(_20, NumCast::from(20u8).unwrap());
1244 assert_eq!(_20, NumCast::from(20u16).unwrap());
1245 assert_eq!(_20, NumCast::from(20u32).unwrap());
1246 assert_eq!(_20, NumCast::from(20u64).unwrap());
1247 assert_eq!(_20, NumCast::from(20i).unwrap());
1248 assert_eq!(_20, NumCast::from(20i8).unwrap());
1249 assert_eq!(_20, NumCast::from(20i16).unwrap());
1250 assert_eq!(_20, NumCast::from(20i32).unwrap());
1251 assert_eq!(_20, NumCast::from(20i64).unwrap());
1252 assert_eq!(_20, NumCast::from(20f32).unwrap());
1253 assert_eq!(_20, NumCast::from(20f64).unwrap());
1255 assert_eq!(_20, cast(20u).unwrap());
1256 assert_eq!(_20, cast(20u8).unwrap());
1257 assert_eq!(_20, cast(20u16).unwrap());
1258 assert_eq!(_20, cast(20u32).unwrap());
1259 assert_eq!(_20, cast(20u64).unwrap());
1260 assert_eq!(_20, cast(20i).unwrap());
1261 assert_eq!(_20, cast(20i8).unwrap());
1262 assert_eq!(_20, cast(20i16).unwrap());
1263 assert_eq!(_20, cast(20i32).unwrap());
1264 assert_eq!(_20, cast(20i64).unwrap());
1265 assert_eq!(_20, cast(20f32).unwrap());
1266 assert_eq!(_20, cast(20f64).unwrap());
1270 #[test] fn test_u8_cast() { test_cast_20!(20u8) }
1271 #[test] fn test_u16_cast() { test_cast_20!(20u16) }
1272 #[test] fn test_u32_cast() { test_cast_20!(20u32) }
1273 #[test] fn test_u64_cast() { test_cast_20!(20u64) }
1274 #[test] fn test_uint_cast() { test_cast_20!(20u) }
1275 #[test] fn test_i8_cast() { test_cast_20!(20i8) }
1276 #[test] fn test_i16_cast() { test_cast_20!(20i16) }
1277 #[test] fn test_i32_cast() { test_cast_20!(20i32) }
1278 #[test] fn test_i64_cast() { test_cast_20!(20i64) }
1279 #[test] fn test_int_cast() { test_cast_20!(20i) }
1280 #[test] fn test_f32_cast() { test_cast_20!(20f32) }
1281 #[test] fn test_f64_cast() { test_cast_20!(20f64) }
1284 fn test_cast_range_int_min() {
1285 assert_eq!(int::MIN.to_int(), Some(int::MIN as int));
1286 assert_eq!(int::MIN.to_i8(), None);
1287 assert_eq!(int::MIN.to_i16(), None);
1288 // int::MIN.to_i32() is word-size specific
1289 assert_eq!(int::MIN.to_i64(), Some(int::MIN as i64));
1290 assert_eq!(int::MIN.to_uint(), None);
1291 assert_eq!(int::MIN.to_u8(), None);
1292 assert_eq!(int::MIN.to_u16(), None);
1293 assert_eq!(int::MIN.to_u32(), None);
1294 assert_eq!(int::MIN.to_u64(), None);
1296 #[cfg(target_word_size = "32")]
1297 fn check_word_size() {
1298 assert_eq!(int::MIN.to_i32(), Some(int::MIN as i32));
1301 #[cfg(target_word_size = "64")]
1302 fn check_word_size() {
1303 assert_eq!(int::MIN.to_i32(), None);
1310 fn test_cast_range_i8_min() {
1311 assert_eq!(i8::MIN.to_int(), Some(i8::MIN as int));
1312 assert_eq!(i8::MIN.to_i8(), Some(i8::MIN as i8));
1313 assert_eq!(i8::MIN.to_i16(), Some(i8::MIN as i16));
1314 assert_eq!(i8::MIN.to_i32(), Some(i8::MIN as i32));
1315 assert_eq!(i8::MIN.to_i64(), Some(i8::MIN as i64));
1316 assert_eq!(i8::MIN.to_uint(), None);
1317 assert_eq!(i8::MIN.to_u8(), None);
1318 assert_eq!(i8::MIN.to_u16(), None);
1319 assert_eq!(i8::MIN.to_u32(), None);
1320 assert_eq!(i8::MIN.to_u64(), None);
1324 fn test_cast_range_i16_min() {
1325 assert_eq!(i16::MIN.to_int(), Some(i16::MIN as int));
1326 assert_eq!(i16::MIN.to_i8(), None);
1327 assert_eq!(i16::MIN.to_i16(), Some(i16::MIN as i16));
1328 assert_eq!(i16::MIN.to_i32(), Some(i16::MIN as i32));
1329 assert_eq!(i16::MIN.to_i64(), Some(i16::MIN as i64));
1330 assert_eq!(i16::MIN.to_uint(), None);
1331 assert_eq!(i16::MIN.to_u8(), None);
1332 assert_eq!(i16::MIN.to_u16(), None);
1333 assert_eq!(i16::MIN.to_u32(), None);
1334 assert_eq!(i16::MIN.to_u64(), None);
1338 fn test_cast_range_i32_min() {
1339 assert_eq!(i32::MIN.to_int(), Some(i32::MIN as int));
1340 assert_eq!(i32::MIN.to_i8(), None);
1341 assert_eq!(i32::MIN.to_i16(), None);
1342 assert_eq!(i32::MIN.to_i32(), Some(i32::MIN as i32));
1343 assert_eq!(i32::MIN.to_i64(), Some(i32::MIN as i64));
1344 assert_eq!(i32::MIN.to_uint(), None);
1345 assert_eq!(i32::MIN.to_u8(), None);
1346 assert_eq!(i32::MIN.to_u16(), None);
1347 assert_eq!(i32::MIN.to_u32(), None);
1348 assert_eq!(i32::MIN.to_u64(), None);
1352 fn test_cast_range_i64_min() {
1353 // i64::MIN.to_int() is word-size specific
1354 assert_eq!(i64::MIN.to_i8(), None);
1355 assert_eq!(i64::MIN.to_i16(), None);
1356 assert_eq!(i64::MIN.to_i32(), None);
1357 assert_eq!(i64::MIN.to_i64(), Some(i64::MIN as i64));
1358 assert_eq!(i64::MIN.to_uint(), None);
1359 assert_eq!(i64::MIN.to_u8(), None);
1360 assert_eq!(i64::MIN.to_u16(), None);
1361 assert_eq!(i64::MIN.to_u32(), None);
1362 assert_eq!(i64::MIN.to_u64(), None);
1364 #[cfg(target_word_size = "32")]
1365 fn check_word_size() {
1366 assert_eq!(i64::MIN.to_int(), None);
1369 #[cfg(target_word_size = "64")]
1370 fn check_word_size() {
1371 assert_eq!(i64::MIN.to_int(), Some(i64::MIN as int));
1378 fn test_cast_range_int_max() {
1379 assert_eq!(int::MAX.to_int(), Some(int::MAX as int));
1380 assert_eq!(int::MAX.to_i8(), None);
1381 assert_eq!(int::MAX.to_i16(), None);
1382 // int::MAX.to_i32() is word-size specific
1383 assert_eq!(int::MAX.to_i64(), Some(int::MAX as i64));
1384 assert_eq!(int::MAX.to_u8(), None);
1385 assert_eq!(int::MAX.to_u16(), None);
1386 // int::MAX.to_u32() is word-size specific
1387 assert_eq!(int::MAX.to_u64(), Some(int::MAX as u64));
1389 #[cfg(target_word_size = "32")]
1390 fn check_word_size() {
1391 assert_eq!(int::MAX.to_i32(), Some(int::MAX as i32));
1392 assert_eq!(int::MAX.to_u32(), Some(int::MAX as u32));
1395 #[cfg(target_word_size = "64")]
1396 fn check_word_size() {
1397 assert_eq!(int::MAX.to_i32(), None);
1398 assert_eq!(int::MAX.to_u32(), None);
1405 fn test_cast_range_i8_max() {
1406 assert_eq!(i8::MAX.to_int(), Some(i8::MAX as int));
1407 assert_eq!(i8::MAX.to_i8(), Some(i8::MAX as i8));
1408 assert_eq!(i8::MAX.to_i16(), Some(i8::MAX as i16));
1409 assert_eq!(i8::MAX.to_i32(), Some(i8::MAX as i32));
1410 assert_eq!(i8::MAX.to_i64(), Some(i8::MAX as i64));
1411 assert_eq!(i8::MAX.to_uint(), Some(i8::MAX as uint));
1412 assert_eq!(i8::MAX.to_u8(), Some(i8::MAX as u8));
1413 assert_eq!(i8::MAX.to_u16(), Some(i8::MAX as u16));
1414 assert_eq!(i8::MAX.to_u32(), Some(i8::MAX as u32));
1415 assert_eq!(i8::MAX.to_u64(), Some(i8::MAX as u64));
1419 fn test_cast_range_i16_max() {
1420 assert_eq!(i16::MAX.to_int(), Some(i16::MAX as int));
1421 assert_eq!(i16::MAX.to_i8(), None);
1422 assert_eq!(i16::MAX.to_i16(), Some(i16::MAX as i16));
1423 assert_eq!(i16::MAX.to_i32(), Some(i16::MAX as i32));
1424 assert_eq!(i16::MAX.to_i64(), Some(i16::MAX as i64));
1425 assert_eq!(i16::MAX.to_uint(), Some(i16::MAX as uint));
1426 assert_eq!(i16::MAX.to_u8(), None);
1427 assert_eq!(i16::MAX.to_u16(), Some(i16::MAX as u16));
1428 assert_eq!(i16::MAX.to_u32(), Some(i16::MAX as u32));
1429 assert_eq!(i16::MAX.to_u64(), Some(i16::MAX as u64));
1433 fn test_cast_range_i32_max() {
1434 assert_eq!(i32::MAX.to_int(), Some(i32::MAX as int));
1435 assert_eq!(i32::MAX.to_i8(), None);
1436 assert_eq!(i32::MAX.to_i16(), None);
1437 assert_eq!(i32::MAX.to_i32(), Some(i32::MAX as i32));
1438 assert_eq!(i32::MAX.to_i64(), Some(i32::MAX as i64));
1439 assert_eq!(i32::MAX.to_uint(), Some(i32::MAX as uint));
1440 assert_eq!(i32::MAX.to_u8(), None);
1441 assert_eq!(i32::MAX.to_u16(), None);
1442 assert_eq!(i32::MAX.to_u32(), Some(i32::MAX as u32));
1443 assert_eq!(i32::MAX.to_u64(), Some(i32::MAX as u64));
1447 fn test_cast_range_i64_max() {
1448 // i64::MAX.to_int() is word-size specific
1449 assert_eq!(i64::MAX.to_i8(), None);
1450 assert_eq!(i64::MAX.to_i16(), None);
1451 assert_eq!(i64::MAX.to_i32(), None);
1452 assert_eq!(i64::MAX.to_i64(), Some(i64::MAX as i64));
1453 // i64::MAX.to_uint() is word-size specific
1454 assert_eq!(i64::MAX.to_u8(), None);
1455 assert_eq!(i64::MAX.to_u16(), None);
1456 assert_eq!(i64::MAX.to_u32(), None);
1457 assert_eq!(i64::MAX.to_u64(), Some(i64::MAX as u64));
1459 #[cfg(target_word_size = "32")]
1460 fn check_word_size() {
1461 assert_eq!(i64::MAX.to_int(), None);
1462 assert_eq!(i64::MAX.to_uint(), None);
1465 #[cfg(target_word_size = "64")]
1466 fn check_word_size() {
1467 assert_eq!(i64::MAX.to_int(), Some(i64::MAX as int));
1468 assert_eq!(i64::MAX.to_uint(), Some(i64::MAX as uint));
1475 fn test_cast_range_uint_min() {
1476 assert_eq!(uint::MIN.to_int(), Some(uint::MIN as int));
1477 assert_eq!(uint::MIN.to_i8(), Some(uint::MIN as i8));
1478 assert_eq!(uint::MIN.to_i16(), Some(uint::MIN as i16));
1479 assert_eq!(uint::MIN.to_i32(), Some(uint::MIN as i32));
1480 assert_eq!(uint::MIN.to_i64(), Some(uint::MIN as i64));
1481 assert_eq!(uint::MIN.to_uint(), Some(uint::MIN as uint));
1482 assert_eq!(uint::MIN.to_u8(), Some(uint::MIN as u8));
1483 assert_eq!(uint::MIN.to_u16(), Some(uint::MIN as u16));
1484 assert_eq!(uint::MIN.to_u32(), Some(uint::MIN as u32));
1485 assert_eq!(uint::MIN.to_u64(), Some(uint::MIN as u64));
1489 fn test_cast_range_u8_min() {
1490 assert_eq!(u8::MIN.to_int(), Some(u8::MIN as int));
1491 assert_eq!(u8::MIN.to_i8(), Some(u8::MIN as i8));
1492 assert_eq!(u8::MIN.to_i16(), Some(u8::MIN as i16));
1493 assert_eq!(u8::MIN.to_i32(), Some(u8::MIN as i32));
1494 assert_eq!(u8::MIN.to_i64(), Some(u8::MIN as i64));
1495 assert_eq!(u8::MIN.to_uint(), Some(u8::MIN as uint));
1496 assert_eq!(u8::MIN.to_u8(), Some(u8::MIN as u8));
1497 assert_eq!(u8::MIN.to_u16(), Some(u8::MIN as u16));
1498 assert_eq!(u8::MIN.to_u32(), Some(u8::MIN as u32));
1499 assert_eq!(u8::MIN.to_u64(), Some(u8::MIN as u64));
1503 fn test_cast_range_u16_min() {
1504 assert_eq!(u16::MIN.to_int(), Some(u16::MIN as int));
1505 assert_eq!(u16::MIN.to_i8(), Some(u16::MIN as i8));
1506 assert_eq!(u16::MIN.to_i16(), Some(u16::MIN as i16));
1507 assert_eq!(u16::MIN.to_i32(), Some(u16::MIN as i32));
1508 assert_eq!(u16::MIN.to_i64(), Some(u16::MIN as i64));
1509 assert_eq!(u16::MIN.to_uint(), Some(u16::MIN as uint));
1510 assert_eq!(u16::MIN.to_u8(), Some(u16::MIN as u8));
1511 assert_eq!(u16::MIN.to_u16(), Some(u16::MIN as u16));
1512 assert_eq!(u16::MIN.to_u32(), Some(u16::MIN as u32));
1513 assert_eq!(u16::MIN.to_u64(), Some(u16::MIN as u64));
1517 fn test_cast_range_u32_min() {
1518 assert_eq!(u32::MIN.to_int(), Some(u32::MIN as int));
1519 assert_eq!(u32::MIN.to_i8(), Some(u32::MIN as i8));
1520 assert_eq!(u32::MIN.to_i16(), Some(u32::MIN as i16));
1521 assert_eq!(u32::MIN.to_i32(), Some(u32::MIN as i32));
1522 assert_eq!(u32::MIN.to_i64(), Some(u32::MIN as i64));
1523 assert_eq!(u32::MIN.to_uint(), Some(u32::MIN as uint));
1524 assert_eq!(u32::MIN.to_u8(), Some(u32::MIN as u8));
1525 assert_eq!(u32::MIN.to_u16(), Some(u32::MIN as u16));
1526 assert_eq!(u32::MIN.to_u32(), Some(u32::MIN as u32));
1527 assert_eq!(u32::MIN.to_u64(), Some(u32::MIN as u64));
1531 fn test_cast_range_u64_min() {
1532 assert_eq!(u64::MIN.to_int(), Some(u64::MIN as int));
1533 assert_eq!(u64::MIN.to_i8(), Some(u64::MIN as i8));
1534 assert_eq!(u64::MIN.to_i16(), Some(u64::MIN as i16));
1535 assert_eq!(u64::MIN.to_i32(), Some(u64::MIN as i32));
1536 assert_eq!(u64::MIN.to_i64(), Some(u64::MIN as i64));
1537 assert_eq!(u64::MIN.to_uint(), Some(u64::MIN as uint));
1538 assert_eq!(u64::MIN.to_u8(), Some(u64::MIN as u8));
1539 assert_eq!(u64::MIN.to_u16(), Some(u64::MIN as u16));
1540 assert_eq!(u64::MIN.to_u32(), Some(u64::MIN as u32));
1541 assert_eq!(u64::MIN.to_u64(), Some(u64::MIN as u64));
1545 fn test_cast_range_uint_max() {
1546 assert_eq!(uint::MAX.to_int(), None);
1547 assert_eq!(uint::MAX.to_i8(), None);
1548 assert_eq!(uint::MAX.to_i16(), None);
1549 assert_eq!(uint::MAX.to_i32(), None);
1550 // uint::MAX.to_i64() is word-size specific
1551 assert_eq!(uint::MAX.to_u8(), None);
1552 assert_eq!(uint::MAX.to_u16(), None);
1553 // uint::MAX.to_u32() is word-size specific
1554 assert_eq!(uint::MAX.to_u64(), Some(uint::MAX as u64));
1556 #[cfg(target_word_size = "32")]
1557 fn check_word_size() {
1558 assert_eq!(uint::MAX.to_u32(), Some(uint::MAX as u32));
1559 assert_eq!(uint::MAX.to_i64(), Some(uint::MAX as i64));
1562 #[cfg(target_word_size = "64")]
1563 fn check_word_size() {
1564 assert_eq!(uint::MAX.to_u32(), None);
1565 assert_eq!(uint::MAX.to_i64(), None);
1572 fn test_cast_range_u8_max() {
1573 assert_eq!(u8::MAX.to_int(), Some(u8::MAX as int));
1574 assert_eq!(u8::MAX.to_i8(), None);
1575 assert_eq!(u8::MAX.to_i16(), Some(u8::MAX as i16));
1576 assert_eq!(u8::MAX.to_i32(), Some(u8::MAX as i32));
1577 assert_eq!(u8::MAX.to_i64(), Some(u8::MAX as i64));
1578 assert_eq!(u8::MAX.to_uint(), Some(u8::MAX as uint));
1579 assert_eq!(u8::MAX.to_u8(), Some(u8::MAX as u8));
1580 assert_eq!(u8::MAX.to_u16(), Some(u8::MAX as u16));
1581 assert_eq!(u8::MAX.to_u32(), Some(u8::MAX as u32));
1582 assert_eq!(u8::MAX.to_u64(), Some(u8::MAX as u64));
1586 fn test_cast_range_u16_max() {
1587 assert_eq!(u16::MAX.to_int(), Some(u16::MAX as int));
1588 assert_eq!(u16::MAX.to_i8(), None);
1589 assert_eq!(u16::MAX.to_i16(), None);
1590 assert_eq!(u16::MAX.to_i32(), Some(u16::MAX as i32));
1591 assert_eq!(u16::MAX.to_i64(), Some(u16::MAX as i64));
1592 assert_eq!(u16::MAX.to_uint(), Some(u16::MAX as uint));
1593 assert_eq!(u16::MAX.to_u8(), None);
1594 assert_eq!(u16::MAX.to_u16(), Some(u16::MAX as u16));
1595 assert_eq!(u16::MAX.to_u32(), Some(u16::MAX as u32));
1596 assert_eq!(u16::MAX.to_u64(), Some(u16::MAX as u64));
1600 fn test_cast_range_u32_max() {
1601 // u32::MAX.to_int() is word-size specific
1602 assert_eq!(u32::MAX.to_i8(), None);
1603 assert_eq!(u32::MAX.to_i16(), None);
1604 assert_eq!(u32::MAX.to_i32(), None);
1605 assert_eq!(u32::MAX.to_i64(), Some(u32::MAX as i64));
1606 assert_eq!(u32::MAX.to_uint(), Some(u32::MAX as uint));
1607 assert_eq!(u32::MAX.to_u8(), None);
1608 assert_eq!(u32::MAX.to_u16(), None);
1609 assert_eq!(u32::MAX.to_u32(), Some(u32::MAX as u32));
1610 assert_eq!(u32::MAX.to_u64(), Some(u32::MAX as u64));
1612 #[cfg(target_word_size = "32")]
1613 fn check_word_size() {
1614 assert_eq!(u32::MAX.to_int(), None);
1617 #[cfg(target_word_size = "64")]
1618 fn check_word_size() {
1619 assert_eq!(u32::MAX.to_int(), Some(u32::MAX as int));
1626 fn test_cast_range_u64_max() {
1627 assert_eq!(u64::MAX.to_int(), None);
1628 assert_eq!(u64::MAX.to_i8(), None);
1629 assert_eq!(u64::MAX.to_i16(), None);
1630 assert_eq!(u64::MAX.to_i32(), None);
1631 assert_eq!(u64::MAX.to_i64(), None);
1632 // u64::MAX.to_uint() is word-size specific
1633 assert_eq!(u64::MAX.to_u8(), None);
1634 assert_eq!(u64::MAX.to_u16(), None);
1635 assert_eq!(u64::MAX.to_u32(), None);
1636 assert_eq!(u64::MAX.to_u64(), Some(u64::MAX as u64));
1638 #[cfg(target_word_size = "32")]
1639 fn check_word_size() {
1640 assert_eq!(u64::MAX.to_uint(), None);
1643 #[cfg(target_word_size = "64")]
1644 fn check_word_size() {
1645 assert_eq!(u64::MAX.to_uint(), Some(u64::MAX as uint));
1652 fn test_saturating_add_uint() {
1654 assert_eq!(3u.saturating_add(5u), 8u);
1655 assert_eq!(3u.saturating_add(MAX-1), MAX);
1656 assert_eq!(MAX.saturating_add(MAX), MAX);
1657 assert_eq!((MAX-2).saturating_add(1), MAX-1);
1661 fn test_saturating_sub_uint() {
1663 assert_eq!(5u.saturating_sub(3u), 2u);
1664 assert_eq!(3u.saturating_sub(5u), 0u);
1665 assert_eq!(0u.saturating_sub(1u), 0u);
1666 assert_eq!((MAX-1).saturating_sub(MAX), 0);
1670 fn test_saturating_add_int() {
1672 assert_eq!(3i.saturating_add(5i), 8i);
1673 assert_eq!(3i.saturating_add(MAX-1), MAX);
1674 assert_eq!(MAX.saturating_add(MAX), MAX);
1675 assert_eq!((MAX-2).saturating_add(1), MAX-1);
1676 assert_eq!(3i.saturating_add(-5i), -2i);
1677 assert_eq!(MIN.saturating_add(-1i), MIN);
1678 assert_eq!((-2i).saturating_add(-MAX), MIN);
1682 fn test_saturating_sub_int() {
1684 assert_eq!(3i.saturating_sub(5i), -2i);
1685 assert_eq!(MIN.saturating_sub(1i), MIN);
1686 assert_eq!((-2i).saturating_sub(MAX), MIN);
1687 assert_eq!(3i.saturating_sub(-5i), 8i);
1688 assert_eq!(3i.saturating_sub(-(MAX-1)), MAX);
1689 assert_eq!(MAX.saturating_sub(-MAX), MAX);
1690 assert_eq!((MAX-2).saturating_sub(-1), MAX-1);
1694 fn test_checked_add() {
1695 let five_less = uint::MAX - 5;
1696 assert_eq!(five_less.checked_add(&0), Some(uint::MAX - 5));
1697 assert_eq!(five_less.checked_add(&1), Some(uint::MAX - 4));
1698 assert_eq!(five_less.checked_add(&2), Some(uint::MAX - 3));
1699 assert_eq!(five_less.checked_add(&3), Some(uint::MAX - 2));
1700 assert_eq!(five_less.checked_add(&4), Some(uint::MAX - 1));
1701 assert_eq!(five_less.checked_add(&5), Some(uint::MAX));
1702 assert_eq!(five_less.checked_add(&6), None);
1703 assert_eq!(five_less.checked_add(&7), None);
1707 fn test_checked_sub() {
1708 assert_eq!(5u.checked_sub(&0), Some(5));
1709 assert_eq!(5u.checked_sub(&1), Some(4));
1710 assert_eq!(5u.checked_sub(&2), Some(3));
1711 assert_eq!(5u.checked_sub(&3), Some(2));
1712 assert_eq!(5u.checked_sub(&4), Some(1));
1713 assert_eq!(5u.checked_sub(&5), Some(0));
1714 assert_eq!(5u.checked_sub(&6), None);
1715 assert_eq!(5u.checked_sub(&7), None);
1719 fn test_checked_mul() {
1720 let third = uint::MAX / 3;
1721 assert_eq!(third.checked_mul(&0), Some(0));
1722 assert_eq!(third.checked_mul(&1), Some(third));
1723 assert_eq!(third.checked_mul(&2), Some(third * 2));
1724 assert_eq!(third.checked_mul(&3), Some(third * 3));
1725 assert_eq!(third.checked_mul(&4), None);
1728 macro_rules! test_next_power_of_two(
1729 ($test_name:ident, $T:ident) => (
1732 assert_eq!(next_power_of_two::<$T>(0), 0);
1733 let mut next_power = 1;
1734 for i in range::<$T>(1, 40) {
1735 assert_eq!(next_power_of_two(i), next_power);
1736 if i == next_power { next_power *= 2 }
1742 test_next_power_of_two!(test_next_power_of_two_u8, u8)
1743 test_next_power_of_two!(test_next_power_of_two_u16, u16)
1744 test_next_power_of_two!(test_next_power_of_two_u32, u32)
1745 test_next_power_of_two!(test_next_power_of_two_u64, u64)
1746 test_next_power_of_two!(test_next_power_of_two_uint, uint)
1748 macro_rules! test_checked_next_power_of_two(
1749 ($test_name:ident, $T:ident) => (
1752 assert_eq!(checked_next_power_of_two::<$T>(0), None);
1753 let mut next_power = 1;
1754 for i in range::<$T>(1, 40) {
1755 assert_eq!(checked_next_power_of_two(i), Some(next_power));
1756 if i == next_power { next_power *= 2 }
1758 assert!(checked_next_power_of_two::<$T>($T::MAX / 2).is_some());
1759 assert_eq!(checked_next_power_of_two::<$T>($T::MAX - 1), None);
1760 assert_eq!(checked_next_power_of_two::<$T>($T::MAX), None);
1765 test_checked_next_power_of_two!(test_checked_next_power_of_two_u8, u8)
1766 test_checked_next_power_of_two!(test_checked_next_power_of_two_u16, u16)
1767 test_checked_next_power_of_two!(test_checked_next_power_of_two_u32, u32)
1768 test_checked_next_power_of_two!(test_checked_next_power_of_two_u64, u64)
1769 test_checked_next_power_of_two!(test_checked_next_power_of_two_uint, uint)
1771 #[deriving(Eq, Show)]
1772 struct Value { x: int }
1774 impl ToPrimitive for Value {
1775 fn to_i64(&self) -> Option<i64> { self.x.to_i64() }
1776 fn to_u64(&self) -> Option<u64> { self.x.to_u64() }
1779 impl FromPrimitive for Value {
1780 fn from_i64(n: i64) -> Option<Value> { Some(Value { x: n as int }) }
1781 fn from_u64(n: u64) -> Option<Value> { Some(Value { x: n as int }) }
1785 fn test_to_primitive() {
1786 let value = Value { x: 5 };
1787 assert_eq!(value.to_int(), Some(5));
1788 assert_eq!(value.to_i8(), Some(5));
1789 assert_eq!(value.to_i16(), Some(5));
1790 assert_eq!(value.to_i32(), Some(5));
1791 assert_eq!(value.to_i64(), Some(5));
1792 assert_eq!(value.to_uint(), Some(5));
1793 assert_eq!(value.to_u8(), Some(5));
1794 assert_eq!(value.to_u16(), Some(5));
1795 assert_eq!(value.to_u32(), Some(5));
1796 assert_eq!(value.to_u64(), Some(5));
1797 assert_eq!(value.to_f32(), Some(5f32));
1798 assert_eq!(value.to_f64(), Some(5f64));
1802 fn test_from_primitive() {
1803 assert_eq!(from_int(5), Some(Value { x: 5 }));
1804 assert_eq!(from_i8(5), Some(Value { x: 5 }));
1805 assert_eq!(from_i16(5), Some(Value { x: 5 }));
1806 assert_eq!(from_i32(5), Some(Value { x: 5 }));
1807 assert_eq!(from_i64(5), Some(Value { x: 5 }));
1808 assert_eq!(from_uint(5), Some(Value { x: 5 }));
1809 assert_eq!(from_u8(5), Some(Value { x: 5 }));
1810 assert_eq!(from_u16(5), Some(Value { x: 5 }));
1811 assert_eq!(from_u32(5), Some(Value { x: 5 }));
1812 assert_eq!(from_u64(5), Some(Value { x: 5 }));
1813 assert_eq!(from_f32(5f32), Some(Value { x: 5 }));
1814 assert_eq!(from_f64(5f64), Some(Value { x: 5 }));
1819 fn naive_pow<T: One + Mul<T, T>>(base: T, exp: uint) -> T {
1820 range(0, exp).fold(one::<T>(), |acc, _| acc * base)
1822 macro_rules! assert_pow(
1823 (($num:expr, $exp:expr) => $expected:expr) => {{
1824 let result = pow($num, $exp);
1825 assert_eq!(result, $expected);
1826 assert_eq!(result, naive_pow($num, $exp));
1829 assert_pow!((3, 0 ) => 1);
1830 assert_pow!((5, 1 ) => 5);
1831 assert_pow!((-4, 2 ) => 16);
1832 assert_pow!((0.5, 5 ) => 0.03125);
1833 assert_pow!((8, 3 ) => 512);
1834 assert_pow!((8.0, 5 ) => 32768.0);
1835 assert_pow!((8.5, 5 ) => 44370.53125);
1836 assert_pow!((2u64, 50) => 1125899906842624);
1844 use self::test::BenchHarness;
1850 fn bench_pow_function(b: &mut BenchHarness) {
1851 let v = slice::from_fn(1024, |n| n);
1852 b.iter(|| {v.iter().fold(0, |old, new| num::pow(old, *new));});