mod.rs 54.3 KB
Newer Older
1 2 3 4 5 6 7 8 9
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// 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.
10 11
//
// ignore-lexer-test FIXME #15679
12

13
//! Numeric traits and functions for the built-in numeric types.
14

15
#![stable]
A
Aaron Turon 已提交
16
#![allow(missing_docs)]
17

18
use char::CharExt;
19
use clone::Clone;
20 21
use cmp::{PartialEq, Eq};
use cmp::{PartialOrd, Ord};
B
Brendan Zabarauskas 已提交
22
use intrinsics;
A
Aaron Turon 已提交
23
use iter::IteratorExt;
24 25 26 27
use kinds::Copy;
use mem::size_of;
use ops::{Add, Sub, Mul, Div, Rem, Neg};
use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
C
Corey Farwell 已提交
28 29
use option::Option;
use option::Option::{Some, None};
A
Alex Crichton 已提交
30
use str::{FromStr, StrExt};
31

32
/// A built-in signed or unsigned integer.
33
#[unstable = "recently settled as part of numerics reform"]
34 35 36 37 38
pub trait Int
    : Copy + Clone
    + NumCast
    + PartialOrd + Ord
    + PartialEq + Eq
J
Jorge Aparicio 已提交
39 40 41 42 43
    + Add<Output=Self>
    + Sub<Output=Self>
    + Mul<Output=Self>
    + Div<Output=Self>
    + Rem<Output=Self>
J
Jorge Aparicio 已提交
44
    + Not<Output=Self>
J
Jorge Aparicio 已提交
45 46 47 48 49
    + BitAnd<Output=Self>
    + BitOr<Output=Self>
    + BitXor<Output=Self>
    + Shl<uint, Output=Self>
    + Shr<uint, Output=Self>
