mod.rs 59.6 KB
Newer Older
C
Chris Wong 已提交
1
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

L
Luca Bruno 已提交
11
//! Numeric traits and functions for generic mathematics
12 13 14
//!
//! These are implemented for the primitive numeric types in `std::{u8, u16,
//! u32, u64, uint, i8, i16, i32, i64, int, f32, f64, float}`.
15 16 17

#[allow(missing_doc)];

18
use clone::{Clone, DeepClone};
19
use cmp::{Eq, Ord};
20
use mem::size_of;
21
use ops::{Add, Sub, Mul, Div, Rem, Neg};
22
use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
23
use option::{Option, Some, None};
P
Patrick Walton 已提交
24

25 26
pub mod strconv;

B
Brendan Zabarauskas 已提交
27
/// The base trait for numeric types
B
Brendan Zabarauskas 已提交
28 29 30 31 32
pub trait Num: Eq + Zero + One
             + Neg<Self>
             + Add<Self,Self>
             + Sub<Self,Self>
             + Mul<Self,Self>
33
             + Div<Self,Self>
34
             + Rem<Self,Self> {}
B
Brendan Zabarauskas 已提交
35

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
/// Defines an additive identity element for `Self`.
///
/// # Deriving
///
/// This trait can be automatically be derived using `#[deriving(Zero)]`
/// attribute. If you choose to use this, make sure that the laws outlined in
/// the documentation for `Zero::zero` still hold.
pub trait Zero: Add<Self, Self> {
    /// Returns the additive identity element of `Self`, `0`.
    ///
    /// # Laws
    ///
    /// ~~~
    /// a + 0 = a       ∀ a ∈ Self
    /// 0 + a = a       ∀ a ∈ Self
    /// ~~~
    ///
    /// # Purity
    ///
    /// This function should return the same result at all times regardless of
    /// external mutable state, for example values stored in TLS or in
    /// `static mut`s.
    // FIXME (#5527): This should be an associated constant
    fn zero() -> Self;

    /// Returns `true` if `self` is equal to the additive identity.
B
Brendan Zabarauskas 已提交
62
    fn is_zero(&self) -> bool;
63 64
}

65
/// Returns the additive identity, `0`.
66 67
#[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() }

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
/// Defines a multiplicative identity element for `Self`.
pub trait One: Mul<Self, Self> {
    /// Returns the multiplicative identity element of `Self`, `1`.
    ///
    /// # Laws
    ///
    /// ~~~
    /// a * 1 = a       ∀ a ∈ Self
    /// 1 * a = a       ∀ a ∈ Self
    /// ~~~
    ///
    /// # Purity
    ///
    /// This function should return the same result at all times regardless of
    /// external mutable state, for example values stored in TLS or in
    /// `static mut`s.
    // FIXME (#5527): This should be an associated constant
    fn one() -> Self;
86
}
M
Marvin Löbel 已提交
87

88
/// Returns the multiplicative identity, `1`.
89 90
#[inline(always)] pub fn one<T: One>() -> T { One::one() }

91 92 93
pub trait Signed: Num
                + Neg<Self> {
    fn abs(&self) -> Self;
94
    fn abs_sub(&self, other: &Self) -> Self;
95
    fn signum(&self) -> Self;
96

97 98 99 100
    fn is_positive(&self) -> bool;
    fn is_negative(&self) -> bool;
}

101 102 103
/// Computes the absolute value.
///
/// For float, f32, and f64, `NaN` will be returned if the number is `NaN`
104
#[inline(always)] pub fn abs<T: Signed>(value: T) -> T { value.abs() }
105 106 107 108
/// The positive difference of two numbers.
///
/// Returns `zero` if the number is less than or equal to `other`,
/// otherwise the difference between `self` and `other` is returned.
109
#[inline(always)] pub fn abs_sub<T: Signed>(x: T, y: T) -> T { x.abs_sub(&y) }
110 111 112
/// Returns the sign of the number.
///
/// For float, f32, f64:
113 114 115
/// - `1.0` if the number is positive, `+0.0` or `INFINITY`
/// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
/// - `NAN` if the number is `NAN`
116 117 118 119 120
///
/// For int:
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
121
#[inline(always)] pub fn signum<T: Signed>(value: T) -> T { value.signum() }
122

123
pub trait Unsigned: Num {}
G
Graydon Hoare 已提交
124

B
Brendan Zabarauskas 已提交
125
pub trait Integer: Num
M
Michael Darakananda 已提交
126
                 + Ord
127
                 + Div<Self,Self>
B
Brendan Zabarauskas 已提交
128
                 + Rem<Self,Self> {
129 130 131 132 133
    fn div_rem(&self, other: &Self) -> (Self,Self);

    fn div_floor(&self, other: &Self) -> Self;
    fn mod_floor(&self, other: &Self) -> Self;
    fn div_mod_floor(&self, other: &Self) -> (Self,Self);
B
Brendan Zabarauskas 已提交
134

135 136
    fn gcd(&self, other: &Self) -> Self;
    fn lcm(&self, other: &Self) -> Self;
137 138

    fn is_multiple_of(&self, other: &Self) -> bool;
B
Brendan Zabarauskas 已提交
139 140 141 142
    fn is_even(&self) -> bool;
    fn is_odd(&self) -> bool;
}

143 144 145
/// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
///
/// The result is always positive.
146
#[inline(always)] pub fn gcd<T: Integer>(x: T, y: T) -> T { x.gcd(&y) }
147
/// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
148 149
#[inline(always)] pub fn lcm<T: Integer>(x: T, y: T) -> T { x.lcm(&y) }

150
/// A collection of rounding operations.
151
pub trait Round {
152
    /// Return the largest integer less than or equal to a number.
153
    fn floor(&self) -> Self;
154 155

    /// Return the smallest integer greater than or equal to a number.
156
    fn ceil(&self) -> Self;
157 158 159

    /// Return the nearest integer to a number. Round half-way cases away from
    /// `0.0`.
160
    fn round(&self) -> Self;
161 162

    /// Return the integer part of a number.
163
    fn trunc(&self) -> Self;
164 165

    /// Return the fractional part of a number.
166 167 168
    fn fract(&self) -> Self;
}

169 170
/// Defines constants and methods common to real numbers
pub trait Real: Signed
M
Michael Darakananda 已提交
171
              + Ord
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
              + Round
              + Div<Self,Self> {
    // Common Constants
    // FIXME (#5527): These should be associated constants
    fn pi() -> Self;
    fn two_pi() -> Self;
    fn frac_pi_2() -> Self;
    fn frac_pi_3() -> Self;
    fn frac_pi_4() -> Self;
    fn frac_pi_6() -> Self;
    fn frac_pi_8() -> Self;
    fn frac_1_pi() -> Self;
    fn frac_2_pi() -> Self;
    fn frac_2_sqrtpi() -> Self;
    fn sqrt2() -> Self;
    fn frac_1_sqrt2() -> Self;
    fn e() -> Self;
    fn log2_e() -> Self;
    fn log10_e() -> Self;
    fn ln_2() -> Self;
    fn ln_10() -> Self;

    // Fractional functions

196
    /// Take the reciprocal (inverse) of a number, `1/x`.
197 198
    fn recip(&self) -> Self;

199
    // Algebraic functions
200
    /// Raise a number to a power.
F
Flavio Percoco 已提交
201 202
    fn powf(&self, n: &Self) -> Self;

H
Huon Wilson 已提交
203
    /// Take the square root of a number.
204
    fn sqrt(&self) -> Self;
205
    /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
206
    fn rsqrt(&self) -> Self;
207
    /// Take the cubic root of a number.
208
    fn cbrt(&self) -> Self;
209 210
    /// Calculate the length of the hypotenuse of a right-angle triangle given
    /// legs of length `x` and `y`.
211
    fn hypot(&self, other: &Self) -> Self;
212

213
    // Trigonometric functions
214

215
    /// Computes the sine of a number (in radians).
216
    fn sin(&self) -> Self;
217
    /// Computes the cosine of a number (in radians).
218
    fn cos(&self) -> Self;
219
    /// Computes the tangent of a number (in radians).
220
    fn tan(&self) -> Self;
221

222 223 224
    /// Computes the arcsine of a number. Return value is in radians in
    /// the range [-pi/2, pi/2] or NaN if the number is outside the range
    /// [-1, 1].
225
    fn asin(&self) -> Self;
226 227 228
    /// Computes the arccosine of a number. Return value is in radians in
    /// the range [0, pi] or NaN if the number is outside the range
    /// [-1, 1].
229
    fn acos(&self) -> Self;
230 231
    /// Computes the arctangent of a number. Return value is in radians in the
    /// range [-pi/2, pi/2];
232
    fn atan(&self) -> Self;
233
    /// Computes the four quadrant arctangent of a number, `y`, and another
234
    /// number `x`. Return value is in radians in the range [-pi, pi].
235
    fn atan2(&self, other: &Self) -> Self;
236 237
    /// Simultaneously computes the sine and cosine of the number, `x`. Returns
    /// `(sin(x), cos(x))`.
238
    fn sin_cos(&self) -> (Self, Self);
239

240
    // Exponential functions
241

242
    /// Returns `e^(self)`, (the exponential function).
243
    fn exp(&self) -> Self;
244
    /// Returns 2 raised to the power of the number, `2^(self)`.
245
    fn exp2(&self) -> Self;
246
    /// Returns the natural logarithm of the number.
247
    fn ln(&self) -> Self;
248
    /// Returns the logarithm of the number with respect to an arbitrary base.
249
    fn log(&self, base: &Self) -> Self;
250
    /// Returns the base 2 logarithm of the number.
251
    fn log2(&self) -> Self;
252
    /// Returns the base 10 logarithm of the number.
253
    fn log10(&self) -> Self;
254

255
    // Hyperbolic functions
256

257
    /// Hyperbolic sine function.
258
    fn sinh(&self) -> Self;
259
    /// Hyperbolic cosine function.
260
    fn cosh(&self) -> Self;
261
    /// Hyperbolic tangent function.
262
    fn tanh(&self) -> Self;
263
    /// Inverse hyperbolic sine function.
264
    fn asinh(&self) -> Self;
265
    /// Inverse hyperbolic cosine function.
266
    fn acosh(&self) -> Self;
267
    /// Inverse hyperbolic tangent function.
268
    fn atanh(&self) -> Self;
M
Marvin Löbel 已提交
269

270
    // Angular conversions
271 272

    /// Convert radians to degrees.
273 274
    fn to_degrees(&self) -> Self;
    /// Convert degrees to radians.
275
    fn to_radians(&self) -> Self;
M
Marvin Löbel 已提交
276 277
}

