]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
Merge pull request #20674 from jbcrail/fix-misspelled-comments
[rust.git] / src / libcore / num / mod.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 //
11 // ignore-lexer-test FIXME #15679
12
13 //! Numeric traits and functions for the built-in numeric types.
14
15 #![stable]
16 #![allow(missing_docs)]
17
18 use char::CharExt;
19 use clone::Clone;
20 use cmp::{PartialEq, Eq};
21 use cmp::{PartialOrd, Ord};
22 use intrinsics;
23 use iter::IteratorExt;
24 use marker::Copy;
25 use mem::size_of;
26 use ops::{Add, Sub, Mul, Div, Rem, Neg};
27 use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr, Index};
28 use option::Option;
29 use option::Option::{Some, None};
30 use str::{FromStr, StrExt};
31
32 /// A built-in signed or unsigned integer.
33 #[stable]
34 pub trait Int
35     : Copy + Clone
36     + NumCast
37     + PartialOrd + Ord
38     + PartialEq + Eq
39     + Add<Output=Self>
40     + Sub<Output=Self>
41     + Mul<Output=Self>
42     + Div<Output=Self>
43     + Rem<Output=Self>
44     + Not<Output=Self>
45     + BitAnd<Output=Self>
46     + BitOr<Output=Self>
47     + BitXor<Output=Self>
48     + Shl<uint, Output=Self>
49     + Shr<uint, Output=Self>
50 {
51     /// Returns the `0` value of this integer type.
52     // FIXME (#5527): Should be an associated constant
53     #[unstable = "unsure about its place in the world"]
54     fn zero() -> Self;
55
56     /// Returns the `1` value of this integer type.
57     // FIXME (#5527): Should be an associated constant
58     #[unstable = "unsure about its place in the world"]
59     fn one() -> Self;
60
61     /// Returns the smallest value that can be represented by this integer type.
62     // FIXME (#5527): Should be and associated constant
63     #[unstable = "unsure about its place in the world"]
64     fn min_value() -> Self;
65
66     /// Returns the largest value that can be represented by this integer type.
67     // FIXME (#5527): Should be and associated constant
68     #[unstable = "unsure about its place in the world"]
69     fn max_value() -> Self;
70
71     /// Returns the number of ones in the binary representation of `self`.
72     ///
73     /// # Example
74     ///
75     /// ```rust
76     /// use std::num::Int;
77     ///
78     /// let n = 0b01001100u8;
79     ///
80     /// assert_eq!(n.count_ones(), 3);
81     /// ```
82     #[unstable = "pending integer conventions"]
83     fn count_ones(self) -> uint;
84
85     /// Returns the number of zeros in the binary representation of `self`.
86     ///
87     /// # Example
88     ///
89     /// ```rust
90     /// use std::num::Int;
91     ///
92     /// let n = 0b01001100u8;
93     ///
94     /// assert_eq!(n.count_zeros(), 5);
95     /// ```
96     #[unstable = "pending integer conventions"]
97     #[inline]
98     fn count_zeros(self) -> uint {
99         (!self).count_ones()
100     }
101
102     /// Returns the number of leading zeros in the binary representation
103     /// of `self`.
104     ///
105     /// # Example
106     ///
107     /// ```rust
108     /// use std::num::Int;
109     ///
110     /// let n = 0b0101000u16;
111     ///
112     /// assert_eq!(n.leading_zeros(), 10);
113     /// ```
114     #[unstable = "pending integer conventions"]
115     fn leading_zeros(self) -> uint;
116
117     /// Returns the number of trailing zeros in the binary representation
118     /// of `self`.
119     ///
120     /// # Example
121     ///
122     /// ```rust
123     /// use std::num::Int;
124     ///
125     /// let n = 0b0101000u16;
126     ///
127     /// assert_eq!(n.trailing_zeros(), 3);
128     /// ```
129     #[unstable = "pending integer conventions"]
130     fn trailing_zeros(self) -> uint;
131
132     /// Shifts the bits to the left by a specified amount amount, `n`, wrapping
133     /// the truncated bits to the end of the resulting integer.
134     ///
135     /// # Example
136     ///
137     /// ```rust
138     /// use std::num::Int;
139     ///
140     /// let n = 0x0123456789ABCDEFu64;
141     /// let m = 0x3456789ABCDEF012u64;
142     ///
143     /// assert_eq!(n.rotate_left(12), m);
144     /// ```
145     #[unstable = "pending integer conventions"]
146     fn rotate_left(self, n: uint) -> Self;
147
148     /// Shifts the bits to the right by a specified amount amount, `n`, wrapping
149     /// the truncated bits to the beginning of the resulting integer.
150     ///
151     /// # Example
152     ///
153     /// ```rust
154     /// use std::num::Int;
155     ///
156     /// let n = 0x0123456789ABCDEFu64;
157     /// let m = 0xDEF0123456789ABCu64;
158     ///
159     /// assert_eq!(n.rotate_right(12), m);
160     /// ```
161     #[unstable = "pending integer conventions"]
162     fn rotate_right(self, n: uint) -> Self;
163
164     /// Reverses the byte order of the integer.
165     ///
166     /// # Example
167     ///
168     /// ```rust
169     /// use std::num::Int;
170     ///
171     /// let n = 0x0123456789ABCDEFu64;
172     /// let m = 0xEFCDAB8967452301u64;
173     ///
174     /// assert_eq!(n.swap_bytes(), m);
175     /// ```
176     #[stable]
177     fn swap_bytes(self) -> Self;
178
179     /// Convert an integer from big endian to the target's endianness.
180     ///
181     /// On big endian this is a no-op. On little endian the bytes are swapped.
182     ///
183     /// # Example
184     ///
185     /// ```rust
186     /// use std::num::Int;
187     ///
188     /// let n = 0x0123456789ABCDEFu64;
189     ///
190     /// if cfg!(target_endian = "big") {
191     ///     assert_eq!(Int::from_be(n), n)
192     /// } else {
193     ///     assert_eq!(Int::from_be(n), n.swap_bytes())
194     /// }
195     /// ```
196     #[stable]
197     #[inline]
198     fn from_be(x: Self) -> Self {
199         if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
200     }
201
202     /// Convert an integer from little endian to the target's endianness.
203     ///
204     /// On little endian this is a no-op. On big endian the bytes are swapped.
205     ///
206     /// # Example
207     ///
208     /// ```rust
209     /// use std::num::Int;
210     ///
211     /// let n = 0x0123456789ABCDEFu64;
212     ///
213     /// if cfg!(target_endian = "little") {
214     ///     assert_eq!(Int::from_le(n), n)
215     /// } else {
216     ///     assert_eq!(Int::from_le(n), n.swap_bytes())
217     /// }
218     /// ```
219     #[stable]
220     #[inline]
221     fn from_le(x: Self) -> Self {
222         if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
223     }
224
225     /// Convert `self` to big endian from the target's endianness.
226     ///
227     /// On big endian this is a no-op. On little endian the bytes are swapped.
228     ///
229     /// # Example
230     ///
231     /// ```rust
232     /// use std::num::Int;
233     ///
234     /// let n = 0x0123456789ABCDEFu64;
235     ///
236     /// if cfg!(target_endian = "big") {
237     ///     assert_eq!(n.to_be(), n)
238     /// } else {
239     ///     assert_eq!(n.to_be(), n.swap_bytes())
240     /// }
241     /// ```
242     #[stable]
243     #[inline]
244     fn to_be(self) -> Self { // or not to be?
245         if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
246     }
247
248     /// Convert `self` to little endian from the target's endianness.
249     ///
250     /// On little endian this is a no-op. On big endian the bytes are swapped.
251     ///
252     /// # Example
253     ///
254     /// ```rust
255     /// use std::num::Int;
256     ///
257     /// let n = 0x0123456789ABCDEFu64;
258     ///
259     /// if cfg!(target_endian = "little") {
260     ///     assert_eq!(n.to_le(), n)
261     /// } else {
262     ///     assert_eq!(n.to_le(), n.swap_bytes())
263     /// }
264     /// ```
265     #[stable]
266     #[inline]
267     fn to_le(self) -> Self {
268         if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
269     }
270
271     /// Checked integer addition. Computes `self + other`, returning `None` if
272     /// overflow occurred.
273     ///
274     /// # Example
275     ///
276     /// ```rust
277     /// use std::num::Int;
278     ///
279     /// assert_eq!(5u16.checked_add(65530), Some(65535));
280     /// assert_eq!(6u16.checked_add(65530), None);
281     /// ```
282     #[stable]
283     fn checked_add(self, other: Self) -> Option<Self>;
284
285     /// Checked integer subtraction. Computes `self - other`, returning `None`
286     /// if underflow occurred.
287     ///
288     /// # Example
289     ///
290     /// ```rust
291     /// use std::num::Int;
292     ///
293     /// assert_eq!((-127i8).checked_sub(1), Some(-128));
294     /// assert_eq!((-128i8).checked_sub(1), None);
295     /// ```
296     #[stable]
297     fn checked_sub(self, other: Self) -> Option<Self>;
298
299     /// Checked integer multiplication. Computes `self * other`, returning
300     /// `None` if underflow or overflow occurred.
301     ///
302     /// # Example
303     ///
304     /// ```rust
305     /// use std::num::Int;
306     ///
307     /// assert_eq!(5u8.checked_mul(51), Some(255));
308     /// assert_eq!(5u8.checked_mul(52), None);
309     /// ```
310     #[stable]
311     fn checked_mul(self, other: Self) -> Option<Self>;
312
313     /// Checked integer division. Computes `self / other`, returning `None` if
314     /// `other == 0` or the operation results in underflow or overflow.
315     ///
316     /// # Example
317     ///
318     /// ```rust
319     /// use std::num::Int;
320     ///
321     /// assert_eq!((-127i8).checked_div(-1), Some(127));
322     /// assert_eq!((-128i8).checked_div(-1), None);
323     /// assert_eq!((1i8).checked_div(0), None);
324     /// ```
325     #[stable]
326     fn checked_div(self, other: Self) -> Option<Self>;
327
328     /// Saturating integer addition. Computes `self + other`, saturating at
329     /// the numeric bounds instead of overflowing.
330     #[stable]
331     #[inline]
332     fn saturating_add(self, other: Self) -> Self {
333         match self.checked_add(other) {
334             Some(x)                      => x,
335             None if other >= Int::zero() => Int::max_value(),
336             None                         => Int::min_value(),
337         }
338     }
339
340     /// Saturating integer subtraction. Computes `self - other`, saturating at
341     /// the numeric bounds instead of overflowing.
342     #[stable]
343     #[inline]
344     fn saturating_sub(self, other: Self) -> Self {
345         match self.checked_sub(other) {
346             Some(x)                      => x,
347             None if other >= Int::zero() => Int::min_value(),
348             None                         => Int::max_value(),
349         }
350     }
351
352     /// Raises self to the power of `exp`, using exponentiation by squaring.
353     ///
354     /// # Example
355     ///
356     /// ```rust
357     /// use std::num::Int;
358     ///
359     /// assert_eq!(2i.pow(4), 16);
360     /// ```
361     #[unstable = "pending integer conventions"]
362     #[inline]
363     fn pow(self, mut exp: uint) -> Self {
364         let mut base = self;
365         let mut acc: Self = Int::one();
366         while exp > 0 {
367             if (exp & 1) == 1 {
368                 acc = acc * base;
369             }
370             base = base * base;
371             exp /= 2;
372         }
373         acc
374     }
375 }
376
377 macro_rules! checked_op {
378     ($T:ty, $U:ty, $op:path, $x:expr, $y:expr) => {{
379         let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
380         if overflowed { None } else { Some(result as $T) }
381     }}
382 }
383
384 macro_rules! uint_impl {
385     ($T:ty = $ActualT:ty, $BITS:expr,
386      $ctpop:path,
387      $ctlz:path,
388      $cttz:path,
389      $bswap:path,
390      $add_with_overflow:path,
391      $sub_with_overflow:path,
392      $mul_with_overflow:path) => {
393         #[stable]
394         impl Int for $T {
395             #[inline]
396             fn zero() -> $T { 0 }
397
398             #[inline]
399             fn one() -> $T { 1 }
400
401             #[inline]
402             fn min_value() -> $T { 0 }
403
404             #[inline]
405             fn max_value() -> $T { -1 }
406
407             #[inline]
408             fn count_ones(self) -> uint { unsafe { $ctpop(self as $ActualT) as uint } }
409
410             #[inline]
411             fn leading_zeros(self) -> uint { unsafe { $ctlz(self as $ActualT) as uint } }
412
413             #[inline]
414             fn trailing_zeros(self) -> uint { unsafe { $cttz(self as $ActualT) as uint } }
415
416             #[inline]
417             fn rotate_left(self, n: uint) -> $T {
418                 // Protect against undefined behaviour for over-long bit shifts
419                 let n = n % $BITS;
420                 (self << n) | (self >> (($BITS - n) % $BITS))
421             }
422
423             #[inline]
424             fn rotate_right(self, n: uint) -> $T {
425                 // Protect against undefined behaviour for over-long bit shifts
426                 let n = n % $BITS;
427                 (self >> n) | (self << (($BITS - n) % $BITS))
428             }
429
430             #[inline]
431             fn swap_bytes(self) -> $T { unsafe { $bswap(self as $ActualT) as $T } }
432
433             #[inline]
434             fn checked_add(self, other: $T) -> Option<$T> {
435                 checked_op!($T, $ActualT, $add_with_overflow, self, other)
436             }
437
438             #[inline]
439             fn checked_sub(self, other: $T) -> Option<$T> {
440                 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
441             }
442
443             #[inline]
444             fn checked_mul(self, other: $T) -> Option<$T> {
445                 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
446             }
447
448             #[inline]
449             fn checked_div(self, v: $T) -> Option<$T> {
450                 match v {
451                     0 => None,
452                     v => Some(self / v),
453                 }
454             }
455         }
456     }
457 }
458
459 /// Swapping a single byte is a no-op. This is marked as `unsafe` for
460 /// consistency with the other `bswap` intrinsics.
461 unsafe fn bswap8(x: u8) -> u8 { x }
462
463 uint_impl! { u8 = u8, 8,
464     intrinsics::ctpop8,
465     intrinsics::ctlz8,
466     intrinsics::cttz8,
467     bswap8,
468     intrinsics::u8_add_with_overflow,
469     intrinsics::u8_sub_with_overflow,
470     intrinsics::u8_mul_with_overflow }
471
472 uint_impl! { u16 = u16, 16,
473     intrinsics::ctpop16,
474     intrinsics::ctlz16,
475     intrinsics::cttz16,
476     intrinsics::bswap16,
477     intrinsics::u16_add_with_overflow,
478     intrinsics::u16_sub_with_overflow,
479     intrinsics::u16_mul_with_overflow }
480
481 uint_impl! { u32 = u32, 32,
482     intrinsics::ctpop32,
483     intrinsics::ctlz32,
484     intrinsics::cttz32,
485     intrinsics::bswap32,
486     intrinsics::u32_add_with_overflow,
487     intrinsics::u32_sub_with_overflow,
488     intrinsics::u32_mul_with_overflow }
489
490 uint_impl! { u64 = u64, 64,
491     intrinsics::ctpop64,
492     intrinsics::ctlz64,
493     intrinsics::cttz64,
494     intrinsics::bswap64,
495     intrinsics::u64_add_with_overflow,
496     intrinsics::u64_sub_with_overflow,
497     intrinsics::u64_mul_with_overflow }
498
499 #[cfg(target_word_size = "32")]
500 uint_impl! { uint = u32, 32,
501     intrinsics::ctpop32,
502     intrinsics::ctlz32,
503     intrinsics::cttz32,
504     intrinsics::bswap32,
505     intrinsics::u32_add_with_overflow,
506     intrinsics::u32_sub_with_overflow,
507     intrinsics::u32_mul_with_overflow }
508
509 #[cfg(target_word_size = "64")]
510 uint_impl! { uint = u64, 64,
511     intrinsics::ctpop64,
512     intrinsics::ctlz64,
513     intrinsics::cttz64,
514     intrinsics::bswap64,
515     intrinsics::u64_add_with_overflow,
516     intrinsics::u64_sub_with_overflow,
517     intrinsics::u64_mul_with_overflow }
518
519 macro_rules! int_impl {
520     ($T:ty = $ActualT:ty, $UnsignedT:ty, $BITS:expr,
521      $add_with_overflow:path,
522      $sub_with_overflow:path,
523      $mul_with_overflow:path) => {
524         #[stable]
525         impl Int for $T {
526             #[inline]
527             fn zero() -> $T { 0 }
528
529             #[inline]
530             fn one() -> $T { 1 }
531
532             #[inline]
533             fn min_value() -> $T { (-1 as $T) << ($BITS - 1) }
534
535             #[inline]
536             fn max_value() -> $T { let min: $T = Int::min_value(); !min }
537
538             #[inline]
539             fn count_ones(self) -> uint { (self as $UnsignedT).count_ones() }
540
541             #[inline]
542             fn leading_zeros(self) -> uint { (self as $UnsignedT).leading_zeros() }
543
544             #[inline]
545             fn trailing_zeros(self) -> uint { (self as $UnsignedT).trailing_zeros() }
546
547             #[inline]
548             fn rotate_left(self, n: uint) -> $T { (self as $UnsignedT).rotate_left(n) as $T }
549
550             #[inline]
551             fn rotate_right(self, n: uint) -> $T { (self as $UnsignedT).rotate_right(n) as $T }
552
553             #[inline]
554             fn swap_bytes(self) -> $T { (self as $UnsignedT).swap_bytes() as $T }
555
556             #[inline]
557             fn checked_add(self, other: $T) -> Option<$T> {
558                 checked_op!($T, $ActualT, $add_with_overflow, self, other)
559             }
560
561             #[inline]
562             fn checked_sub(self, other: $T) -> Option<$T> {
563                 checked_op!($T, $ActualT, $sub_with_overflow, self, other)
564             }
565
566             #[inline]
567             fn checked_mul(self, other: $T) -> Option<$T> {
568                 checked_op!($T, $ActualT, $mul_with_overflow, self, other)
569             }
570
571             #[inline]
572             fn checked_div(self, v: $T) -> Option<$T> {
573                 match v {
574                     0   => None,
575                    -1 if self == Int::min_value()
576                         => None,
577                     v   => Some(self / v),
578                 }
579             }
580         }
581     }
582 }
583
584 int_impl! { i8 = i8, u8, 8,
585     intrinsics::i8_add_with_overflow,
586     intrinsics::i8_sub_with_overflow,
587     intrinsics::i8_mul_with_overflow }
588
589 int_impl! { i16 = i16, u16, 16,
590     intrinsics::i16_add_with_overflow,
591     intrinsics::i16_sub_with_overflow,
592     intrinsics::i16_mul_with_overflow }
593
594 int_impl! { i32 = i32, u32, 32,
595     intrinsics::i32_add_with_overflow,
596     intrinsics::i32_sub_with_overflow,
597     intrinsics::i32_mul_with_overflow }
598
599 int_impl! { i64 = i64, u64, 64,
600     intrinsics::i64_add_with_overflow,
601     intrinsics::i64_sub_with_overflow,
602     intrinsics::i64_mul_with_overflow }
603
604 #[cfg(target_word_size = "32")]
605 int_impl! { int = i32, u32, 32,
606     intrinsics::i32_add_with_overflow,
607     intrinsics::i32_sub_with_overflow,
608     intrinsics::i32_mul_with_overflow }
609
610 #[cfg(target_word_size = "64")]
611 int_impl! { int = i64, u64, 64,
612     intrinsics::i64_add_with_overflow,
613     intrinsics::i64_sub_with_overflow,
614     intrinsics::i64_mul_with_overflow }
615
616 /// A built-in two's complement integer.
617 #[stable]
618 pub trait SignedInt
619     : Int
620     + Neg<Output=Self>
621 {
622     /// Computes the absolute value of `self`. `Int::min_value()` will be
623     /// returned if the number is `Int::min_value()`.
624     #[unstable = "overflow in debug builds?"]
625     fn abs(self) -> Self;
626
627     /// Returns a number representing sign of `self`.
628     ///
629     /// - `0` if the number is zero
630     /// - `1` if the number is positive
631     /// - `-1` if the number is negative
632     #[stable]
633     fn signum(self) -> Self;
634
635     /// Returns `true` if `self` is positive and `false` if the number
636     /// is zero or negative.
637     #[stable]
638     fn is_positive(self) -> bool;
639
640     /// Returns `true` if `self` is negative and `false` if the number
641     /// is zero or positive.
642     #[stable]
643     fn is_negative(self) -> bool;
644 }
645
646 macro_rules! signed_int_impl {
647     ($T:ty) => {
648         #[stable]
649         impl SignedInt for $T {
650             #[inline]
651             fn abs(self) -> $T {
652                 if self.is_negative() { -self } else { self }
653             }
654
655             #[inline]
656             fn signum(self) -> $T {
657                 match self {
658                     n if n > 0 =>  1,
659                     0          =>  0,
660                     _          => -1,
661                 }
662             }
663
664             #[inline]
665             fn is_positive(self) -> bool { self > 0 }
666
667             #[inline]
668             fn is_negative(self) -> bool { self < 0 }
669         }
670     }
671 }
672
673 signed_int_impl! { i8 }
674 signed_int_impl! { i16 }
675 signed_int_impl! { i32 }
676 signed_int_impl! { i64 }
677 signed_int_impl! { int }
678
679 /// A built-in unsigned integer.
680 #[stable]
681 pub trait UnsignedInt: Int {
682     /// Returns `true` iff `self == 2^k` for some `k`.
683     #[stable]
684     #[inline]
685     fn is_power_of_two(self) -> bool {
686         (self - Int::one()) & self == Int::zero() && !(self == Int::zero())
687     }
688
689     /// Returns the smallest power of two greater than or equal to `self`.
690     /// Unspecified behavior on overflow.
691     #[stable]
692     #[inline]
693     fn next_power_of_two(self) -> Self {
694         let bits = size_of::<Self>() * 8;
695         let one: Self = Int::one();
696         one << ((bits - (self - one).leading_zeros()) % bits)
697     }
698
699     /// Returns the smallest power of two greater than or equal to `n`. If the
700     /// next power of two is greater than the type's maximum value, `None` is
701     /// returned, otherwise the power of two is wrapped in `Some`.
702     #[stable]
703     fn checked_next_power_of_two(self) -> Option<Self> {
704         let npot = self.next_power_of_two();
705         if npot >= self {
706             Some(npot)
707         } else {
708             None
709         }
710     }
711 }
712
713 #[stable]
714 impl UnsignedInt for uint {}
715
716 #[stable]
717 impl UnsignedInt for u8 {}
718
719 #[stable]
720 impl UnsignedInt for u16 {}
721
722 #[stable]
723 impl UnsignedInt for u32 {}
724
725 #[stable]
726 impl UnsignedInt for u64 {}
727
728 /// A generic trait for converting a value to a number.
729 #[experimental = "trait is likely to be removed"]
730 pub trait ToPrimitive {
731     /// Converts the value of `self` to an `int`.
732     #[inline]
733     fn to_int(&self) -> Option<int> {
734         self.to_i64().and_then(|x| x.to_int())
735     }
736
737     /// Converts the value of `self` to an `i8`.
738     #[inline]
739     fn to_i8(&self) -> Option<i8> {
740         self.to_i64().and_then(|x| x.to_i8())
741     }
742
743     /// Converts the value of `self` to an `i16`.
744     #[inline]
745     fn to_i16(&self) -> Option<i16> {
746         self.to_i64().and_then(|x| x.to_i16())
747     }
748
749     /// Converts the value of `self` to an `i32`.
750     #[inline]
751     fn to_i32(&self) -> Option<i32> {
752         self.to_i64().and_then(|x| x.to_i32())
753     }
754
755     /// Converts the value of `self` to an `i64`.
756     fn to_i64(&self) -> Option<i64>;
757
758     /// Converts the value of `self` to an `uint`.
759     #[inline]
760     fn to_uint(&self) -> Option<uint> {
761         self.to_u64().and_then(|x| x.to_uint())
762     }
763
764     /// Converts the value of `self` to an `u8`.
765     #[inline]
766     fn to_u8(&self) -> Option<u8> {
767         self.to_u64().and_then(|x| x.to_u8())
768     }
769
770     /// Converts the value of `self` to an `u16`.
771     #[inline]
772     fn to_u16(&self) -> Option<u16> {
773         self.to_u64().and_then(|x| x.to_u16())
774     }
775
776     /// Converts the value of `self` to an `u32`.
777     #[inline]
778     fn to_u32(&self) -> Option<u32> {
779         self.to_u64().and_then(|x| x.to_u32())
780     }
781
782     /// Converts the value of `self` to an `u64`.
783     #[inline]
784     fn to_u64(&self) -> Option<u64>;
785
786     /// Converts the value of `self` to an `f32`.
787     #[inline]
788     fn to_f32(&self) -> Option<f32> {
789         self.to_f64().and_then(|x| x.to_f32())
790     }
791
792     /// Converts the value of `self` to an `f64`.
793     #[inline]
794     fn to_f64(&self) -> Option<f64> {
795         self.to_i64().and_then(|x| x.to_f64())
796     }
797 }
798
799 macro_rules! impl_to_primitive_int_to_int {
800     ($SrcT:ty, $DstT:ty, $slf:expr) => (
801         {
802             if size_of::<$SrcT>() <= size_of::<$DstT>() {
803                 Some($slf as $DstT)
804             } else {
805                 let n = $slf as i64;
806                 let min_value: $DstT = Int::min_value();
807                 let max_value: $DstT = Int::max_value();
808                 if min_value as i64 <= n && n <= max_value as i64 {
809                     Some($slf as $DstT)
810                 } else {
811                     None
812                 }
813             }
814         }
815     )
816 }
817
818 macro_rules! impl_to_primitive_int_to_uint {
819     ($SrcT:ty, $DstT:ty, $slf:expr) => (
820         {
821             let zero: $SrcT = Int::zero();
822             let max_value: $DstT = Int::max_value();
823             if zero <= $slf && $slf as u64 <= max_value as u64 {
824                 Some($slf as $DstT)
825             } else {
826                 None
827             }
828         }
829     )
830 }
831
832 macro_rules! impl_to_primitive_int {
833     ($T:ty) => (
834         impl ToPrimitive for $T {
835             #[inline]
836             fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int, *self) }
837             #[inline]
838             fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) }
839             #[inline]
840             fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) }
841             #[inline]
842             fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32, *self) }
843             #[inline]
844             fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self) }
845
846             #[inline]
847             fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint, *self) }
848             #[inline]
849             fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) }
850             #[inline]
851             fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) }
852             #[inline]
853             fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32, *self) }
854             #[inline]
855             fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64, *self) }
856
857             #[inline]
858             fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
859             #[inline]
860             fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
861         }
862     )
863 }
864
865 impl_to_primitive_int! { int }
866 impl_to_primitive_int! { i8 }
867 impl_to_primitive_int! { i16 }
868 impl_to_primitive_int! { i32 }
869 impl_to_primitive_int! { i64 }
870
871 macro_rules! impl_to_primitive_uint_to_int {
872     ($DstT:ty, $slf:expr) => (
873         {
874             let max_value: $DstT = Int::max_value();
875             if $slf as u64 <= max_value as u64 {
876                 Some($slf as $DstT)
877             } else {
878                 None
879             }
880         }
881     )
882 }
883
884 macro_rules! impl_to_primitive_uint_to_uint {
885     ($SrcT:ty, $DstT:ty, $slf:expr) => (
886         {
887             if size_of::<$SrcT>() <= size_of::<$DstT>() {
888                 Some($slf as $DstT)
889             } else {
890                 let zero: $SrcT = Int::zero();
891                 let max_value: $DstT = Int::max_value();
892                 if zero <= $slf && $slf as u64 <= max_value as u64 {
893                     Some($slf as $DstT)
894                 } else {
895                     None
896                 }
897             }
898         }
899     )
900 }
901
902 macro_rules! impl_to_primitive_uint {
903     ($T:ty) => (
904         impl ToPrimitive for $T {
905             #[inline]
906             fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int, *self) }
907             #[inline]
908             fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) }
909             #[inline]
910             fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) }
911             #[inline]
912             fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32, *self) }
913             #[inline]
914             fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) }
915
916             #[inline]
917             fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint, *self) }
918             #[inline]
919             fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) }
920             #[inline]
921             fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) }
922             #[inline]
923             fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32, *self) }
924             #[inline]
925             fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64, *self) }
926
927             #[inline]
928             fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
929             #[inline]
930             fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
931         }
932     )
933 }
934
935 impl_to_primitive_uint! { uint }
936 impl_to_primitive_uint! { u8 }
937 impl_to_primitive_uint! { u16 }
938 impl_to_primitive_uint! { u32 }
939 impl_to_primitive_uint! { u64 }
940
941 macro_rules! impl_to_primitive_float_to_float {
942     ($SrcT:ident, $DstT:ident, $slf:expr) => (
943         if size_of::<$SrcT>() <= size_of::<$DstT>() {
944             Some($slf as $DstT)
945         } else {
946             let n = $slf as f64;
947             let max_value: $SrcT = ::$SrcT::MAX_VALUE;
948             if -max_value as f64 <= n && n <= max_value as f64 {
949                 Some($slf as $DstT)
950             } else {
951                 None
952             }
953         }
954     )
955 }
956
957 macro_rules! impl_to_primitive_float {
958     ($T:ident) => (
959         impl ToPrimitive for $T {
960             #[inline]
961             fn to_int(&self) -> Option<int> { Some(*self as int) }
962             #[inline]
963             fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
964             #[inline]
965             fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
966             #[inline]
967             fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
968             #[inline]
969             fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
970
971             #[inline]
972             fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
973             #[inline]
974             fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
975             #[inline]
976             fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
977             #[inline]
978             fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
979             #[inline]
980             fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
981
982             #[inline]
983             fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32, *self) }
984             #[inline]
985             fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64, *self) }
986         }
987     )
988 }
989
990 impl_to_primitive_float! { f32 }
991 impl_to_primitive_float! { f64 }
992
993 /// A generic trait for converting a number to a value.
994 #[experimental = "trait is likely to be removed"]
995 pub trait FromPrimitive : ::marker::Sized {
996     /// Convert an `int` to return an optional value of this type. If the
997     /// value cannot be represented by this value, the `None` is returned.
998     #[inline]
999     fn from_int(n: int) -> Option<Self> {
1000         FromPrimitive::from_i64(n as i64)
1001     }
1002
1003     /// Convert an `i8` to return an optional value of this type. If the
1004     /// type cannot be represented by this value, the `None` is returned.
1005     #[inline]
1006     fn from_i8(n: i8) -> Option<Self> {
1007         FromPrimitive::from_i64(n as i64)
1008     }
1009
1010     /// Convert an `i16` to return an optional value of this type. If the
1011     /// type cannot be represented by this value, the `None` is returned.
1012     #[inline]
1013     fn from_i16(n: i16) -> Option<Self> {
1014         FromPrimitive::from_i64(n as i64)
1015     }
1016
1017     /// Convert an `i32` to return an optional value of this type. If the
1018     /// type cannot be represented by this value, the `None` is returned.
1019     #[inline]
1020     fn from_i32(n: i32) -> Option<Self> {
1021         FromPrimitive::from_i64(n as i64)
1022     }
1023
1024     /// Convert an `i64` to return an optional value of this type. If the
1025     /// type cannot be represented by this value, the `None` is returned.
1026     fn from_i64(n: i64) -> Option<Self>;
1027
1028     /// Convert an `uint` to return an optional value of this type. If the
1029     /// type cannot be represented by this value, the `None` is returned.
1030     #[inline]
1031     fn from_uint(n: uint) -> Option<Self> {
1032         FromPrimitive::from_u64(n as u64)
1033     }
1034
1035     /// Convert an `u8` to return an optional value of this type. If the
1036     /// type cannot be represented by this value, the `None` is returned.
1037     #[inline]
1038     fn from_u8(n: u8) -> Option<Self> {
1039         FromPrimitive::from_u64(n as u64)
1040     }
1041
1042     /// Convert an `u16` to return an optional value of this type. If the
1043     /// type cannot be represented by this value, the `None` is returned.
1044     #[inline]
1045     fn from_u16(n: u16) -> Option<Self> {
1046         FromPrimitive::from_u64(n as u64)
1047     }
1048
1049     /// Convert an `u32` to return an optional value of this type. If the
1050     /// type cannot be represented by this value, the `None` is returned.
1051     #[inline]
1052     fn from_u32(n: u32) -> Option<Self> {
1053         FromPrimitive::from_u64(n as u64)
1054     }
1055
1056     /// Convert an `u64` to return an optional value of this type. If the
1057     /// type cannot be represented by this value, the `None` is returned.
1058     fn from_u64(n: u64) -> Option<Self>;
1059
1060     /// Convert a `f32` to return an optional value of this type. If the
1061     /// type cannot be represented by this value, the `None` is returned.
1062     #[inline]
1063     fn from_f32(n: f32) -> Option<Self> {
1064         FromPrimitive::from_f64(n as f64)
1065     }
1066
1067     /// Convert a `f64` to return an optional value of this type. If the
1068     /// type cannot be represented by this value, the `None` is returned.
1069     #[inline]
1070     fn from_f64(n: f64) -> Option<Self> {
1071         FromPrimitive::from_i64(n as i64)
1072     }
1073 }
1074
1075 /// A utility function that just calls `FromPrimitive::from_int`.
1076 #[experimental = "likely to be removed"]
1077 pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
1078     FromPrimitive::from_int(n)
1079 }
1080
1081 /// A utility function that just calls `FromPrimitive::from_i8`.
1082 #[experimental = "likely to be removed"]
1083 pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> {
1084     FromPrimitive::from_i8(n)
1085 }
1086
1087 /// A utility function that just calls `FromPrimitive::from_i16`.
1088 #[experimental = "likely to be removed"]
1089 pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> {
1090     FromPrimitive::from_i16(n)
1091 }
1092
1093 /// A utility function that just calls `FromPrimitive::from_i32`.
1094 #[experimental = "likely to be removed"]
1095 pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> {
1096     FromPrimitive::from_i32(n)
1097 }
1098
1099 /// A utility function that just calls `FromPrimitive::from_i64`.
1100 #[experimental = "likely to be removed"]
1101 pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
1102     FromPrimitive::from_i64(n)
1103 }
1104
1105 /// A utility function that just calls `FromPrimitive::from_uint`.
1106 #[experimental = "likely to be removed"]
1107 pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
1108     FromPrimitive::from_uint(n)
1109 }
1110
1111 /// A utility function that just calls `FromPrimitive::from_u8`.
1112 #[experimental = "likely to be removed"]
1113 pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> {
1114     FromPrimitive::from_u8(n)
1115 }
1116
1117 /// A utility function that just calls `FromPrimitive::from_u16`.
1118 #[experimental = "likely to be removed"]
1119 pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> {
1120     FromPrimitive::from_u16(n)
1121 }
1122
1123 /// A utility function that just calls `FromPrimitive::from_u32`.
1124 #[experimental = "likely to be removed"]
1125 pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> {
1126     FromPrimitive::from_u32(n)
1127 }
1128
1129 /// A utility function that just calls `FromPrimitive::from_u64`.
1130 #[experimental = "likely to be removed"]
1131 pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> {
1132     FromPrimitive::from_u64(n)
1133 }
1134
1135 /// A utility function that just calls `FromPrimitive::from_f32`.
1136 #[experimental = "likely to be removed"]
1137 pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> {
1138     FromPrimitive::from_f32(n)
1139 }
1140
1141 /// A utility function that just calls `FromPrimitive::from_f64`.
1142 #[experimental = "likely to be removed"]
1143 pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {
1144     FromPrimitive::from_f64(n)
1145 }
1146
1147 macro_rules! impl_from_primitive {
1148     ($T:ty, $to_ty:ident) => (
1149         impl FromPrimitive for $T {
1150             #[inline] fn from_int(n: int) -> Option<$T> { n.$to_ty() }
1151             #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() }
1152             #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() }
1153             #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() }
1154             #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() }
1155
1156             #[inline] fn from_uint(n: uint) -> Option<$T> { n.$to_ty() }
1157             #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() }
1158             #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() }
1159             #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() }
1160             #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() }
1161
1162             #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() }
1163             #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() }
1164         }
1165     )
1166 }
1167
1168 impl_from_primitive! { int, to_int }
1169 impl_from_primitive! { i8, to_i8 }
1170 impl_from_primitive! { i16, to_i16 }
1171 impl_from_primitive! { i32, to_i32 }
1172 impl_from_primitive! { i64, to_i64 }
1173 impl_from_primitive! { uint, to_uint }
1174 impl_from_primitive! { u8, to_u8 }
1175 impl_from_primitive! { u16, to_u16 }
1176 impl_from_primitive! { u32, to_u32 }
1177 impl_from_primitive! { u64, to_u64 }
1178 impl_from_primitive! { f32, to_f32 }
1179 impl_from_primitive! { f64, to_f64 }
1180
1181 /// Cast from one machine scalar to another.
1182 ///
1183 /// # Example
1184 ///
1185 /// ```
1186 /// use std::num;
1187 ///
1188 /// let twenty: f32 = num::cast(0x14i).unwrap();
1189 /// assert_eq!(twenty, 20f32);
1190 /// ```
1191 ///
1192 #[inline]
1193 #[experimental = "likely to be removed"]
1194 pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
1195     NumCast::from(n)
1196 }
1197
1198 /// An interface for casting between machine scalars.
1199 #[experimental = "trait is likely to be removed"]
1200 pub trait NumCast: ToPrimitive {
1201     /// Creates a number from another value that can be converted into a primitive via the
1202     /// `ToPrimitive` trait.
1203     fn from<T: ToPrimitive>(n: T) -> Option<Self>;
1204 }
1205
1206 macro_rules! impl_num_cast {
1207     ($T:ty, $conv:ident) => (
1208         impl NumCast for $T {
1209             #[inline]
1210             fn from<N: ToPrimitive>(n: N) -> Option<$T> {
1211                 // `$conv` could be generated using `concat_idents!`, but that
1212                 // macro seems to be broken at the moment
1213                 n.$conv()
1214             }
1215         }
1216     )
1217 }
1218
1219 impl_num_cast! { u8,    to_u8 }
1220 impl_num_cast! { u16,   to_u16 }
1221 impl_num_cast! { u32,   to_u32 }
1222 impl_num_cast! { u64,   to_u64 }
1223 impl_num_cast! { uint,  to_uint }
1224 impl_num_cast! { i8,    to_i8 }
1225 impl_num_cast! { i16,   to_i16 }
1226 impl_num_cast! { i32,   to_i32 }
1227 impl_num_cast! { i64,   to_i64 }
1228 impl_num_cast! { int,   to_int }
1229 impl_num_cast! { f32,   to_f32 }
1230 impl_num_cast! { f64,   to_f64 }
1231
1232 /// Used for representing the classification of floating point numbers
1233 #[derive(Copy, PartialEq, Show)]
1234 #[unstable = "may be renamed"]
1235 pub enum FpCategory {
1236     /// "Not a Number", often obtained by dividing by zero
1237     Nan,
1238     /// Positive or negative infinity
1239     Infinite ,
1240     /// Positive or negative zero
1241     Zero,
1242     /// De-normalized floating point representation (less precise than `Normal`)
1243     Subnormal,
1244     /// A regular floating point number
1245     Normal,
1246 }
1247
1248 /// A built-in floating point number.
1249 // FIXME(#5527): In a future version of Rust, many of these functions will
1250 //               become constants.
1251 //
1252 // FIXME(#8888): Several of these functions have a parameter named
1253 //               `unused_self`. Removing it requires #8888 to be fixed.
1254 #[unstable = "distribution of methods between core/std is unclear"]
1255 pub trait Float
1256     : Copy + Clone
1257     + NumCast
1258     + PartialOrd
1259     + PartialEq
1260     + Neg<Output=Self>
1261     + Add<Output=Self>
1262     + Sub<Output=Self>
1263     + Mul<Output=Self>
1264     + Div<Output=Self>
1265     + Rem<Output=Self>
1266 {
1267     /// Returns the NaN value.
1268     fn nan() -> Self;
1269     /// Returns the infinite value.
1270     fn infinity() -> Self;
1271     /// Returns the negative infinite value.
1272     fn neg_infinity() -> Self;
1273     /// Returns the `0` value.
1274     fn zero() -> Self;
1275     /// Returns -0.0.
1276     fn neg_zero() -> Self;
1277     /// Returns the `1` value.
1278     fn one() -> Self;
1279
1280     // FIXME (#5527): These should be associated constants
1281
1282     /// Returns the number of binary digits of mantissa that this type supports.
1283     #[deprecated = "use `std::f32::MANTISSA_DIGITS` or `std::f64::MANTISSA_DIGITS` as appropriate"]
1284     fn mantissa_digits(unused_self: Option<Self>) -> uint;
1285     /// Returns the number of base-10 digits of precision that this type supports.
1286     #[deprecated = "use `std::f32::DIGITS` or `std::f64::DIGITS` as appropriate"]
1287     fn digits(unused_self: Option<Self>) -> uint;
1288     /// Returns the difference between 1.0 and the smallest representable number larger than 1.0.
1289     #[deprecated = "use `std::f32::EPSILON` or `std::f64::EPSILON` as appropriate"]
1290     fn epsilon() -> Self;
1291     /// Returns the minimum binary exponent that this type can represent.
1292     #[deprecated = "use `std::f32::MIN_EXP` or `std::f64::MIN_EXP` as appropriate"]
1293     fn min_exp(unused_self: Option<Self>) -> int;
1294     /// Returns the maximum binary exponent that this type can represent.
1295     #[deprecated = "use `std::f32::MAX_EXP` or `std::f64::MAX_EXP` as appropriate"]
1296     fn max_exp(unused_self: Option<Self>) -> int;
1297     /// Returns the minimum base-10 exponent that this type can represent.
1298     #[deprecated = "use `std::f32::MIN_10_EXP` or `std::f64::MIN_10_EXP` as appropriate"]
1299     fn min_10_exp(unused_self: Option<Self>) -> int;
1300     /// Returns the maximum base-10 exponent that this type can represent.
1301     #[deprecated = "use `std::f32::MAX_10_EXP` or `std::f64::MAX_10_EXP` as appropriate"]
1302     fn max_10_exp(unused_self: Option<Self>) -> int;
1303     /// Returns the smallest finite value that this type can represent.
1304     #[deprecated = "use `std::f32::MIN_VALUE` or `std::f64::MIN_VALUE` as appropriate"]
1305     fn min_value() -> Self;
1306     /// Returns the smallest normalized positive number that this type can represent.
1307     #[deprecated = "use `std::f32::MIN_POS_VALUE` or `std::f64::MIN_POS_VALUE` as appropriate"]
1308     fn min_pos_value(unused_self: Option<Self>) -> Self;
1309     /// Returns the largest finite value that this type can represent.
1310     #[deprecated = "use `std::f32::MAX_VALUE` or `std::f64::MAX_VALUE` as appropriate"]
1311     fn max_value() -> Self;
1312
1313     /// Returns true if this value is NaN and false otherwise.
1314     fn is_nan(self) -> bool;
1315     /// Returns true if this value is positive infinity or negative infinity and
1316     /// false otherwise.
1317     fn is_infinite(self) -> bool;
1318     /// Returns true if this number is neither infinite nor NaN.
1319     fn is_finite(self) -> bool;
1320     /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1321     fn is_normal(self) -> bool;
1322     /// Returns the category that this number falls into.
1323     fn classify(self) -> FpCategory;
1324
1325     /// Returns the mantissa, exponent and sign as integers, respectively.
1326     fn integer_decode(self) -> (u64, i16, i8);
1327
1328     /// Return the largest integer less than or equal to a number.
1329     fn floor(self) -> Self;
1330     /// Return the smallest integer greater than or equal to a number.
1331     fn ceil(self) -> Self;
1332     /// Return the nearest integer to a number. Round half-way cases away from
1333     /// `0.0`.
1334     fn round(self) -> Self;
1335     /// Return the integer part of a number.
1336     fn trunc(self) -> Self;
1337     /// Return the fractional part of a number.
1338     fn fract(self) -> Self;
1339
1340     /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1341     /// number is `Float::nan()`.
1342     fn abs(self) -> Self;
1343     /// Returns a number that represents the sign of `self`.
1344     ///
1345     /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1346     /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1347     /// - `Float::nan()` if the number is `Float::nan()`
1348     fn signum(self) -> Self;
1349     /// Returns `true` if `self` is positive, including `+0.0` and
1350     /// `Float::infinity()`.
1351     fn is_positive(self) -> bool;
1352     /// Returns `true` if `self` is negative, including `-0.0` and
1353     /// `Float::neg_infinity()`.
1354     fn is_negative(self) -> bool;
1355
1356     /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1357     /// error. This produces a more accurate result with better performance than
1358     /// a separate multiplication operation followed by an add.
1359     fn mul_add(self, a: Self, b: Self) -> Self;
1360     /// Take the reciprocal (inverse) of a number, `1/x`.
1361     fn recip(self) -> Self;
1362
1363     /// Raise a number to an integer power.
1364     ///
1365     /// Using this function is generally faster than using `powf`
1366     fn powi(self, n: i32) -> Self;
1367     /// Raise a number to a floating point power.
1368     fn powf(self, n: Self) -> Self;
1369
1370     /// Take the square root of a number.
1371     ///
1372     /// Returns NaN if `self` is a negative number.
1373     fn sqrt(self) -> Self;
1374     /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1375     fn rsqrt(self) -> Self;
1376
1377     /// Returns `e^(self)`, (the exponential function).
1378     fn exp(self) -> Self;
1379     /// Returns 2 raised to the power of the number, `2^(self)`.
1380     fn exp2(self) -> Self;
1381     /// Returns the natural logarithm of the number.
1382     fn ln(self) -> Self;
1383     /// Returns the logarithm of the number with respect to an arbitrary base.
1384     fn log(self, base: Self) -> Self;
1385     /// Returns the base 2 logarithm of the number.
1386     fn log2(self) -> Self;
1387     /// Returns the base 10 logarithm of the number.
1388     fn log10(self) -> Self;
1389
1390     /// Convert radians to degrees.
1391     fn to_degrees(self) -> Self;
1392     /// Convert degrees to radians.
1393     fn to_radians(self) -> Self;
1394 }
1395
1396 /// A generic trait for converting a string with a radix (base) to a value
1397 #[experimental = "might need to return Result"]
1398 pub trait FromStrRadix {
1399     fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
1400 }
1401
1402 /// A utility function that just calls FromStrRadix::from_str_radix.
1403 #[experimental = "might need to return Result"]
1404 pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint) -> Option<T> {
1405     FromStrRadix::from_str_radix(str, radix)
1406 }
1407
1408 macro_rules! from_str_radix_float_impl {
1409     ($T:ty) => {
1410         #[experimental = "might need to return Result"]
1411         impl FromStr for $T {
1412             /// Convert a string in base 10 to a float.
1413             /// Accepts an optional decimal exponent.
1414             ///
1415             /// This function accepts strings such as
1416             ///
1417             /// * '3.14'
1418             /// * '+3.14', equivalent to '3.14'
1419             /// * '-3.14'
1420             /// * '2.5E10', or equivalently, '2.5e10'
1421             /// * '2.5E-10'
1422             /// * '.' (understood as 0)
1423             /// * '5.'
1424             /// * '.5', or, equivalently,  '0.5'
1425             /// * '+inf', 'inf', '-inf', 'NaN'
1426             ///
1427             /// Leading and trailing whitespace represent an error.
1428             ///
1429             /// # Arguments
1430             ///
1431             /// * src - A string
1432             ///
1433             /// # Return value
1434             ///
1435             /// `None` if the string did not represent a valid number.  Otherwise,
1436             /// `Some(n)` where `n` is the floating-point number represented by `src`.
1437             #[inline]
1438             fn from_str(src: &str) -> Option<$T> {
1439                 from_str_radix(src, 10)
1440             }
1441         }
1442
1443         #[experimental = "might need to return Result"]
1444         impl FromStrRadix for $T {
1445             /// Convert a string in a given base to a float.
1446             ///
1447             /// Due to possible conflicts, this function does **not** accept
1448             /// the special values `inf`, `-inf`, `+inf` and `NaN`, **nor**
1449             /// does it recognize exponents of any kind.
1450             ///
1451             /// Leading and trailing whitespace represent an error.
1452             ///
1453             /// # Arguments
1454             ///
1455             /// * src - A string
1456             /// * radix - The base to use. Must lie in the range [2 .. 36]
1457             ///
1458             /// # Return value
1459             ///
1460             /// `None` if the string did not represent a valid number. Otherwise,
1461             /// `Some(n)` where `n` is the floating-point number represented by `src`.
1462             fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
1463                assert!(radix >= 2 && radix <= 36,
1464                        "from_str_radix_float: must lie in the range `[2, 36]` - found {}",
1465                        radix);
1466
1467                 // Special values
1468                 match src {
1469                     "inf"   => return Some(Float::infinity()),
1470                     "-inf"  => return Some(Float::neg_infinity()),
1471                     "NaN"   => return Some(Float::nan()),
1472                     _       => {},
1473                 }
1474
1475                 let (is_positive, src) =  match src.slice_shift_char() {
1476                     None             => return None,
1477                     Some(('-', ""))  => return None,
1478                     Some(('-', src)) => (false, src),
1479                     Some((_, _))     => (true,  src),
1480                 };
1481
1482                 // The significand to accumulate
1483                 let mut sig = if is_positive { 0.0 } else { -0.0 };
1484                 // Necessary to detect overflow
1485                 let mut prev_sig = sig;
1486                 let mut cs = src.chars().enumerate();
1487                 // Exponent prefix and exponent index offset
1488                 let mut exp_info = None::<(char, uint)>;
1489
1490                 // Parse the integer part of the significand
1491                 for (i, c) in cs {
1492                     match c.to_digit(radix) {
1493                         Some(digit) => {
1494                             // shift significand one digit left
1495                             sig = sig * (radix as $T);
1496
1497                             // add/subtract current digit depending on sign
1498                             if is_positive {
1499                                 sig = sig + ((digit as int) as $T);
1500                             } else {
1501                                 sig = sig - ((digit as int) as $T);
1502                             }
1503
1504                             // Detect overflow by comparing to last value, except
1505                             // if we've not seen any non-zero digits.
1506                             if prev_sig != 0.0 {
1507                                 if is_positive && sig <= prev_sig
1508                                     { return Some(Float::infinity()); }
1509                                 if !is_positive && sig >= prev_sig
1510                                     { return Some(Float::neg_infinity()); }
1511
1512                                 // Detect overflow by reversing the shift-and-add process
1513                                 if is_positive && (prev_sig != (sig - digit as $T) / radix as $T)
1514                                     { return Some(Float::infinity()); }
1515                                 if !is_positive && (prev_sig != (sig + digit as $T) / radix as $T)
1516                                     { return Some(Float::neg_infinity()); }
1517                             }
1518                             prev_sig = sig;
1519                         },
1520                         None => match c {
1521                             'e' | 'E' | 'p' | 'P' => {
1522                                 exp_info = Some((c, i + 1));
1523                                 break;  // start of exponent
1524                             },
1525                             '.' => {
1526                                 break;  // start of fractional part
1527                             },
1528                             _ => {
1529                                 return None;
1530                             },
1531                         },
1532                     }
1533                 }
1534
1535                 // If we are not yet at the exponent parse the fractional
1536                 // part of the significand
1537                 if exp_info.is_none() {
1538                     let mut power = 1.0;
1539                     for (i, c) in cs {
1540                         match c.to_digit(radix) {
1541                             Some(digit) => {
1542                                 // Decrease power one order of magnitude
1543                                 power = power / (radix as $T);
1544                                 // add/subtract current digit depending on sign
1545                                 sig = if is_positive {
1546                                     sig + (digit as $T) * power
1547                                 } else {
1548                                     sig - (digit as $T) * power
1549                                 };
1550                                 // Detect overflow by comparing to last value
1551                                 if is_positive && sig < prev_sig
1552                                     { return Some(Float::infinity()); }
1553                                 if !is_positive && sig > prev_sig
1554                                     { return Some(Float::neg_infinity()); }
1555                                 prev_sig = sig;
1556                             },
1557                             None => match c {
1558                                 'e' | 'E' | 'p' | 'P' => {
1559                                     exp_info = Some((c, i + 1));
1560                                     break; // start of exponent
1561                                 },
1562                                 _ => {
1563                                     return None; // invalid number
1564                                 },
1565                             },
1566                         }
1567                     }
1568                 }
1569
1570                 // Parse and calculate the exponent
1571                 let exp = match exp_info {
1572                     Some((c, offset)) => {
1573                         let base = match c {
1574                             'E' | 'e' if radix == 10 => 10u as $T,
1575                             'P' | 'p' if radix == 16 => 2u as $T,
1576                             _ => return None,
1577                         };
1578
1579                         // Parse the exponent as decimal integer
1580                         let src = src.index(&(offset..));
1581                         let (is_positive, exp) = match src.slice_shift_char() {
1582                             Some(('-', src)) => (false, src.parse::<uint>()),
1583                             Some(('+', src)) => (true,  src.parse::<uint>()),
1584                             Some((_, _))     => (true,  src.parse::<uint>()),
1585                             None             => return None,
1586                         };
1587
1588                         match (is_positive, exp) {
1589                             (true,  Some(exp)) => base.powi(exp as i32),
1590                             (false, Some(exp)) => 1.0 / base.powi(exp as i32),
1591                             (_, None)          => return None,
1592                         }
1593                     },
1594                     None => 1.0, // no exponent
1595                 };
1596
1597                 Some(sig * exp)
1598             }
1599         }
1600     }
1601 }
1602 from_str_radix_float_impl! { f32 }
1603 from_str_radix_float_impl! { f64 }
1604
1605 macro_rules! from_str_radix_int_impl {
1606     ($T:ty) => {
1607         #[experimental = "might need to return Result"]
1608         impl FromStr for $T {
1609             #[inline]
1610             fn from_str(src: &str) -> Option<$T> {
1611                 from_str_radix(src, 10)
1612             }
1613         }
1614
1615         #[experimental = "might need to return Result"]
1616         impl FromStrRadix for $T {
1617             fn from_str_radix(src: &str, radix: uint) -> Option<$T> {
1618                 assert!(radix >= 2 && radix <= 36,
1619                        "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1620                        radix);
1621
1622                 let is_signed_ty = (0 as $T) > Int::min_value();
1623
1624                 match src.slice_shift_char() {
1625                     Some(('-', src)) if is_signed_ty => {
1626                         // The number is negative
1627                         let mut result = 0;
1628                         for c in src.chars() {
1629                             let x = match c.to_digit(radix) {
1630                                 Some(x) => x,
1631                                 None => return None,
1632                             };
1633                             result = match result.checked_mul(radix as $T) {
1634                                 Some(result) => result,
1635                                 None => return None,
1636                             };
1637                             result = match result.checked_sub(x as $T) {
1638                                 Some(result) => result,
1639                                 None => return None,
1640                             };
1641                         }
1642                         Some(result)
1643                     },
1644                     Some((_, _)) => {
1645                         // The number is signed
1646                         let mut result = 0;
1647                         for c in src.chars() {
1648                             let x = match c.to_digit(radix) {
1649                                 Some(x) => x,
1650                                 None => return None,
1651                             };
1652                             result = match result.checked_mul(radix as $T) {
1653                                 Some(result) => result,
1654                                 None => return None,
1655                             };
1656                             result = match result.checked_add(x as $T) {
1657                                 Some(result) => result,
1658                                 None => return None,
1659                             };
1660                         }
1661                         Some(result)
1662                     },
1663                     None => None,
1664                 }
1665             }
1666         }
1667     }
1668 }
1669 from_str_radix_int_impl! { int }
1670 from_str_radix_int_impl! { i8 }
1671 from_str_radix_int_impl! { i16 }
1672 from_str_radix_int_impl! { i32 }
1673 from_str_radix_int_impl! { i64 }
1674 from_str_radix_int_impl! { uint }
1675 from_str_radix_int_impl! { u8 }
1676 from_str_radix_int_impl! { u16 }
1677 from_str_radix_int_impl! { u32 }
1678 from_str_radix_int_impl! { u64 }