50
{
51
    /// Returns the `0` value of this integer type.
52 53 54
    // FIXME (#5527): Should be an associated constant
    fn zero() -> Self;

55
    /// Returns the `1` value of this integer type.
56 57 58
    // FIXME (#5527): Should be an associated constant
    fn one() -> Self;

59
    /// Returns the smallest value that can be represented by this integer type.
B
Brendan Zabarauskas 已提交
60 61 62
    // FIXME (#5527): Should be and associated constant
    fn min_value() -> Self;

63
    /// Returns the largest value that can be represented by this integer type.
B
Brendan Zabarauskas 已提交
64 65 66
    // FIXME (#5527): Should be and associated constant
    fn max_value() -> Self;

67
    /// Returns the number of ones in the binary representation of `self`.
68 69 70 71
    ///
    /// # Example
    ///
    /// ```rust
72 73
    /// use std::num::Int;
    ///
74
    /// let n = 0b01001100u8;
75
    ///
76 77
    /// assert_eq!(n.count_ones(), 3);
    /// ```
78
    fn count_ones(self) -> uint;
79

80
    /// Returns the number of zeros in the binary representation of `self`.
81 82 83 84
    ///
    /// # Example
    ///
    /// ```rust
85 86
    /// use std::num::Int;
    ///
87
    /// let n = 0b01001100u8;
88
    ///
89 90 91
    /// assert_eq!(n.count_zeros(), 5);
    /// ```
    #[inline]
92
    fn count_zeros(self) -> uint {
93
        (!self).count_ones()
94 95
    }

96
    /// Returns the number of leading zeros in the binary representation
97
    /// of `self`.
98 99 100 101
    ///
    /// # Example
    ///
    /// ```rust
102 103
    /// use std::num::Int;
    ///
104
    /// let n = 0b0101000u16;
105
    ///
106 107
    /// assert_eq!(n.leading_zeros(), 10);
    /// ```
108
    fn leading_zeros(self) -> uint;
109

110
    /// Returns the number of trailing zeros in the binary representation
111
    /// of `self`.
112 113 114 115
    ///
    /// # Example
    ///
    /// ```rust
116 117
    /// use std::num::Int;
    ///
118
    /// let n = 0b0101000u16;
119
    ///
120 121
    /// assert_eq!(n.trailing_zeros(), 3);
    /// ```
122
    fn trailing_zeros(self) -> uint;
123

124 125
    /// Shifts the bits to the left by a specified amount amount, `n`, wrapping
    /// the truncated bits to the end of the resulting integer.
126 127 128 129
    ///
    /// # Example
    ///
    /// ```rust
130 131
    /// use std::num::Int;
    ///
132 133
    /// let n = 0x0123456789ABCDEFu64;
    /// let m = 0x3456789ABCDEF012u64;
134
    ///
135 136
    /// assert_eq!(n.rotate_left(12), m);
    /// ```
137
    fn rotate_left(self, n: uint) -> Self;
138

139 140
    /// Shifts the bits to the right by a specified amount amount, `n`, wrapping
    /// the truncated bits to the beginning of the resulting integer.
141 142 143 144
    ///
    /// # Example
    ///
    /// ```rust
145 146
    /// use std::num::Int;
    ///
147 148
    /// let n = 0x0123456789ABCDEFu64;
    /// let m = 0xDEF0123456789ABCu64;
149
    ///
150 151
    /// assert_eq!(n.rotate_right(12), m);
    /// ```
152 153 154 155 156 157 158
    fn rotate_right(self, n: uint) -> Self;

    /// Reverses the byte order of the integer.
    ///
    /// # Example
    ///
    /// ```rust
159 160
    /// use std::num::Int;
    ///
161 162 163 164 165 166 167
    /// let n = 0x0123456789ABCDEFu64;
    /// let m = 0xEFCDAB8967452301u64;
    ///
    /// assert_eq!(n.swap_bytes(), m);
    /// ```
    fn swap_bytes(self) -> Self;

A
Alex Gaynor 已提交
168
    /// Convert an integer from big endian to the target's endianness.
169 170 171 172 173 174
    ///
    /// On big endian this is a no-op. On little endian the bytes are swapped.
    ///
    /// # Example
    ///
    /// ```rust
175 176
    /// use std::num::Int;
    ///
177 178 179
    /// let n = 0x0123456789ABCDEFu64;
    ///
    /// if cfg!(target_endian = "big") {
180
    ///     assert_eq!(Int::from_be(n), n)
181
    /// } else {
182
    ///     assert_eq!(Int::from_be(n), n.swap_bytes())
183 184 185
    /// }
    /// ```
    #[inline]
186
    fn from_be(x: Self) -> Self {
187 188 189
        if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
    }

A
Alex Gaynor 已提交
190
    /// Convert an integer from little endian to the target's endianness.
191 192 193 194 195 196
    ///
    /// On little endian this is a no-op. On big endian the bytes are swapped.
    ///
    /// # Example
    ///
    /// ```rust
197 198
    /// use std::num::Int;
    ///
199 200 201
    /// let n = 0x0123456789ABCDEFu64;
    ///
    /// if cfg!(target_endian = "little") {
202
    ///     assert_eq!(Int::from_le(n), n)
203
    /// } else {
204
    ///     assert_eq!(Int::from_le(n), n.swap_bytes())
205 206 207
    /// }
    /// ```
    #[inline]
208
    fn from_le(x: Self) -> Self {
209 210 211
        if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
    }

212
    /// Convert `self` to big endian from the target's endianness.
213 214 215 216 217 218
    ///
    /// On big endian this is a no-op. On little endian the bytes are swapped.
    ///
    /// # Example
    ///
    /// ```rust
219 220
    /// use std::num::Int;
    ///
221 222 223
    /// let n = 0x0123456789ABCDEFu64;
    ///
    /// if cfg!(target_endian = "big") {
224
    ///     assert_eq!(n.to_be(), n)
225
    /// } else {
226
    ///     assert_eq!(n.to_be(), n.swap_bytes())
227 228 229
    /// }
    /// ```
    #[inline]
230
    fn to_be(self) -> Self { // or not to be?
231 232 233
        if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
    }

234
    /// Convert `self` to little endian from the target's endianness.
235 236 237 238 239 240
    ///
    /// On little endian this is a no-op. On big endian the bytes are swapped.
    ///
    /// # Example
    ///
    /// ```rust
241 242
    /// use std::num::Int;
    ///
243 244 245
    /// let n = 0x0123456789ABCDEFu64;
    ///
    /// if cfg!(target_endian = "little") {
246
    ///     assert_eq!(n.to_le(), n)
247
    /// } else {
248
    ///     assert_eq!(n.to_le(), n.swap_bytes())
249 250 251
    /// }
    /// ```
    #[inline]
252
    fn to_le(self) -> Self {
253 254
        if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
    }
255

256 257
    /// Checked integer addition. Computes `self + other`, returning `None` if
    /// overflow occurred.
258 259 260 261 262 263 264 265 266 267 268
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::num::Int;
    ///
    /// assert_eq!(5u16.checked_add(65530), Some(65535));
    /// assert_eq!(6u16.checked_add(65530), None);
    /// ```
    fn checked_add(self, other: Self) -> Option<Self>;

269
    /// Checked integer subtraction. Computes `self - other`, returning `None`
270
    /// if underflow occurred.
271 272 273 274 275 276 277 278 279 280 281
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::num::Int;
    ///
    /// assert_eq!((-127i8).checked_sub(1), Some(-128));
    /// assert_eq!((-128i8).checked_sub(1), None);
    /// ```
    fn checked_sub(self, other: Self) -> Option<Self>;

282
    /// Checked integer multiplication. Computes `self * other`, returning
283
    /// `None` if underflow or overflow occurred.
284 285 286 287 288 289 290 291 292 293 294
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::num::Int;
    ///
    /// assert_eq!(5u8.checked_mul(51), Some(255));
    /// assert_eq!(5u8.checked_mul(52), None);
    /// ```
    fn checked_mul(self, other: Self) -> Option<Self>;

295 296
    /// Checked integer division. Computes `self / other`, returning `None` if
    /// `other == 0` or the operation results in underflow or overflow.
297 298 299 300 301 302 303 304 305 306 307 308 309
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::num::Int;
    ///
    /// assert_eq!((-127i8).checked_div(-1), Some(127));
    /// assert_eq!((-128i8).checked_div(-1), None);
    /// assert_eq!((1i8).checked_div(0), None);
    /// ```
    #[inline]
    fn checked_div(self, other: Self) -> Option<Self>;

310 311
    /// Saturating integer addition. Computes `self + other`, saturating at
    /// the numeric bounds instead of overflowing.
312 313
    #[inline]
    fn saturating_add(self, other: Self) -> Self {
314
        match self.checked_add(other) {
315 316 317
            Some(x)                      => x,
            None if other >= Int::zero() => Int::max_value(),
            None                         => Int::min_value(),
318 319 320
        }
    }

321 322
    /// Saturating integer subtraction. Computes `self - other`, saturating at
    /// the numeric bounds instead of overflowing.
323 324
    #[inline]
    fn saturating_sub(self, other: Self) -> Self {
325
        match self.checked_sub(other) {
326 327 328
            Some(x)                      => x,
            None if other >= Int::zero() => Int::min_value(),
            None                         => Int::max_value(),
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

    /// Raises self to the power of `exp`, using exponentiation by squaring.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::num::Int;
    ///
    /// assert_eq!(2i.pow(4), 16);
    /// ```
    #[inline]
    fn pow(self, mut exp: uint) -> Self {
        let mut base = self;
        let mut acc: Self = Int::one();
        while exp > 0 {
            if (exp & 1) == 1 {
                acc = acc * base;
            }
            base = base * base;
            exp /= 2;
        }
        acc
    }
354 355
}

356 357 358 359 360 361 362
macro_rules! checked_op {
    ($T:ty, $U:ty, $op:path, $x:expr, $y:expr) => {{
        let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
        if overflowed { None } else { Some(result as $T) }
    }}
}

B
Brendan Zabarauskas 已提交
363
macro_rules! uint_impl {
364 365 366 367 368 369 370 371
    ($T:ty = $ActualT:ty, $BITS:expr,
     $ctpop:path,
     $ctlz:path,
     $cttz:path,
     $bswap:path,
     $add_with_overflow:path,
     $sub_with_overflow:path,
     $mul_with_overflow:path) => {
372
        #[unstable = "trait is unstable"]
373
        impl Int for $T {
374 375 376 377 378 379
            #[inline]
            fn zero() -> $T { 0 }

            #[inline]
            fn one() -> $T { 1 }

B
Brendan Zabarauskas 已提交
380 381 382 383 384 385
            #[inline]
            fn min_value() -> $T { 0 }

            #[inline]
            fn max_value() -> $T { -1 }

386
            #[inline]
B
Brendan Zabarauskas 已提交
387
            fn count_ones(self) -> uint { unsafe { $ctpop(self as $ActualT) as uint } }
388 389

            #[inline]
B
Brendan Zabarauskas 已提交
390
            fn leading_zeros(self) -> uint { unsafe { $ctlz(self as $ActualT) as uint } }
391 392

            #[inline]
B
Brendan Zabarauskas 已提交
393
            fn trailing_zeros(self) -> uint { unsafe { $cttz(self as $ActualT) as uint } }
394 395

            #[inline]
396 397 398
            fn rotate_left(self, n: uint) -> $T {
                // Protect against undefined behaviour for over-long bit shifts
                let n = n % $BITS;
399
                (self << n) | (self >> (($BITS - n) % $BITS))
400 401 402
            }

            #[inline]
403 404 405
            fn rotate_right(self, n: uint) -> $T {
                // Protect against undefined behaviour for over-long bit shifts
                let n = n % $BITS;
406
                (self >> n) | (self << (($BITS - n) % $BITS))
407
            }
408 409

            #[inline]
B
Brendan Zabarauskas 已提交
410
            fn swap_bytes(self) -> $T { unsafe { $bswap(self as $ActualT) as $T } }
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433

            #[inline]
            fn checked_add(self, other: $T) -> Option<$T> {
                checked_op!($T, $ActualT, $add_with_overflow, self, other)
            }

            #[inline]
            fn checked_sub(self, other: $T) -> Option<$T> {
                checked_op!($T, $ActualT, $sub_with_overflow, self, other)
            }

            #[inline]
            fn checked_mul(self, other: $T) -> Option<$T> {
                checked_op!($T, $ActualT, $mul_with_overflow, self, other)
            }

            #[inline]
            fn checked_div(self, v: $T) -> Option<$T> {
                match v {
                    0 => None,
                    v => Some(self / v),
                }
            }
434 435
        }
    }
436
}
437

438 439 440 441
/// Swapping a single byte is a no-op. This is marked as `unsafe` for
/// consistency with the other `bswap` intrinsics.
unsafe fn bswap8(x: u8) -> u8 { x }

442
uint_impl! { u8 = u8, 8,
443 444 445
    intrinsics::ctpop8,
    intrinsics::ctlz8,
    intrinsics::cttz8,
446 447 448
    bswap8,
    intrinsics::u8_add_with_overflow,
    intrinsics::u8_sub_with_overflow,
449
    intrinsics::u8_mul_with_overflow }
450

451
uint_impl! { u16 = u16, 16,
452 453 454
    intrinsics::ctpop16,
    intrinsics::ctlz16,
    intrinsics::cttz16,
455 456 457
    intrinsics::bswap16,
    intrinsics::u16_add_with_overflow,
    intrinsics::u16_sub_with_overflow,
458
    intrinsics::u16_mul_with_overflow }
459

460
uint_impl! { u32 = u32, 32,
461 462 463
    intrinsics::ctpop32,
    intrinsics::ctlz32,
    intrinsics::cttz32,
464 465 466
    intrinsics::bswap32,
    intrinsics::u32_add_with_overflow,
    intrinsics::u32_sub_with_overflow,
467
    intrinsics::u32_mul_with_overflow }
468

469
uint_impl! { u64 = u64, 64,
470 471 472
    intrinsics::ctpop64,
    intrinsics::ctlz64,
    intrinsics::cttz64,
473 474 475
    intrinsics::bswap64,
    intrinsics::u64_add_with_overflow,
    intrinsics::u64_sub_with_overflow,
476
    intrinsics::u64_mul_with_overflow }
477

B
Brendan Zabarauskas 已提交
478
#[cfg(target_word_size = "32")]
479
uint_impl! { uint = u32, 32,
B
Brendan Zabarauskas 已提交
480 481 482
    intrinsics::ctpop32,
    intrinsics::ctlz32,
    intrinsics::cttz32,
483 484 485
    intrinsics::bswap32,
    intrinsics::u32_add_with_overflow,
    intrinsics::u32_sub_with_overflow,
486
    intrinsics::u32_mul_with_overflow }
B
Brendan Zabarauskas 已提交
487 488

#[cfg(target_word_size = "64")]
489
uint_impl! { uint = u64, 64,
B
Brendan Zabarauskas 已提交
490 491 492
    intrinsics::ctpop64,
    intrinsics::ctlz64,
    intrinsics::cttz64,
493 494 495
    intrinsics::bswap64,
    intrinsics::u64_add_with_overflow,
    intrinsics::u64_sub_with_overflow,
496
    intrinsics::u64_mul_with_overflow }
B
Brendan Zabarauskas 已提交
497 498

macro_rules! int_impl {
B
Brendan Zabarauskas 已提交
499
    ($T:ty = $ActualT:ty, $UnsignedT:ty, $BITS:expr,
500 501 502
     $add_with_overflow:path,
     $sub_with_overflow:path,
     $mul_with_overflow:path) => {
503
        #[unstable = "trait is unstable"]
504
        impl Int for $T {
505 506 507 508 509 510
            #[inline]
            fn zero() -> $T { 0 }

            #[inline]
            fn one() -> $T { 1 }

B
Brendan Zabarauskas 已提交
511 512 513 514 515 516
            #[inline]
            fn min_value() -> $T { (-1 as $T) << ($BITS - 1) }

            #[inline]
            fn max_value() -> $T { let min: $T = Int::min_value(); !min }

517
            #[inline]
518 519 520 521 522 523 524 525 526 527
            fn count_ones(self) -> uint { (self as $UnsignedT).count_ones() }

            #[inline]
            fn leading_zeros(self) -> uint { (self as $UnsignedT).leading_zeros() }

            #[inline]
            fn trailing_zeros(self) -> uint { (self as $UnsignedT).trailing_zeros() }

            #[inline]
            fn rotate_left(self, n: uint) -> $T { (self as $UnsignedT).rotate_left(n) as $T }
528 529

            #[inline]
530
            fn rotate_right(self, n: uint) -> $T { (self as $UnsignedT).rotate_right(n) as $T }
531 532

            #[inline]
533
            fn swap_bytes(self) -> $T { (self as $UnsignedT).swap_bytes() as $T }
534 535

            #[inline]
536 537 538 539 540 541 542 543
            fn checked_add(self, other: $T) -> Option<$T> {
                checked_op!($T, $ActualT, $add_with_overflow, self, other)
            }

            #[inline]
            fn checked_sub(self, other: $T) -> Option<$T> {
                checked_op!($T, $ActualT, $sub_with_overflow, self, other)
            }
544 545

            #[inline]
546 547 548
            fn checked_mul(self, other: $T) -> Option<$T> {
                checked_op!($T, $ActualT, $mul_with_overflow, self, other)
            }
549 550

            #[inline]
551 552 553
            fn checked_div(self, v: $T) -> Option<$T> {
                match v {
                    0   => None,
B
Brendan Zabarauskas 已提交
554
                   -1 if self == Int::min_value()
555 556 557 558
                        => None,
                    v   => Some(self / v),
                }
            }
559 560
        }
    }
561
}
562

563
int_impl! { i8 = i8, u8, 8,
564 565
    intrinsics::i8_add_with_overflow,
    intrinsics::i8_sub_with_overflow,
566
    intrinsics::i8_mul_with_overflow }
567

568
int_impl! { i16 = i16, u16, 16,
569 570
    intrinsics::i16_add_with_overflow,
    intrinsics::i16_sub_with_overflow,
571
    intrinsics::i16_mul_with_overflow }
572

573
int_impl! { i32 = i32, u32, 32,
574 575
    intrinsics::i32_add_with_overflow,
    intrinsics::i32_sub_with_overflow,
576
    intrinsics::i32_mul_with_overflow }
577

578
int_impl! { i64 = i64, u64, 64,
579 580
    intrinsics::i64_add_with_overflow,
    intrinsics::i64_sub_with_overflow,
581
    intrinsics::i64_mul_with_overflow }
582 583

#[cfg(target_word_size = "32")]
584
int_impl! { int = i32, u32, 32,
585 586
    intrinsics::i32_add_with_overflow,
    intrinsics::i32_sub_with_overflow,
587
    intrinsics::i32_mul_with_overflow }
588 589

#[cfg(target_word_size = "64")]
590
int_impl! { int = i64, u64, 64,
591 592
    intrinsics::i64_add_with_overflow,
    intrinsics::i64_sub_with_overflow,
593
    intrinsics::i64_mul_with_overflow }
594

595
/// A built-in two's complement integer.
596
#[unstable = "recently settled as part of numerics reform"]
597 598
pub trait SignedInt
    : Int
J
Jorge Aparicio 已提交
599
    + Neg<Output=Self>
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
{
    /// Computes the absolute value of `self`. `Int::min_value()` will be
    /// returned if the number is `Int::min_value()`.
    fn abs(self) -> Self;

    /// Returns a number representing sign of `self`.
    ///
    /// - `0` if the number is zero
    /// - `1` if the number is positive
    /// - `-1` if the number is negative
    fn signum(self) -> Self;

    /// Returns `true` if `self` is positive and `false` if the number
    /// is zero or negative.
    fn is_positive(self) -> bool;

    /// Returns `true` if `self` is negative and `false` if the number
    /// is zero or positive.
    fn is_negative(self) -> bool;
}

macro_rules! signed_int_impl {
    ($T:ty) => {
        impl SignedInt for $T {
            #[inline]
            fn abs(self) -> $T {
                if self.is_negative() { -self } else { self }
            }

            #[inline]
            fn signum(self) -> $T {
                match self {
                    n if n > 0 =>  1,
                    0          =>  0,
                    _          => -1,
                }
            }

            #[inline]
            fn is_positive(self) -> bool { self > 0 }

            #[inline]
            fn is_negative(self) -> bool { self < 0 }
        }
    }
}

647 648 649 650 651
signed_int_impl! { i8 }
signed_int_impl! { i16 }
signed_int_impl! { i32 }
signed_int_impl! { i64 }
signed_int_impl! { int }
652

653
/// A built-in unsigned integer.
654
#[unstable = "recently settled as part of numerics reform"]
655 656
pub trait UnsignedInt: Int {
    /// Returns `true` iff `self == 2^k` for some `k`.
657
    #[inline]
658
    fn is_power_of_two(self) -> bool {
659
        (self - Int::one()) & self == Int::zero() && !(self == Int::zero())
660 661
    }

662
    /// Returns the smallest power of two greater than or equal to `self`.
663
    /// Unspecified behavior on overflow.
664 665
    #[inline]
    fn next_power_of_two(self) -> Self {
666 667 668
        let bits = size_of::<Self>() * 8;
        let one: Self = Int::one();
        one << ((bits - (self - one).leading_zeros()) % bits)
669
    }
670

671 672 673 674
    /// Returns the smallest power of two 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 two is wrapped in `Some`.
    fn checked_next_power_of_two(self) -> Option<Self> {
675 676 677 678 679
        let npot = self.next_power_of_two();
        if npot >= self {
            Some(npot)
        } else {
            None
680
        }
681 682 683
    }
}

684
#[unstable = "trait is unstable"]
685
impl UnsignedInt for uint {}
686 687

#[unstable = "trait is unstable"]
688
impl UnsignedInt for u8 {}
689 690

#[unstable = "trait is unstable"]
691
impl UnsignedInt for u16 {}
692 693

#[unstable = "trait is unstable"]
694
impl UnsignedInt for u32 {}
695 696

#[unstable = "trait is unstable"]
697 698
impl UnsignedInt for u64 {}

699
/// A generic trait for converting a value to a number.
700
#[experimental = "trait is likely to be removed"]
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 737 738 739 740 741 742 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
pub trait ToPrimitive {
    /// Converts the value of `self` to an `int`.
    #[inline]
    fn to_int(&self) -> Option<int> {
        self.to_i64().and_then(|x| x.to_int())
    }

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

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

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

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

    /// Converts the value of `self` to an `uint`.
    #[inline]
    fn to_uint(&self) -> Option<uint> {
        self.to_u64().and_then(|x| x.to_uint())
    }

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

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

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

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

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

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

770
macro_rules! impl_to_primitive_int_to_int {
J
John Clements 已提交
771
    ($SrcT:ty, $DstT:ty, $slf:expr) => (
772 773
        {
            if size_of::<$SrcT>() <= size_of::<$DstT>() {
J
John Clements 已提交
774
                Some($slf as $DstT)
775
            } else {
J
John Clements 已提交
776
                let n = $slf as i64;
B
Brendan Zabarauskas 已提交
777 778
                let min_value: $DstT = Int::min_value();
                let max_value: $DstT = Int::max_value();
779
                if min_value as i64 <= n && n <= max_value as i64 {
J
John Clements 已提交
780
                    Some($slf as $DstT)
781 782 783 784 785 786
                } else {
                    None
                }
            }
        }
    )
787
}
788

789
macro_rules! impl_to_primitive_int_to_uint {
J
John Clements 已提交
790
    ($SrcT:ty, $DstT:ty, $slf:expr) => (
791
        {
792
            let zero: $SrcT = Int::zero();
B
Brendan Zabarauskas 已提交
793
            let max_value: $DstT = Int::max_value();
J
John Clements 已提交
794 795
            if zero <= $slf && $slf as u64 <= max_value as u64 {
                Some($slf as $DstT)
796 797 798 799 800
            } else {
                None
            }
        }
    )
801
}
802

803
macro_rules! impl_to_primitive_int {
804 805 806
    ($T:ty) => (
        impl ToPrimitive for $T {
            #[inline]
J
John Clements 已提交
807
            fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int, *self) }
808
            #[inline]
J
John Clements 已提交
809
            fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) }
810
            #[inline]
J
John Clements 已提交
811
            fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) }
