]> git.lizzy.rs Git - rust.git/blob - src/libstd/num/mod.rs
libstd: Document the following modules:
[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::Pod;
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 pub trait Unsigned: Num {}
163
164 /// A collection of rounding operations.
165 pub trait Round {
166     /// Return the largest integer less than or equal to a number.
167     fn floor(&self) -> Self;
168
169     /// Return the smallest integer greater than or equal to a number.
170     fn ceil(&self) -> Self;
171
172     /// Return the nearest integer to a number. Round half-way cases away from
173     /// `0.0`.
174     fn round(&self) -> Self;
175
176     /// Return the integer part of a number.
177     fn trunc(&self) -> Self;
178
179     /// Return the fractional part of a number.
180     fn fract(&self) -> Self;
181 }
182
183 /// Raises a value to the power of exp, using exponentiation by squaring.
184 ///
185 /// # Example
186 ///
187 /// ```rust
188 /// use std::num;
189 ///
190 /// assert_eq!(num::pow(2, 4), 16);
191 /// ```
192 #[inline]
193 pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
194     if exp == 1 { base }
195     else {
196         let mut acc = one::<T>();
197         while exp > 0 {
198             if (exp & 1) == 1 {
199                 acc = acc * base;
200             }
201             base = base * base;
202             exp = exp >> 1;
203         }
204         acc
205     }
206 }
207
208 pub trait Bounded {
209     // FIXME (#5527): These should be associated constants
210     fn min_value() -> Self;
211     fn max_value() -> Self;
212 }
213
214 /// Numbers with a fixed binary representation.
215 pub trait Bitwise: Bounded
216                  + Not<Self>
217                  + BitAnd<Self,Self>
218                  + BitOr<Self,Self>
219                  + BitXor<Self,Self>
220                  + Shl<Self,Self>
221                  + Shr<Self,Self> {
222     /// Returns the number of ones in the binary representation of the number.
223     ///
224     /// # Example
225     ///
226     /// ```rust
227     /// use std::num::Bitwise;
228     ///
229     /// let n = 0b01001100u8;
230     /// assert_eq!(n.count_ones(), 3);
231     /// ```
232     fn count_ones(&self) -> Self;
233
234     /// Returns the number of zeros in the binary representation of the number.
235     ///
236     /// # Example
237     ///
238     /// ```rust
239     /// use std::num::Bitwise;
240     ///
241     /// let n = 0b01001100u8;
242     /// assert_eq!(n.count_zeros(), 5);
243     /// ```
244     #[inline]
245     fn count_zeros(&self) -> Self {
246         (!*self).count_ones()
247     }
248
249     /// Returns the number of leading zeros in the in the binary representation
250     /// of the number.
251     ///
252     /// # Example
253     ///
254     /// ```rust
255     /// use std::num::Bitwise;
256     ///
257     /// let n = 0b0101000u16;
258     /// assert_eq!(n.leading_zeros(), 10);
259     /// ```
260     fn leading_zeros(&self) -> Self;
261
262     /// Returns the number of trailing zeros in the in the binary representation
263     /// of the number.
264     ///
265     /// # Example
266     ///
267     /// ```rust
268     /// use std::num::Bitwise;
269     ///
270     /// let n = 0b0101000u16;
271     /// assert_eq!(n.trailing_zeros(), 3);
272     /// ```
273     fn trailing_zeros(&self) -> Self;
274 }
275
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
280                    + Clone
281                    + Num
282                    + NumCast
283                    + Ord
284                    + Bounded {}
285
286 /// A collection of traits relevant to primitive signed and unsigned integers
287 pub trait Int: Primitive
288              + Bitwise
289              + CheckedAdd
290              + CheckedSub
291              + CheckedMul
292              + CheckedDiv
293              + Show
294              + Binary
295              + Octal
296              + LowerHex
297              + UpperHex {}
298
299 /// Returns the smallest power of 2 greater than or equal to `n`.
300 #[inline]
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();
308     }
309     tmp + one()
310 }
311
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`.
315 #[inline]
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();
323     }
324     tmp.checked_add(&one())
325 }
326
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
331     FPNaN,
332     /// Positive or negative infinity
333     FPInfinite ,
334     /// Positive or negative zero
335     FPZero,
336     /// De-normalized floating point representation (less precise than `FPNormal`)
337     FPSubnormal,
338     /// A regular floating point number
339     FPNormal,
340 }
341
342 /// Operations on primitive floating point numbers.
343 ///
344 /// TODO(#5527): In a future version of Rust, many of these functions will become constants.
345 ///
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;
353
354     /// Returns the NaN value.
355     fn nan() -> Self;
356
357     /// Returns the infinite value.
358     fn infinity() -> Self;
359
360     /// Returns the negative infinite value.
361     fn neg_infinity() -> Self;
362
363     /// Returns -0.0.
364     fn neg_zero() -> Self;
365
366     /// Returns true if this value is NaN and false otherwise.
367     fn is_nan(&self) -> bool;
368
369     /// Returns true if this value is positive infinity or negative infinity and false otherwise.
370     fn is_infinite(&self) -> bool;
371
372     /// Returns true if this number is neither infinite nor NaN.
373     fn is_finite(&self) -> bool;
374
375     /// Returns true if this number is neither zero, infinite, denormal, or NaN.
376     fn is_normal(&self) -> bool;
377
378     /// Returns the category that this number falls into.
379     fn classify(&self) -> FPCategory;
380
381     /// Returns the number of binary digits of mantissa that this type supports.
382     fn mantissa_digits(unused_self: Option<Self>) -> uint;
383
384     /// Returns the number of binary digits of exponent that this type supports.
385     fn digits(unused_self: Option<Self>) -> uint;
386
387     /// Returns the smallest positive number that this type can represent.
388     fn epsilon() -> Self;
389
390     /// Returns the minimum binary exponent that this type can represent.
391     fn min_exp(unused_self: Option<Self>) -> int;
392
393     /// Returns the maximum binary exponent that this type can represent.
394     fn max_exp(unused_self: Option<Self>) -> int;
395
396     /// Returns the minimum base-10 exponent that this type can represent.
397     fn min_10_exp(unused_self: Option<Self>) -> int;
398
399     /// Returns the maximum base-10 exponent that this type can represent.
400     fn max_10_exp(unused_self: Option<Self>) -> int;
401
402     /// Constructs a floating point number created by multiplying `x` by 2 raised to the power of
403     /// `exp`.
404     fn ldexp(x: Self, exp: int) -> Self;
405
406     /// Breaks the number into a normalized fraction and a base-2 exponent, satisfying:
407     ///
408     ///  * `self = x * pow(2, exp)`
409     ///
410     ///  * `0.5 <= abs(x) < 1.0`
411     fn frexp(&self) -> (Self, int);
412
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;
416
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;
420
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;
425
426     /// Returns the next representable floating-point value in the direction of `other`.
427     fn next_after(&self, other: Self) -> Self;
428
429     /// Returns the mantissa, exponent and sign as integers, respectively.
430     fn integer_decode(&self) -> (u64, i16, i8);
431
432     /// Archimedes' constant.
433     fn pi() -> Self;
434
435     /// 2.0 * pi.
436     fn two_pi() -> Self;
437
438     /// pi / 2.0.
439     fn frac_pi_2() -> Self;
440
441     /// pi / 3.0.
442     fn frac_pi_3() -> Self;
443
444     /// pi / 4.0.
445     fn frac_pi_4() -> Self;
446
447     /// pi / 6.0.
448     fn frac_pi_6() -> Self;
449
450     /// pi / 8.0.
451     fn frac_pi_8() -> Self;
452
453     /// 1.0 / pi.
454     fn frac_1_pi() -> Self;
455
456     /// 2.0 / pi.
457     fn frac_2_pi() -> Self;
458
459     /// 2.0 / sqrt(pi).
460     fn frac_2_sqrtpi() -> Self;
461
462     /// sqrt(2.0).
463     fn sqrt2() -> Self;
464
465     /// 1.0 / sqrt(2.0).
466     fn frac_1_sqrt2() -> Self;
467
468     /// Euler's number.
469     fn e() -> Self;
470
471     /// log2(e).
472     fn log2_e() -> Self;
473
474     /// log10(e).
475     fn log10_e() -> Self;
476
477     /// ln(2.0).
478     fn ln_2() -> Self;
479
480     /// ln(10.0).
481     fn ln_10() -> Self;
482
483     /// Take the reciprocal (inverse) of a number, `1/x`.
484     fn recip(&self) -> Self;
485
486     /// Raise a number to a power.
487     fn powf(&self, n: &Self) -> Self;
488
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;
498
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;
505
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
508     /// [-1, 1].
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
512     /// [-1, 1].
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);
523
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;
536
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;
549
550     /// Convert radians to degrees.
551     fn to_degrees(&self) -> Self;
552     /// Convert degrees to radians.
553     fn to_radians(&self) -> Self;
554 }
555
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.
563 ///
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) }
567
568 /// Raise a number to a power.
569 ///
570 /// # Example
571 ///
572 /// ```rust
573 /// use std::num;
574 ///
575 /// let sixteen: f64 = num::powf(2.0, 4.0);
576 /// assert_eq!(sixteen, 16.0);
577 /// ```
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) }
588 /// Sine function.
589 #[inline(always)] pub fn sin<T: Float>(value: T) -> T { value.sin() }
590 /// Cosine function.
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() }
628
629 /// A generic trait for converting a value to a number.
630 pub trait ToPrimitive {
631     /// Converts the value of `self` to an `int`.
632     #[inline]
633     fn to_int(&self) -> Option<int> {
634         self.to_i64().and_then(|x| x.to_int())
635     }
636
637     /// Converts the value of `self` to an `i8`.
638     #[inline]
639     fn to_i8(&self) -> Option<i8> {
640         self.to_i64().and_then(|x| x.to_i8())
641     }
642
643     /// Converts the value of `self` to an `i16`.
644     #[inline]
645     fn to_i16(&self) -> Option<i16> {
646         self.to_i64().and_then(|x| x.to_i16())
647     }
648
649     /// Converts the value of `self` to an `i32`.
650     #[inline]
651     fn to_i32(&self) -> Option<i32> {
652         self.to_i64().and_then(|x| x.to_i32())
653     }
654
655     /// Converts the value of `self` to an `i64`.
656     fn to_i64(&self) -> Option<i64>;
657
658     /// Converts the value of `self` to an `uint`.
659     #[inline]
660     fn to_uint(&self) -> Option<uint> {
661         self.to_u64().and_then(|x| x.to_uint())
662     }
663
664     /// Converts the value of `self` to an `u8`.
665     #[inline]
666     fn to_u8(&self) -> Option<u8> {
667         self.to_u64().and_then(|x| x.to_u8())
668     }
669
670     /// Converts the value of `self` to an `u16`.
671     #[inline]
672     fn to_u16(&self) -> Option<u16> {
673         self.to_u64().and_then(|x| x.to_u16())
674     }
675
676     /// Converts the value of `self` to an `u32`.
677     #[inline]
678     fn to_u32(&self) -> Option<u32> {
679         self.to_u64().and_then(|x| x.to_u32())
680     }
681
682     /// Converts the value of `self` to an `u64`.
683     #[inline]
684     fn to_u64(&self) -> Option<u64>;
685
686     /// Converts the value of `self` to an `f32`.
687     #[inline]
688     fn to_f32(&self) -> Option<f32> {
689         self.to_f64().and_then(|x| x.to_f32())
690     }
691
692     /// Converts the value of `self` to an `f64`.
693     #[inline]
694     fn to_f64(&self) -> Option<f64> {
695         self.to_i64().and_then(|x| x.to_f64())
696     }
697 }
698
699 macro_rules! impl_to_primitive_int_to_int(
700     ($SrcT:ty, $DstT:ty) => (
701         {
702             if size_of::<$SrcT>() <= size_of::<$DstT>() {
703                 Some(*self as $DstT)
704             } else {
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 {
709                     Some(*self as $DstT)
710                 } else {
711                     None
712                 }
713             }
714         }
715     )
716 )
717
718 macro_rules! impl_to_primitive_int_to_uint(
719     ($SrcT:ty, $DstT:ty) => (
720         {
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 {
724                 Some(*self as $DstT)
725             } else {
726                 None
727             }
728         }
729     )
730 )
731
732 macro_rules! impl_to_primitive_int(
733     ($T:ty) => (
734         impl ToPrimitive for $T {
735             #[inline]
736             fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int) }
737             #[inline]
738             fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8) }
739             #[inline]
740             fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16) }
741             #[inline]
742             fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32) }
743             #[inline]
744             fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64) }
745
746             #[inline]
747             fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint) }
748             #[inline]
749             fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8) }
750             #[inline]
751             fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16) }
752             #[inline]
753             fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32) }
754             #[inline]
755             fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64) }
756
757             #[inline]
758             fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
759             #[inline]
760             fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
761         }
762     )
763 )
764
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)
770
771 macro_rules! impl_to_primitive_uint_to_int(
772     ($DstT:ty) => (
773         {
774             let max_value: $DstT = Bounded::max_value();
775             if *self as u64 <= max_value as u64 {
776                 Some(*self as $DstT)
777             } else {
778                 None
779             }
780         }
781     )
782 )
783
784 macro_rules! impl_to_primitive_uint_to_uint(
785     ($SrcT:ty, $DstT:ty) => (
786         {
787             if size_of::<$SrcT>() <= size_of::<$DstT>() {
788                 Some(*self as $DstT)
789             } else {
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 {
793                     Some(*self as $DstT)
794                 } else {
795                     None
796                 }
797             }
798         }
799     )
800 )
801
802 macro_rules! impl_to_primitive_uint(
803     ($T:ty) => (
804         impl ToPrimitive for $T {
805             #[inline]
806             fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int) }
807             #[inline]
808             fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8) }
809             #[inline]
810             fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16) }
811             #[inline]
812             fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32) }
813             #[inline]
814             fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64) }
815
816             #[inline]
817             fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint) }
818             #[inline]
819             fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8) }
820             #[inline]
821             fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16) }
822             #[inline]
823             fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32) }
824             #[inline]
825             fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64) }
826
827             #[inline]
828             fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
829             #[inline]
830             fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
831         }
832     )
833 )
834
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)
840
841 macro_rules! impl_to_primitive_float_to_float(
842     ($SrcT:ty, $DstT:ty) => (
843         if size_of::<$SrcT>() <= size_of::<$DstT>() {
844             Some(*self as $DstT)
845         } else {
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 {
849                 Some(*self as $DstT)
850             } else {
851                 None
852             }
853         }
854     )
855 )
856
857 macro_rules! impl_to_primitive_float(
858     ($T:ty) => (
859         impl ToPrimitive for $T {
860             #[inline]
861             fn to_int(&self) -> Option<int> { Some(*self as int) }
862             #[inline]
863             fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
864             #[inline]
865             fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
866             #[inline]
867             fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
868             #[inline]
869             fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
870
871             #[inline]
872             fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
873             #[inline]
874             fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
875             #[inline]
876             fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
877             #[inline]
878             fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
879             #[inline]
880             fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
881
882             #[inline]
883             fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32) }
884             #[inline]
885             fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64) }
886         }
887     )
888 )
889
890 impl_to_primitive_float!(f32)
891 impl_to_primitive_float!(f64)
892
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.
897     #[inline]
898     fn from_int(n: int) -> Option<Self> {
899         FromPrimitive::from_i64(n as i64)
900     }
901
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.
904     #[inline]
905     fn from_i8(n: i8) -> Option<Self> {
906         FromPrimitive::from_i64(n as i64)
907     }
908
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.
911     #[inline]
912     fn from_i16(n: i16) -> Option<Self> {
913         FromPrimitive::from_i64(n as i64)
914     }
915
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.
918     #[inline]
919     fn from_i32(n: i32) -> Option<Self> {
920         FromPrimitive::from_i64(n as i64)
921     }
922
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>;
926
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.
929     #[inline]
930     fn from_uint(n: uint) -> Option<Self> {
931         FromPrimitive::from_u64(n as u64)
932     }
933
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.
936     #[inline]
937     fn from_u8(n: u8) -> Option<Self> {
938         FromPrimitive::from_u64(n as u64)
939     }
940
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.
943     #[inline]
944     fn from_u16(n: u16) -> Option<Self> {
945         FromPrimitive::from_u64(n as u64)
946     }
947
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.
950     #[inline]
951     fn from_u32(n: u32) -> Option<Self> {
952         FromPrimitive::from_u64(n as u64)
953     }
954
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>;
958
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.
961     #[inline]
962     fn from_f32(n: f32) -> Option<Self> {
963         FromPrimitive::from_f64(n as f64)
964     }
965
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.
968     #[inline]
969     fn from_f64(n: f64) -> Option<Self> {
970         FromPrimitive::from_i64(n as i64)
971     }
972 }
973
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)
977 }
978
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)
982 }
983
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)
987 }
988
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)
992 }
993
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)
997 }
998
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)
1002 }
1003
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)
1007 }
1008
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)
1012 }
1013
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)
1017 }
1018
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)
1022 }
1023
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)
1027 }
1028
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)
1032 }
1033
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 }
1042
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 }
1048
1049             #[inline] fn from_f32(n: f32) -> Option<$T> { $to_ty }
1050             #[inline] fn from_f64(n: f64) -> Option<$T> { $to_ty }
1051         }
1052     )
1053 )
1054
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())
1067
1068 /// Cast from one machine scalar to another.
1069 ///
1070 /// # Example
1071 ///
1072 /// ```
1073 /// use std::num;
1074 ///
1075 /// let twenty: f32 = num::cast(0x14).unwrap();
1076 /// assert_eq!(twenty, 20f32);
1077 /// ```
1078 ///
1079 #[inline]
1080 pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
1081     NumCast::from(n)
1082 }
1083
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>;
1089 }
1090
1091 macro_rules! impl_num_cast(
1092     ($T:ty, $conv:ident) => (
1093         impl NumCast for $T {
1094             #[inline]
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
1098                 n.$conv()
1099             }
1100         }
1101     )
1102 )
1103
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)
1116
1117 pub trait ToStrRadix {
1118     fn to_str_radix(&self, radix: uint) -> ~str;
1119 }
1120
1121 pub trait FromStrRadix {
1122     fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
1123 }
1124
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)
1128 }
1129
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;
1135
1136     /// Saturating subtraction operator.
1137     /// Returns a-b, saturating at the numeric bounds instead of overflowing.
1138     fn saturating_sub(self, v: Self) -> Self;
1139 }
1140
1141 impl<T: CheckedAdd + CheckedSub + Zero + Ord + Bounded> Saturating for T {
1142     #[inline]
1143     fn saturating_add(self, v: T) -> T {
1144         match self.checked_add(&v) {
1145             Some(x) => x,
1146             None => if v >= Zero::zero() {
1147                 Bounded::max_value()
1148             } else {
1149                 Bounded::min_value()
1150             }
1151         }
1152     }
1153
1154     #[inline]
1155     fn saturating_sub(self, v: T) -> T {
1156         match self.checked_sub(&v) {
1157             Some(x) => x,
1158             None => if v >= Zero::zero() {
1159                 Bounded::min_value()
1160             } else {
1161                 Bounded::max_value()
1162             }
1163         }
1164     }
1165 }
1166
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>;
1171 }
1172
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>;
1177 }
1178
1179 /// Performs multiplication that returns `None` instead of wrapping around on underflow or
1180 /// overflow.
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>;
1185 }
1186
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>;
1192 }
1193
1194 /// Helper function for testing numeric operations
1195 #[cfg(test)]
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());
1202
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);
1208 }
1209
1210 #[cfg(test)]
1211 mod tests {
1212     use prelude::*;
1213     use super::*;
1214     use i8;
1215     use i16;
1216     use i32;
1217     use i64;
1218     use int;
1219     use u8;
1220     use u16;
1221     use u32;
1222     use u64;
1223     use uint;
1224
1225     macro_rules! test_cast_20(
1226         ($_20:expr) => ({
1227             let _20 = $_20;
1228
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());
1241
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());
1254
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());
1267         })
1268     )
1269
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) }
1282
1283     #[test]
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);
1295
1296         #[cfg(target_word_size = "32")]
1297         fn check_word_size() {
1298             assert_eq!(int::MIN.to_i32(), Some(int::MIN as i32));
1299         }
1300
1301         #[cfg(target_word_size = "64")]
1302         fn check_word_size() {
1303             assert_eq!(int::MIN.to_i32(), None);
1304         }
1305
1306         check_word_size();
1307     }
1308
1309     #[test]
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);
1321     }
1322
1323     #[test]
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);
1335     }
1336
1337     #[test]
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);
1349     }
1350
1351     #[test]
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);
1363
1364         #[cfg(target_word_size = "32")]
1365         fn check_word_size() {
1366             assert_eq!(i64::MIN.to_int(), None);
1367         }
1368
1369         #[cfg(target_word_size = "64")]
1370         fn check_word_size() {
1371             assert_eq!(i64::MIN.to_int(), Some(i64::MIN as int));
1372         }
1373
1374         check_word_size();
1375     }
1376
1377     #[test]
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));
1388
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));
1393         }
1394
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);
1399         }
1400
1401         check_word_size();
1402     }
1403
1404     #[test]
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));
1416     }
1417
1418     #[test]
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));
1430     }
1431
1432     #[test]
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));
1444     }
1445
1446     #[test]
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));
1458
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);
1463         }
1464
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));
1469         }
1470
1471         check_word_size();
1472     }
1473
1474     #[test]
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));
1486     }
1487
1488     #[test]
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));
1500     }
1501
1502     #[test]
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));
1514     }
1515
1516     #[test]
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));
1528     }
1529
1530     #[test]
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));
1542     }
1543
1544     #[test]
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));
1555
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));
1560         }
1561
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);
1566         }
1567
1568         check_word_size();
1569     }
1570
1571     #[test]
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));
1583     }
1584
1585     #[test]
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));
1597     }
1598
1599     #[test]
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));
1611
1612         #[cfg(target_word_size = "32")]
1613         fn check_word_size() {
1614             assert_eq!(u32::MAX.to_int(),  None);
1615         }
1616
1617         #[cfg(target_word_size = "64")]
1618         fn check_word_size() {
1619             assert_eq!(u32::MAX.to_int(),  Some(u32::MAX as int));
1620         }
1621
1622         check_word_size();
1623     }
1624
1625     #[test]
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));
1637
1638         #[cfg(target_word_size = "32")]
1639         fn check_word_size() {
1640             assert_eq!(u64::MAX.to_uint(), None);
1641         }
1642
1643         #[cfg(target_word_size = "64")]
1644         fn check_word_size() {
1645             assert_eq!(u64::MAX.to_uint(), Some(u64::MAX as uint));
1646         }
1647
1648         check_word_size();
1649     }
1650
1651     #[test]
1652     fn test_saturating_add_uint() {
1653         use uint::MAX;
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);
1658     }
1659
1660     #[test]
1661     fn test_saturating_sub_uint() {
1662         use uint::MAX;
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);
1667     }
1668
1669     #[test]
1670     fn test_saturating_add_int() {
1671         use int::{MIN,MAX};
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);
1679     }
1680
1681     #[test]
1682     fn test_saturating_sub_int() {
1683         use int::{MIN,MAX};
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);
1691     }
1692
1693     #[test]
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);
1704     }
1705
1706     #[test]
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);
1716     }
1717
1718     #[test]
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);
1726     }
1727
1728     macro_rules! test_next_power_of_two(
1729         ($test_name:ident, $T:ident) => (
1730             fn $test_name() {
1731                 #[test];
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 }
1737                 }
1738             }
1739         )
1740     )
1741
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)
1747
1748     macro_rules! test_checked_next_power_of_two(
1749         ($test_name:ident, $T:ident) => (
1750             fn $test_name() {
1751                 #[test];
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 }
1757                 }
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);
1761             }
1762         )
1763     )
1764
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)
1770
1771     #[deriving(Eq, Show)]
1772     struct Value { x: int }
1773
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() }
1777     }
1778
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 }) }
1782     }
1783
1784     #[test]
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));
1799     }
1800
1801     #[test]
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 }));
1815     }
1816
1817     #[test]
1818     fn test_pow() {
1819         fn naive_pow<T: One + Mul<T, T>>(base: T, exp: uint) -> T {
1820             range(0, exp).fold(one::<T>(), |acc, _| acc * base)
1821         }
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));
1827             }}
1828         )
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);
1837     }
1838 }
1839
1840
1841 #[cfg(test)]
1842 mod bench {
1843     extern crate test;
1844     use self::test::BenchHarness;
1845     use num;
1846     use slice;
1847     use prelude::*;
1848
1849     #[bench]
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));});
1853     }
1854 }