278
/// Raises a value to the power of exp, using exponentiation by squaring.
F
Flavio Percoco 已提交
279 280 281 282 283 284
///
/// # Example
///
/// ```rust
/// use std::num;
///
285
/// assert_eq!(num::pow(2, 4), 16);
F
Flavio Percoco 已提交
286 287
/// ```
#[inline]
288 289 290 291 292 293 294 295 296 297
pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
    if exp == 1 { base }
    else {
        let mut acc = one::<T>();
        while exp > 0 {
            if (exp & 1) == 1 {
                acc = acc * base;
            }
            base = base * base;
            exp = exp >> 1;
F
Flavio Percoco 已提交
298
        }
299
        acc
F
Flavio Percoco 已提交
300 301 302
    }
}

303 304 305 306 307 308 309
/// Raise a number to a power.
///
/// # Example
///
/// ```rust
/// use std::num;
///
F
Flavio Percoco 已提交
310
/// let sixteen: f64 = num::powf(2.0, 4.0);
311 312
/// assert_eq!(sixteen, 16.0);
/// ```
F
Flavio Percoco 已提交
313
#[inline(always)] pub fn powf<T: Real>(value: T, n: T) -> T { value.powf(&n) }
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
/// Take the square root of a number.
#[inline(always)] pub fn sqrt<T: Real>(value: T) -> T { value.sqrt() }
/// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
#[inline(always)] pub fn rsqrt<T: Real>(value: T) -> T { value.rsqrt() }
/// Take the cubic root of a number.
#[inline(always)] pub fn cbrt<T: Real>(value: T) -> T { value.cbrt() }
/// Calculate the length of the hypotenuse of a right-angle triangle given legs of length `x` and
/// `y`.
#[inline(always)] pub fn hypot<T: Real>(x: T, y: T) -> T { x.hypot(&y) }
/// Sine function.
#[inline(always)] pub fn sin<T: Real>(value: T) -> T { value.sin() }
/// Cosine function.
#[inline(always)] pub fn cos<T: Real>(value: T) -> T { value.cos() }
/// Tangent function.
#[inline(always)] pub fn tan<T: Real>(value: T) -> T { value.tan() }
/// Compute the arcsine of the number.
#[inline(always)] pub fn asin<T: Real>(value: T) -> T { value.asin() }
/// Compute the arccosine of the number.
#[inline(always)] pub fn acos<T: Real>(value: T) -> T { value.acos() }
/// Compute the arctangent of the number.
#[inline(always)] pub fn atan<T: Real>(value: T) -> T { value.atan() }
/// Compute the arctangent with 2 arguments.
#[inline(always)] pub fn atan2<T: Real>(x: T, y: T) -> T { x.atan2(&y) }
/// Simultaneously computes the sine and cosine of the number.
#[inline(always)] pub fn sin_cos<T: Real>(value: T) -> (T, T) { value.sin_cos() }
/// Returns `e^(value)`, (the exponential function).
#[inline(always)] pub fn exp<T: Real>(value: T) -> T { value.exp() }
/// Returns 2 raised to the power of the number, `2^(value)`.
#[inline(always)] pub fn exp2<T: Real>(value: T) -> T { value.exp2() }
/// Returns the natural logarithm of the number.
#[inline(always)] pub fn ln<T: Real>(value: T) -> T { value.ln() }
/// Returns the logarithm of the number with respect to an arbitrary base.
#[inline(always)] pub fn log<T: Real>(value: T, base: T) -> T { value.log(&base) }
/// Returns the base 2 logarithm of the number.
#[inline(always)] pub fn log2<T: Real>(value: T) -> T { value.log2() }
/// Returns the base 10 logarithm of the number.
#[inline(always)] pub fn log10<T: Real>(value: T) -> T { value.log10() }
/// Hyperbolic sine function.
#[inline(always)] pub fn sinh<T: Real>(value: T) -> T { value.sinh() }
/// Hyperbolic cosine function.
#[inline(always)] pub fn cosh<T: Real>(value: T) -> T { value.cosh() }
/// Hyperbolic tangent function.
#[inline(always)] pub fn tanh<T: Real>(value: T) -> T { value.tanh() }
/// Inverse hyperbolic sine function.
#[inline(always)] pub fn asinh<T: Real>(value: T) -> T { value.asinh() }
/// Inverse hyperbolic cosine function.
#[inline(always)] pub fn acosh<T: Real>(value: T) -> T { value.acosh() }
/// Inverse hyperbolic tangent function.
#[inline(always)] pub fn atanh<T: Real>(value: T) -> T { value.atanh() }

364 365 366 367 368 369 370 371 372
pub trait Bounded {
    // FIXME (#5527): These should be associated constants
    fn min_value() -> Self;
    fn max_value() -> Self;
}

/// Numbers with a fixed binary representation.
pub trait Bitwise: Bounded
                 + Not<Self>
373 374 375 376
                 + BitAnd<Self,Self>
                 + BitOr<Self,Self>
                 + BitXor<Self,Self>
                 + Shl<Self,Self>
377
                 + Shr<Self,Self> {
378 379 380 381 382
    /// Returns the number of bits set in the number.
    ///
    /// # Example
    ///
    /// ```rust
383 384
    /// use std::num::Bitwise;
    ///
385 386 387
    /// let n = 0b0101000u16;
    /// assert_eq!(n.population_count(), 2);
    /// ```
B
Brendan Zabarauskas 已提交
388
    fn population_count(&self) -> Self;
389 390 391 392 393
    /// Returns the number of leading zeros in the number.
    ///
    /// # Example
    ///
    /// ```rust
394 395
    /// use std::num::Bitwise;
    ///
396 397 398
    /// let n = 0b0101000u16;
    /// assert_eq!(n.leading_zeros(), 10);
    /// ```
B
Brendan Zabarauskas 已提交
399
    fn leading_zeros(&self) -> Self;
400 401 402 403 404
    /// Returns the number of trailing zeros in the number.
    ///
    /// # Example
    ///
    /// ```rust
405 406
    /// use std::num::Bitwise;
    ///
407 408 409
    /// let n = 0b0101000u16;
    /// assert_eq!(n.trailing_zeros(), 3);
    /// ```
B
Brendan Zabarauskas 已提交
410 411 412
    fn trailing_zeros(&self) -> Self;
}

413 414 415
/// Specifies the available operations common to all of Rust's core numeric primitives.
/// These may not always make sense from a purely mathematical point of view, but
/// may be useful for systems programming.
416 417 418
pub trait Primitive: Clone
                   + DeepClone
                   + Num
419
                   + NumCast
M
Michael Darakananda 已提交
420
                   + Ord
421
                   + Bounded {}
422 423

/// A collection of traits relevant to primitive signed and unsigned integers
424 425
pub trait Int: Integer
             + Primitive
426 427 428
             + Bitwise
             + CheckedAdd
             + CheckedSub
429
             + CheckedMul
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
             + CheckedDiv {}

/// Returns the smallest power of 2 greater than or equal to `n`.
#[inline]
pub fn next_power_of_two<T: Unsigned + Int>(n: T) -> T {
    let halfbits: T = cast(size_of::<T>() * 4).unwrap();
    let mut tmp: T = n - one();
    let mut shift: T = one();
    while shift <= halfbits {
        tmp = tmp | (tmp >> shift);
        shift = shift << one();
    }
    tmp + one()
}

/// Returns the smallest power of 2 greater than or equal to `n`. If the next
/// power of two is greater than the type's maximum value, `None` is returned,
/// otherwise the power of 2 is wrapped in `Some`.
#[inline]
pub fn checked_next_power_of_two<T: Unsigned + Int>(n: T) -> Option<T> {
    let halfbits: T = cast(size_of::<T>() * 4).unwrap();
    let mut tmp: T = n - one();
    let mut shift: T = one();
    while shift <= halfbits {
        tmp = tmp | (tmp >> shift);
        shift = shift << one();
    }
    tmp.checked_add(&one())
}
459

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
/// Used for representing the classification of floating point numbers
#[deriving(Eq)]
pub enum FPCategory {
    /// "Not a Number", often obtained by dividing by zero
    FPNaN,
    /// Positive or negative infinity
    FPInfinite ,
    /// Positive or negative zero
    FPZero,
    /// De-normalized floating point representation (less precise than `FPNormal`)
    FPSubnormal,
    /// A regular floating point number
    FPNormal,
}