812
            #[inline]
J
John Clements 已提交
813
            fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32, *self) }
814
            #[inline]
J
John Clements 已提交
815
            fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self) }
816 817

            #[inline]
J
John Clements 已提交
818
            fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint, *self) }
819
            #[inline]
J
John Clements 已提交
820
            fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) }
821
            #[inline]
J
John Clements 已提交
822
            fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) }
823
            #[inline]
J
John Clements 已提交
824
            fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32, *self) }
825
            #[inline]
J
John Clements 已提交
826
            fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64, *self) }
827 828 829 830 831 832 833

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

836 837 838 839 840
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 }
841

842
macro_rules! impl_to_primitive_uint_to_int {
J
John Clements 已提交
843
    ($DstT:ty, $slf:expr) => (
844
        {
B
Brendan Zabarauskas 已提交
845
            let max_value: $DstT = Int::max_value();
J
John Clements 已提交
846 847
            if $slf as u64 <= max_value as u64 {
                Some($slf as $DstT)
848 849 850 851 852
            } else {
                None
            }
        }
    )
853
}
854

855
macro_rules! impl_to_primitive_uint_to_uint {
J
John Clements 已提交
856
    ($SrcT:ty, $DstT:ty, $slf:expr) => (
857 858
        {
            if size_of::<$SrcT>() <= size_of::<$DstT>() {
J
John Clements 已提交
859
                Some($slf as $DstT)
860
            } else {
861
                let zero: $SrcT = Int::zero();
B
Brendan Zabarauskas 已提交
862
                let max_value: $DstT = Int::max_value();
J
John Clements 已提交
863 864
                if zero <= $slf && $slf as u64 <= max_value as u64 {
                    Some($slf as $DstT)
865 866 867 868 869 870
                } else {
                    None
                }
            }
        }
    )
871
}
872

