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