475
/// Primitive floating point numbers
476 477
pub trait Float: Real
               + Signed
478
               + Primitive {
479
    // FIXME (#5527): These should be associated constants
480
    fn nan() -> Self;
481 482 483 484
    fn infinity() -> Self;
    fn neg_infinity() -> Self;
    fn neg_zero() -> Self;

485
    fn is_nan(&self) -> bool;
486 487
    fn is_infinite(&self) -> bool;
    fn is_finite(&self) -> bool;
488 489
    fn is_normal(&self) -> bool;
    fn classify(&self) -> FPCategory;
490

491
    // FIXME (#8888): Removing `unused_self` requires #8888 to be fixed.
492 493
    fn mantissa_digits(unused_self: Option<Self>) -> uint;
    fn digits(unused_self: Option<Self>) -> uint;
494
    fn epsilon() -> Self;
495 496 497 498
    fn min_exp(unused_self: Option<Self>) -> int;
    fn max_exp(unused_self: Option<Self>) -> int;
    fn min_10_exp(unused_self: Option<Self>) -> int;
    fn max_10_exp(unused_self: Option<Self>) -> int;
499

500 501 502
    fn ldexp(x: Self, exp: int) -> Self;
    fn frexp(&self) -> (Self, int);

503 504
    fn exp_m1(&self) -> Self;
    fn ln_1p(&self) -> Self;
505 506
    fn mul_add(&self, a: Self, b: Self) -> Self;
    fn next_after(&self, other: Self) -> Self;
V
Volker Mische 已提交
507 508

    fn integer_decode(&self) -> (u64, i16, i8);
509 510
}

511 512
/// Returns the exponential of the number, minus `1`, `exp(n) - 1`, in a way
/// that is accurate even if the number is close to zero.
513
#[inline(always)] pub fn exp_m1<T: Float>(value: T) -> T { value.exp_m1() }
514 515
/// Returns the natural logarithm of the number plus `1`, `ln(n + 1)`, more
/// accurately than if the operations were performed separately.
516
#[inline(always)] pub fn ln_1p<T: Float>(value: T) -> T { value.ln_1p() }
517 518 519 520
/// Fused multiply-add. Computes `(a * b) + c` with only one rounding error.
///
/// This produces a more accurate result with better performance (on some
/// architectures) than a separate multiplication operation followed by an add.
521 522
#[inline(always)] pub fn mul_add<T: Float>(a: T, b: T, c: T) -> T { a.mul_add(b, c) }

523 524 525
/// A generic trait for converting a value to a number.
pub trait ToPrimitive {
    /// Converts the value of `self` to an `int`.
526 527
    #[inline]
    fn to_int(&self) -> Option<int> {
528
        self.to_i64().and_then(|x| x.to_int())
529
    }
530 531 532 533

    /// Converts the value of `self` to an `i8`.
    #[inline]
    fn to_i8(&self) -> Option<i8> {
534
        self.to_i64().and_then(|x| x.to_i8())
535 536 537 538 539
    }

    /// Converts the value of `self` to an `i16`.
    #[inline]
    fn to_i16(&self) -> Option<i16> {
540
        self.to_i64().and_then(|x| x.to_i16())
541 542 543 544 545
    }

    /// Converts the value of `self` to an `i32`.
    #[inline]
    fn to_i32(&self) -> Option<i32> {
546
        self.to_i64().and_then(|x| x.to_i32())
547 548 549
    }

    /// Converts the value of `self` to an `i64`.
550 551 552
    fn to_i64(&self) -> Option<i64>;

    /// Converts the value of `self` to an `uint`.
553
    #[inline]
554
    fn to_uint(&self) -> Option<uint> {
555
        self.to_u64().and_then(|x| x.to_uint())
556 557 558 559 560
    }

    /// Converts the value of `self` to an `u8`.
    #[inline]
    fn to_u8(&self) -> Option<u8> {
561
        self.to_u64().and_then(|x| x.to_u8())
562 563 564 565 566
    }

    /// Converts the value of `self` to an `u16`.
    #[inline]
    fn to_u16(&self) -> Option<u16> {
567
        self.to_u64().and_then(|x| x.to_u16())
568 569 570 571 572
    }

    /// Converts the value of `self` to an `u32`.
    #[inline]
    fn to_u32(&self) -> Option<u32> {
573
        self.to_u64().and_then(|x| x.to_u32())
574 575 576 577
    }

    /// Converts the value of `self` to an `u64`.
    #[inline]
578
    fn to_u64(&self) -> Option<u64>;
579 580 581 582

    /// Converts the value of `self` to an `f32`.
    #[inline]
    fn to_f32(&self) -> Option<f32> {
583
        self.to_f64().and_then(|x| x.to_f32())
584 585 586 587 588
    }

    /// Converts the value of `self` to an `f64`.
    #[inline]
    fn to_f64(&self) -> Option<f64> {
589
        self.to_i64().and_then(|x| x.to_f64())
590 591 592
    }
}

593 594 595
macro_rules! impl_to_primitive_int_to_int(
    ($SrcT:ty, $DstT:ty) => (
        {
596
            if size_of::<$SrcT>() <= size_of::<$DstT>() {
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
                Some(*self as $DstT)
            } else {
                let n = *self as i64;
                let min_value: $DstT = Bounded::min_value();
                let max_value: $DstT = Bounded::max_value();
                if min_value as i64 <= n && n <= max_value as i64 {
                    Some(*self as $DstT)
                } else {
                    None
                }
            }
        }
    )
)

macro_rules! impl_to_primitive_int_to_uint(
    ($SrcT:ty, $DstT:ty) => (
        {
            let zero: $SrcT = Zero::zero();
            let max_value: $DstT = Bounded::max_value();
            if zero <= *self && *self as u64 <= max_value as u64 {
                Some(*self as $DstT)
            } else {
                None
            }
        }
    )
)

macro_rules! impl_to_primitive_int(
    ($T:ty) => (
        impl ToPrimitive for $T {
            #[inline]
            fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int) }
            #[inline]
            fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8) }
            #[inline]
            fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16) }
            #[inline]
            fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32) }
            #[inline]
            fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64) }

            #[inline]
            fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint) }
            #[inline]
            fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8) }
            #[inline]
            fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16) }
            #[inline]
            fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32) }
            #[inline]
            fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64) }

            #[inline]
            fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
            #[inline]
            fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
        }
    )
)

impl_to_primitive_int!(int)
impl_to_primitive_int!(i8)
impl_to_primitive_int!(i16)
impl_to_primitive_int!(i32)
impl_to_primitive_int!(i64)

macro_rules! impl_to_primitive_uint_to_int(
    ($DstT:ty) => (
        {
            let max_value: $DstT = Bounded::max_value();
            if *self as u64 <= max_value as u64 {
                Some(*self as $DstT)
            } else {
                None
            }
        }
    )
)

macro_rules! impl_to_primitive_uint_to_uint(
    ($SrcT:ty, $DstT:ty) => (
        {
681
            if size_of::<$SrcT>() <= size_of::<$DstT>() {
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
                Some(*self as $DstT)
            } else {
                let zero: $SrcT = Zero::zero();
                let max_value: $DstT = Bounded::max_value();
                if zero <= *self && *self as u64 <= max_value as u64 {
                    Some(*self as $DstT)
                } else {
                    None
                }
            }
        }
    )
)

macro_rules! impl_to_primitive_uint(
697 698
    ($T:ty) => (
        impl ToPrimitive for $T {
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
            #[inline]
            fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int) }
            #[inline]
            fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8) }
            #[inline]
            fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16) }
            #[inline]
            fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32) }
            #[inline]
            fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64) }

            #[inline]
            fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint) }
            #[inline]
            fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8) }
            #[inline]
            fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16) }
            #[inline]
            fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32) }
            #[inline]
            fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64) }

            #[inline]
            fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
            #[inline]
            fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
        }
    )
)

impl_to_primitive_uint!(uint)
impl_to_primitive_uint!(u8)
impl_to_primitive_uint!(u16)
impl_to_primitive_uint!(u32)
impl_to_primitive_uint!(u64)

macro_rules! impl_to_primitive_float_to_float(
    ($SrcT:ty, $DstT:ty) => (
737
        if size_of::<$SrcT>() <= size_of::<$DstT>() {
738 739 740 741
            Some(*self as $DstT)
        } else {
            let n = *self as f64;
            let max_value: $SrcT = Bounded::max_value();
742
            if -max_value as f64 <= n && n <= max_value as f64 {
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
                Some(*self as $DstT)
            } else {
                None
            }
        }
    )
)

macro_rules! impl_to_primitive_float(
    ($T:ty) => (
        impl ToPrimitive for $T {
            #[inline]
            fn to_int(&self) -> Option<int> { Some(*self as int) }
            #[inline]
            fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
            #[inline]
            fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
            #[inline]
            fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
            #[inline]
            fn to_i64(&self) -> Option<i64> { Some(*self as i64) }

            #[inline]
            fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
            #[inline]
            fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
            #[inline]
            fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
            #[inline]
            fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
            #[inline]
            fn to_u64(&self) -> Option<u64> { Some(*self as u64) }

            #[inline]
            fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32) }
            #[inline]
            fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64) }
780 781 782 783
        }
    )
)

784 785
impl_to_primitive_float!(f32)
impl_to_primitive_float!(f64)
786 787 788 789 790