873
macro_rules! impl_to_primitive_uint {
874 875 876
    ($T:ty) => (
        impl ToPrimitive for $T {
            #[inline]
J
John Clements 已提交
877
            fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int, *self) }
878
            #[inline]
J
John Clements 已提交
879
            fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) }
880
            #[inline]
J
John Clements 已提交
881
            fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) }
882
            #[inline]
J
John Clements 已提交
883
            fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32, *self) }
884
            #[inline]
J
John Clements 已提交
885
            fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) }
886 887

            #[inline]
J
John Clements 已提交
888
            fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint, *self) }
889
            #[inline]
J
John Clements 已提交
890
            fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) }
891
            #[inline]
J
John Clements 已提交
892
            fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) }
893
            #[inline]
J
John Clements 已提交
894
            fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32, *self) }
895
            #[inline]
J
John Clements 已提交
896
            fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64, *self) }
897 898 899 900 901 902 903

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

906 907 908 909 910
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 }
911

912
macro_rules! impl_to_primitive_float_to_float {
913
    ($SrcT:ident, $DstT:ident, $slf:expr) => (
914
        if size_of::<$SrcT>() <= size_of::<$DstT>() {
J
John Clements 已提交
915
            Some($slf as $DstT)
916
        } else {
J
John Clements 已提交
917
            let n = $slf as f64;
918
            let max_value: $SrcT = ::$SrcT::MAX_VALUE;
919
            if -max_value as f64 <= n && n <= max_value as f64 {
J
John Clements 已提交
920
                Some($slf as $DstT)
921 922 923 924 925
            } else {
                None
            }
        }
    )
926
}
927

