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