/// A generic trait for converting a number to a value.
pub trait FromPrimitive {
    /// Convert an `int` to return an optional value of this type. If the
    /// value cannot be represented by this value, the `None` is returned.
791 792 793 794
    #[inline]
    fn from_int(n: int) -> Option<Self> {
        FromPrimitive::from_i64(n as i64)
    }
795 796 797 798 799

    /// Convert an `i8` to return an optional value of this type. If the
    /// type cannot be represented by this value, the `None` is returned.
    #[inline]
    fn from_i8(n: i8) -> Option<Self> {
800
        FromPrimitive::from_i64(n as i64)
801 802 803 804 805 806
    }

    /// Convert an `i16` to return an optional value of this type. If the
    /// type cannot be represented by this value, the `None` is returned.
    #[inline]
    fn from_i16(n: i16) -> Option<Self> {
807
        FromPrimitive::from_i64(n as i64)
808 809 810 811 812 813
    }

    /// Convert an `i32` to return an optional value of this type. If the
    /// type cannot be represented by this value, the `None` is returned.
    #[inline]
    fn from_i32(n: i32) -> Option<Self> {
814
        FromPrimitive::from_i64(n as i64)
815 816 817 818
    }

    /// Convert an `i64` to return an optional value of this type. If the
    /// type cannot be represented by this value, the `None` is returned.
819
    fn from_i64(n: i64) -> Option<Self>;
820 821 822

    /// Convert an `uint` to return an optional value of this type. If the
    /// type cannot be represented by this value, the `None` is returned.
823 824 825 826
    #[inline]
    fn from_uint(n: uint) -> Option<Self> {
        FromPrimitive::from_u64(n as u64)
    }
827 828 829 830 831

    /// Convert an `u8` to return an optional value of this type. If the
    /// type cannot be represented by this value, the `None` is returned.
    #[inline]
    fn from_u8(n: u8) -> Option<Self> {
832
        FromPrimitive::from_u64(n as u64)
833 834 835 836 837 838
    }

    /// Convert an `u16` to return an optional value of this type. If the
    /// type cannot be represented by this value, the `None` is returned.
    #[inline]
    fn from_u16(n: u16) -> Option<Self> {
839
        FromPrimitive::from_u64(n as u64)
840 841 842 843 844 845
    }

    /// Convert an `u32` to return an optional value of this type. If the
    /// type cannot be represented by this value, the `None` is returned.
    #[inline]
    fn from_u32(n: u32) -> Option<Self> {
846
        FromPrimitive::from_u64(n as u64)
847 848 849 850
    }

    /// Convert an `u64` to return an optional value of this type. If the
    /// type cannot be represented by this value, the `None` is returned.
851
    fn from_u64(n: u64) -> Option<Self>;
852 853 854 855 856

    /// Convert a `f32` to return an optional value of this type. If the
    /// type cannot be represented by this value, the `None` is returned.
    #[inline]
    fn from_f32(n: f32) -> Option<Self> {
857
        FromPrimitive::from_f64(n as f64)
858 859 860 861 862 863
    }

    /// Convert a `f64` to return an optional value of this type. If the
    /// type cannot be represented by this value, the `None` is returned.
    #[inline]
    fn from_f64(n: f64) -> Option<Self> {
864
        FromPrimitive::from_i64(n as i64)
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
    }
}

/// A utility function that just calls `FromPrimitive::from_int`.
pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
    FromPrimitive::from_int(n)
}

/// A utility function that just calls `FromPrimitive::from_i8`.
pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> {
    FromPrimitive::from_i8(n)
}

/// A utility function that just calls `FromPrimitive::from_i16`.
pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> {
    FromPrimitive::from_i16(n)
}

/// A utility function that just calls `FromPrimitive::from_i32`.
pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> {
    FromPrimitive::from_i32(n)
}

/// A utility function that just calls `FromPrimitive::from_i64`.
pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
    FromPrimitive::from_i64(n)
}

/// A utility function that just calls `FromPrimitive::from_uint`.
pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
    FromPrimitive::from_uint(n)
}

/// A utility function that just calls `FromPrimitive::from_u8`.
pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> {
    FromPrimitive::from_u8(n)
}

/// A utility function that just calls `FromPrimitive::from_u16`.
pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> {
    FromPrimitive::from_u16(n)
}

/// A utility function that just calls `FromPrimitive::from_u32`.
pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> {
    FromPrimitive::from_u32(n)
}

/// A utility function that just calls `FromPrimitive::from_u64`.
pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> {
    FromPrimitive::from_u64(n)
}

/// A utility function that just calls `FromPrimitive::from_f32`.
pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> {
    FromPrimitive::from_f32(n)
}

/// A utility function that just calls `FromPrimitive::from_f64`.
pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {
    FromPrimitive::from_f64(n)
}

macro_rules! impl_from_primitive(
929
    ($T:ty, $to_ty:expr) => (
930
        impl FromPrimitive for $T {
931 932 933 934 935 936 937 938 939 940 941 942 943 944
            #[inline] fn from_int(n: int) -> Option<$T> { $to_ty }
            #[inline] fn from_i8(n: i8) -> Option<$T> { $to_ty }
            #[inline] fn from_i16(n: i16) -> Option<$T> { $to_ty }
            #[inline] fn from_i32(n: i32) -> Option<$T> { $to_ty }
            #[inline] fn from_i64(n: i64) -> Option<$T> { $to_ty }

            #[inline] fn from_uint(n: uint) -> Option<$T> { $to_ty }
            #[inline] fn from_u8(n: u8) -> Option<$T> { $to_ty }
            #[inline] fn from_u16(n: u16) -> Option<$T> { $to_ty }
            #[inline] fn from_u32(n: u32) -> Option<$T> { $to_ty }
            #[inline] fn from_u64(n: u64) -> Option<$T> { $to_ty }

            #[inline] fn from_f32(n: f32) -> Option<$T> { $to_ty }
            #[inline] fn from_f64(n: f64) -> Option<$T> { $to_ty }
945 946 947 948
        }
    )
)

949 950 951 952 953 954 955 956 957 958 959 960
impl_from_primitive!(int, n.to_int())
impl_from_primitive!(i8, n.to_i8())
impl_from_primitive!(i16, n.to_i16())
impl_from_primitive!(i32, n.to_i32())
impl_from_primitive!(i64, n.to_i64())
impl_from_primitive!(uint, n.to_uint())
impl_from_primitive!(u8, n.to_u8())
impl_from_primitive!(u16, n.to_u16())
impl_from_primitive!(u32, n.to_u32())
impl_from_primitive!(u64, n.to_u64())
impl_from_primitive!(f32, n.to_f32())
impl_from_primitive!(f64, n.to_f64())
961

962
/// Cast from one machine scalar to another.
963 964 965
///
/// # Example
///
966
/// ```
967
/// let twenty: f32 = num::cast(0x14).unwrap();
968
/// assert_eq!(twenty, 20f32);
969
/// ```
970
///
971
#[inline]
972
pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
973 974 975
    NumCast::from(n)
}

976
/// An interface for casting between machine scalars
977 978
pub trait NumCast: ToPrimitive {
    fn from<T: ToPrimitive>(n: T) -> Option<Self>;
979 980
}

981 982
macro_rules! impl_num_cast(
    ($T:ty, $conv:ident) => (
983
        impl NumCast for $T {
984
            #[inline]
985
            fn from<N: ToPrimitive>(n: N) -> Option<$T> {
986 987 988
                // `$conv` could be generated using `concat_idents!`, but that
                // macro seems to be broken at the moment
                n.$conv()
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
            }
        }
    )
)

impl_num_cast!(u8,    to_u8)
impl_num_cast!(u16,   to_u16)
impl_num_cast!(u32,   to_u32)
impl_num_cast!(u64,   to_u64)
impl_num_cast!(uint,  to_uint)
impl_num_cast!(i8,    to_i8)
impl_num_cast!(i16,   to_i16)
impl_num_cast!(i32,   to_i32)
impl_num_cast!(i64,   to_i64)
impl_num_cast!(int,   to_int)
impl_num_cast!(f32,   to_f32)
impl_num_cast!(f64,   to_f64)

1007
pub trait ToStrRadix {
1008
    fn to_str_radix(&self, radix: uint) -> ~str;
1009 1010 1011
}

pub trait FromStrRadix {
1012
    fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
1013 1014
}

1015
/// A utility function that just calls FromStrRadix::from_str_radix.
1016 1017 1018 1019
pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint) -> Option<T> {
    FromStrRadix::from_str_radix(str, radix)
}

K
Kevin Ballard 已提交
1020
/// Saturating math operations
1021
pub trait Saturating {
K
Kevin Ballard 已提交
1022 1023
    /// Saturating addition operator.
    /// Returns a+b, saturating at the numeric bounds instead of overflowing.
1024 1025 1026 1027 1028 1029 1030
    fn saturating_add(self, v: Self) -> Self;

    /// Saturating subtraction operator.
    /// Returns a-b, saturating at the numeric bounds instead of overflowing.
    fn saturating_sub(self, v: Self) -> Self;
}

1031
impl<T: CheckedAdd + CheckedSub + Zero + Ord + Bounded> Saturating for T {
K
Kevin Ballard 已提交
1032
    #[inline]
1033 1034 1035 1036
    fn saturating_add(self, v: T) -> T {
        match self.checked_add(&v) {
            Some(x) => x,
            None => if v >= Zero::zero() {
1037
                Bounded::max_value()
1038
            } else {
1039
                Bounded::min_value()
1040
            }
K
Kevin Ballard 已提交
1041 1042 1043 1044
        }
    }