928
macro_rules! impl_to_primitive_float {
929
    ($T:ident) => (
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
        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]
J
John Clements 已提交
954
            fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32, *self) }
955
            #[inline]
J
John Clements 已提交
956
            fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64, *self) }
957 958
        }
    )
959
}
960

961 962
impl_to_primitive_float! { f32 }
impl_to_primitive_float! { f64 }
963 964

/// A generic trait for converting a number to a value.
965
#[experimental = "trait is likely to be removed"]
966
pub trait FromPrimitive : ::kinds::Sized {
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
    /// Convert an `int` to return an optional value of this type. If the
    /// value cannot be represented by this value, the `None` is returned.
    #[inline]
    fn from_int(n: int) -> Option<Self> {
        FromPrimitive::from_i64(n as i64)
    }

    /// 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> {
        FromPrimitive::from_i64(n as i64)
    }

    /// 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> {
        FromPrimitive::from_i64(n as i64)
    }

    /// 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> {
        FromPrimitive::from_i64(n as i64)
    }

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

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

    /// 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> {
        FromPrimitive::from_u64(n as u64)
    }

    /// 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> {
        FromPrimitive::from_u64(n as u64)
    }

    /// 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> {
        FromPrimitive::from_u64(n as u64)
    }

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

    /// 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> {
        FromPrimitive::from_f64(n as f64)
    }

    /// 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> {
        FromPrimitive::from_i64(n as i64)
    }
}

/// A utility function that just calls `FromPrimitive::from_int`.
1047
#[experimental = "likely to be removed"]
1048 1049 1050 1051 1052
pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
    FromPrimitive::from_int(n)
}

/// A utility function that just calls `FromPrimitive::from_i8`.
1053
#[experimental = "likely to be removed"]
1054 1055 1056 1057 1058
pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> {
    FromPrimitive::from_i8(n)
}

/// A utility function that just calls `FromPrimitive::from_i16`.
1059
#[experimental = "likely to be removed"]
1060 1061 1062 1063 1064
pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> {
    FromPrimitive::from_i16(n)
}

/// A utility function that just calls `FromPrimitive::from_i32`.
1065
#[experimental = "likely to be removed"]
1066 1067 1068 1069 1070
pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> {
    FromPrimitive::from_i32(n)
}

/// A utility function that just calls `FromPrimitive::from_i64`.
1071
#[experimental = "likely to be removed"]
1072 1073 1074 1075 1076
pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
    FromPrimitive::from_i64(n)
}

/// A utility function that just calls `FromPrimitive::from_uint`.
1077
#[experimental = "likely to be removed"]
1078 1079 1080 1081 1082
pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
    FromPrimitive::from_uint(n)
}

/// A utility function that just calls `FromPrimitive::from_u8`.
1083
#[experimental = "likely to be removed"]
1084 1085 1086 1087 1088
pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> {
    FromPrimitive::from_u8(n)
}

/// A utility function that just calls `FromPrimitive::from_u16`.
1089
#[experimental = "likely to be removed"]
1090 1091 1092 1093 1094
pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> {
    FromPrimitive::from_u16(n)
}

/// A utility function that just calls `FromPrimitive::from_u32`.
1095
#[experimental = "likely to be removed"]
1096 1097 1098 1099 1100
pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> {
    FromPrimitive::from_u32(n)
}

