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