]> git.lizzy.rs Git - rust.git/blob - src/libstd/num/mod.rs
auto merge of #13711 : alexcrichton/rust/snapshots, r=brson
[rust.git] / src / libstd / num / mod.rs
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.
4 //
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.
10
11 //! Numeric traits and functions for generic mathematics
12 //!
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}`.
15
16 #![allow(missing_doc)]
17
18 use clone::Clone;
19 use cmp::{Eq, Ord};
20 use kinds::Copy;
21 use mem::size_of;
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};
26
27 pub mod strconv;
28
29 /// The base trait for numeric types
30 pub trait Num: Eq + Zero + One
31              + Neg<Self>
32              + Add<Self,Self>
33              + Sub<Self,Self>
34              + Mul<Self,Self>
35              + Div<Self,Self>
36              + Rem<Self,Self> {}
37
38 /// Simultaneous division and remainder
39 #[inline]
40 pub fn div_rem<T: Div<T, T> + Rem<T, T>>(x: T, y: T) -> (T, T) {
41     (x / y, x % y)
42 }
43
44 /// Defines an additive identity element for `Self`.
45 ///
46 /// # Deriving
47 ///
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`.
53     ///
54     /// # Laws
55     ///
56     /// ~~~notrust
57     /// a + 0 = a       ∀ a ∈ Self
58     /// 0 + a = a       ∀ a ∈ Self
59     /// ~~~
60     ///
61     /// # Purity
62     ///
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
65     /// `static mut`s.
66     // FIXME (#5527): This should be an associated constant
67     fn zero() -> Self;
68
69     /// Returns `true` if `self` is equal to the additive identity.
70     fn is_zero(&self) -> bool;
71 }
72
73 /// Returns the additive identity, `0`.
74 #[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() }
75
76 /// Defines a multiplicative identity element for `Self`.
77 pub trait One: Mul<Self, Self> {
78     /// Returns the multiplicative identity element of `Self`, `1`.
79     ///
80     /// # Laws
81     ///
82     /// ~~~notrust
83     /// a * 1 = a       ∀ a ∈ Self
84     /// 1 * a = a       ∀ a ∈ Self
85     /// ~~~
86     ///
87     /// # Purity
88     ///
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
91     /// `static mut`s.
92     // FIXME (#5527): This should be an associated constant
93     fn one() -> Self;
94 }
95
96 /// Returns the multiplicative identity, `1`.
97 #[inline(always)] pub fn one<T: One>() -> T { One::one() }
98
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.
102     ///
103     /// For float, f32, and f64, `NaN` will be returned if the number is `NaN`.
104     fn abs(&self) -> Self;
105
106     /// The positive difference of two numbers.
107     ///
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;
111
112     /// Returns the sign of the number.
113     ///
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`
118     ///
119     /// For `int`:
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;
124
125     /// Returns true if the number is positive and false if the number is zero or negative.
126     fn is_positive(&self) -> bool;
127
128     /// Returns true if the number is negative and false if the number is zero or positive.
129     fn is_negative(&self) -> bool;
130 }
131
132 /// Computes the absolute value.
133 ///
134 /// For float, f32, and f64, `NaN` will be returned if the number is `NaN`
135 #[inline(always)]
136 pub fn abs<T: Signed>(value: T) -> T {
137     value.abs()
138 }
139
140 /// The positive difference of two numbers.
141 ///
142 /// Returns `zero` if the number is less than or equal to `other`,
143 /// otherwise the difference between `self` and `other` is returned.
144 #[inline(always)]
145 pub fn abs_sub<T: Signed>(x: T, y: T) -> T {
146     x.abs_sub(&y)
147 }
148
149 /// Returns the sign of the number.
150 ///
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`
155 ///
156 /// For int:
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() }
161
162 /// A trait for values which cannot be negative
163 pub trait Unsigned: Num {}
164
165 /// Raises a value to the power of exp, using exponentiation by squaring.
166 ///
167 /// # Example
168 ///
169 /// ```rust
170 /// use std::num;
171 ///
172 /// assert_eq!(num::pow(2, 4), 16);
173 /// ```
174 #[inline]
175 pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
176     if exp == 1 { base }
177     else {
178         let mut acc = one::<T>();
179         while exp > 0 {
180             if (exp & 1) == 1 {
181                 acc = acc * base;
182             }
183             base = base * base;
184             exp = exp >> 1;
185         }
186         acc
187     }
188 }
189
190 /// Numbers which have upper and lower bounds
191 pub trait Bounded {
192     // FIXME (#5527): These should be associated constants
193     fn min_value() -> Self;
194     fn max_value() -> Self;
195 }
196
197 /// Numbers with a fixed binary representation.
198 pub trait Bitwise: Bounded
199                  + Not<Self>
200                  + BitAnd<Self,Self>
201                  + BitOr<Self,Self>
202                  + BitXor<Self,Self>
203                  + Shl<Self,Self>
204                  + Shr<Self,Self> {
205     /// Returns the number of ones in the binary representation of the number.
206     ///
207     /// # Example
208     ///
209     /// ```rust
210     /// use std::num::Bitwise;
211     ///
212     /// let n = 0b01001100u8;
213     /// assert_eq!(n.count_ones(), 3);
214     /// ```
215     fn count_ones(&self) -> Self;
216
217     /// Returns the number of zeros in the binary representation of the number.
218     ///
219     /// # Example
220     ///
221     /// ```rust
222     /// use std::num::Bitwise;
223     ///
224     /// let n = 0b01001100u8;
225     /// assert_eq!(n.count_zeros(), 5);
226     /// ```
227     #[inline]
228     fn count_zeros(&self) -> Self {
229         (!*self).count_ones()
230     }
231
232     /// Returns the number of leading zeros in the in the binary representation
233     /// of the number.
234     ///
235     /// # Example
236     ///
237     /// ```rust
238     /// use std::num::Bitwise;
239     ///
240     /// let n = 0b0101000u16;
241     /// assert_eq!(n.leading_zeros(), 10);
242     /// ```
243     fn leading_zeros(&self) -> Self;
244
245     /// Returns the number of trailing zeros in the in the binary representation
246     /// of the number.
247     ///
248     /// # Example
249     ///
250     /// ```rust
251     /// use std::num::Bitwise;
252     ///
253     /// let n = 0b0101000u16;
254     /// assert_eq!(n.trailing_zeros(), 3);
255     /// ```
256     fn trailing_zeros(&self) -> Self;
257 }
258
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
263                    + Clone
264                    + Num
265                    + NumCast
266                    + Ord
267                    + Bounded {}
268
269 /// A collection of traits relevant to primitive signed and unsigned integers
270 pub trait Int: Primitive
271              + Bitwise
272              + CheckedAdd
273              + CheckedSub
274              + CheckedMul
275              + CheckedDiv
276              + Show
277              + Binary
278              + Octal
279              + LowerHex
280              + UpperHex {}
281
282 /// Returns the smallest power of 2 greater than or equal to `n`.
283 #[inline]
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();
291     }
292     tmp + one()
293 }
294
295 // Returns `true` iff `n == 2^k` for some k.
296 #[inline]
297 pub fn is_power_of_two<T: Unsigned + Int>(n: T) -> bool {
298     (n - one()) & n == zero()
299 }
300
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`.
304 #[inline]
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();
312     }
313     tmp.checked_add(&one())
314 }
315
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
320     FPNaN,
321     /// Positive or negative infinity
322     FPInfinite ,
323     /// Positive or negative zero
324     FPZero,
325     /// De-normalized floating point representation (less precise than `FPNormal`)
326     FPSubnormal,
327     /// A regular floating point number
328     FPNormal,
329 }
330
331 /// Operations on primitive floating point numbers.
332 // FIXME(#5527): In a future version of Rust, many of these functions will
333 //               become constants.
334 //
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.
339     fn nan() -> Self;
340     /// Returns the infinite value.
341     fn infinity() -> Self;
342     /// Returns the negative infinite value.
343     fn neg_infinity() -> Self;
344     /// Returns -0.0.
345     fn neg_zero() -> Self;
346
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
350     /// false otherwise.
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;
358
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;
373
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,
378     /// satisfying:
379     ///
380     ///  * `self = x * pow(2, exp)`
381     ///
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);
386
387     /// Returns the next representable floating-point value in the direction of
388     /// `other`.
389     fn next_after(self, other: Self) -> Self;
390
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
396     /// `0.0`.
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;
402
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;
407
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;
414
415     /// Raise a number to an integer power.
416     ///
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;
421
422     /// sqrt(2.0).
423     fn sqrt2() -> Self;
424     /// 1.0 / sqrt(2.0).
425     fn frac_1_sqrt2() -> Self;
426
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;
436
437     /// Archimedes' constant.
438     fn pi() -> Self;
439     /// 2.0 * pi.
440     fn two_pi() -> Self;
441     /// pi / 2.0.
442     fn frac_pi_2() -> Self;
443     /// pi / 3.0.
444     fn frac_pi_3() -> Self;
445     /// pi / 4.0.
446     fn frac_pi_4() -> Self;
447     /// pi / 6.0.
448     fn frac_pi_6() -> Self;
449     /// pi / 8.0.
450     fn frac_pi_8() -> Self;
451     /// 1.0 / pi.
452     fn frac_1_pi() -> Self;
453     /// 2.0 / pi.
454     fn frac_2_pi() -> Self;
455     /// 2.0 / sqrt(pi).
456     fn frac_2_sqrtpi() -> Self;
457
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;
464
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
467     /// [-1, 1].
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
471     /// [-1, 1].
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);
482
483     /// Euler's number.
484     fn e() -> Self;
485     /// log2(e).
486     fn log2_e() -> Self;
487     /// log10(e).
488     fn log10_e() -> Self;
489     /// ln(2.0).
490     fn ln_2() -> Self;
491     /// ln(10.0).
492     fn ln_10() -> Self;
493
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.
502     fn ln(self) -> Self;
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;
512
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;
525
526     /// Convert radians to degrees.
527     fn to_degrees(self) -> Self;
528     /// Convert degrees to radians.
529     fn to_radians(self) -> Self;
530 }
531
532 /// A generic trait for converting a value to a number.
533 pub trait ToPrimitive {
534     /// Converts the value of `self` to an `int`.
535     #[inline]
536     fn to_int(&self) -> Option<int> {
537         self.to_i64().and_then(|x| x.to_int())
538     }
539
540     /// Converts the value of `self` to an `i8`.
541     #[inline]
542     fn to_i8(&self) -> Option<i8> {
543         self.to_i64().and_then(|x| x.to_i8())
544     }
545
546     /// Converts the value of `self` to an `i16`.
547     #[inline]
548     fn to_i16(&self) -> Option<i16> {
549         self.to_i64().and_then(|x| x.to_i16())
550     }
551
552     /// Converts the value of `self` to an `i32`.
553     #[inline]
554     fn to_i32(&self) -> Option<i32> {
555         self.to_i64().and_then(|x| x.to_i32())
556     }
557
558     /// Converts the value of `self` to an `i64`.
559     fn to_i64(&self) -> Option<i64>;
560
561     /// Converts the value of `self` to an `uint`.
562     #[inline]
563     fn to_uint(&self) -> Option<uint> {
564         self.to_u64().and_then(|x| x.to_uint())
565     }
566
567     /// Converts the value of `self` to an `u8`.
568     #[inline]
569     fn to_u8(&self) -> Option<u8> {
570         self.to_u64().and_then(|x| x.to_u8())
571     }
572
573     /// Converts the value of `self` to an `u16`.
574     #[inline]
575     fn to_u16(&self) -> Option<u16> {
576         self.to_u64().and_then(|x| x.to_u16())
577     }
578
579     /// Converts the value of `self` to an `u32`.
580     #[inline]
581     fn to_u32(&self) -> Option<u32> {
582         self.to_u64().and_then(|x| x.to_u32())
583     }
584
585     /// Converts the value of `self` to an `u64`.
586     #[inline]
587     fn to_u64(&self) -> Option<u64>;
588
589     /// Converts the value of `self` to an `f32`.
590     #[inline]
591     fn to_f32(&self) -> Option<f32> {
592         self.to_f64().and_then(|x| x.to_f32())
593     }
594
595     /// Converts the value of `self` to an `f64`.
596     #[inline]
597     fn to_f64(&self) -> Option<f64> {
598         self.to_i64().and_then(|x| x.to_f64())
599     }
600 }
601
602 macro_rules! impl_to_primitive_int_to_int(
603     ($SrcT:ty, $DstT:ty) => (
604         {
605             if size_of::<$SrcT>() <= size_of::<$DstT>() {
606                 Some(*self as $DstT)
607             } else {
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 {
612                     Some(*self as $DstT)
613                 } else {
614                     None
615                 }
616             }
617         }
618     )
619 )
620
621 macro_rules! impl_to_primitive_int_to_uint(
622     ($SrcT:ty, $DstT:ty) => (
623         {
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 {
627                 Some(*self as $DstT)
628             } else {
629                 None
630             }
631         }
632     )
633 )
634
635 macro_rules! impl_to_primitive_int(
636     ($T:ty) => (
637         impl ToPrimitive for $T {
638             #[inline]
639             fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int) }
640             #[inline]
641             fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8) }
642             #[inline]
643             fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16) }
644             #[inline]
645             fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32) }
646             #[inline]
647             fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64) }
648
649             #[inline]
650             fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint) }
651             #[inline]
652             fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8) }
653             #[inline]
654             fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16) }
655             #[inline]
656             fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32) }
657             #[inline]
658             fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64) }
659
660             #[inline]
661             fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
662             #[inline]
663             fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
664         }
665     )
666 )
667
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)
673
674 macro_rules! impl_to_primitive_uint_to_int(
675     ($DstT:ty) => (
676         {
677             let max_value: $DstT = Bounded::max_value();
678             if *self as u64 <= max_value as u64 {
679                 Some(*self as $DstT)
680             } else {
681                 None
682             }
683         }
684     )
685 )
686
687 macro_rules! impl_to_primitive_uint_to_uint(
688     ($SrcT:ty, $DstT:ty) => (
689         {
690             if size_of::<$SrcT>() <= size_of::<$DstT>() {
691                 Some(*self as $DstT)
692             } else {
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 {
696                     Some(*self as $DstT)
697                 } else {
698                     None
699                 }
700             }
701         }
702     )
703 )
704
705 macro_rules! impl_to_primitive_uint(
706     ($T:ty) => (
707         impl ToPrimitive for $T {
708             #[inline]
709             fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int) }
710             #[inline]
711             fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8) }
712             #[inline]
713             fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16) }
714             #[inline]
715             fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32) }
716             #[inline]
717             fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64) }
718
719             #[inline]
720             fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint) }
721             #[inline]
722             fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8) }
723             #[inline]
724             fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16) }
725             #[inline]
726             fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32) }
727             #[inline]
728             fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64) }
729
730             #[inline]
731             fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
732             #[inline]
733             fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
734         }
735     )
736 )
737
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)
743
744 macro_rules! impl_to_primitive_float_to_float(
745     ($SrcT:ty, $DstT:ty) => (
746         if size_of::<$SrcT>() <= size_of::<$DstT>() {
747             Some(*self as $DstT)
748         } else {
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 {
752                 Some(*self as $DstT)
753             } else {
754                 None
755             }
756         }
757     )
758 )
759
760 macro_rules! impl_to_primitive_float(
761     ($T:ty) => (
762         impl ToPrimitive for $T {
763             #[inline]
764             fn to_int(&self) -> Option<int> { Some(*self as int) }
765             #[inline]
766             fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
767             #[inline]
768             fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
769             #[inline]
770             fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
771             #[inline]
772             fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
773
774             #[inline]
775             fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
776             #[inline]
777             fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
778             #[inline]
779             fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
780             #[inline]
781             fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
782             #[inline]
783             fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
784
785             #[inline]
786             fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32) }
787             #[inline]
788             fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64) }
789         }
790     )
791 )
792
793 impl_to_primitive_float!(f32)
794 impl_to_primitive_float!(f64)
795
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.
800     #[inline]
801     fn from_int(n: int) -> Option<Self> {
802         FromPrimitive::from_i64(n as i64)
803     }
804
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.
807     #[inline]
808     fn from_i8(n: i8) -> Option<Self> {
809         FromPrimitive::from_i64(n as i64)
810     }
811
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.
814     #[inline]
815     fn from_i16(n: i16) -> Option<Self> {
816         FromPrimitive::from_i64(n as i64)
817     }
818
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.
821     #[inline]
822     fn from_i32(n: i32) -> Option<Self> {
823         FromPrimitive::from_i64(n as i64)
824     }
825
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>;
829
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.
832     #[inline]
833     fn from_uint(n: uint) -> Option<Self> {
834         FromPrimitive::from_u64(n as u64)
835     }
836
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.
839     #[inline]
840     fn from_u8(n: u8) -> Option<Self> {
841         FromPrimitive::from_u64(n as u64)
842     }
843
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.
846     #[inline]
847     fn from_u16(n: u16) -> Option<Self> {
848         FromPrimitive::from_u64(n as u64)
849     }
850
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.
853     #[inline]
854     fn from_u32(n: u32) -> Option<Self> {
855         FromPrimitive::from_u64(n as u64)
856     }
857
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>;
861
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.
864     #[inline]
865     fn from_f32(n: f32) -> Option<Self> {
866         FromPrimitive::from_f64(n as f64)
867     }
868
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.
871     #[inline]
872     fn from_f64(n: f64) -> Option<Self> {
873         FromPrimitive::from_i64(n as i64)
874     }
875 }
876
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)
880 }
881
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)
885 }
886
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)
890 }
891
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)
895 }
896
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)
900 }
901
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)
905 }
906
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)
910 }
911
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)
915 }
916
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)
920 }
921
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)
925 }
926
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)
930 }
931
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)
935 }
936
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 }
945
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 }
951
952             #[inline] fn from_f32(n: f32) -> Option<$T> { $to_ty }
953             #[inline] fn from_f64(n: f64) -> Option<$T> { $to_ty }
954         }
955     )
956 )
957
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())
970
971 /// Cast from one machine scalar to another.
972 ///
973 /// # Example
974 ///
975 /// ```
976 /// use std::num;
977 ///
978 /// let twenty: f32 = num::cast(0x14).unwrap();
979 /// assert_eq!(twenty, 20f32);
980 /// ```
981 ///
982 #[inline]
983 pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
984     NumCast::from(n)
985 }
986
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>;
992 }
993
994 macro_rules! impl_num_cast(
995     ($T:ty, $conv:ident) => (
996         impl NumCast for $T {
997             #[inline]
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
1001                 n.$conv()
1002             }
1003         }
1004     )
1005 )
1006
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)
1019
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;
1023 }
1024
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>;
1028 }
1029
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)
1033 }
1034
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;
1040
1041     /// Saturating subtraction operator.
1042     /// Returns a-b, saturating at the numeric bounds instead of overflowing.
1043     fn saturating_sub(self, v: Self) -> Self;
1044 }
1045
1046 impl<T: CheckedAdd + CheckedSub + Zero + Ord + Bounded> Saturating for T {
1047     #[inline]
1048     fn saturating_add(self, v: T) -> T {
1049         match self.checked_add(&v) {
1050             Some(x) => x,
1051             None => if v >= Zero::zero() {
1052                 Bounded::max_value()
1053             } else {
1054                 Bounded::min_value()
1055             }
1056         }
1057     }
1058
1059     #[inline]
1060     fn saturating_sub(self, v: T) -> T {
1061         match self.checked_sub(&v) {
1062             Some(x) => x,
1063             None => if v >= Zero::zero() {
1064                 Bounded::min_value()
1065             } else {
1066                 Bounded::max_value()
1067             }
1068         }
1069     }
1070 }
1071
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>;
1076 }
1077
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>;
1082 }
1083
1084 /// Performs multiplication that returns `None` instead of wrapping around on underflow or
1085 /// overflow.
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>;
1090 }
1091
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>;
1097 }
1098
1099 /// Helper function for testing numeric operations
1100 #[cfg(test)]
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());
1107
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);
1113 }
1114
1115 #[cfg(test)]
1116 mod tests {
1117     use prelude::*;
1118     use super::*;
1119     use i8;
1120     use i16;
1121     use i32;
1122     use i64;
1123     use int;
1124     use u8;
1125     use u16;
1126     use u32;
1127     use u64;
1128     use uint;
1129
1130     macro_rules! test_cast_20(
1131         ($_20:expr) => ({
1132             let _20 = $_20;
1133
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());
1146
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());
1159
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());
1172         })
1173     )
1174
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) }
1187
1188     #[test]
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);
1200
1201         #[cfg(target_word_size = "32")]
1202         fn check_word_size() {
1203             assert_eq!(int::MIN.to_i32(), Some(int::MIN as i32));
1204         }
1205
1206         #[cfg(target_word_size = "64")]
1207         fn check_word_size() {
1208             assert_eq!(int::MIN.to_i32(), None);
1209         }
1210
1211         check_word_size();
1212     }
1213
1214     #[test]
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);
1226     }
1227
1228     #[test]
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);
1240     }
1241
1242     #[test]
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);
1254     }
1255
1256     #[test]
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);
1268
1269         #[cfg(target_word_size = "32")]
1270         fn check_word_size() {
1271             assert_eq!(i64::MIN.to_int(), None);
1272         }
1273
1274         #[cfg(target_word_size = "64")]
1275         fn check_word_size() {
1276             assert_eq!(i64::MIN.to_int(), Some(i64::MIN as int));
1277         }
1278
1279         check_word_size();
1280     }
1281
1282     #[test]
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));
1293
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));
1298         }
1299
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);
1304         }
1305
1306         check_word_size();
1307     }
1308
1309     #[test]
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));
1321     }
1322
1323     #[test]
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));
1335     }
1336
1337     #[test]
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));
1349     }
1350
1351     #[test]
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));
1363
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);
1368         }
1369
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));
1374         }
1375
1376         check_word_size();
1377     }
1378
1379     #[test]
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));
1391     }
1392
1393     #[test]
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));
1405     }
1406
1407     #[test]
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));
1419     }
1420
1421     #[test]
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));
1433     }
1434
1435     #[test]
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));
1447     }
1448
1449     #[test]
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));
1460
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));
1465         }
1466
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);
1471         }
1472
1473         check_word_size();
1474     }
1475
1476     #[test]
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));
1488     }
1489
1490     #[test]
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));
1502     }
1503
1504     #[test]
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));
1516
1517         #[cfg(target_word_size = "32")]
1518         fn check_word_size() {
1519             assert_eq!(u32::MAX.to_int(),  None);
1520         }
1521
1522         #[cfg(target_word_size = "64")]
1523         fn check_word_size() {
1524             assert_eq!(u32::MAX.to_int(),  Some(u32::MAX as int));
1525         }
1526
1527         check_word_size();
1528     }
1529
1530     #[test]
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));
1542
1543         #[cfg(target_word_size = "32")]
1544         fn check_word_size() {
1545             assert_eq!(u64::MAX.to_uint(), None);
1546         }
1547
1548         #[cfg(target_word_size = "64")]
1549         fn check_word_size() {
1550             assert_eq!(u64::MAX.to_uint(), Some(u64::MAX as uint));
1551         }
1552
1553         check_word_size();
1554     }
1555
1556     #[test]
1557     fn test_saturating_add_uint() {
1558         use uint::MAX;
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);
1563     }
1564
1565     #[test]
1566     fn test_saturating_sub_uint() {
1567         use uint::MAX;
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);
1572     }
1573
1574     #[test]
1575     fn test_saturating_add_int() {
1576         use int::{MIN,MAX};
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);
1584     }
1585
1586     #[test]
1587     fn test_saturating_sub_int() {
1588         use int::{MIN,MAX};
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);
1596     }
1597
1598     #[test]
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);
1609     }
1610
1611     #[test]
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);
1621     }
1622
1623     #[test]
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);
1631     }
1632
1633     macro_rules! test_next_power_of_two(
1634         ($test_name:ident, $T:ident) => (
1635             fn $test_name() {
1636                 #![test]
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 }
1642                 }
1643             }
1644         )
1645     )
1646
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)
1652
1653     macro_rules! test_checked_next_power_of_two(
1654         ($test_name:ident, $T:ident) => (
1655             fn $test_name() {
1656                 #![test]
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 }
1662                 }
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);
1666             }
1667         )
1668     )
1669
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)
1675
1676     #[deriving(Eq, Show)]
1677     struct Value { x: int }
1678
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() }
1682     }
1683
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 }) }
1687     }
1688
1689     #[test]
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));
1704     }
1705
1706     #[test]
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 }));
1720     }
1721
1722     #[test]
1723     fn test_pow() {
1724         fn naive_pow<T: One + Mul<T, T>>(base: T, exp: uint) -> T {
1725             range(0, exp).fold(one::<T>(), |acc, _| acc * base)
1726         }
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));
1732             }}
1733         )
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);
1742     }
1743 }
1744
1745
1746 #[cfg(test)]
1747 mod bench {
1748     extern crate test;
1749     use self::test::Bencher;
1750     use num;
1751     use prelude::*;
1752
1753     #[bench]
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));});
1757     }
1758 }