/// A utility function that just calls `FromPrimitive::from_u64`.
1101
#[experimental = "likely to be removed"]
1102 1103 1104 1105 1106
pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> {
    FromPrimitive::from_u64(n)
}

/// A utility function that just calls `FromPrimitive::from_f32`.
1107
#[experimental = "likely to be removed"]
1108 1109 1110 1111 1112
pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> {
    FromPrimitive::from_f32(n)
}

/// A utility function that just calls `FromPrimitive::from_f64`.
1113
#[experimental = "likely to be removed"]
1114 1115 1116 1117
pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {
    FromPrimitive::from_f64(n)
}

1118
macro_rules! impl_from_primitive {
J
John Clements 已提交
1119
    ($T:ty, $to_ty:ident) => (
1120
        impl FromPrimitive for $T {
J
John Clements 已提交
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
            #[inline] fn from_int(n: int) -> Option<$T> { n.$to_ty() }
            #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() }
            #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() }
            #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() }
            #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() }

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

            #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() }
            #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() }
1135 1136
        }
    )
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
}

impl_from_primitive! { int, to_int }
impl_from_primitive! { i8, to_i8 }
impl_from_primitive! { i16, to_i16 }
impl_from_primitive! { i32, to_i32 }
impl_from_primitive! { i64, to_i64 }
impl_from_primitive! { uint, to_uint }
impl_from_primitive! { u8, to_u8 }
impl_from_primitive! { u16, to_u16 }
impl_from_primitive! { u32, to_u32 }
impl_from_primitive! { u64, to_u64 }
impl_from_primitive! { f32, to_f32 }
impl_from_primitive! { f64, to_f64 }
1151 1152 1153 1154 1155 1156 1157 1158

/// Cast from one machine scalar to another.
///
/// # Example
///
/// ```
/// use std::num;
///
1159
/// let twenty: f32 = num::cast(0x14i).unwrap();
1160 1161 1162 1163
/// assert_eq!(twenty, 20f32);
/// ```
///
#[inline]
1164
#[experimental = "likely to be removed"]
1165 1166 1167 1168 1169
pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
    NumCast::from(n)
}

/// An interface for casting between machine scalars.
1170
#[experimental = "trait is likely to be removed"]
1171 1172 1173 1174 1175 1176
pub trait NumCast: ToPrimitive {
    /// Creates a number from another value that can be converted into a primitive via the
    /// `ToPrimitive` trait.
    fn from<T: ToPrimitive>(n: T) -> Option<Self>;
}

1177
macro_rules! impl_num_cast {
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    ($T:ty, $conv:ident) => (
        impl NumCast for $T {
            #[inline]
            fn from<N: ToPrimitive>(n: N) -> Option<$T> {
                // `$conv` could be generated using `concat_idents!`, but that
                // macro seems to be broken at the moment
                n.$conv()
            }
        }
    )
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
}

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 }
1202

1203
/// Used for representing the classification of floating point numbers
1204
#[derive(Copy, PartialEq, Show)]
1205
#[unstable = "may be renamed"]
T
Tobias Bucher 已提交
1206
pub enum FpCategory {
1207
    /// "Not a Number", often obtained by dividing by zero
T
Tobias Bucher 已提交
1208
    Nan,
1209
    /// Positive or negative infinity
T
Tobias Bucher 已提交
1210
    Infinite ,
1211
    /// Positive or negative zero
T
Tobias Bucher 已提交
1212 1213 1214
    Zero,
    /// De-normalized floating point representation (less precise than `Normal`)
    Subnormal,
1215
    /// A regular floating point number
T
Tobias Bucher 已提交
1216
    Normal,
1217 1218
}

1219
/// A built-in floating point number.
1220 1221 1222 1223 1224
// FIXME(#5527): In a future version of Rust, many of these functions will
//               become constants.
//
// FIXME(#8888): Several of these functions have a parameter named
//               `unused_self`. Removing it requires #8888 to be fixed.
1225
#[unstable = "distribution of methods between core/std is unclear"]
1226 1227 1228 1229 1230
pub trait Float
    : Copy + Clone
    + NumCast
    + PartialOrd
    + PartialEq
J
Jorge Aparicio 已提交
1231
    + Neg<Output=Self>
J
Jorge Aparicio 已提交
1232 1233 1234 1235 1236
    + Add<Output=Self>
    + Sub<Output=Self>
    + Mul<Output=Self>
    + Div<Output=Self>
    + Rem<Output=Self>
