]> git.lizzy.rs Git - rust.git/blob - src/libstd/num/mod.rs
rollup merge of #20642: michaelwoerister/sane-source-locations-pt1
[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}`.
15
16 #![stable]
17 #![allow(missing_docs)]
18
19 #[cfg(test)] use fmt::Debug;
20 use ops::{Add, Sub, Mul, Div, Rem, Neg};
21
22 use marker::Copy;
23 use clone::Clone;
24 use cmp::{PartialOrd, PartialEq};
25
26 pub use core::num::{Int, SignedInt, UnsignedInt};
27 pub use core::num::{cast, FromPrimitive, NumCast, ToPrimitive};
28 pub use core::num::{from_int, from_i8, from_i16, from_i32, from_i64};
29 pub use core::num::{from_uint, from_u8, from_u16, from_u32, from_u64};
30 pub use core::num::{from_f32, from_f64};
31 pub use core::num::{FromStrRadix, from_str_radix};
32 pub use core::num::{FpCategory};
33
34 use option::Option;
35
36 #[unstable = "may be removed or relocated"]
37 pub mod strconv;
38
39 /// Mathematical operations on primitive floating point numbers.
40 #[stable]
41 pub trait Float
42     : Copy + Clone
43     + NumCast
44     + PartialOrd
45     + PartialEq
46     + Neg<Output=Self>
47     + Add<Output=Self>
48     + Sub<Output=Self>
49     + Mul<Output=Self>
50     + Div<Output=Self>
51     + Rem<Output=Self>
52 {
53     // inlined methods from `num::Float`
54     /// Returns the NaN value.
55     #[unstable = "unsure about its place in the world"]
56     fn nan() -> Self;
57     /// Returns the infinite value.
58     #[unstable = "unsure about its place in the world"]
59     fn infinity() -> Self;
60     /// Returns the negative infinite value.
61     #[unstable = "unsure about its place in the world"]
62     fn neg_infinity() -> Self;
63     /// Returns the `0` value.
64     #[unstable = "unsure about its place in the world"]
65     fn zero() -> Self;
66     /// Returns -0.0.
67     #[unstable = "unsure about its place in the world"]
68     fn neg_zero() -> Self;
69     /// Returns the `1` value.
70     #[unstable = "unsure about its place in the world"]
71     fn one() -> Self;
72
73     // FIXME (#5527): These should be associated constants
74
75     /// Returns the number of binary digits of mantissa that this type supports.
76     #[deprecated = "use `std::f32::MANTISSA_DIGITS` or `std::f64::MANTISSA_DIGITS` as appropriate"]
77     fn mantissa_digits(unused_self: Option<Self>) -> uint;
78     /// Returns the number of base-10 digits of precision that this type supports.
79     #[deprecated = "use `std::f32::DIGITS` or `std::f64::DIGITS` as appropriate"]
80     fn digits(unused_self: Option<Self>) -> uint;
81     /// Returns the difference between 1.0 and the smallest representable number larger than 1.0.
82     #[deprecated = "use `std::f32::EPSILON` or `std::f64::EPSILON` as appropriate"]
83     fn epsilon() -> Self;
84     /// Returns the minimum binary exponent that this type can represent.
85     #[deprecated = "use `std::f32::MIN_EXP` or `std::f64::MIN_EXP` as appropriate"]
86     fn min_exp(unused_self: Option<Self>) -> int;
87     /// Returns the maximum binary exponent that this type can represent.
88     #[deprecated = "use `std::f32::MAX_EXP` or `std::f64::MAX_EXP` as appropriate"]
89     fn max_exp(unused_self: Option<Self>) -> int;
90     /// Returns the minimum base-10 exponent that this type can represent.
91     #[deprecated = "use `std::f32::MIN_10_EXP` or `std::f64::MIN_10_EXP` as appropriate"]
92     fn min_10_exp(unused_self: Option<Self>) -> int;
93     /// Returns the maximum base-10 exponent that this type can represent.
94     #[deprecated = "use `std::f32::MAX_10_EXP` or `std::f64::MAX_10_EXP` as appropriate"]
95     fn max_10_exp(unused_self: Option<Self>) -> int;
96
97     /// Returns the smallest finite value that this type can represent.
98     #[unstable = "unsure about its place in the world"]
99     fn min_value() -> Self;
100     /// Returns the smallest normalized positive number that this type can represent.
101     #[unstable = "unsure about its place in the world"]
102     fn min_pos_value(unused_self: Option<Self>) -> Self;
103     /// Returns the largest finite value that this type can represent.
104     #[unstable = "unsure about its place in the world"]
105     fn max_value() -> Self;
106
107     /// Returns true if this value is NaN and false otherwise.
108     #[unstable = "position is undecided"]
109     fn is_nan(self) -> bool;
110     /// Returns true if this value is positive infinity or negative infinity and
111     /// false otherwise.
112     #[unstable = "position is undecided"]
113     fn is_infinite(self) -> bool;
114     /// Returns true if this number is neither infinite nor NaN.
115     #[unstable = "position is undecided"]
116     fn is_finite(self) -> bool;
117     /// Returns true if this number is neither zero, infinite, denormal, or NaN.
118     #[unstable = "position is undecided"]
119     fn is_normal(self) -> bool;
120     /// Returns the category that this number falls into.
121     #[stable]
122     fn classify(self) -> FpCategory;
123
124     /// Returns the mantissa, exponent and sign as integers, respectively.
125     #[unstable = "signature is undecided"]
126     fn integer_decode(self) -> (u64, i16, i8);
127
128     /// Return the largest integer less than or equal to a number.
129     #[stable]
130     fn floor(self) -> Self;
131     /// Return the smallest integer greater than or equal to a number.
132     #[stable]
133     fn ceil(self) -> Self;
134     /// Return the nearest integer to a number. Round half-way cases away from
135     /// `0.0`.
136     #[stable]
137     fn round(self) -> Self;
138     /// Return the integer part of a number.
139     #[stable]
140     fn trunc(self) -> Self;
141     /// Return the fractional part of a number.
142     #[stable]
143     fn fract(self) -> Self;
144
145     /// Computes the absolute value of `self`. Returns `Float::nan()` if the
146     /// number is `Float::nan()`.
147     #[stable]
148     fn abs(self) -> Self;
149     /// Returns a number that represents the sign of `self`.
150     ///
151     /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
152     /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
153     /// - `Float::nan()` if the number is `Float::nan()`
154     #[stable]
155     fn signum(self) -> Self;
156     /// Returns `true` if `self` is positive, including `+0.0` and
157     /// `Float::infinity()`.
158     #[stable]
159     fn is_positive(self) -> bool;
160     /// Returns `true` if `self` is negative, including `-0.0` and
161     /// `Float::neg_infinity()`.
162     #[stable]
163     fn is_negative(self) -> bool;
164
165     /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
166     /// error. This produces a more accurate result with better performance than
167     /// a separate multiplication operation followed by an add.
168     #[unstable = "unsure about its place in the world"]
169     fn mul_add(self, a: Self, b: Self) -> Self;
170     /// Take the reciprocal (inverse) of a number, `1/x`.
171     #[unstable = "unsure about its place in the world"]
172     fn recip(self) -> Self;
173
174     /// Raise a number to an integer power.
175     ///
176     /// Using this function is generally faster than using `powf`
177     #[stable]
178     fn powi(self, n: i32) -> Self;
179     /// Raise a number to a floating point power.
180     #[stable]
181     fn powf(self, n: Self) -> Self;
182
183     /// Take the square root of a number.
184     ///
185     /// Returns NaN if `self` is a negative number.
186     #[stable]
187     fn sqrt(self) -> Self;
188     /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
189     #[unstable = "unsure about its place in the world"]
190     fn rsqrt(self) -> Self;
191
192     /// Returns `e^(self)`, (the exponential function).
193     #[stable]
194     fn exp(self) -> Self;
195     /// Returns 2 raised to the power of the number, `2^(self)`.
196     #[stable]
197     fn exp2(self) -> Self;
198     /// Returns the natural logarithm of the number.
199     #[stable]
200     fn ln(self) -> Self;
201     /// Returns the logarithm of the number with respect to an arbitrary base.
202     #[stable]
203     fn log(self, base: Self) -> Self;
204     /// Returns the base 2 logarithm of the number.
205     #[stable]
206     fn log2(self) -> Self;
207     /// Returns the base 10 logarithm of the number.
208     #[stable]
209     fn log10(self) -> Self;
210
211     /// Convert radians to degrees.
212     #[unstable = "desirability is unclear"]
213     fn to_degrees(self) -> Self;
214     /// Convert degrees to radians.
215     #[unstable = "desirability is unclear"]
216     fn to_radians(self) -> Self;
217
218     /// Constructs a floating point number created by multiplying `x` by 2
219     /// raised to the power of `exp`.
220     #[unstable = "pending integer conventions"]
221     fn ldexp(x: Self, exp: int) -> Self;
222     /// Breaks the number into a normalized fraction and a base-2 exponent,
223     /// satisfying:
224     ///
225     ///  * `self = x * pow(2, exp)`
226     ///
227     ///  * `0.5 <= abs(x) < 1.0`
228     #[unstable = "pending integer conventions"]
229     fn frexp(self) -> (Self, int);
230
231     /// Returns the next representable floating-point value in the direction of
232     /// `other`.
233     #[unstable = "unsure about its place in the world"]
234     fn next_after(self, other: Self) -> Self;
235
236     /// Returns the maximum of the two numbers.
237     #[stable]
238     fn max(self, other: Self) -> Self;
239     /// Returns the minimum of the two numbers.
240     #[stable]
241     fn min(self, other: Self) -> Self;
242
243     /// The positive difference of two numbers. Returns `0.0` if the number is
244     /// less than or equal to `other`, otherwise the difference between`self`
245     /// and `other` is returned.
246     #[unstable = "may be renamed"]
247     fn abs_sub(self, other: Self) -> Self;
248
249     /// Take the cubic root of a number.
250     #[unstable = "may be renamed"]
251     fn cbrt(self) -> Self;
252     /// Calculate the length of the hypotenuse of a right-angle triangle given
253     /// legs of length `x` and `y`.
254     #[unstable = "unsure about its place in the world"]
255     fn hypot(self, other: Self) -> Self;
256
257     /// Computes the sine of a number (in radians).
258     #[stable]
259     fn sin(self) -> Self;
260     /// Computes the cosine of a number (in radians).
261     #[stable]
262     fn cos(self) -> Self;
263     /// Computes the tangent of a number (in radians).
264     #[stable]
265     fn tan(self) -> Self;
266
267     /// Computes the arcsine of a number. Return value is in radians in
268     /// the range [-pi/2, pi/2] or NaN if the number is outside the range
269     /// [-1, 1].
270     #[stable]
271     fn asin(self) -> Self;
272     /// Computes the arccosine of a number. Return value is in radians in
273     /// the range [0, pi] or NaN if the number is outside the range
274     /// [-1, 1].
275     #[stable]
276     fn acos(self) -> Self;
277     /// Computes the arctangent of a number. Return value is in radians in the
278     /// range [-pi/2, pi/2];
279     #[stable]
280     fn atan(self) -> Self;
281     /// Computes the four quadrant arctangent of a number, `y`, and another
282     /// number `x`. Return value is in radians in the range [-pi, pi].
283     #[stable]
284     fn atan2(self, other: Self) -> Self;
285     /// Simultaneously computes the sine and cosine of the number, `x`. Returns
286     /// `(sin(x), cos(x))`.
287     #[stable]
288     fn sin_cos(self) -> (Self, Self);
289
290     /// Returns the exponential of the number, minus 1, in a way that is
291     /// accurate even if the number is close to zero.
292     #[unstable = "may be renamed"]
293     fn exp_m1(self) -> Self;
294     /// Returns the natural logarithm of the number plus 1 (`ln(1+n)`) more
295     /// accurately than if the operations were performed separately.
296     #[unstable = "may be renamed"]
297     fn ln_1p(self) -> Self;
298
299     /// Hyperbolic sine function.
300     #[stable]
301     fn sinh(self) -> Self;
302     /// Hyperbolic cosine function.
303     #[stable]
304     fn cosh(self) -> Self;
305     /// Hyperbolic tangent function.
306     #[stable]
307     fn tanh(self) -> Self;
308     /// Inverse hyperbolic sine function.
309     #[stable]
310     fn asinh(self) -> Self;
311     /// Inverse hyperbolic cosine function.
312     #[stable]
313     fn acosh(self) -> Self;
314     /// Inverse hyperbolic tangent function.
315     #[stable]
316     fn atanh(self) -> Self;
317 }
318
319 /// Helper function for testing numeric operations
320 #[cfg(test)]
321 pub fn test_num<T>(ten: T, two: T) where
322     T: PartialEq + NumCast
323      + Add<Output=T> + Sub<Output=T>
324      + Mul<Output=T> + Div<Output=T>
325      + Rem<Output=T> + Debug
326      + Copy
327 {
328     assert_eq!(ten.add(two),  cast(12i).unwrap());
329     assert_eq!(ten.sub(two),  cast(8i).unwrap());
330     assert_eq!(ten.mul(two),  cast(20i).unwrap());
331     assert_eq!(ten.div(two),  cast(5i).unwrap());
332     assert_eq!(ten.rem(two),  cast(0i).unwrap());
333
334     assert_eq!(ten.add(two),  ten + two);
335     assert_eq!(ten.sub(two),  ten - two);
336     assert_eq!(ten.mul(two),  ten * two);
337     assert_eq!(ten.div(two),  ten / two);
338     assert_eq!(ten.rem(two),  ten % two);
339 }
340
341 #[cfg(test)]
342 mod tests {
343     use prelude::v1::*;
344     use super::*;
345     use i8;
346     use i16;
347     use i32;
348     use i64;
349     use int;
350     use u8;
351     use u16;
352     use u32;
353     use u64;
354     use uint;
355
356     macro_rules! test_cast_20 {
357         ($_20:expr) => ({
358             let _20 = $_20;
359
360             assert_eq!(20u,   _20.to_uint().unwrap());
361             assert_eq!(20u8,  _20.to_u8().unwrap());
362             assert_eq!(20u16, _20.to_u16().unwrap());
363             assert_eq!(20u32, _20.to_u32().unwrap());
364             assert_eq!(20u64, _20.to_u64().unwrap());
365             assert_eq!(20i,   _20.to_int().unwrap());
366             assert_eq!(20i8,  _20.to_i8().unwrap());
367             assert_eq!(20i16, _20.to_i16().unwrap());
368             assert_eq!(20i32, _20.to_i32().unwrap());
369             assert_eq!(20i64, _20.to_i64().unwrap());
370             assert_eq!(20f32, _20.to_f32().unwrap());
371             assert_eq!(20f64, _20.to_f64().unwrap());
372
373             assert_eq!(_20, NumCast::from(20u).unwrap());
374             assert_eq!(_20, NumCast::from(20u8).unwrap());
375             assert_eq!(_20, NumCast::from(20u16).unwrap());
376             assert_eq!(_20, NumCast::from(20u32).unwrap());
377             assert_eq!(_20, NumCast::from(20u64).unwrap());
378             assert_eq!(_20, NumCast::from(20i).unwrap());
379             assert_eq!(_20, NumCast::from(20i8).unwrap());
380             assert_eq!(_20, NumCast::from(20i16).unwrap());
381             assert_eq!(_20, NumCast::from(20i32).unwrap());
382             assert_eq!(_20, NumCast::from(20i64).unwrap());
383             assert_eq!(_20, NumCast::from(20f32).unwrap());
384             assert_eq!(_20, NumCast::from(20f64).unwrap());
385
386             assert_eq!(_20, cast(20u).unwrap());
387             assert_eq!(_20, cast(20u8).unwrap());
388             assert_eq!(_20, cast(20u16).unwrap());
389             assert_eq!(_20, cast(20u32).unwrap());
390             assert_eq!(_20, cast(20u64).unwrap());
391             assert_eq!(_20, cast(20i).unwrap());
392             assert_eq!(_20, cast(20i8).unwrap());
393             assert_eq!(_20, cast(20i16).unwrap());
394             assert_eq!(_20, cast(20i32).unwrap());
395             assert_eq!(_20, cast(20i64).unwrap());
396             assert_eq!(_20, cast(20f32).unwrap());
397             assert_eq!(_20, cast(20f64).unwrap());
398         })
399     }
400
401     #[test] fn test_u8_cast()    { test_cast_20!(20u8)  }
402     #[test] fn test_u16_cast()   { test_cast_20!(20u16) }
403     #[test] fn test_u32_cast()   { test_cast_20!(20u32) }
404     #[test] fn test_u64_cast()   { test_cast_20!(20u64) }
405     #[test] fn test_uint_cast()  { test_cast_20!(20u)   }
406     #[test] fn test_i8_cast()    { test_cast_20!(20i8)  }
407     #[test] fn test_i16_cast()   { test_cast_20!(20i16) }
408     #[test] fn test_i32_cast()   { test_cast_20!(20i32) }
409     #[test] fn test_i64_cast()   { test_cast_20!(20i64) }
410     #[test] fn test_int_cast()   { test_cast_20!(20i)   }
411     #[test] fn test_f32_cast()   { test_cast_20!(20f32) }
412     #[test] fn test_f64_cast()   { test_cast_20!(20f64) }
413
414     #[test]
415     fn test_cast_range_int_min() {
416         assert_eq!(int::MIN.to_int(),  Some(int::MIN as int));
417         assert_eq!(int::MIN.to_i8(),   None);
418         assert_eq!(int::MIN.to_i16(),  None);
419         // int::MIN.to_i32() is word-size specific
420         assert_eq!(int::MIN.to_i64(),  Some(int::MIN as i64));
421         assert_eq!(int::MIN.to_uint(), None);
422         assert_eq!(int::MIN.to_u8(),   None);
423         assert_eq!(int::MIN.to_u16(),  None);
424         assert_eq!(int::MIN.to_u32(),  None);
425         assert_eq!(int::MIN.to_u64(),  None);
426
427         #[cfg(target_pointer_width = "32")]
428         fn check_word_size() {
429             assert_eq!(int::MIN.to_i32(), Some(int::MIN as i32));
430         }
431
432         #[cfg(target_pointer_width = "64")]
433         fn check_word_size() {
434             assert_eq!(int::MIN.to_i32(), None);
435         }
436
437         check_word_size();
438     }
439
440     #[test]
441     fn test_cast_range_i8_min() {
442         assert_eq!(i8::MIN.to_int(),  Some(i8::MIN as int));
443         assert_eq!(i8::MIN.to_i8(),   Some(i8::MIN as i8));
444         assert_eq!(i8::MIN.to_i16(),  Some(i8::MIN as i16));
445         assert_eq!(i8::MIN.to_i32(),  Some(i8::MIN as i32));
446         assert_eq!(i8::MIN.to_i64(),  Some(i8::MIN as i64));
447         assert_eq!(i8::MIN.to_uint(), None);
448         assert_eq!(i8::MIN.to_u8(),   None);
449         assert_eq!(i8::MIN.to_u16(),  None);
450         assert_eq!(i8::MIN.to_u32(),  None);
451         assert_eq!(i8::MIN.to_u64(),  None);
452     }
453
454     #[test]
455     fn test_cast_range_i16_min() {
456         assert_eq!(i16::MIN.to_int(),  Some(i16::MIN as int));
457         assert_eq!(i16::MIN.to_i8(),   None);
458         assert_eq!(i16::MIN.to_i16(),  Some(i16::MIN as i16));
459         assert_eq!(i16::MIN.to_i32(),  Some(i16::MIN as i32));
460         assert_eq!(i16::MIN.to_i64(),  Some(i16::MIN as i64));
461         assert_eq!(i16::MIN.to_uint(), None);
462         assert_eq!(i16::MIN.to_u8(),   None);
463         assert_eq!(i16::MIN.to_u16(),  None);
464         assert_eq!(i16::MIN.to_u32(),  None);
465         assert_eq!(i16::MIN.to_u64(),  None);
466     }
467
468     #[test]
469     fn test_cast_range_i32_min() {
470         assert_eq!(i32::MIN.to_int(),  Some(i32::MIN as int));
471         assert_eq!(i32::MIN.to_i8(),   None);
472         assert_eq!(i32::MIN.to_i16(),  None);
473         assert_eq!(i32::MIN.to_i32(),  Some(i32::MIN as i32));
474         assert_eq!(i32::MIN.to_i64(),  Some(i32::MIN as i64));
475         assert_eq!(i32::MIN.to_uint(), None);
476         assert_eq!(i32::MIN.to_u8(),   None);
477         assert_eq!(i32::MIN.to_u16(),  None);
478         assert_eq!(i32::MIN.to_u32(),  None);
479         assert_eq!(i32::MIN.to_u64(),  None);
480     }
481
482     #[test]
483     fn test_cast_range_i64_min() {
484         // i64::MIN.to_int() is word-size specific
485         assert_eq!(i64::MIN.to_i8(),   None);
486         assert_eq!(i64::MIN.to_i16(),  None);
487         assert_eq!(i64::MIN.to_i32(),  None);
488         assert_eq!(i64::MIN.to_i64(),  Some(i64::MIN as i64));
489         assert_eq!(i64::MIN.to_uint(), None);
490         assert_eq!(i64::MIN.to_u8(),   None);
491         assert_eq!(i64::MIN.to_u16(),  None);
492         assert_eq!(i64::MIN.to_u32(),  None);
493         assert_eq!(i64::MIN.to_u64(),  None);
494
495         #[cfg(target_pointer_width = "32")]
496         fn check_word_size() {
497             assert_eq!(i64::MIN.to_int(), None);
498         }
499
500         #[cfg(target_pointer_width = "64")]
501         fn check_word_size() {
502             assert_eq!(i64::MIN.to_int(), Some(i64::MIN as int));
503         }
504
505         check_word_size();
506     }
507
508     #[test]
509     fn test_cast_range_int_max() {
510         assert_eq!(int::MAX.to_int(),  Some(int::MAX as int));
511         assert_eq!(int::MAX.to_i8(),   None);
512         assert_eq!(int::MAX.to_i16(),  None);
513         // int::MAX.to_i32() is word-size specific
514         assert_eq!(int::MAX.to_i64(),  Some(int::MAX as i64));
515         assert_eq!(int::MAX.to_u8(),   None);
516         assert_eq!(int::MAX.to_u16(),  None);
517         // int::MAX.to_u32() is word-size specific
518         assert_eq!(int::MAX.to_u64(),  Some(int::MAX as u64));
519
520         #[cfg(target_pointer_width = "32")]
521         fn check_word_size() {
522             assert_eq!(int::MAX.to_i32(), Some(int::MAX as i32));
523             assert_eq!(int::MAX.to_u32(), Some(int::MAX as u32));
524         }
525
526         #[cfg(target_pointer_width = "64")]
527         fn check_word_size() {
528             assert_eq!(int::MAX.to_i32(), None);
529             assert_eq!(int::MAX.to_u32(), None);
530         }
531
532         check_word_size();
533     }
534
535     #[test]
536     fn test_cast_range_i8_max() {
537         assert_eq!(i8::MAX.to_int(),  Some(i8::MAX as int));
538         assert_eq!(i8::MAX.to_i8(),   Some(i8::MAX as i8));
539         assert_eq!(i8::MAX.to_i16(),  Some(i8::MAX as i16));
540         assert_eq!(i8::MAX.to_i32(),  Some(i8::MAX as i32));
541         assert_eq!(i8::MAX.to_i64(),  Some(i8::MAX as i64));
542         assert_eq!(i8::MAX.to_uint(), Some(i8::MAX as uint));
543         assert_eq!(i8::MAX.to_u8(),   Some(i8::MAX as u8));
544         assert_eq!(i8::MAX.to_u16(),  Some(i8::MAX as u16));
545         assert_eq!(i8::MAX.to_u32(),  Some(i8::MAX as u32));
546         assert_eq!(i8::MAX.to_u64(),  Some(i8::MAX as u64));
547     }
548
549     #[test]
550     fn test_cast_range_i16_max() {
551         assert_eq!(i16::MAX.to_int(),  Some(i16::MAX as int));
552         assert_eq!(i16::MAX.to_i8(),   None);
553         assert_eq!(i16::MAX.to_i16(),  Some(i16::MAX as i16));
554         assert_eq!(i16::MAX.to_i32(),  Some(i16::MAX as i32));
555         assert_eq!(i16::MAX.to_i64(),  Some(i16::MAX as i64));
556         assert_eq!(i16::MAX.to_uint(), Some(i16::MAX as uint));
557         assert_eq!(i16::MAX.to_u8(),   None);
558         assert_eq!(i16::MAX.to_u16(),  Some(i16::MAX as u16));
559         assert_eq!(i16::MAX.to_u32(),  Some(i16::MAX as u32));
560         assert_eq!(i16::MAX.to_u64(),  Some(i16::MAX as u64));
561     }
562
563     #[test]
564     fn test_cast_range_i32_max() {
565         assert_eq!(i32::MAX.to_int(),  Some(i32::MAX as int));
566         assert_eq!(i32::MAX.to_i8(),   None);
567         assert_eq!(i32::MAX.to_i16(),  None);
568         assert_eq!(i32::MAX.to_i32(),  Some(i32::MAX as i32));
569         assert_eq!(i32::MAX.to_i64(),  Some(i32::MAX as i64));
570         assert_eq!(i32::MAX.to_uint(), Some(i32::MAX as uint));
571         assert_eq!(i32::MAX.to_u8(),   None);
572         assert_eq!(i32::MAX.to_u16(),  None);
573         assert_eq!(i32::MAX.to_u32(),  Some(i32::MAX as u32));
574         assert_eq!(i32::MAX.to_u64(),  Some(i32::MAX as u64));
575     }
576
577     #[test]
578     fn test_cast_range_i64_max() {
579         // i64::MAX.to_int() is word-size specific
580         assert_eq!(i64::MAX.to_i8(),   None);
581         assert_eq!(i64::MAX.to_i16(),  None);
582         assert_eq!(i64::MAX.to_i32(),  None);
583         assert_eq!(i64::MAX.to_i64(),  Some(i64::MAX as i64));
584         // i64::MAX.to_uint() is word-size specific
585         assert_eq!(i64::MAX.to_u8(),   None);
586         assert_eq!(i64::MAX.to_u16(),  None);
587         assert_eq!(i64::MAX.to_u32(),  None);
588         assert_eq!(i64::MAX.to_u64(),  Some(i64::MAX as u64));
589
590         #[cfg(target_pointer_width = "32")]
591         fn check_word_size() {
592             assert_eq!(i64::MAX.to_int(),  None);
593             assert_eq!(i64::MAX.to_uint(), None);
594         }
595
596         #[cfg(target_pointer_width = "64")]
597         fn check_word_size() {
598             assert_eq!(i64::MAX.to_int(),  Some(i64::MAX as int));
599             assert_eq!(i64::MAX.to_uint(), Some(i64::MAX as uint));
600         }
601
602         check_word_size();
603     }
604
605     #[test]
606     fn test_cast_range_uint_min() {
607         assert_eq!(uint::MIN.to_int(),  Some(uint::MIN as int));
608         assert_eq!(uint::MIN.to_i8(),   Some(uint::MIN as i8));
609         assert_eq!(uint::MIN.to_i16(),  Some(uint::MIN as i16));
610         assert_eq!(uint::MIN.to_i32(),  Some(uint::MIN as i32));
611         assert_eq!(uint::MIN.to_i64(),  Some(uint::MIN as i64));
612         assert_eq!(uint::MIN.to_uint(), Some(uint::MIN as uint));
613         assert_eq!(uint::MIN.to_u8(),   Some(uint::MIN as u8));
614         assert_eq!(uint::MIN.to_u16(),  Some(uint::MIN as u16));
615         assert_eq!(uint::MIN.to_u32(),  Some(uint::MIN as u32));
616         assert_eq!(uint::MIN.to_u64(),  Some(uint::MIN as u64));
617     }
618
619     #[test]
620     fn test_cast_range_u8_min() {
621         assert_eq!(u8::MIN.to_int(),  Some(u8::MIN as int));
622         assert_eq!(u8::MIN.to_i8(),   Some(u8::MIN as i8));
623         assert_eq!(u8::MIN.to_i16(),  Some(u8::MIN as i16));
624         assert_eq!(u8::MIN.to_i32(),  Some(u8::MIN as i32));
625         assert_eq!(u8::MIN.to_i64(),  Some(u8::MIN as i64));
626         assert_eq!(u8::MIN.to_uint(), Some(u8::MIN as uint));
627         assert_eq!(u8::MIN.to_u8(),   Some(u8::MIN as u8));
628         assert_eq!(u8::MIN.to_u16(),  Some(u8::MIN as u16));
629         assert_eq!(u8::MIN.to_u32(),  Some(u8::MIN as u32));
630         assert_eq!(u8::MIN.to_u64(),  Some(u8::MIN as u64));
631     }
632
633     #[test]
634     fn test_cast_range_u16_min() {
635         assert_eq!(u16::MIN.to_int(),  Some(u16::MIN as int));
636         assert_eq!(u16::MIN.to_i8(),   Some(u16::MIN as i8));
637         assert_eq!(u16::MIN.to_i16(),  Some(u16::MIN as i16));
638         assert_eq!(u16::MIN.to_i32(),  Some(u16::MIN as i32));
639         assert_eq!(u16::MIN.to_i64(),  Some(u16::MIN as i64));
640         assert_eq!(u16::MIN.to_uint(), Some(u16::MIN as uint));
641         assert_eq!(u16::MIN.to_u8(),   Some(u16::MIN as u8));
642         assert_eq!(u16::MIN.to_u16(),  Some(u16::MIN as u16));
643         assert_eq!(u16::MIN.to_u32(),  Some(u16::MIN as u32));
644         assert_eq!(u16::MIN.to_u64(),  Some(u16::MIN as u64));
645     }
646
647     #[test]
648     fn test_cast_range_u32_min() {
649         assert_eq!(u32::MIN.to_int(),  Some(u32::MIN as int));
650         assert_eq!(u32::MIN.to_i8(),   Some(u32::MIN as i8));
651         assert_eq!(u32::MIN.to_i16(),  Some(u32::MIN as i16));
652         assert_eq!(u32::MIN.to_i32(),  Some(u32::MIN as i32));
653         assert_eq!(u32::MIN.to_i64(),  Some(u32::MIN as i64));
654         assert_eq!(u32::MIN.to_uint(), Some(u32::MIN as uint));
655         assert_eq!(u32::MIN.to_u8(),   Some(u32::MIN as u8));
656         assert_eq!(u32::MIN.to_u16(),  Some(u32::MIN as u16));
657         assert_eq!(u32::MIN.to_u32(),  Some(u32::MIN as u32));
658         assert_eq!(u32::MIN.to_u64(),  Some(u32::MIN as u64));
659     }
660
661     #[test]
662     fn test_cast_range_u64_min() {
663         assert_eq!(u64::MIN.to_int(),  Some(u64::MIN as int));
664         assert_eq!(u64::MIN.to_i8(),   Some(u64::MIN as i8));
665         assert_eq!(u64::MIN.to_i16(),  Some(u64::MIN as i16));
666         assert_eq!(u64::MIN.to_i32(),  Some(u64::MIN as i32));
667         assert_eq!(u64::MIN.to_i64(),  Some(u64::MIN as i64));
668         assert_eq!(u64::MIN.to_uint(), Some(u64::MIN as uint));
669         assert_eq!(u64::MIN.to_u8(),   Some(u64::MIN as u8));
670         assert_eq!(u64::MIN.to_u16(),  Some(u64::MIN as u16));
671         assert_eq!(u64::MIN.to_u32(),  Some(u64::MIN as u32));
672         assert_eq!(u64::MIN.to_u64(),  Some(u64::MIN as u64));
673     }
674
675     #[test]
676     fn test_cast_range_uint_max() {
677         assert_eq!(uint::MAX.to_int(),  None);
678         assert_eq!(uint::MAX.to_i8(),   None);
679         assert_eq!(uint::MAX.to_i16(),  None);
680         assert_eq!(uint::MAX.to_i32(),  None);
681         // uint::MAX.to_i64() is word-size specific
682         assert_eq!(uint::MAX.to_u8(),   None);
683         assert_eq!(uint::MAX.to_u16(),  None);
684         // uint::MAX.to_u32() is word-size specific
685         assert_eq!(uint::MAX.to_u64(),  Some(uint::MAX as u64));
686
687         #[cfg(target_pointer_width = "32")]
688         fn check_word_size() {
689             assert_eq!(uint::MAX.to_u32(), Some(uint::MAX as u32));
690             assert_eq!(uint::MAX.to_i64(), Some(uint::MAX as i64));
691         }
692
693         #[cfg(target_pointer_width = "64")]
694         fn check_word_size() {
695             assert_eq!(uint::MAX.to_u32(), None);
696             assert_eq!(uint::MAX.to_i64(), None);
697         }
698
699         check_word_size();
700     }
701
702     #[test]
703     fn test_cast_range_u8_max() {
704         assert_eq!(u8::MAX.to_int(),  Some(u8::MAX as int));
705         assert_eq!(u8::MAX.to_i8(),   None);
706         assert_eq!(u8::MAX.to_i16(),  Some(u8::MAX as i16));
707         assert_eq!(u8::MAX.to_i32(),  Some(u8::MAX as i32));
708         assert_eq!(u8::MAX.to_i64(),  Some(u8::MAX as i64));
709         assert_eq!(u8::MAX.to_uint(), Some(u8::MAX as uint));
710         assert_eq!(u8::MAX.to_u8(),   Some(u8::MAX as u8));
711         assert_eq!(u8::MAX.to_u16(),  Some(u8::MAX as u16));
712         assert_eq!(u8::MAX.to_u32(),  Some(u8::MAX as u32));
713         assert_eq!(u8::MAX.to_u64(),  Some(u8::MAX as u64));
714     }
715
716     #[test]
717     fn test_cast_range_u16_max() {
718         assert_eq!(u16::MAX.to_int(),  Some(u16::MAX as int));
719         assert_eq!(u16::MAX.to_i8(),   None);
720         assert_eq!(u16::MAX.to_i16(),  None);
721         assert_eq!(u16::MAX.to_i32(),  Some(u16::MAX as i32));
722         assert_eq!(u16::MAX.to_i64(),  Some(u16::MAX as i64));
723         assert_eq!(u16::MAX.to_uint(), Some(u16::MAX as uint));
724         assert_eq!(u16::MAX.to_u8(),   None);
725         assert_eq!(u16::MAX.to_u16(),  Some(u16::MAX as u16));
726         assert_eq!(u16::MAX.to_u32(),  Some(u16::MAX as u32));
727         assert_eq!(u16::MAX.to_u64(),  Some(u16::MAX as u64));
728     }
729
730     #[test]
731     fn test_cast_range_u32_max() {
732         // u32::MAX.to_int() is word-size specific
733         assert_eq!(u32::MAX.to_i8(),   None);
734         assert_eq!(u32::MAX.to_i16(),  None);
735         assert_eq!(u32::MAX.to_i32(),  None);
736         assert_eq!(u32::MAX.to_i64(),  Some(u32::MAX as i64));
737         assert_eq!(u32::MAX.to_uint(), Some(u32::MAX as uint));
738         assert_eq!(u32::MAX.to_u8(),   None);
739         assert_eq!(u32::MAX.to_u16(),  None);
740         assert_eq!(u32::MAX.to_u32(),  Some(u32::MAX as u32));
741         assert_eq!(u32::MAX.to_u64(),  Some(u32::MAX as u64));
742
743         #[cfg(target_pointer_width = "32")]
744         fn check_word_size() {
745             assert_eq!(u32::MAX.to_int(),  None);
746         }
747
748         #[cfg(target_pointer_width = "64")]
749         fn check_word_size() {
750             assert_eq!(u32::MAX.to_int(),  Some(u32::MAX as int));
751         }
752
753         check_word_size();
754     }
755
756     #[test]
757     fn test_cast_range_u64_max() {
758         assert_eq!(u64::MAX.to_int(),  None);
759         assert_eq!(u64::MAX.to_i8(),   None);
760         assert_eq!(u64::MAX.to_i16(),  None);
761         assert_eq!(u64::MAX.to_i32(),  None);
762         assert_eq!(u64::MAX.to_i64(),  None);
763         // u64::MAX.to_uint() is word-size specific
764         assert_eq!(u64::MAX.to_u8(),   None);
765         assert_eq!(u64::MAX.to_u16(),  None);
766         assert_eq!(u64::MAX.to_u32(),  None);
767         assert_eq!(u64::MAX.to_u64(),  Some(u64::MAX as u64));
768
769         #[cfg(target_pointer_width = "32")]
770         fn check_word_size() {
771             assert_eq!(u64::MAX.to_uint(), None);
772         }
773
774         #[cfg(target_pointer_width = "64")]
775         fn check_word_size() {
776             assert_eq!(u64::MAX.to_uint(), Some(u64::MAX as uint));
777         }
778
779         check_word_size();
780     }
781
782     #[test]
783     fn test_saturating_add_uint() {
784         use uint::MAX;
785         assert_eq!(3u.saturating_add(5u), 8u);
786         assert_eq!(3u.saturating_add(MAX-1), MAX);
787         assert_eq!(MAX.saturating_add(MAX), MAX);
788         assert_eq!((MAX-2).saturating_add(1), MAX-1);
789     }
790
791     #[test]
792     fn test_saturating_sub_uint() {
793         use uint::MAX;
794         assert_eq!(5u.saturating_sub(3u), 2u);
795         assert_eq!(3u.saturating_sub(5u), 0u);
796         assert_eq!(0u.saturating_sub(1u), 0u);
797         assert_eq!((MAX-1).saturating_sub(MAX), 0);
798     }
799
800     #[test]
801     fn test_saturating_add_int() {
802         use int::{MIN,MAX};
803         assert_eq!(3i.saturating_add(5i), 8i);
804         assert_eq!(3i.saturating_add(MAX-1), MAX);
805         assert_eq!(MAX.saturating_add(MAX), MAX);
806         assert_eq!((MAX-2).saturating_add(1), MAX-1);
807         assert_eq!(3i.saturating_add(-5i), -2i);
808         assert_eq!(MIN.saturating_add(-1i), MIN);
809         assert_eq!((-2i).saturating_add(-MAX), MIN);
810     }
811
812     #[test]
813     fn test_saturating_sub_int() {
814         use int::{MIN,MAX};
815         assert_eq!(3i.saturating_sub(5i), -2i);
816         assert_eq!(MIN.saturating_sub(1i), MIN);
817         assert_eq!((-2i).saturating_sub(MAX), MIN);
818         assert_eq!(3i.saturating_sub(-5i), 8i);
819         assert_eq!(3i.saturating_sub(-(MAX-1)), MAX);
820         assert_eq!(MAX.saturating_sub(-MAX), MAX);
821         assert_eq!((MAX-2).saturating_sub(-1), MAX-1);
822     }
823
824     #[test]
825     fn test_checked_add() {
826         let five_less = uint::MAX - 5;
827         assert_eq!(five_less.checked_add(0), Some(uint::MAX - 5));
828         assert_eq!(five_less.checked_add(1), Some(uint::MAX - 4));
829         assert_eq!(five_less.checked_add(2), Some(uint::MAX - 3));
830         assert_eq!(five_less.checked_add(3), Some(uint::MAX - 2));
831         assert_eq!(five_less.checked_add(4), Some(uint::MAX - 1));
832         assert_eq!(five_less.checked_add(5), Some(uint::MAX));
833         assert_eq!(five_less.checked_add(6), None);
834         assert_eq!(five_less.checked_add(7), None);
835     }
836
837     #[test]
838     fn test_checked_sub() {
839         assert_eq!(5u.checked_sub(0), Some(5));
840         assert_eq!(5u.checked_sub(1), Some(4));
841         assert_eq!(5u.checked_sub(2), Some(3));
842         assert_eq!(5u.checked_sub(3), Some(2));
843         assert_eq!(5u.checked_sub(4), Some(1));
844         assert_eq!(5u.checked_sub(5), Some(0));
845         assert_eq!(5u.checked_sub(6), None);
846         assert_eq!(5u.checked_sub(7), None);
847     }
848
849     #[test]
850     fn test_checked_mul() {
851         let third = uint::MAX / 3;
852         assert_eq!(third.checked_mul(0), Some(0));
853         assert_eq!(third.checked_mul(1), Some(third));
854         assert_eq!(third.checked_mul(2), Some(third * 2));
855         assert_eq!(third.checked_mul(3), Some(third * 3));
856         assert_eq!(third.checked_mul(4), None);
857     }
858
859     macro_rules! test_is_power_of_two {
860         ($test_name:ident, $T:ident) => (
861             fn $test_name() {
862                 #![test]
863                 assert_eq!((0 as $T).is_power_of_two(), false);
864                 assert_eq!((1 as $T).is_power_of_two(), true);
865                 assert_eq!((2 as $T).is_power_of_two(), true);
866                 assert_eq!((3 as $T).is_power_of_two(), false);
867                 assert_eq!((4 as $T).is_power_of_two(), true);
868                 assert_eq!((5 as $T).is_power_of_two(), false);
869                 assert!(($T::MAX / 2 + 1).is_power_of_two(), true);
870             }
871         )
872     }
873
874     test_is_power_of_two!{ test_is_power_of_two_u8, u8 }
875     test_is_power_of_two!{ test_is_power_of_two_u16, u16 }
876     test_is_power_of_two!{ test_is_power_of_two_u32, u32 }
877     test_is_power_of_two!{ test_is_power_of_two_u64, u64 }
878     test_is_power_of_two!{ test_is_power_of_two_uint, uint }
879
880     macro_rules! test_next_power_of_two {
881         ($test_name:ident, $T:ident) => (
882             fn $test_name() {
883                 #![test]
884                 assert_eq!((0 as $T).next_power_of_two(), 1);
885                 let mut next_power = 1;
886                 for i in range::<$T>(1, 40) {
887                      assert_eq!(i.next_power_of_two(), next_power);
888                      if i == next_power { next_power *= 2 }
889                 }
890             }
891         )
892     }
893
894     test_next_power_of_two! { test_next_power_of_two_u8, u8 }
895     test_next_power_of_two! { test_next_power_of_two_u16, u16 }
896     test_next_power_of_two! { test_next_power_of_two_u32, u32 }
897     test_next_power_of_two! { test_next_power_of_two_u64, u64 }
898     test_next_power_of_two! { test_next_power_of_two_uint, uint }
899
900     macro_rules! test_checked_next_power_of_two {
901         ($test_name:ident, $T:ident) => (
902             fn $test_name() {
903                 #![test]
904                 assert_eq!((0 as $T).checked_next_power_of_two(), Some(1));
905                 assert!(($T::MAX / 2).checked_next_power_of_two().is_some());
906                 assert_eq!(($T::MAX - 1).checked_next_power_of_two(), None);
907                 assert_eq!($T::MAX.checked_next_power_of_two(), None);
908                 let mut next_power = 1;
909                 for i in range::<$T>(1, 40) {
910                      assert_eq!(i.checked_next_power_of_two(), Some(next_power));
911                      if i == next_power { next_power *= 2 }
912                 }
913             }
914         )
915     }
916
917     test_checked_next_power_of_two! { test_checked_next_power_of_two_u8, u8 }
918     test_checked_next_power_of_two! { test_checked_next_power_of_two_u16, u16 }
919     test_checked_next_power_of_two! { test_checked_next_power_of_two_u32, u32 }
920     test_checked_next_power_of_two! { test_checked_next_power_of_two_u64, u64 }
921     test_checked_next_power_of_two! { test_checked_next_power_of_two_uint, uint }
922
923     #[derive(PartialEq, Show)]
924     struct Value { x: int }
925
926     impl ToPrimitive for Value {
927         fn to_i64(&self) -> Option<i64> { self.x.to_i64() }
928         fn to_u64(&self) -> Option<u64> { self.x.to_u64() }
929     }
930
931     impl FromPrimitive for Value {
932         fn from_i64(n: i64) -> Option<Value> { Some(Value { x: n as int }) }
933         fn from_u64(n: u64) -> Option<Value> { Some(Value { x: n as int }) }
934     }
935
936     #[test]
937     fn test_to_primitive() {
938         let value = Value { x: 5 };
939         assert_eq!(value.to_int(),  Some(5));
940         assert_eq!(value.to_i8(),   Some(5));
941         assert_eq!(value.to_i16(),  Some(5));
942         assert_eq!(value.to_i32(),  Some(5));
943         assert_eq!(value.to_i64(),  Some(5));
944         assert_eq!(value.to_uint(), Some(5));
945         assert_eq!(value.to_u8(),   Some(5));
946         assert_eq!(value.to_u16(),  Some(5));
947         assert_eq!(value.to_u32(),  Some(5));
948         assert_eq!(value.to_u64(),  Some(5));
949         assert_eq!(value.to_f32(),  Some(5f32));
950         assert_eq!(value.to_f64(),  Some(5f64));
951     }
952
953     #[test]
954     fn test_from_primitive() {
955         assert_eq!(from_int(5),    Some(Value { x: 5 }));
956         assert_eq!(from_i8(5),     Some(Value { x: 5 }));
957         assert_eq!(from_i16(5),    Some(Value { x: 5 }));
958         assert_eq!(from_i32(5),    Some(Value { x: 5 }));
959         assert_eq!(from_i64(5),    Some(Value { x: 5 }));
960         assert_eq!(from_uint(5),   Some(Value { x: 5 }));
961         assert_eq!(from_u8(5),     Some(Value { x: 5 }));
962         assert_eq!(from_u16(5),    Some(Value { x: 5 }));
963         assert_eq!(from_u32(5),    Some(Value { x: 5 }));
964         assert_eq!(from_u64(5),    Some(Value { x: 5 }));
965         assert_eq!(from_f32(5f32), Some(Value { x: 5 }));
966         assert_eq!(from_f64(5f64), Some(Value { x: 5 }));
967     }
968
969     #[test]
970     fn test_pow() {
971         fn naive_pow<T: Int>(base: T, exp: uint) -> T {
972             let one: T = Int::one();
973             range(0, exp).fold(one, |acc, _| acc * base)
974         }
975         macro_rules! assert_pow {
976             (($num:expr, $exp:expr) => $expected:expr) => {{
977                 let result = $num.pow($exp);
978                 assert_eq!(result, $expected);
979                 assert_eq!(result, naive_pow($num, $exp));
980             }}
981         }
982         assert_pow!((3i,     0 ) => 1);
983         assert_pow!((5i,     1 ) => 5);
984         assert_pow!((-4i,    2 ) => 16);
985         assert_pow!((8i,     3 ) => 512);
986         assert_pow!((2u64,   50) => 1125899906842624);
987     }
988 }
989
990
991 #[cfg(test)]
992 mod bench {
993     extern crate test;
994     use self::test::Bencher;
995     use num::Int;
996     use prelude::v1::*;
997
998     #[bench]
999     fn bench_pow_function(b: &mut Bencher) {
1000         let v = range(0, 1024u).collect::<Vec<_>>();
1001         b.iter(|| {v.iter().fold(0u, |old, new| old.pow(*new));});
1002     }
1003 }