    #[inline]
1045 1046 1047 1048
    fn saturating_sub(self, v: T) -> T {
        match self.checked_sub(&v) {
            Some(x) => x,
            None => if v >= Zero::zero() {
1049
                Bounded::min_value()
1050
            } else {
1051
                Bounded::max_value()
1052
            }
K
Kevin Ballard 已提交
1053 1054 1055 1056
        }
    }
}

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
pub trait CheckedAdd: Add<Self, Self> {
    fn checked_add(&self, v: &Self) -> Option<Self>;
}

pub trait CheckedSub: Sub<Self, Self> {
    fn checked_sub(&self, v: &Self) -> Option<Self>;
}

pub trait CheckedMul: Mul<Self, Self> {
    fn checked_mul(&self, v: &Self) -> Option<Self>;
}

D
Daniel Micay 已提交
1069 1070 1071 1072
pub trait CheckedDiv: Div<Self, Self> {
    fn checked_div(&self, v: &Self) -> Option<Self>;
}

1073
/// Helper function for testing numeric operations
B
Brian Anderson 已提交
1074
#[cfg(test)]
1075
pub fn test_num<T:Num + NumCast>(ten: T, two: T) {
1076 1077 1078 1079 1080
    assert_eq!(ten.add(&two),  cast(12).unwrap());
    assert_eq!(ten.sub(&two),  cast(8).unwrap());
    assert_eq!(ten.mul(&two),  cast(20).unwrap());
    assert_eq!(ten.div(&two),  cast(5).unwrap());
    assert_eq!(ten.rem(&two),  cast(0).unwrap());
1081 1082 1083 1084

    assert_eq!(ten.add(&two),  ten + two);
    assert_eq!(ten.sub(&two),  ten - two);
    assert_eq!(ten.mul(&two),  ten * two);
M
Marvin Löbel 已提交
1085
    assert_eq!(ten.div(&two),  ten / two);
1086 1087
    assert_eq!(ten.rem(&two),  ten % two);
}
1088

K
Kevin Ballard 已提交
1089 1090
#[cfg(test)]
mod tests {
1091
    use prelude::*;
K
Kevin Ballard 已提交
1092
    use super::*;
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
    use i8;
    use i16;
    use i32;
    use i64;
    use int;
    use u8;
    use u16;
    use u32;
    use u64;
    use uint;
K
Kevin Ballard 已提交
1103 1104 1105 1106 1107

    macro_rules! test_cast_20(
        ($_20:expr) => ({
            let _20 = $_20;

1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
            assert_eq!(20u,   _20.to_uint().unwrap());
            assert_eq!(20u8,  _20.to_u8().unwrap());
            assert_eq!(20u16, _20.to_u16().unwrap());
            assert_eq!(20u32, _20.to_u32().unwrap());
            assert_eq!(20u64, _20.to_u64().unwrap());
            assert_eq!(20i,   _20.to_int().unwrap());
            assert_eq!(20i8,  _20.to_i8().unwrap());
            assert_eq!(20i16, _20.to_i16().unwrap());
            assert_eq!(20i32, _20.to_i32().unwrap());
            assert_eq!(20i64, _20.to_i64().unwrap());
            assert_eq!(20f32, _20.to_f32().unwrap());
            assert_eq!(20f64, _20.to_f64().unwrap());

            assert_eq!(_20, NumCast::from(20u).unwrap());
            assert_eq!(_20, NumCast::from(20u8).unwrap());
            assert_eq!(_20, NumCast::from(20u16).unwrap());
            assert_eq!(_20, NumCast::from(20u32).unwrap());
            assert_eq!(_20, NumCast::from(20u64).unwrap());
            assert_eq!(_20, NumCast::from(20i).unwrap());
            assert_eq!(_20, NumCast::from(20i8).unwrap());
            assert_eq!(_20, NumCast::from(20i16).unwrap());
            assert_eq!(_20, NumCast::from(20i32).unwrap());
            assert_eq!(_20, NumCast::from(20i64).unwrap());
            assert_eq!(_20, NumCast::from(20f32).unwrap());
            assert_eq!(_20, NumCast::from(20f64).unwrap());

            assert_eq!(_20, cast(20u).unwrap());
            assert_eq!(_20, cast(20u8).unwrap());
            assert_eq!(_20, cast(20u16).unwrap());
            assert_eq!(_20, cast(20u32).unwrap());
            assert_eq!(_20, cast(20u64).unwrap());
            assert_eq!(_20, cast(20i).unwrap());
            assert_eq!(_20, cast(20i8).unwrap());
            assert_eq!(_20, cast(20i16).unwrap());
            assert_eq!(_20, cast(20i32).unwrap());
            assert_eq!(_20, cast(20i64).unwrap());
            assert_eq!(_20, cast(20f32).unwrap());
            assert_eq!(_20, cast(20f64).unwrap());
K
Kevin Ballard 已提交
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
        })
    )

    #[test] fn test_u8_cast()    { test_cast_20!(20u8)  }
    #[test] fn test_u16_cast()   { test_cast_20!(20u16) }
    #[test] fn test_u32_cast()   { test_cast_20!(20u32) }
    #[test] fn test_u64_cast()   { test_cast_20!(20u64) }
    #[test] fn test_uint_cast()  { test_cast_20!(20u)   }
    #[test] fn test_i8_cast()    { test_cast_20!(20i8)  }
    #[test] fn test_i16_cast()   { test_cast_20!(20i16) }
    #[test] fn test_i32_cast()   { test_cast_20!(20i32) }
    #[test] fn test_i64_cast()   { test_cast_20!(20i64) }
    #[test] fn test_int_cast()   { test_cast_20!(20i)   }
    #[test] fn test_f32_cast()   { test_cast_20!(20f32) }
    #[test] fn test_f64_cast()   { test_cast_20!(20f64) }

1162 1163
    #[test]
    fn test_cast_range_int_min() {
C
Chris Wong 已提交
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
        assert_eq!(int::MIN.to_int(),  Some(int::MIN as int));
        assert_eq!(int::MIN.to_i8(),   None);
        assert_eq!(int::MIN.to_i16(),  None);
        // int::MIN.to_i32() is word-size specific
        assert_eq!(int::MIN.to_i64(),  Some(int::MIN as i64));
        assert_eq!(int::MIN.to_uint(), None);
        assert_eq!(int::MIN.to_u8(),   None);
        assert_eq!(int::MIN.to_u16(),  None);
        assert_eq!(int::MIN.to_u32(),  None);
        assert_eq!(int::MIN.to_u64(),  None);
1174 1175 1176

        #[cfg(target_word_size = "32")]
        fn check_word_size() {
C
Chris Wong 已提交
1177
            assert_eq!(int::MIN.to_i32(), Some(int::MIN as i32));
1178 1179 1180 1181
        }

        #[cfg(target_word_size = "64")]
        fn check_word_size() {
C
Chris Wong 已提交
1182
            assert_eq!(int::MIN.to_i32(), None);
1183 1184 1185 1186 1187 1188 1189
        }

        check_word_size();
    }

    #[test]
    fn test_cast_range_i8_min() {
C
Chris Wong 已提交
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
        assert_eq!(i8::MIN.to_int(),  Some(i8::MIN as int));
        assert_eq!(i8::MIN.to_i8(),   Some(i8::MIN as i8));
        assert_eq!(i8::MIN.to_i16(),  Some(i8::MIN as i16));
        assert_eq!(i8::MIN.to_i32(),  Some(i8::MIN as i32));
        assert_eq!(i8::MIN.to_i64(),  Some(i8::MIN as i64));
        assert_eq!(i8::MIN.to_uint(), None);
        assert_eq!(i8::MIN.to_u8(),   None);
        assert_eq!(i8::MIN.to_u16(),  None);
        assert_eq!(i8::MIN.to_u32(),  None);
        assert_eq!(i8::MIN.to_u64(),  None);
1200 1201 1202 1203
    }

    #[test]
    fn test_cast_range_i16_min() {
C
Chris Wong 已提交
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
        assert_eq!(i16::MIN.to_int(),  Some(i16::MIN as int));
        assert_eq!(i16::MIN.to_i8(),   None);
        assert_eq!(i16::MIN.to_i16(),  Some(i16::MIN as i16));
        assert_eq!(i16::MIN.to_i32(),  Some(i16::MIN as i32));
        assert_eq!(i16::MIN.to_i64(),  Some(i16::MIN as i64));
        assert_eq!(i16::MIN.to_uint(), None);
        assert_eq!(i16::MIN.to_u8(),   None);
        assert_eq!(i16::MIN.to_u16(),  None);
        assert_eq!(i16::MIN.to_u32(),  None);
        assert_eq!(i16::MIN.to_u64(),  None);
1214 1215 1216 1217
    }

    #[test]
    fn test_cast_range_i32_min() {
C
Chris Wong 已提交
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
        assert_eq!(i32::MIN.to_int(),  Some(i32::MIN as int));
        assert_eq!(i32::MIN.to_i8(),   None);
        assert_eq!(i32::MIN.to_i16(),  None);
        assert_eq!(i32::MIN.to_i32(),  Some(i32::MIN as i32));
        assert_eq!(i32::MIN.to_i64(),  Some(i32::MIN as i64));
        assert_eq!(i32::MIN.to_uint(), None);
        assert_eq!(i32::MIN.to_u8(),   None);
        assert_eq!(i32::MIN.to_u16(),  None);
        assert_eq!(i32::MIN.to_u32(),  None);
        assert_eq!(i32::MIN.to_u64(),  None);
1228 1229 1230 1231
    }