1237
{
1238 1239 1240 1241 1242 1243
    /// Returns the NaN value.
    fn nan() -> Self;
    /// Returns the infinite value.
    fn infinity() -> Self;
    /// Returns the negative infinite value.
    fn neg_infinity() -> Self;
1244 1245
    /// Returns the `0` value.
    fn zero() -> Self;
1246 1247
    /// Returns -0.0.
    fn neg_zero() -> Self;
1248 1249
    /// Returns the `1` value.
    fn one() -> Self;
1250 1251 1252 1253

    // FIXME (#5527): These should be associated constants

    /// Returns the number of binary digits of mantissa that this type supports.
1254
    #[deprecated = "use `std::f32::MANTISSA_DIGITS` or `std::f64::MANTISSA_DIGITS` as appropriate"]
1255 1256
    fn mantissa_digits(unused_self: Option<Self>) -> uint;
    /// Returns the number of base-10 digits of precision that this type supports.
1257
    #[deprecated = "use `std::f32::DIGITS` or `std::f64::DIGITS` as appropriate"]
1258 1259
    fn digits(unused_self: Option<Self>) -> uint;
    /// Returns the difference between 1.0 and the smallest representable number larger than 1.0.
1260
    #[deprecated = "use `std::f32::EPSILON` or `std::f64::EPSILON` as appropriate"]
1261 1262
    fn epsilon() -> Self;
    /// Returns the minimum binary exponent that this type can represent.
1263
    #[deprecated = "use `std::f32::MIN_EXP` or `std::f64::MIN_EXP` as appropriate"]
1264 1265
    fn min_exp(unused_self: Option<Self>) -> int;
    /// Returns the maximum binary exponent that this type can represent.
1266
    #[deprecated = "use `std::f32::MAX_EXP` or `std::f64::MAX_EXP` as appropriate"]
1267 1268
    fn max_exp(unused_self: Option<Self>) -> int;
    /// Returns the minimum base-10 exponent that this type can represent.
1269
    #[deprecated = "use `std::f32::MIN_10_EXP` or `std::f64::MIN_10_EXP` as appropriate"]
1270 1271
    fn min_10_exp(unused_self: Option<Self>) -> int;
    /// Returns the maximum base-10 exponent that this type can represent.
1272
    #[deprecated = "use `std::f32::MAX_10_EXP` or `std::f64::MAX_10_EXP` as appropriate"]
1273
    fn max_10_exp(unused_self: Option<Self>) -> int;
B
Brendan Zabarauskas 已提交
1274
    /// Returns the smallest finite value that this type can represent.
1275
    #[deprecated = "use `std::f32::MIN_VALUE` or `std::f64::MIN_VALUE` as appropriate"]
B
Brendan Zabarauskas 已提交
1276
    fn min_value() -> Self;
1277
    /// Returns the smallest normalized positive number that this type can represent.
1278
    #[deprecated = "use `std::f32::MIN_POS_VALUE` or `std::f64::MIN_POS_VALUE` as appropriate"]
1279
    fn min_pos_value(unused_self: Option<Self>) -> Self;
B
Brendan Zabarauskas 已提交
1280
    /// Returns the largest finite value that this type can represent.
1281
    #[deprecated = "use `std::f32::MAX_VALUE` or `std::f64::MAX_VALUE` as appropriate"]
B
Brendan Zabarauskas 已提交
1282
    fn max_value() -> Self;
1283

1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
    /// Returns true if this value is NaN and false otherwise.
    fn is_nan(self) -> bool;
    /// Returns true if this value is positive infinity or negative infinity and
    /// false otherwise.
    fn is_infinite(self) -> bool;
    /// Returns true if this number is neither infinite nor NaN.
    fn is_finite(self) -> bool;
    /// Returns true if this number is neither zero, infinite, denormal, or NaN.
    fn is_normal(self) -> bool;
    /// Returns the category that this number falls into.
    fn classify(self) -> FpCategory;

1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
    /// Returns the mantissa, exponent and sign as integers, respectively.
    fn integer_decode(self) -> (u64, i16, i8);

    /// Return the largest integer less than or equal to a number.
    fn floor(self) -> Self;
    /// Return the smallest integer greater than or equal to a number.
    fn ceil(self) -> Self;
    /// Return the nearest integer to a number. Round half-way cases away from
    /// `0.0`.
    fn round(self) -> Self;
    /// Return the integer part of a number.
    fn trunc(self) -> Self;
    /// Return the fractional part of a number.
    fn fract(self) -> Self;

1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
    /// Computes the absolute value of `self`. Returns `Float::nan()` if the
    /// number is `Float::nan()`.
    fn abs(self) -> Self;
    /// Returns a number that represents the sign of `self`.
    ///
    /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
    /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
    /// - `Float::nan()` if the number is `Float::nan()`
    fn signum(self) -> Self;
    /// Returns `true` if `self` is positive, including `+0.0` and
    /// `Float::infinity()`.
    fn is_positive(self) -> bool;
    /// Returns `true` if `self` is negative, including `-0.0` and
    /// `Float::neg_infinity()`.
    fn is_negative(self) -> bool;

1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
    /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
    /// error. This produces a more accurate result with better performance than
    /// a separate multiplication operation followed by an add.
    fn mul_add(self, a: Self, b: Self) -> Self;
    /// Take the reciprocal (inverse) of a number, `1/x`.
    fn recip(self) -> Self;

    /// Raise a number to an integer power.
    ///
    /// Using this function is generally faster than using `powf`
    fn powi(self, n: i32) -> Self;
    /// Raise a number to a floating point power.
    fn powf(self, n: Self) -> Self;

    /// Take the square root of a number.
1342
    ///
1343
    /// Returns NaN if `self` is a negative number.
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
    fn sqrt(self) -> Self;
    /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
    fn rsqrt(self) -> Self;

    /// Returns `e^(self)`, (the exponential function).
    fn exp(self) -> Self;
    /// Returns 2 raised to the power of the number, `2^(self)`.
    fn exp2(self) -> Self;
    /// Returns the natural logarithm of the number.
    fn ln(self) -> Self;
    /// Returns the logarithm of the number with respect to an arbitrary base.
    fn log(self, base: Self) -> Self;
    /// Returns the base 2 logarithm of the number.
    fn log2(self) -> Self;
    /// Returns the base 10 logarithm of the number.
    fn log10(self) -> Self;

    /// Convert radians to degrees.
    fn to_degrees(self) -> Self;
    /// Convert degrees to radians.
    fn to_radians(self) -> Self;
}
1366

B
Brendan Zabarauskas 已提交
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
/// A generic trait for converting a string with a radix (base) to a value
#[experimental = "might need to return Result"]
pub trait FromStrRadix {
    fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
}

/// A utility function that just calls FromStrRadix::from_str_radix.
#[experimental = "might need to return Result"]
pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint) -> Option<T> {
    FromStrRadix::from_str_radix(str, radix)
}

B
Brendan Zabarauskas 已提交
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
macro_rules! from_str_radix_float_impl {
    ($T:ty) => {
        #[experimental = "might need to return Result"]
        impl FromStr for $T {
            /// Convert a string in base 10 to a float.
            /// Accepts an optional decimal exponent.
            ///
            /// This function accepts strings such as
            ///
            /// * '3.14'
            /// * '+3.14', equivalent to '3.14'
            /// * '-3.14'
            /// * '2.5E10', or equivalently, '2.5e10'
            /// * '2.5E-10'
            /// * '.' (understood as 0)
            /// * '5.'
            /// * '.5', or, equivalently,  '0.5'
            /// * '+inf', 'inf', '-inf', 'NaN'
            ///
            /// Leading and trailing whitespace represent an error.
            ///
            /// # Arguments
            ///
            /// * src - A string
            ///
            /// # Return value
            ///
            /// `None` if the string did not represent a valid number.  Otherwise,
            /// `Some(n)` where `n` is the floating-point number represented by `src`.
            #[inline]
            fn from_str(src: &str) -> Option<$T> {
                from_str_radix(src, 10)
            }
        }

        #[experimental = "might need to return Result"]
        impl FromStrRadix for $T {
            /// Convert a string in a given base to a float.
            ///
            /// Due to possible conflicts, this function does **not** accept
            /// the special values `inf`, `-inf`, `+inf` and `NaN`, **nor**
            /// does it recognize exponents of any kind.
            ///
            /// Leading and trailing whitespace represent an error.
            ///
            /// # Arguments
            ///
            /// * src - A string
            /// * radix - The base to use. Must lie in the range [2 .. 36]
            ///
            /// # Return value
            ///
            /// `None` if the string did not represent a valid number. Otherwise,
            /// `Some(n)` where `n` is the floating-point number represented by `src`.
            fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
               assert!(radix >= 2 && radix <= 36,
                       "from_str_radix_float: must lie in the range `[2, 36]` - found {}",
                       radix);

                // Special values
                match src {
                    "inf"   => return Some(Float::infinity()),
                    "-inf"  => return Some(Float::neg_infinity()),
                    "NaN"   => return Some(Float::nan()),
                    _       => {},
                }

                let (is_positive, src) =  match src.slice_shift_char() {
1447 1448 1449 1450
                    None             => return None,
                    Some(('-', ""))  => return None,
                    Some(('-', src)) => (false, src),
                    Some((_, _))     => (true,  src),
B
Brendan Zabarauskas 已提交
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
                };

                // The significand to accumulate
                let mut sig = if is_positive { 0.0 } else { -0.0 };
                // Necessary to detect overflow
                let mut prev_sig = sig;
                let mut cs = src.chars().enumerate();
                // Exponent prefix and exponent index offset
                let mut exp_info = None::<(char, uint)>;

                // Parse the integer part of the significand
                for (i, c) in cs {
                    match c.to_digit(radix) {
                        Some(digit) => {
                            // shift significand one digit left
                            sig = sig * (radix as $T);

                            // add/subtract current digit depending on sign
                            if is_positive {
                                sig = sig + ((digit as int) as $T);
                            } else {
                                sig = sig - ((digit as int) as $T);
                            }

                            // Detect overflow by comparing to last value, except
                            // if we've not seen any non-zero digits.
                            if prev_sig != 0.0 {
                                if is_positive && sig <= prev_sig
                                    { return Some(Float::infinity()); }
                                if !is_positive && sig >= prev_sig
                                    { return Some(Float::neg_infinity()); }

                                // Detect overflow by reversing the shift-and-add process
                                if is_positive && (prev_sig != (sig - digit as $T) / radix as $T)
                                    { return Some(Float::infinity()); }
                                if !is_positive && (prev_sig != (sig + digit as $T) / radix as $T)
                                    { return Some(Float::neg_infinity()); }
                            }
                            prev_sig = sig;
                        },
                        None => match c {
                            'e' | 'E' | 'p' | 'P' => {
                                exp_info = Some((c, i + 1));
                                break;  // start of exponent
                            },
                            '.' => {
                                break;  // start of fractional part
                            },
                            _ => {
                                return None;
                            },
                        },
                    }
                }

                // If we are not yet at the exponent parse the fractional
                // part of the significand
                if exp_info.is_none() {
                    let mut power = 1.0;
                    for (i, c) in cs {
                        match c.to_digit(radix) {
                            Some(digit) => {
                                // Decrease power one order of magnitude
                                power = power / (radix as $T);
                                // add/subtract current digit depending on sign
                                sig = if is_positive {
                                    sig + (digit as $T) * power
                                } else {
                                    sig - (digit as $T) * power
                                };
                                // Detect overflow by comparing to last value
                                if is_positive && sig < prev_sig
                                    { return Some(Float::infinity()); }
                                if !is_positive && sig > prev_sig
                                    { return Some(Float::neg_infinity()); }
                                prev_sig = sig;
                            },
                            None => match c {
                                'e' | 'E' | 'p' | 'P' => {
                                    exp_info = Some((c, i + 1));
                                    break; // start of exponent
                                },
                                _ => {
                                    return None; // invalid number
                                },
                            },
                        }
                    }
                }

                // Parse and calculate the exponent
                let exp = match exp_info {
                    Some((c, offset)) => {
                        let base = match c {
                            'E' | 'e' if radix == 10 => 10u as $T,
                            'P' | 'p' if radix == 16 => 2u as $T,
                            _ => return None,
                        };

                        // Parse the exponent as decimal integer
                        let src = src[offset..];
                        let (is_positive, exp) = match src.slice_shift_char() {
A
Alex Crichton 已提交
1553 1554 1555
                            Some(('-', src)) => (false, src.parse::<uint>()),
                            Some(('+', src)) => (true,  src.parse::<uint>()),
                            Some((_, _))     => (true,  src.parse::<uint>()),
1556
                            None             => return None,
B
Brendan Zabarauskas 已提交
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
                        };

                        match (is_positive, exp) {
                            (true,  Some(exp)) => base.powi(exp as i32),
                            (false, Some(exp)) => 1.0 / base.powi(exp as i32),
                            (_, None)          => return None,
                        }
                    },
                    None => 1.0, // no exponent
                };

                Some(sig * exp)
            }
        }
    }
}
1573 1574
from_str_radix_float_impl! { f32 }
from_str_radix_float_impl! { f64 }
B
Brendan Zabarauskas 已提交
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595

macro_rules! from_str_radix_int_impl {
    ($T:ty) => {
        #[experimental = "might need to return Result"]
        impl FromStr for $T {
            #[inline]
            fn from_str(src: &str) -> Option<$T> {
                from_str_radix(src, 10)
            }
        }

        #[experimental = "might need to return Result"]
        impl FromStrRadix for $T {
            fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
                assert!(radix >= 2 && radix <= 36,
                       "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
                       radix);

                let is_signed_ty = (0 as $T) > Int::min_value();

                match src.slice_shift_char() {
1596
                    Some(('-', src)) if is_signed_ty => {
B
Brendan Zabarauskas 已提交
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
                        // The number is negative
                        let mut result = 0;
                        for c in src.chars() {
                            let x = match c.to_digit(radix) {
                                Some(x) => x,
                                None => return None,
                            };
                            result = match result.checked_mul(radix as $T) {
                                Some(result) => result,
                                None => return None,
                            };
                            result = match result.checked_sub(x as $T) {
                                Some(result) => result,
                                None => return None,
                            };
                        }
                        Some(result)
                    },
1615
                    Some((_, _)) => {
B
Brendan Zabarauskas 已提交
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
                        // The number is signed
                        let mut result = 0;
                        for c in src.chars() {
                            let x = match c.to_digit(radix) {
                                Some(x) => x,
                                None => return None,
                            };
                            result = match result.checked_mul(radix as $T) {
                                Some(result) => result,
                                None => return None,
                            };
                            result = match result.checked_add(x as $T) {
                                Some(result) => result,
                                None => return None,
                            };
                        }
                        Some(result)
                    },
1634
                    None => None,
B
Brendan Zabarauskas 已提交
1635 1636 1637 1638 1639
                }
            }
        }
    }
}
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
from_str_radix_int_impl! { int }
from_str_radix_int_impl! { i8 }
from_str_radix_int_impl! { i16 }
from_str_radix_int_impl! { i32 }
from_str_radix_int_impl! { i64 }
from_str_radix_int_impl! { uint }
from_str_radix_int_impl! { u8 }
from_str_radix_int_impl! { u16 }
from_str_radix_int_impl! { u32 }
from_str_radix_int_impl! { u64 }