    #[test]
    fn test_cast_range_i64_min() {
C
Chris Wong 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
        // i64::MIN.to_int() is word-size specific
        assert_eq!(i64::MIN.to_i8(),   None);
        assert_eq!(i64::MIN.to_i16(),  None);
        assert_eq!(i64::MIN.to_i32(),  None);
        assert_eq!(i64::MIN.to_i64(),  Some(i64::MIN as i64));
        assert_eq!(i64::MIN.to_uint(), None);
        assert_eq!(i64::MIN.to_u8(),   None);
        assert_eq!(i64::MIN.to_u16(),  None);
        assert_eq!(i64::MIN.to_u32(),  None);
        assert_eq!(i64::MIN.to_u64(),  None);
1242 1243 1244

        #[cfg(target_word_size = "32")]
        fn check_word_size() {
C
Chris Wong 已提交
1245
            assert_eq!(i64::MIN.to_int(), None);
1246 1247 1248 1249
        }

        #[cfg(target_word_size = "64")]
        fn check_word_size() {
C
Chris Wong 已提交
1250
            assert_eq!(i64::MIN.to_int(), Some(i64::MIN as int));
1251 1252 1253 1254 1255 1256 1257
        }

        check_word_size();
    }

    #[test]
    fn test_cast_range_int_max() {
C
Chris Wong 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266
        assert_eq!(int::MAX.to_int(),  Some(int::MAX as int));
        assert_eq!(int::MAX.to_i8(),   None);
        assert_eq!(int::MAX.to_i16(),  None);
        // int::MAX.to_i32() is word-size specific
        assert_eq!(int::MAX.to_i64(),  Some(int::MAX as i64));
        assert_eq!(int::MAX.to_u8(),   None);
        assert_eq!(int::MAX.to_u16(),  None);
        // int::MAX.to_u32() is word-size specific
        assert_eq!(int::MAX.to_u64(),  Some(int::MAX as u64));
1267 1268 1269

        #[cfg(target_word_size = "32")]
        fn check_word_size() {
C
Chris Wong 已提交
1270 1271
            assert_eq!(int::MAX.to_i32(), Some(int::MAX as i32));
            assert_eq!(int::MAX.to_u32(), Some(int::MAX as u32));
1272 1273 1274 1275
        }

        #[cfg(target_word_size = "64")]
        fn check_word_size() {
C
Chris Wong 已提交
1276 1277
            assert_eq!(int::MAX.to_i32(), None);
            assert_eq!(int::MAX.to_u32(), None);
1278 1279 1280 1281 1282 1283 1284
        }

        check_word_size();
    }

    #[test]
    fn test_cast_range_i8_max() {
C
Chris Wong 已提交
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
        assert_eq!(i8::MAX.to_int(),  Some(i8::MAX as int));
        assert_eq!(i8::MAX.to_i8(),   Some(i8::MAX as i8));
        assert_eq!(i8::MAX.to_i16(),  Some(i8::MAX as i16));
        assert_eq!(i8::MAX.to_i32(),  Some(i8::MAX as i32));
        assert_eq!(i8::MAX.to_i64(),  Some(i8::MAX as i64));
        assert_eq!(i8::MAX.to_uint(), Some(i8::MAX as uint));
        assert_eq!(i8::MAX.to_u8(),   Some(i8::MAX as u8));
        assert_eq!(i8::MAX.to_u16(),  Some(i8::MAX as u16));
        assert_eq!(i8::MAX.to_u32(),  Some(i8::MAX as u32));
        assert_eq!(i8::MAX.to_u64(),  Some(i8::MAX as u64));
1295 1296 1297 1298
    }

    #[test]
    fn test_cast_range_i16_max() {
C
Chris Wong 已提交
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
        assert_eq!(i16::MAX.to_int(),  Some(i16::MAX as int));
        assert_eq!(i16::MAX.to_i8(),   None);
        assert_eq!(i16::MAX.to_i16(),  Some(i16::MAX as i16));
        assert_eq!(i16::MAX.to_i32(),  Some(i16::MAX as i32));
        assert_eq!(i16::MAX.to_i64(),  Some(i16::MAX as i64));
        assert_eq!(i16::MAX.to_uint(), Some(i16::MAX as uint));
        assert_eq!(i16::MAX.to_u8(),   None);
        assert_eq!(i16::MAX.to_u16(),  Some(i16::MAX as u16));
        assert_eq!(i16::MAX.to_u32(),  Some(i16::MAX as u32));
        assert_eq!(i16::MAX.to_u64(),  Some(i16::MAX as u64));
1309 1310 1311 1312
    }

    #[test]
    fn test_cast_range_i32_max() {
C
Chris Wong 已提交
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
        assert_eq!(i32::MAX.to_int(),  Some(i32::MAX as int));
        assert_eq!(i32::MAX.to_i8(),   None);
        assert_eq!(i32::MAX.to_i16(),  None);
        assert_eq!(i32::MAX.to_i32(),  Some(i32::MAX as i32));
        assert_eq!(i32::MAX.to_i64(),  Some(i32::MAX as i64));
        assert_eq!(i32::MAX.to_uint(), Some(i32::MAX as uint));
        assert_eq!(i32::MAX.to_u8(),   None);
        assert_eq!(i32::MAX.to_u16(),  None);
        assert_eq!(i32::MAX.to_u32(),  Some(i32::MAX as u32));
        assert_eq!(i32::MAX.to_u64(),  Some(i32::MAX as u64));
1323 1324 1325 1326
    }

    #[test]
    fn test_cast_range_i64_max() {
C
Chris Wong 已提交
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
        // i64::MAX.to_int() is word-size specific
        assert_eq!(i64::MAX.to_i8(),   None);
        assert_eq!(i64::MAX.to_i16(),  None);
        assert_eq!(i64::MAX.to_i32(),  None);
        assert_eq!(i64::MAX.to_i64(),  Some(i64::MAX as i64));
        // i64::MAX.to_uint() is word-size specific
        assert_eq!(i64::MAX.to_u8(),   None);
        assert_eq!(i64::MAX.to_u16(),  None);
        assert_eq!(i64::MAX.to_u32(),  None);
        assert_eq!(i64::MAX.to_u64(),  Some(i64::MAX as u64));
1337 1338 1339

        #[cfg(target_word_size = "32")]
        fn check_word_size() {
C
Chris Wong 已提交
1340 1341
            assert_eq!(i64::MAX.to_int(),  None);
            assert_eq!(i64::MAX.to_uint(), None);
1342 1343 1344 1345
        }

        #[cfg(target_word_size = "64")]
        fn check_word_size() {
C
Chris Wong 已提交
1346 1347
            assert_eq!(i64::MAX.to_int(),  Some(i64::MAX as int));
            assert_eq!(i64::MAX.to_uint(), Some(i64::MAX as uint));
1348 1349 1350 1351 1352 1353 1354
        }

        check_word_size();
    }

    #[test]
    fn test_cast_range_uint_min() {
C
Chris Wong 已提交
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
        assert_eq!(uint::MIN.to_int(),  Some(uint::MIN as int));
        assert_eq!(uint::MIN.to_i8(),   Some(uint::MIN as i8));
        assert_eq!(uint::MIN.to_i16(),  Some(uint::MIN as i16));
        assert_eq!(uint::MIN.to_i32(),  Some(uint::MIN as i32));
        assert_eq!(uint::MIN.to_i64(),  Some(uint::MIN as i64));
        assert_eq!(uint::MIN.to_uint(), Some(uint::MIN as uint));
        assert_eq!(uint::MIN.to_u8(),   Some(uint::MIN as u8));
        assert_eq!(uint::MIN.to_u16(),  Some(uint::MIN as u16));
        assert_eq!(uint::MIN.to_u32(),  Some(uint::MIN as u32));
        assert_eq!(uint::MIN.to_u64(),  Some(uint::MIN as u64));
1365 1366 1367 1368
    }

    #[test]
    fn test_cast_range_u8_min() {
C
Chris Wong 已提交
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
        assert_eq!(u8::MIN.to_int(),  Some(u8::MIN as int));
        assert_eq!(u8::MIN.to_i8(),   Some(u8::MIN as i8));
        assert_eq!(u8::MIN.to_i16(),  Some(u8::MIN as i16));
        assert_eq!(u8::MIN.to_i32(),  Some(u8::MIN as i32));
        assert_eq!(u8::MIN.to_i64(),  Some(u8::MIN as i64));
        assert_eq!(u8::MIN.to_uint(), Some(u8::MIN as uint));
        assert_eq!(u8::MIN.to_u8(),   Some(u8::MIN as u8));
        assert_eq!(u8::MIN.to_u16(),  Some(u8::MIN as u16));
        assert_eq!(u8::MIN.to_u32(),  Some(u8::MIN as u32));
        assert_eq!(u8::MIN.to_u64(),  Some(u8::MIN as u64));
1379 1380 1381 1382
    }

    #[test]
    fn test_cast_range_u16_min() {
C
Chris Wong 已提交
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
        assert_eq!(u16::MIN.to_int(),  Some(u16::MIN as int));
        assert_eq!(u16::MIN.to_i8(),   Some(u16::MIN as i8));
        assert_eq!(u16::MIN.to_i16(),  Some(u16::MIN as i16));
        assert_eq!(u16::MIN.to_i32(),  Some(u16::MIN as i32));
        assert_eq!(u16::MIN.to_i64(),  Some(u16::MIN as i64));
        assert_eq!(u16::MIN.to_uint(), Some(u16::MIN as uint));
        assert_eq!(u16::MIN.to_u8(),   Some(u16::MIN as u8));
        assert_eq!(u16::MIN.to_u16(),  Some(u16::MIN as u16));
        assert_eq!(u16::MIN.to_u32(),  Some(u16::MIN as u32));
        assert_eq!(u16::MIN.to_u64(),  Some(u16::MIN as u64));
1393 1394 1395 1396
    }

    #[test]
    fn test_cast_range_u32_min() {
C
Chris Wong 已提交
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
        assert_eq!(u32::MIN.to_int(),  Some(u32::MIN as int));
        assert_eq!(u32::MIN.to_i8(),   Some(u32::MIN as i8));
        assert_eq!(u32::MIN.to_i16(),  Some(u32::MIN as i16));
        assert_eq!(u32::MIN.to_i32(),  Some(u32::MIN as i32));
        assert_eq!(u32::MIN.to_i64(),  Some(u32::MIN as i64));
        assert_eq!(u32::MIN.to_uint(), Some(u32::MIN as uint));
        assert_eq!(u32::MIN.to_u8(),   Some(u32::MIN as u8));
        assert_eq!(u32::MIN.to_u16(),  Some(u32::MIN as u16));
        assert_eq!(u32::MIN.to_u32(),  Some(u32::MIN as u32));
        assert_eq!(u32::MIN.to_u64(),  Some(u32::MIN as u64));
1407 1408 1409 1410
    }

    #[test]
    fn test_cast_range_u64_min() {
C
Chris Wong 已提交
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
        assert_eq!(u64::MIN.to_int(),  Some(u64::MIN as int));
        assert_eq!(u64::MIN.to_i8(),   Some(u64::MIN as i8));
        assert_eq!(u64::MIN.to_i16(),  Some(u64::MIN as i16));
        assert_eq!(u64::MIN.to_i32(),  Some(u64::MIN as i32));
        assert_eq!(u64::MIN.to_i64(),  Some(u64::MIN as i64));
        assert_eq!(u64::MIN.to_uint(), Some(u64::MIN as uint));
        assert_eq!(u64::MIN.to_u8(),   Some(u64::MIN as u8));
        assert_eq!(u64::MIN.to_u16(),  Some(u64::MIN as u16));
        assert_eq!(u64::MIN.to_u32(),  Some(u64::MIN as u32));
        assert_eq!(u64::MIN.to_u64(),  Some(u64::MIN as u64));
1421 1422 1423 1424
    }

    #[test]
    fn test_cast_range_uint_max() {
C
Chris Wong 已提交
1425 1426 1427 1428 1429 1430 1431 1432 1433
        assert_eq!(uint::MAX.to_int(),  None);
        assert_eq!(uint::MAX.to_i8(),   None);
        assert_eq!(uint::MAX.to_i16(),  None);
        assert_eq!(uint::MAX.to_i32(),  None);
        // uint::MAX.to_i64() is word-size specific
        assert_eq!(uint::MAX.to_u8(),   None);
        assert_eq!(uint::MAX.to_u16(),  None);
        // uint::MAX.to_u32() is word-size specific
        assert_eq!(uint::MAX.to_u64(),  Some(uint::MAX as u64));
1434 1435 1436

        #[cfg(target_word_size = "32")]
        fn check_word_size() {
C
Chris Wong 已提交
1437 1438
            assert_eq!(uint::MAX.to_u32(), Some(uint::MAX as u32));
            assert_eq!(uint::MAX.to_i64(), Some(uint::MAX as i64));
1439 1440 1441 1442
        }

        #[cfg(target_word_size = "64")]
        fn check_word_size() {
C
Chris Wong 已提交
1443 1444
            assert_eq!(uint::MAX.to_u32(), None);
            assert_eq!(uint::MAX.to_i64(), None);
1445 1446 1447 1448 1449 1450 1451
        }

        check_word_size();
    }

    #[test]
    fn test_cast_range_u8_max() {
C
Chris Wong 已提交
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
        assert_eq!(u8::MAX.to_int(),  Some(u8::MAX as int));
        assert_eq!(u8::MAX.to_i8(),   None);
        assert_eq!(u8::MAX.to_i16(),  Some(u8::MAX as i16));
        assert_eq!(u8::MAX.to_i32(),  Some(u8::MAX as i32));
        assert_eq!(u8::MAX.to_i64(),  Some(u8::MAX as i64));
        assert_eq!(u8::MAX.to_uint(), Some(u8::MAX as uint));
        assert_eq!(u8::MAX.to_u8(),   Some(u8::MAX as u8));
        assert_eq!(u8::MAX.to_u16(),  Some(u8::MAX as u16));
        assert_eq!(u8::MAX.to_u32(),  Some(u8::MAX as u32));
        assert_eq!(u8::MAX.to_u64(),  Some(u8::MAX as u64));
1462 1463 1464 1465
    }

    #[test]
    fn test_cast_range_u16_max() {
C
Chris Wong 已提交
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
        assert_eq!(u16::MAX.to_int(),  Some(u16::MAX as int));
        assert_eq!(u16::MAX.to_i8(),   None);
        assert_eq!(u16::MAX.to_i16(),  None);
        assert_eq!(u16::MAX.to_i32(),  Some(u16::MAX as i32));
        assert_eq!(u16::MAX.to_i64(),  Some(u16::MAX as i64));
        assert_eq!(u16::MAX.to_uint(), Some(u16::MAX as uint));
        assert_eq!(u16::MAX.to_u8(),   None);
        assert_eq!(u16::MAX.to_u16(),  Some(u16::MAX as u16));
        assert_eq!(u16::MAX.to_u32(),  Some(u16::MAX as u32));
        assert_eq!(u16::MAX.to_u64(),  Some(u16::MAX as u64));
1476 1477 1478 1479
    }

    #[test]
    fn test_cast_range_u32_max() {
C
Chris Wong 已提交
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
        // u32::MAX.to_int() is word-size specific
        assert_eq!(u32::MAX.to_i8(),   None);
        assert_eq!(u32::MAX.to_i16(),  None);
        assert_eq!(u32::MAX.to_i32(),  None);
        assert_eq!(u32::MAX.to_i64(),  Some(u32::MAX as i64));
        assert_eq!(u32::MAX.to_uint(), Some(u32::MAX as uint));
        assert_eq!(u32::MAX.to_u8(),   None);
        assert_eq!(u32::MAX.to_u16(),  None);
        assert_eq!(u32::MAX.to_u32(),  Some(u32::MAX as u32));
        assert_eq!(u32::MAX.to_u64(),  Some(u32::MAX as u64));
1490 1491 1492

        #[cfg(target_word_size = "32")]
        fn check_word_size() {
C
Chris Wong 已提交
1493
            assert_eq!(u32::MAX.to_int(),  None);
1494 1495 1496 1497
        }

        #[cfg(target_word_size = "64")]
        fn check_word_size() {
C
Chris Wong 已提交
1498
            assert_eq!(u32::MAX.to_int(),  Some(u32::MAX as int));
1499 1500 1501 1502 1503 1504 1505
        }

        check_word_size();
    }

    #[test]
    fn test_cast_range_u64_max() {
C
Chris Wong 已提交
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
        assert_eq!(u64::MAX.to_int(),  None);
        assert_eq!(u64::MAX.to_i8(),   None);
        assert_eq!(u64::MAX.to_i16(),  None);
        assert_eq!(u64::MAX.to_i32(),  None);
        assert_eq!(u64::MAX.to_i64(),  None);
        // u64::MAX.to_uint() is word-size specific
        assert_eq!(u64::MAX.to_u8(),   None);
        assert_eq!(u64::MAX.to_u16(),  None);
        assert_eq!(u64::MAX.to_u32(),  None);
        assert_eq!(u64::MAX.to_u64(),  Some(u64::MAX as u64));
1516 1517 1518

        #[cfg(target_word_size = "32")]
        fn check_word_size() {
C
Chris Wong 已提交
1519
            assert_eq!(u64::MAX.to_uint(), None);
1520 1521 1522 1523
        }

        #[cfg(target_word_size = "64")]
        fn check_word_size() {
C
Chris Wong 已提交
1524
            assert_eq!(u64::MAX.to_uint(), Some(u64::MAX as uint));
1525 1526 1527 1528 1529
        }

        check_word_size();
    }

K
Kevin Ballard 已提交
1530 1531
    #[test]
    fn test_saturating_add_uint() {
C
Chris Wong 已提交
1532
        use uint::MAX;
K
Kevin Ballard 已提交
1533
        assert_eq!(3u.saturating_add(5u), 8u);
C
Chris Wong 已提交
1534 1535 1536
        assert_eq!(3u.saturating_add(MAX-1), MAX);
        assert_eq!(MAX.saturating_add(MAX), MAX);
        assert_eq!((MAX-2).saturating_add(1), MAX-1);
K
Kevin Ballard 已提交
1537 1538 1539 1540
    }

    #[test]
    fn test_saturating_sub_uint() {
C
Chris Wong 已提交
1541
        use uint::MAX;
K
Kevin Ballard 已提交
1542 1543 1544
        assert_eq!(5u.saturating_sub(3u), 2u);
        assert_eq!(3u.saturating_sub(5u), 0u);
        assert_eq!(0u.saturating_sub(1u), 0u);
C
Chris Wong 已提交
1545
        assert_eq!((MAX-1).saturating_sub(MAX), 0);
K
Kevin Ballard 已提交
1546
    }
1547

K
Kevin Ballard 已提交
1548 1549
    #[test]
    fn test_saturating_add_int() {
C
Chris Wong 已提交
1550
        use int::{MIN,MAX};
K
Kevin Ballard 已提交
1551
        assert_eq!(3i.saturating_add(5i), 8i);
C
Chris Wong 已提交
1552 1553 1554
        assert_eq!(3i.saturating_add(MAX-1), MAX);
        assert_eq!(MAX.saturating_add(MAX), MAX);
        assert_eq!((MAX-2).saturating_add(1), MAX-1);
K
Kevin Ballard 已提交
1555
        assert_eq!(3i.saturating_add(-5i), -2i);
C
Chris Wong 已提交
1556 1557
        assert_eq!(MIN.saturating_add(-1i), MIN);
        assert_eq!((-2i).saturating_add(-MAX), MIN);
K
Kevin Ballard 已提交
1558 1559 1560 1561
    }

    #[test]
    fn test_saturating_sub_int() {
C
Chris Wong 已提交
1562
        use int::{MIN,MAX};
K
Kevin Ballard 已提交
1563
        assert_eq!(3i.saturating_sub(5i), -2i);
C
Chris Wong 已提交
1564 1565
        assert_eq!(MIN.saturating_sub(1i), MIN);
        assert_eq!((-2i).saturating_sub(MAX), MIN);
K
Kevin Ballard 已提交
1566
        assert_eq!(3i.saturating_sub(-5i), 8i);
C
Chris Wong 已提交
1567 1568 1569
        assert_eq!(3i.saturating_sub(-(MAX-1)), MAX);
        assert_eq!(MAX.saturating_sub(-MAX), MAX);
        assert_eq!((MAX-2).saturating_sub(-1), MAX-1);
K
Kevin Ballard 已提交
1570
    }
1571 1572 1573

    #[test]
    fn test_checked_add() {
C
Chris Wong 已提交
1574 1575 1576 1577 1578 1579 1580
        let five_less = uint::MAX - 5;
        assert_eq!(five_less.checked_add(&0), Some(uint::MAX - 5));
        assert_eq!(five_less.checked_add(&1), Some(uint::MAX - 4));
        assert_eq!(five_less.checked_add(&2), Some(uint::MAX - 3));
        assert_eq!(five_less.checked_add(&3), Some(uint::MAX - 2));
        assert_eq!(five_less.checked_add(&4), Some(uint::MAX - 1));
        assert_eq!(five_less.checked_add(&5), Some(uint::MAX));
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
        assert_eq!(five_less.checked_add(&6), None);
        assert_eq!(five_less.checked_add(&7), None);
    }

    #[test]
    fn test_checked_sub() {
        assert_eq!(5u.checked_sub(&0), Some(5));
        assert_eq!(5u.checked_sub(&1), Some(4));
        assert_eq!(5u.checked_sub(&2), Some(3));
        assert_eq!(5u.checked_sub(&3), Some(2));
        assert_eq!(5u.checked_sub(&4), Some(1));
        assert_eq!(5u.checked_sub(&5), Some(0));
        assert_eq!(5u.checked_sub(&6), None);
        assert_eq!(5u.checked_sub(&7), None);
    }

    #[test]
    fn test_checked_mul() {
C
Chris Wong 已提交
1599
        let third = uint::MAX / 3;
1600 1601 1602 1603 1604 1605
        assert_eq!(third.checked_mul(&0), Some(0));
        assert_eq!(third.checked_mul(&1), Some(third));
        assert_eq!(third.checked_mul(&2), Some(third * 2));
        assert_eq!(third.checked_mul(&3), Some(third * 3));
        assert_eq!(third.checked_mul(&4), None);
    }
1606

1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
    macro_rules! test_next_power_of_two(
        ($test_name:ident, $T:ident) => (
            fn $test_name() {
                #[test];
                assert_eq!(next_power_of_two::<$T>(0), 0);
                let mut next_power = 1;
                for i in range::<$T>(1, 40) {
                     assert_eq!(next_power_of_two(i), next_power);
                     if i == next_power { next_power *= 2 }
                }
            }
        )
    )

    test_next_power_of_two!(test_next_power_of_two_u8, u8)
    test_next_power_of_two!(test_next_power_of_two_u16, u16)
    test_next_power_of_two!(test_next_power_of_two_u32, u32)
    test_next_power_of_two!(test_next_power_of_two_u64, u64)
    test_next_power_of_two!(test_next_power_of_two_uint, uint)

    macro_rules! test_checked_next_power_of_two(
        ($test_name:ident, $T:ident) => (
            fn $test_name() {
                #[test];
                assert_eq!(checked_next_power_of_two::<$T>(0), None);
                let mut next_power = 1;
                for i in range::<$T>(1, 40) {
                     assert_eq!(checked_next_power_of_two(i), Some(next_power));
                     if i == next_power { next_power *= 2 }
                }
                assert!(checked_next_power_of_two::<$T>($T::MAX / 2).is_some());
                assert_eq!(checked_next_power_of_two::<$T>($T::MAX - 1), None);
                assert_eq!(checked_next_power_of_two::<$T>($T::MAX), None);
            }
        )
    )

    test_checked_next_power_of_two!(test_checked_next_power_of_two_u8, u8)
    test_checked_next_power_of_two!(test_checked_next_power_of_two_u16, u16)
    test_checked_next_power_of_two!(test_checked_next_power_of_two_u32, u32)
    test_checked_next_power_of_two!(test_checked_next_power_of_two_u64, u64)
    test_checked_next_power_of_two!(test_checked_next_power_of_two_uint, uint)
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694

    #[deriving(Eq)]
    struct Value { x: int }

    impl ToPrimitive for Value {
        fn to_i64(&self) -> Option<i64> { self.x.to_i64() }
        fn to_u64(&self) -> Option<u64> { self.x.to_u64() }
    }

    impl FromPrimitive for Value {
        fn from_i64(n: i64) -> Option<Value> { Some(Value { x: n as int }) }
        fn from_u64(n: u64) -> Option<Value> { Some(Value { x: n as int }) }
    }

    #[test]
    fn test_to_primitive() {
        let value = Value { x: 5 };
        assert_eq!(value.to_int(),  Some(5));
        assert_eq!(value.to_i8(),   Some(5));
        assert_eq!(value.to_i16(),  Some(5));
        assert_eq!(value.to_i32(),  Some(5));
        assert_eq!(value.to_i64(),  Some(5));
        assert_eq!(value.to_uint(), Some(5));
        assert_eq!(value.to_u8(),   Some(5));
        assert_eq!(value.to_u16(),  Some(5));
        assert_eq!(value.to_u32(),  Some(5));
        assert_eq!(value.to_u64(),  Some(5));
        assert_eq!(value.to_f32(),  Some(5f32));
        assert_eq!(value.to_f64(),  Some(5f64));
    }

    #[test]
    fn test_from_primitive() {
        assert_eq!(from_int(5),    Some(Value { x: 5 }));
        assert_eq!(from_i8(5),     Some(Value { x: 5 }));
        assert_eq!(from_i16(5),    Some(Value { x: 5 }));
        assert_eq!(from_i32(5),    Some(Value { x: 5 }));
        assert_eq!(from_i64(5),    Some(Value { x: 5 }));
        assert_eq!(from_uint(5),   Some(Value { x: 5 }));
        assert_eq!(from_u8(5),     Some(Value { x: 5 }));
        assert_eq!(from_u16(5),    Some(Value { x: 5 }));
        assert_eq!(from_u32(5),    Some(Value { x: 5 }));
        assert_eq!(from_u64(5),    Some(Value { x: 5 }));
        assert_eq!(from_f32(5f32), Some(Value { x: 5 }));
        assert_eq!(from_f64(5f64), Some(Value { x: 5 }));
    }
F
Flavio Percoco 已提交
1695 1696 1697

    #[test]
    fn test_pow() {
1698 1699
        fn naive_pow<T: One + Mul<T, T>>(base: T, exp: uint) -> T {
            range(0, exp).fold(one::<T>(), |acc, _| acc * base)
F
Flavio Percoco 已提交
1700
        }
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
        macro_rules! assert_pow(
            (($num:expr, $exp:expr) => $expected:expr) => {{
                let result = pow($num, $exp);
                assert_eq!(result, $expected);
                assert_eq!(result, naive_pow($num, $exp));
            }}
        )
        assert_pow!((3,    0 ) => 1);
        assert_pow!((5,    1 ) => 5);
        assert_pow!((-4,   2 ) => 16);
        assert_pow!((0.5,  5 ) => 0.03125);
        assert_pow!((8,    3 ) => 512);
        assert_pow!((8.0,  5 ) => 32768.0);
        assert_pow!((8.5,  5 ) => 44370.53125);
        assert_pow!((2u64, 50) => 1125899906842624);
F
Flavio Percoco 已提交
1716
    }
K
Kevin Ballard 已提交
1717
}
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732


#[cfg(test)]
mod bench {
    use num;
    use vec;
    use prelude::*;
    use extra::test::BenchHarness;

    #[bench]
    fn bench_pow_function(b: &mut BenchHarness) {
        let v = vec::from_fn(1024, |n| n);
        b.iter(|| {v.iter().fold(0, |old, new| num::pow(old, *new));});
    }
}