]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
ed0c24e7fa00864f917bfc3a088cdb5ab754ed17
[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 //! Numeric traits and functions for generic mathematics
12
13 #![allow(missing_doc)]
14
15 use intrinsics;
16 use {int, i8, i16, i32, i64};
17 use {uint, u8, u16, u32, u64};
18 use {f32, f64};
19 use clone::Clone;
20 use cmp::{PartialEq, PartialOrd};
21 use kinds::Copy;
22 use mem::size_of;
23 use ops::{Add, Sub, Mul, Div, Rem, Neg};
24 use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
25 use option::{Option, Some, None};
26
27 /// The base trait for numeric types
28 pub trait Num: PartialEq + Zero + One
29              + Neg<Self>
30              + Add<Self,Self>
31              + Sub<Self,Self>
32              + Mul<Self,Self>
33              + Div<Self,Self>
34              + Rem<Self,Self> {}
35
36 macro_rules! trait_impl(
37     ($name:ident for $($t:ty)*) => ($(
38         impl $name for $t {}
39     )*)
40 )
41
42 trait_impl!(Num for uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
43
44 /// Simultaneous division and remainder
45 #[inline]
46 pub fn div_rem<T: Div<T, T> + Rem<T, T>>(x: T, y: T) -> (T, T) {
47     (x / y, x % y)
48 }
49
50 /// Defines an additive identity element for `Self`.
51 ///
52 /// # Deriving
53 ///
54 /// This trait can be automatically be derived using `#[deriving(Zero)]`
55 /// attribute. If you choose to use this, make sure that the laws outlined in
56 /// the documentation for `Zero::zero` still hold.
57 pub trait Zero: Add<Self, Self> {
58     /// Returns the additive identity element of `Self`, `0`.
59     ///
60     /// # Laws
61     ///
62     /// ~~~text
63     /// a + 0 = a       ∀ a ∈ Self
64     /// 0 + a = a       ∀ a ∈ Self
65     /// ~~~
66     ///
67     /// # Purity
68     ///
69     /// This function should return the same result at all times regardless of
70     /// external mutable state, for example values stored in TLS or in
71     /// `static mut`s.
72     // FIXME (#5527): This should be an associated constant
73     fn zero() -> Self;
74
75     /// Returns `true` if `self` is equal to the additive identity.
76     fn is_zero(&self) -> bool;
77 }
78
79 macro_rules! zero_impl(
80     ($t:ty, $v:expr) => {
81         impl Zero for $t {
82             #[inline]
83             fn zero() -> $t { $v }
84             #[inline]
85             fn is_zero(&self) -> bool { *self == $v }
86         }
87     }
88 )
89
90 macro_rules! zero_float_impl(
91     ($t:ty, $v:expr) => {
92         impl Zero for $t {
93             #[inline]
94             fn zero() -> $t { $v }
95
96             #[inline]
97             fn is_zero(&self) -> bool { *self == $v || *self == -$v }
98         }
99     }
100 )
101
102 zero_impl!(uint, 0u)
103 zero_impl!(u8,  0u8)
104 zero_impl!(u16, 0u16)
105 zero_impl!(u32, 0u32)
106 zero_impl!(u64, 0u64)
107
108 zero_impl!(int, 0i)
109 zero_impl!(i8,  0i8)
110 zero_impl!(i16, 0i16)
111 zero_impl!(i32, 0i32)
112 zero_impl!(i64, 0i64)
113
114 zero_float_impl!(f32, 0.0f32)
115 zero_float_impl!(f64, 0.0f64)
116
117 /// Returns the additive identity, `0`.
118 #[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() }
119
120 /// Defines a multiplicative identity element for `Self`.
121 pub trait One: Mul<Self, Self> {
122     /// Returns the multiplicative identity element of `Self`, `1`.
123     ///
124     /// # Laws
125     ///
126     /// ~~~text
127     /// a * 1 = a       ∀ a ∈ Self
128     /// 1 * a = a       ∀ a ∈ Self
129     /// ~~~
130     ///
131     /// # Purity
132     ///
133     /// This function should return the same result at all times regardless of
134     /// external mutable state, for example values stored in TLS or in
135     /// `static mut`s.
136     // FIXME (#5527): This should be an associated constant
137     fn one() -> Self;
138 }
139
140 macro_rules! one_impl(
141     ($t:ty, $v:expr) => {
142         impl One for $t {
143             #[inline]
144             fn one() -> $t { $v }
145         }
146     }
147 )
148
149 one_impl!(uint, 1u)
150 one_impl!(u8,  1u8)
151 one_impl!(u16, 1u16)
152 one_impl!(u32, 1u32)
153 one_impl!(u64, 1u64)
154
155 one_impl!(int, 1i)
156 one_impl!(i8,  1i8)
157 one_impl!(i16, 1i16)
158 one_impl!(i32, 1i32)
159 one_impl!(i64, 1i64)
160
161 one_impl!(f32, 1.0f32)
162 one_impl!(f64, 1.0f64)
163
164 /// Returns the multiplicative identity, `1`.
165 #[inline(always)] pub fn one<T: One>() -> T { One::one() }
166
167 /// Useful functions for signed numbers (i.e. numbers that can be negative).
168 pub trait Signed: Num + Neg<Self> {
169     /// Computes the absolute value.
170     ///
171     /// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`.
172     fn abs(&self) -> Self;
173
174     /// The positive difference of two numbers.
175     ///
176     /// Returns `zero` if the number is less than or equal to `other`, otherwise the difference
177     /// between `self` and `other` is returned.
178     fn abs_sub(&self, other: &Self) -> Self;
179
180     /// Returns the sign of the number.
181     ///
182     /// For `f32` and `f64`:
183     ///
184     /// * `1.0` if the number is positive, `+0.0` or `INFINITY`
185     /// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
186     /// * `NaN` if the number is `NaN`
187     ///
188     /// For `int`:
189     ///
190     /// * `0` if the number is zero
191     /// * `1` if the number is positive
192     /// * `-1` if the number is negative
193     fn signum(&self) -> Self;
194
195     /// Returns true if the number is positive and false if the number is zero or negative.
196     fn is_positive(&self) -> bool;
197
198     /// Returns true if the number is negative and false if the number is zero or positive.
199     fn is_negative(&self) -> bool;
200 }
201
202 macro_rules! signed_impl(
203     ($($t:ty)*) => ($(
204         impl Signed for $t {
205             #[inline]
206             fn abs(&self) -> $t {
207                 if self.is_negative() { -*self } else { *self }
208             }
209
210             #[inline]
211             fn abs_sub(&self, other: &$t) -> $t {
212                 if *self <= *other { 0 } else { *self - *other }
213             }
214
215             #[inline]
216             fn signum(&self) -> $t {
217                 match *self {
218                     n if n > 0 => 1,
219                     0 => 0,
220                     _ => -1,
221                 }
222             }
223
224             #[inline]
225             fn is_positive(&self) -> bool { *self > 0 }
226
227             #[inline]
228             fn is_negative(&self) -> bool { *self < 0 }
229         }
230     )*)
231 )
232
233 signed_impl!(int i8 i16 i32 i64)
234
235 macro_rules! signed_float_impl(
236     ($t:ty, $nan:expr, $inf:expr, $neg_inf:expr, $fabs:path, $fcopysign:path, $fdim:ident) => {
237         impl Signed for $t {
238             /// Computes the absolute value. Returns `NAN` if the number is `NAN`.
239             #[inline]
240             fn abs(&self) -> $t {
241                 unsafe { $fabs(*self) }
242             }
243
244             /// The positive difference of two numbers. Returns `0.0` if the number is
245             /// less than or equal to `other`, otherwise the difference between`self`
246             /// and `other` is returned.
247             #[inline]
248             fn abs_sub(&self, other: &$t) -> $t {
249                 extern { fn $fdim(a: $t, b: $t) -> $t; }
250                 unsafe { $fdim(*self, *other) }
251             }
252
253             /// # Returns
254             ///
255             /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
256             /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
257             /// - `NAN` if the number is NaN
258             #[inline]
259             fn signum(&self) -> $t {
260                 if self != self { $nan } else {
261                     unsafe { $fcopysign(1.0, *self) }
262                 }
263             }
264
265             /// Returns `true` if the number is positive, including `+0.0` and `INFINITY`
266             #[inline]
267             fn is_positive(&self) -> bool { *self > 0.0 || (1.0 / *self) == $inf }
268
269             /// Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY`
270             #[inline]
271             fn is_negative(&self) -> bool { *self < 0.0 || (1.0 / *self) == $neg_inf }
272         }
273     }
274 )
275
276 signed_float_impl!(f32, f32::NAN, f32::INFINITY, f32::NEG_INFINITY,
277                    intrinsics::fabsf32, intrinsics::copysignf32, fdimf)
278 signed_float_impl!(f64, f64::NAN, f64::INFINITY, f64::NEG_INFINITY,
279                    intrinsics::fabsf64, intrinsics::copysignf64, fdim)
280
281 /// Computes the absolute value.
282 ///
283 /// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`
284 #[inline(always)]
285 pub fn abs<T: Signed>(value: T) -> T {
286     value.abs()
287 }
288
289 /// The positive difference of two numbers.
290 ///
291 /// Returns `zero` if the number is less than or equal to `other`,
292 /// otherwise the difference between `self` and `other` is returned.
293 #[inline(always)]
294 pub fn abs_sub<T: Signed>(x: T, y: T) -> T {
295     x.abs_sub(&y)
296 }
297
298 /// Returns the sign of the number.
299 ///
300 /// For `f32` and `f64`:
301 ///
302 /// * `1.0` if the number is positive, `+0.0` or `INFINITY`
303 /// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
304 /// * `NaN` if the number is `NaN`
305 ///
306 /// For int:
307 ///
308 /// * `0` if the number is zero
309 /// * `1` if the number is positive
310 /// * `-1` if the number is negative
311 #[inline(always)] pub fn signum<T: Signed>(value: T) -> T { value.signum() }
312
313 /// A trait for values which cannot be negative
314 pub trait Unsigned: Num {}
315
316 trait_impl!(Unsigned for uint u8 u16 u32 u64)
317
318 /// Raises a value to the power of exp, using exponentiation by squaring.
319 ///
320 /// # Example
321 ///
322 /// ```rust
323 /// use std::num;
324 ///
325 /// assert_eq!(num::pow(2, 4), 16);
326 /// ```
327 #[inline]
328 pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
329     if exp == 1 { base }
330     else {
331         let mut acc = one::<T>();
332         while exp > 0 {
333             if (exp & 1) == 1 {
334                 acc = acc * base;
335             }
336             base = base * base;
337             exp = exp >> 1;
338         }
339         acc
340     }
341 }
342
343 /// Numbers which have upper and lower bounds
344 pub trait Bounded {
345     // FIXME (#5527): These should be associated constants
346     /// returns the smallest finite number this type can represent
347     fn min_value() -> Self;
348     /// returns the largest finite number this type can represent
349     fn max_value() -> Self;
350 }
351
352 macro_rules! bounded_impl(
353     ($t:ty, $min:expr, $max:expr) => {
354         impl Bounded for $t {
355             #[inline]
356             fn min_value() -> $t { $min }
357
358             #[inline]
359             fn max_value() -> $t { $max }
360         }
361     }
362 )
363
364 bounded_impl!(uint, uint::MIN, uint::MAX)
365 bounded_impl!(u8, u8::MIN, u8::MAX)
366 bounded_impl!(u16, u16::MIN, u16::MAX)
367 bounded_impl!(u32, u32::MIN, u32::MAX)
368 bounded_impl!(u64, u64::MIN, u64::MAX)
369
370 bounded_impl!(int, int::MIN, int::MAX)
371 bounded_impl!(i8, i8::MIN, i8::MAX)
372 bounded_impl!(i16, i16::MIN, i16::MAX)
373 bounded_impl!(i32, i32::MIN, i32::MAX)
374 bounded_impl!(i64, i64::MIN, i64::MAX)
375
376 bounded_impl!(f32, f32::MIN_VALUE, f32::MAX_VALUE)
377 bounded_impl!(f64, f64::MIN_VALUE, f64::MAX_VALUE)
378
379 /// Specifies the available operations common to all of Rust's core numeric primitives.
380 /// These may not always make sense from a purely mathematical point of view, but
381 /// may be useful for systems programming.
382 pub trait Primitive: Copy
383                    + Clone
384                    + Num
385                    + NumCast
386                    + PartialOrd
387                    + Bounded {}
388
389 trait_impl!(Primitive for uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
390
391 /// A collection of traits relevant to primitive signed and unsigned integers
392 pub trait Int: Primitive
393              + CheckedAdd
394              + CheckedSub
395              + CheckedMul
396              + CheckedDiv
397              + Bounded
398              + Not<Self>
399              + BitAnd<Self,Self>
400              + BitOr<Self,Self>
401              + BitXor<Self,Self>
402              + Shl<Self,Self>
403              + Shr<Self,Self> {
404     /// Returns the number of ones in the binary representation of the integer.
405     ///
406     /// # Example
407     ///
408     /// ```rust
409     /// let n = 0b01001100u8;
410     ///
411     /// assert_eq!(n.count_ones(), 3);
412     /// ```
413     fn count_ones(self) -> Self;
414
415     /// Returns the number of zeros in the binary representation of the integer.
416     ///
417     /// # Example
418     ///
419     /// ```rust
420     /// let n = 0b01001100u8;
421     ///
422     /// assert_eq!(n.count_zeros(), 5);
423     /// ```
424     #[inline]
425     fn count_zeros(self) -> Self {
426         (!self).count_ones()
427     }
428
429     /// Returns the number of leading zeros in the in the binary representation
430     /// of the integer.
431     ///
432     /// # Example
433     ///
434     /// ```rust
435     /// let n = 0b0101000u16;
436     ///
437     /// assert_eq!(n.leading_zeros(), 10);
438     /// ```
439     fn leading_zeros(self) -> Self;
440
441     /// Returns the number of trailing zeros in the in the binary representation
442     /// of the integer.
443     ///
444     /// # Example
445     ///
446     /// ```rust
447     /// let n = 0b0101000u16;
448     ///
449     /// assert_eq!(n.trailing_zeros(), 3);
450     /// ```
451     fn trailing_zeros(self) -> Self;
452
453     /// Shifts the bits to the left by a specified amount amount, `n`, wrapping
454     /// the truncated bits to the end of the resulting integer.
455     ///
456     /// # Example
457     ///
458     /// ```rust
459     /// let n = 0x0123456789ABCDEFu64;
460     /// let m = 0x3456789ABCDEF012u64;
461     ///
462     /// assert_eq!(n.rotate_left(12), m);
463     /// ```
464     fn rotate_left(self, n: uint) -> Self;
465
466     /// Shifts the bits to the right by a specified amount amount, `n`, wrapping
467     /// the truncated bits to the beginning of the resulting integer.
468     ///
469     /// # Example
470     ///
471     /// ```rust
472     /// let n = 0x0123456789ABCDEFu64;
473     /// let m = 0xDEF0123456789ABCu64;
474     ///
475     /// assert_eq!(n.rotate_right(12), m);
476     /// ```
477     fn rotate_right(self, n: uint) -> Self;
478
479     /// Reverses the byte order of the integer.
480     ///
481     /// # Example
482     ///
483     /// ```rust
484     /// let n = 0x0123456789ABCDEFu64;
485     /// let m = 0xEFCDAB8967452301u64;
486     ///
487     /// assert_eq!(n.swap_bytes(), m);
488     /// ```
489     fn swap_bytes(self) -> Self;
490
491     /// Convert a integer from big endian to the target's endianness.
492     ///
493     /// On big endian this is a no-op. On little endian the bytes are swapped.
494     ///
495     /// # Example
496     ///
497     /// ```rust
498     /// let n = 0x0123456789ABCDEFu64;
499     ///
500     /// if cfg!(target_endian = "big") {
501     ///     assert_eq!(Int::from_big_endian(n), n)
502     /// } else {
503     ///     assert_eq!(Int::from_big_endian(n), n.swap_bytes())
504     /// }
505     /// ```
506     #[inline]
507     fn from_big_endian(x: Self) -> Self {
508         if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
509     }
510
511     /// Convert a integer from little endian to the target's endianness.
512     ///
513     /// On little endian this is a no-op. On big endian the bytes are swapped.
514     ///
515     /// # Example
516     ///
517     /// ```rust
518     /// let n = 0x0123456789ABCDEFu64;
519     ///
520     /// if cfg!(target_endian = "little") {
521     ///     assert_eq!(Int::from_little_endian(n), n)
522     /// } else {
523     ///     assert_eq!(Int::from_little_endian(n), n.swap_bytes())
524     /// }
525     /// ```
526     #[inline]
527     fn from_little_endian(x: Self) -> Self {
528         if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
529     }
530
531     /// Convert the integer to big endian from the target's endianness.
532     ///
533     /// On big endian this is a no-op. On little endian the bytes are swapped.
534     ///
535     /// # Example
536     ///
537     /// ```rust
538     /// let n = 0x0123456789ABCDEFu64;
539     ///
540     /// if cfg!(target_endian = "big") {
541     ///     assert_eq!(n.to_big_endian(), n)
542     /// } else {
543     ///     assert_eq!(n.to_big_endian(), n.swap_bytes())
544     /// }
545     /// ```
546     #[inline]
547     fn to_big_endian(self) -> Self {
548         if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
549     }
550
551     /// Convert the integer to little endian from the target's endianness.
552     ///
553     /// On little endian this is a no-op. On big endian the bytes are swapped.
554     ///
555     /// # Example
556     ///
557     /// ```rust
558     /// let n = 0x0123456789ABCDEFu64;
559     ///
560     /// if cfg!(target_endian = "little") {
561     ///     assert_eq!(n.to_little_endian(), n)
562     /// } else {
563     ///     assert_eq!(n.to_little_endian(), n.swap_bytes())
564     /// }
565     /// ```
566     #[inline]
567     fn to_little_endian(self) -> Self {
568         if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
569     }
570 }
571
572 macro_rules! int_impl {
573     ($T:ty, $BITS:expr, $ctpop:path, $ctlz:path, $cttz:path, $bswap:path) => {
574         impl Int for $T {
575             #[inline]
576             fn count_ones(self) -> $T { unsafe { $ctpop(self) } }
577
578             #[inline]
579             fn leading_zeros(self) -> $T { unsafe { $ctlz(self) } }
580
581             #[inline]
582             fn trailing_zeros(self) -> $T { unsafe { $cttz(self) } }
583
584             #[inline]
585             fn rotate_left(self, n: uint) -> $T {
586                 // Protect against undefined behaviour for over-long bit shifts
587                 let n = n % $BITS;
588                 (self << n) | (self >> ($BITS - n))
589             }
590
591             #[inline]
592             fn rotate_right(self, n: uint) -> $T {
593                 // Protect against undefined behaviour for over-long bit shifts
594                 let n = n % $BITS;
595                 (self >> n) | (self << ($BITS - n))
596             }
597
598             #[inline]
599             fn swap_bytes(self) -> $T { unsafe { $bswap(self) } }
600         }
601     }
602 }
603
604 /// Swapping a single byte is a no-op. This is marked as `unsafe` for
605 /// consistency with the other `bswap` intrinsics.
606 unsafe fn bswap8(x: u8) -> u8 { x }
607
608 int_impl!(u8, 8,
609     intrinsics::ctpop8,
610     intrinsics::ctlz8,
611     intrinsics::cttz8,
612     bswap8)
613
614 int_impl!(u16, 16,
615     intrinsics::ctpop16,
616     intrinsics::ctlz16,
617     intrinsics::cttz16,
618     intrinsics::bswap16)
619
620 int_impl!(u32, 32,
621     intrinsics::ctpop32,
622     intrinsics::ctlz32,
623     intrinsics::cttz32,
624     intrinsics::bswap32)
625
626 int_impl!(u64, 64,
627     intrinsics::ctpop64,
628     intrinsics::ctlz64,
629     intrinsics::cttz64,
630     intrinsics::bswap64)
631
632 macro_rules! int_cast_impl {
633     ($T:ty, $U:ty) => {
634         impl Int for $T {
635             #[inline]
636             fn count_ones(self) -> $T { (self as $U).count_ones() as $T }
637
638             #[inline]
639             fn leading_zeros(self) -> $T { (self as $U).leading_zeros() as $T }
640
641             #[inline]
642             fn trailing_zeros(self) -> $T { (self as $U).trailing_zeros() as $T }
643
644             #[inline]
645             fn rotate_left(self, n: uint) -> $T { (self as $U).rotate_left(n) as $T }
646
647             #[inline]
648             fn rotate_right(self, n: uint) -> $T { (self as $U).rotate_right(n) as $T }
649
650             #[inline]
651             fn swap_bytes(self) -> $T { (self as $U).swap_bytes() as $T }
652         }
653     }
654 }
655
656 int_cast_impl!(i8, u8)
657 int_cast_impl!(i16, u16)
658 int_cast_impl!(i32, u32)
659 int_cast_impl!(i64, u64)
660
661 #[cfg(target_word_size = "32")] int_cast_impl!(uint, u32)
662 #[cfg(target_word_size = "64")] int_cast_impl!(uint, u64)
663 #[cfg(target_word_size = "32")] int_cast_impl!(int, u32)
664 #[cfg(target_word_size = "64")] int_cast_impl!(int, u64)
665
666 /// Returns the smallest power of 2 greater than or equal to `n`.
667 #[inline]
668 pub fn next_power_of_two<T: Unsigned + Int>(n: T) -> T {
669     let halfbits: T = cast(size_of::<T>() * 4).unwrap();
670     let mut tmp: T = n - one();
671     let mut shift: T = one();
672     while shift <= halfbits {
673         tmp = tmp | (tmp >> shift);
674         shift = shift << one();
675     }
676     tmp + one()
677 }
678
679 // Returns `true` iff `n == 2^k` for some k.
680 #[inline]
681 pub fn is_power_of_two<T: Unsigned + Int>(n: T) -> bool {
682     (n - one()) & n == zero()
683 }
684
685 /// Returns the smallest power of 2 greater than or equal to `n`. If the next
686 /// power of two is greater than the type's maximum value, `None` is returned,
687 /// otherwise the power of 2 is wrapped in `Some`.
688 #[inline]
689 pub fn checked_next_power_of_two<T: Unsigned + Int>(n: T) -> Option<T> {
690     let halfbits: T = cast(size_of::<T>() * 4).unwrap();
691     let mut tmp: T = n - one();
692     let mut shift: T = one();
693     while shift <= halfbits {
694         tmp = tmp | (tmp >> shift);
695         shift = shift << one();
696     }
697     tmp.checked_add(&one())
698 }
699
700 /// A generic trait for converting a value to a number.
701 pub trait ToPrimitive {
702     /// Converts the value of `self` to an `int`.
703     #[inline]
704     fn to_int(&self) -> Option<int> {
705         self.to_i64().and_then(|x| x.to_int())
706     }
707
708     /// Converts the value of `self` to an `i8`.
709     #[inline]
710     fn to_i8(&self) -> Option<i8> {
711         self.to_i64().and_then(|x| x.to_i8())
712     }
713
714     /// Converts the value of `self` to an `i16`.
715     #[inline]
716     fn to_i16(&self) -> Option<i16> {
717         self.to_i64().and_then(|x| x.to_i16())
718     }
719
720     /// Converts the value of `self` to an `i32`.
721     #[inline]
722     fn to_i32(&self) -> Option<i32> {
723         self.to_i64().and_then(|x| x.to_i32())
724     }
725
726     /// Converts the value of `self` to an `i64`.
727     fn to_i64(&self) -> Option<i64>;
728
729     /// Converts the value of `self` to an `uint`.
730     #[inline]
731     fn to_uint(&self) -> Option<uint> {
732         self.to_u64().and_then(|x| x.to_uint())
733     }
734
735     /// Converts the value of `self` to an `u8`.
736     #[inline]
737     fn to_u8(&self) -> Option<u8> {
738         self.to_u64().and_then(|x| x.to_u8())
739     }
740
741     /// Converts the value of `self` to an `u16`.
742     #[inline]
743     fn to_u16(&self) -> Option<u16> {
744         self.to_u64().and_then(|x| x.to_u16())
745     }
746
747     /// Converts the value of `self` to an `u32`.
748     #[inline]
749     fn to_u32(&self) -> Option<u32> {
750         self.to_u64().and_then(|x| x.to_u32())
751     }
752
753     /// Converts the value of `self` to an `u64`.
754     #[inline]
755     fn to_u64(&self) -> Option<u64>;
756
757     /// Converts the value of `self` to an `f32`.
758     #[inline]
759     fn to_f32(&self) -> Option<f32> {
760         self.to_f64().and_then(|x| x.to_f32())
761     }
762
763     /// Converts the value of `self` to an `f64`.
764     #[inline]
765     fn to_f64(&self) -> Option<f64> {
766         self.to_i64().and_then(|x| x.to_f64())
767     }
768 }
769
770 macro_rules! impl_to_primitive_int_to_int(
771     ($SrcT:ty, $DstT:ty) => (
772         {
773             if size_of::<$SrcT>() <= size_of::<$DstT>() {
774                 Some(*self as $DstT)
775             } else {
776                 let n = *self as i64;
777                 let min_value: $DstT = Bounded::min_value();
778                 let max_value: $DstT = Bounded::max_value();
779                 if min_value as i64 <= n && n <= max_value as i64 {
780                     Some(*self as $DstT)
781                 } else {
782                     None
783                 }
784             }
785         }
786     )
787 )
788
789 macro_rules! impl_to_primitive_int_to_uint(
790     ($SrcT:ty, $DstT:ty) => (
791         {
792             let zero: $SrcT = Zero::zero();
793             let max_value: $DstT = Bounded::max_value();
794             if zero <= *self && *self as u64 <= max_value as u64 {
795                 Some(*self as $DstT)
796             } else {
797                 None
798             }
799         }
800     )
801 )
802
803 macro_rules! impl_to_primitive_int(
804     ($T:ty) => (
805         impl ToPrimitive for $T {
806             #[inline]
807             fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int) }
808             #[inline]
809             fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8) }
810             #[inline]
811             fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16) }
812             #[inline]
813             fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32) }
814             #[inline]
815             fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64) }
816
817             #[inline]
818             fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint) }
819             #[inline]
820             fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8) }
821             #[inline]
822             fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16) }
823             #[inline]
824             fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32) }
825             #[inline]
826             fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64) }
827
828             #[inline]
829             fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
830             #[inline]
831             fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
832         }
833     )
834 )
835
836 impl_to_primitive_int!(int)
837 impl_to_primitive_int!(i8)
838 impl_to_primitive_int!(i16)
839 impl_to_primitive_int!(i32)
840 impl_to_primitive_int!(i64)
841
842 macro_rules! impl_to_primitive_uint_to_int(
843     ($DstT:ty) => (
844         {
845             let max_value: $DstT = Bounded::max_value();
846             if *self as u64 <= max_value as u64 {
847                 Some(*self as $DstT)
848             } else {
849                 None
850             }
851         }
852     )
853 )
854
855 macro_rules! impl_to_primitive_uint_to_uint(
856     ($SrcT:ty, $DstT:ty) => (
857         {
858             if size_of::<$SrcT>() <= size_of::<$DstT>() {
859                 Some(*self as $DstT)
860             } else {
861                 let zero: $SrcT = Zero::zero();
862                 let max_value: $DstT = Bounded::max_value();
863                 if zero <= *self && *self as u64 <= max_value as u64 {
864                     Some(*self as $DstT)
865                 } else {
866                     None
867                 }
868             }
869         }
870     )
871 )
872
873 macro_rules! impl_to_primitive_uint(
874     ($T:ty) => (
875         impl ToPrimitive for $T {
876             #[inline]
877             fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int) }
878             #[inline]
879             fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8) }
880             #[inline]
881             fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16) }
882             #[inline]
883             fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32) }
884             #[inline]
885             fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64) }
886
887             #[inline]
888             fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint) }
889             #[inline]
890             fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8) }
891             #[inline]
892             fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16) }
893             #[inline]
894             fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32) }
895             #[inline]
896             fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64) }
897
898             #[inline]
899             fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
900             #[inline]
901             fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
902         }
903     )
904 )
905
906 impl_to_primitive_uint!(uint)
907 impl_to_primitive_uint!(u8)
908 impl_to_primitive_uint!(u16)
909 impl_to_primitive_uint!(u32)
910 impl_to_primitive_uint!(u64)
911
912 macro_rules! impl_to_primitive_float_to_float(
913     ($SrcT:ty, $DstT:ty) => (
914         if size_of::<$SrcT>() <= size_of::<$DstT>() {
915             Some(*self as $DstT)
916         } else {
917             let n = *self as f64;
918             let max_value: $SrcT = Bounded::max_value();
919             if -max_value as f64 <= n && n <= max_value as f64 {
920                 Some(*self as $DstT)
921             } else {
922                 None
923             }
924         }
925     )
926 )
927
928 macro_rules! impl_to_primitive_float(
929     ($T:ty) => (
930         impl ToPrimitive for $T {
931             #[inline]
932             fn to_int(&self) -> Option<int> { Some(*self as int) }
933             #[inline]
934             fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
935             #[inline]
936             fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
937             #[inline]
938             fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
939             #[inline]
940             fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
941
942             #[inline]
943             fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
944             #[inline]
945             fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
946             #[inline]
947             fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
948             #[inline]
949             fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
950             #[inline]
951             fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
952
953             #[inline]
954             fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32) }
955             #[inline]
956             fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64) }
957         }
958     )
959 )
960
961 impl_to_primitive_float!(f32)
962 impl_to_primitive_float!(f64)
963
964 /// A generic trait for converting a number to a value.
965 pub trait FromPrimitive {
966     /// Convert an `int` to return an optional value of this type. If the
967     /// value cannot be represented by this value, the `None` is returned.
968     #[inline]
969     fn from_int(n: int) -> Option<Self> {
970         FromPrimitive::from_i64(n as i64)
971     }
972
973     /// Convert an `i8` to return an optional value of this type. If the
974     /// type cannot be represented by this value, the `None` is returned.
975     #[inline]
976     fn from_i8(n: i8) -> Option<Self> {
977         FromPrimitive::from_i64(n as i64)
978     }
979
980     /// Convert an `i16` to return an optional value of this type. If the
981     /// type cannot be represented by this value, the `None` is returned.
982     #[inline]
983     fn from_i16(n: i16) -> Option<Self> {
984         FromPrimitive::from_i64(n as i64)
985     }
986
987     /// Convert an `i32` to return an optional value of this type. If the
988     /// type cannot be represented by this value, the `None` is returned.
989     #[inline]
990     fn from_i32(n: i32) -> Option<Self> {
991         FromPrimitive::from_i64(n as i64)
992     }
993
994     /// Convert an `i64` to return an optional value of this type. If the
995     /// type cannot be represented by this value, the `None` is returned.
996     fn from_i64(n: i64) -> Option<Self>;
997
998     /// Convert an `uint` 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_uint(n: uint) -> Option<Self> {
1002         FromPrimitive::from_u64(n as u64)
1003     }
1004
1005     /// Convert an `u8` 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_u8(n: u8) -> Option<Self> {
1009         FromPrimitive::from_u64(n as u64)
1010     }
1011
1012     /// Convert an `u16` 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_u16(n: u16) -> Option<Self> {
1016         FromPrimitive::from_u64(n as u64)
1017     }
1018
1019     /// Convert an `u32` to return an optional value of this type. If the
1020     /// type cannot be represented by this value, the `None` is returned.
1021     #[inline]
1022     fn from_u32(n: u32) -> Option<Self> {
1023         FromPrimitive::from_u64(n as u64)
1024     }
1025
1026     /// Convert an `u64` to return an optional value of this type. If the
1027     /// type cannot be represented by this value, the `None` is returned.
1028     fn from_u64(n: u64) -> Option<Self>;
1029
1030     /// Convert a `f32` 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_f32(n: f32) -> Option<Self> {
1034         FromPrimitive::from_f64(n as f64)
1035     }
1036
1037     /// Convert a `f64` 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_f64(n: f64) -> Option<Self> {
1041         FromPrimitive::from_i64(n as i64)
1042     }
1043 }
1044
1045 /// A utility function that just calls `FromPrimitive::from_int`.
1046 pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
1047     FromPrimitive::from_int(n)
1048 }
1049
1050 /// A utility function that just calls `FromPrimitive::from_i8`.
1051 pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> {
1052     FromPrimitive::from_i8(n)
1053 }
1054
1055 /// A utility function that just calls `FromPrimitive::from_i16`.
1056 pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> {
1057     FromPrimitive::from_i16(n)
1058 }
1059
1060 /// A utility function that just calls `FromPrimitive::from_i32`.
1061 pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> {
1062     FromPrimitive::from_i32(n)
1063 }
1064
1065 /// A utility function that just calls `FromPrimitive::from_i64`.
1066 pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
1067     FromPrimitive::from_i64(n)
1068 }
1069
1070 /// A utility function that just calls `FromPrimitive::from_uint`.
1071 pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
1072     FromPrimitive::from_uint(n)
1073 }
1074
1075 /// A utility function that just calls `FromPrimitive::from_u8`.
1076 pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> {
1077     FromPrimitive::from_u8(n)
1078 }
1079
1080 /// A utility function that just calls `FromPrimitive::from_u16`.
1081 pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> {
1082     FromPrimitive::from_u16(n)
1083 }
1084
1085 /// A utility function that just calls `FromPrimitive::from_u32`.
1086 pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> {
1087     FromPrimitive::from_u32(n)
1088 }
1089
1090 /// A utility function that just calls `FromPrimitive::from_u64`.
1091 pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> {
1092     FromPrimitive::from_u64(n)
1093 }
1094
1095 /// A utility function that just calls `FromPrimitive::from_f32`.
1096 pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> {
1097     FromPrimitive::from_f32(n)
1098 }
1099
1100 /// A utility function that just calls `FromPrimitive::from_f64`.
1101 pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {
1102     FromPrimitive::from_f64(n)
1103 }
1104
1105 macro_rules! impl_from_primitive(
1106     ($T:ty, $to_ty:expr) => (
1107         impl FromPrimitive for $T {
1108             #[inline] fn from_int(n: int) -> Option<$T> { $to_ty }
1109             #[inline] fn from_i8(n: i8) -> Option<$T> { $to_ty }
1110             #[inline] fn from_i16(n: i16) -> Option<$T> { $to_ty }
1111             #[inline] fn from_i32(n: i32) -> Option<$T> { $to_ty }
1112             #[inline] fn from_i64(n: i64) -> Option<$T> { $to_ty }
1113
1114             #[inline] fn from_uint(n: uint) -> Option<$T> { $to_ty }
1115             #[inline] fn from_u8(n: u8) -> Option<$T> { $to_ty }
1116             #[inline] fn from_u16(n: u16) -> Option<$T> { $to_ty }
1117             #[inline] fn from_u32(n: u32) -> Option<$T> { $to_ty }
1118             #[inline] fn from_u64(n: u64) -> Option<$T> { $to_ty }
1119
1120             #[inline] fn from_f32(n: f32) -> Option<$T> { $to_ty }
1121             #[inline] fn from_f64(n: f64) -> Option<$T> { $to_ty }
1122         }
1123     )
1124 )
1125
1126 impl_from_primitive!(int, n.to_int())
1127 impl_from_primitive!(i8, n.to_i8())
1128 impl_from_primitive!(i16, n.to_i16())
1129 impl_from_primitive!(i32, n.to_i32())
1130 impl_from_primitive!(i64, n.to_i64())
1131 impl_from_primitive!(uint, n.to_uint())
1132 impl_from_primitive!(u8, n.to_u8())
1133 impl_from_primitive!(u16, n.to_u16())
1134 impl_from_primitive!(u32, n.to_u32())
1135 impl_from_primitive!(u64, n.to_u64())
1136 impl_from_primitive!(f32, n.to_f32())
1137 impl_from_primitive!(f64, n.to_f64())
1138
1139 /// Cast from one machine scalar to another.
1140 ///
1141 /// # Example
1142 ///
1143 /// ```
1144 /// use std::num;
1145 ///
1146 /// let twenty: f32 = num::cast(0x14).unwrap();
1147 /// assert_eq!(twenty, 20f32);
1148 /// ```
1149 ///
1150 #[inline]
1151 pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
1152     NumCast::from(n)
1153 }
1154
1155 /// An interface for casting between machine scalars.
1156 pub trait NumCast: ToPrimitive {
1157     /// Creates a number from another value that can be converted into a primitive via the
1158     /// `ToPrimitive` trait.
1159     fn from<T: ToPrimitive>(n: T) -> Option<Self>;
1160 }
1161
1162 macro_rules! impl_num_cast(
1163     ($T:ty, $conv:ident) => (
1164         impl NumCast for $T {
1165             #[inline]
1166             fn from<N: ToPrimitive>(n: N) -> Option<$T> {
1167                 // `$conv` could be generated using `concat_idents!`, but that
1168                 // macro seems to be broken at the moment
1169                 n.$conv()
1170             }
1171         }
1172     )
1173 )
1174
1175 impl_num_cast!(u8,    to_u8)
1176 impl_num_cast!(u16,   to_u16)
1177 impl_num_cast!(u32,   to_u32)
1178 impl_num_cast!(u64,   to_u64)
1179 impl_num_cast!(uint,  to_uint)
1180 impl_num_cast!(i8,    to_i8)
1181 impl_num_cast!(i16,   to_i16)
1182 impl_num_cast!(i32,   to_i32)
1183 impl_num_cast!(i64,   to_i64)
1184 impl_num_cast!(int,   to_int)
1185 impl_num_cast!(f32,   to_f32)
1186 impl_num_cast!(f64,   to_f64)
1187
1188 /// Saturating math operations
1189 pub trait Saturating {
1190     /// Saturating addition operator.
1191     /// Returns a+b, saturating at the numeric bounds instead of overflowing.
1192     fn saturating_add(self, v: Self) -> Self;
1193
1194     /// Saturating subtraction operator.
1195     /// Returns a-b, saturating at the numeric bounds instead of overflowing.
1196     fn saturating_sub(self, v: Self) -> Self;
1197 }
1198
1199 impl<T: CheckedAdd + CheckedSub + Zero + PartialOrd + Bounded> Saturating for T {
1200     #[inline]
1201     fn saturating_add(self, v: T) -> T {
1202         match self.checked_add(&v) {
1203             Some(x) => x,
1204             None => if v >= Zero::zero() {
1205                 Bounded::max_value()
1206             } else {
1207                 Bounded::min_value()
1208             }
1209         }
1210     }
1211
1212     #[inline]
1213     fn saturating_sub(self, v: T) -> T {
1214         match self.checked_sub(&v) {
1215             Some(x) => x,
1216             None => if v >= Zero::zero() {
1217                 Bounded::min_value()
1218             } else {
1219                 Bounded::max_value()
1220             }
1221         }
1222     }
1223 }
1224
1225 /// Performs addition that returns `None` instead of wrapping around on overflow.
1226 pub trait CheckedAdd: Add<Self, Self> {
1227     /// Adds two numbers, checking for overflow. If overflow happens, `None` is returned.
1228     fn checked_add(&self, v: &Self) -> Option<Self>;
1229 }
1230
1231 macro_rules! checked_impl(
1232     ($trait_name:ident, $method:ident, $t:ty, $op:path) => {
1233         impl $trait_name for $t {
1234             #[inline]
1235             fn $method(&self, v: &$t) -> Option<$t> {
1236                 unsafe {
1237                     let (x, y) = $op(*self, *v);
1238                     if y { None } else { Some(x) }
1239                 }
1240             }
1241         }
1242     }
1243 )
1244 macro_rules! checked_cast_impl(
1245     ($trait_name:ident, $method:ident, $t:ty, $cast:ty, $op:path) => {
1246         impl $trait_name for $t {
1247             #[inline]
1248             fn $method(&self, v: &$t) -> Option<$t> {
1249                 unsafe {
1250                     let (x, y) = $op(*self as $cast, *v as $cast);
1251                     if y { None } else { Some(x as $t) }
1252                 }
1253             }
1254         }
1255     }
1256 )
1257
1258 #[cfg(target_word_size = "32")]
1259 checked_cast_impl!(CheckedAdd, checked_add, uint, u32, intrinsics::u32_add_with_overflow)
1260 #[cfg(target_word_size = "64")]
1261 checked_cast_impl!(CheckedAdd, checked_add, uint, u64, intrinsics::u64_add_with_overflow)
1262
1263 checked_impl!(CheckedAdd, checked_add, u8,  intrinsics::u8_add_with_overflow)
1264 checked_impl!(CheckedAdd, checked_add, u16, intrinsics::u16_add_with_overflow)
1265 checked_impl!(CheckedAdd, checked_add, u32, intrinsics::u32_add_with_overflow)
1266 checked_impl!(CheckedAdd, checked_add, u64, intrinsics::u64_add_with_overflow)
1267
1268 #[cfg(target_word_size = "32")]
1269 checked_cast_impl!(CheckedAdd, checked_add, int, i32, intrinsics::i32_add_with_overflow)
1270 #[cfg(target_word_size = "64")]
1271 checked_cast_impl!(CheckedAdd, checked_add, int, i64, intrinsics::i64_add_with_overflow)
1272
1273 checked_impl!(CheckedAdd, checked_add, i8,  intrinsics::i8_add_with_overflow)
1274 checked_impl!(CheckedAdd, checked_add, i16, intrinsics::i16_add_with_overflow)
1275 checked_impl!(CheckedAdd, checked_add, i32, intrinsics::i32_add_with_overflow)
1276 checked_impl!(CheckedAdd, checked_add, i64, intrinsics::i64_add_with_overflow)
1277
1278 /// Performs subtraction that returns `None` instead of wrapping around on underflow.
1279 pub trait CheckedSub: Sub<Self, Self> {
1280     /// Subtracts two numbers, checking for underflow. If underflow happens, `None` is returned.
1281     fn checked_sub(&self, v: &Self) -> Option<Self>;
1282 }
1283
1284 #[cfg(target_word_size = "32")]
1285 checked_cast_impl!(CheckedSub, checked_sub, uint, u32, intrinsics::u32_sub_with_overflow)
1286 #[cfg(target_word_size = "64")]
1287 checked_cast_impl!(CheckedSub, checked_sub, uint, u64, intrinsics::u64_sub_with_overflow)
1288
1289 checked_impl!(CheckedSub, checked_sub, u8,  intrinsics::u8_sub_with_overflow)
1290 checked_impl!(CheckedSub, checked_sub, u16, intrinsics::u16_sub_with_overflow)
1291 checked_impl!(CheckedSub, checked_sub, u32, intrinsics::u32_sub_with_overflow)
1292 checked_impl!(CheckedSub, checked_sub, u64, intrinsics::u64_sub_with_overflow)
1293
1294 #[cfg(target_word_size = "32")]
1295 checked_cast_impl!(CheckedSub, checked_sub, int, i32, intrinsics::i32_sub_with_overflow)
1296 #[cfg(target_word_size = "64")]
1297 checked_cast_impl!(CheckedSub, checked_sub, int, i64, intrinsics::i64_sub_with_overflow)
1298
1299 checked_impl!(CheckedSub, checked_sub, i8,  intrinsics::i8_sub_with_overflow)
1300 checked_impl!(CheckedSub, checked_sub, i16, intrinsics::i16_sub_with_overflow)
1301 checked_impl!(CheckedSub, checked_sub, i32, intrinsics::i32_sub_with_overflow)
1302 checked_impl!(CheckedSub, checked_sub, i64, intrinsics::i64_sub_with_overflow)
1303
1304 /// Performs multiplication that returns `None` instead of wrapping around on underflow or
1305 /// overflow.
1306 pub trait CheckedMul: Mul<Self, Self> {
1307     /// Multiplies two numbers, checking for underflow or overflow. If underflow or overflow
1308     /// happens, `None` is returned.
1309     fn checked_mul(&self, v: &Self) -> Option<Self>;
1310 }
1311
1312 #[cfg(target_word_size = "32")]
1313 checked_cast_impl!(CheckedMul, checked_mul, uint, u32, intrinsics::u32_mul_with_overflow)
1314 #[cfg(target_word_size = "64")]
1315 checked_cast_impl!(CheckedMul, checked_mul, uint, u64, intrinsics::u64_mul_with_overflow)
1316
1317 checked_impl!(CheckedMul, checked_mul, u8,  intrinsics::u8_mul_with_overflow)
1318 checked_impl!(CheckedMul, checked_mul, u16, intrinsics::u16_mul_with_overflow)
1319 checked_impl!(CheckedMul, checked_mul, u32, intrinsics::u32_mul_with_overflow)
1320 checked_impl!(CheckedMul, checked_mul, u64, intrinsics::u64_mul_with_overflow)
1321
1322 #[cfg(target_word_size = "32")]
1323 checked_cast_impl!(CheckedMul, checked_mul, int, i32, intrinsics::i32_mul_with_overflow)
1324 #[cfg(target_word_size = "64")]
1325 checked_cast_impl!(CheckedMul, checked_mul, int, i64, intrinsics::i64_mul_with_overflow)
1326
1327 checked_impl!(CheckedMul, checked_mul, i8,  intrinsics::i8_mul_with_overflow)
1328 checked_impl!(CheckedMul, checked_mul, i16, intrinsics::i16_mul_with_overflow)
1329 checked_impl!(CheckedMul, checked_mul, i32, intrinsics::i32_mul_with_overflow)
1330 checked_impl!(CheckedMul, checked_mul, i64, intrinsics::i64_mul_with_overflow)
1331
1332 /// Performs division that returns `None` instead of wrapping around on underflow or overflow.
1333 pub trait CheckedDiv: Div<Self, Self> {
1334     /// Divides two numbers, checking for underflow or overflow. If underflow or overflow happens,
1335     /// `None` is returned.
1336     fn checked_div(&self, v: &Self) -> Option<Self>;
1337 }
1338
1339 macro_rules! checkeddiv_int_impl(
1340     ($t:ty, $min:expr) => {
1341         impl CheckedDiv for $t {
1342             #[inline]
1343             fn checked_div(&self, v: &$t) -> Option<$t> {
1344                 if *v == 0 || (*self == $min && *v == -1) {
1345                     None
1346                 } else {
1347                     Some(self / *v)
1348                 }
1349             }
1350         }
1351     }
1352 )
1353
1354 checkeddiv_int_impl!(int, int::MIN)
1355 checkeddiv_int_impl!(i8, i8::MIN)
1356 checkeddiv_int_impl!(i16, i16::MIN)
1357 checkeddiv_int_impl!(i32, i32::MIN)
1358 checkeddiv_int_impl!(i64, i64::MIN)
1359
1360 macro_rules! checkeddiv_uint_impl(
1361     ($($t:ty)*) => ($(
1362         impl CheckedDiv for $t {
1363             #[inline]
1364             fn checked_div(&self, v: &$t) -> Option<$t> {
1365                 if *v == 0 {
1366                     None
1367                 } else {
1368                     Some(self / *v)
1369                 }
1370             }
1371         }
1372     )*)
1373 )
1374
1375 checkeddiv_uint_impl!(uint u8 u16 u32 u64)
1376
1377 /// Helper function for testing numeric operations
1378 #[cfg(test)]
1379 pub fn test_num<T:Num + NumCast + ::std::fmt::Show>(ten: T, two: T) {
1380     assert_eq!(ten.add(&two),  cast(12).unwrap());
1381     assert_eq!(ten.sub(&two),  cast(8).unwrap());
1382     assert_eq!(ten.mul(&two),  cast(20).unwrap());
1383     assert_eq!(ten.div(&two),  cast(5).unwrap());
1384     assert_eq!(ten.rem(&two),  cast(0).unwrap());
1385
1386     assert_eq!(ten.add(&two),  ten + two);
1387     assert_eq!(ten.sub(&two),  ten - two);
1388     assert_eq!(ten.mul(&two),  ten * two);
1389     assert_eq!(ten.div(&two),  ten / two);
1390     assert_eq!(ten.rem(&two),  ten % two);
1391 }
1392
1393 /// Used for representing the classification of floating point numbers
1394 #[deriving(PartialEq, Show)]
1395 pub enum FPCategory {
1396     /// "Not a Number", often obtained by dividing by zero
1397     FPNaN,
1398     /// Positive or negative infinity
1399     FPInfinite ,
1400     /// Positive or negative zero
1401     FPZero,
1402     /// De-normalized floating point representation (less precise than `FPNormal`)
1403     FPSubnormal,
1404     /// A regular floating point number
1405     FPNormal,
1406 }
1407
1408 /// Operations on primitive floating point numbers.
1409 // FIXME(#5527): In a future version of Rust, many of these functions will
1410 //               become constants.
1411 //
1412 // FIXME(#8888): Several of these functions have a parameter named
1413 //               `unused_self`. Removing it requires #8888 to be fixed.
1414 pub trait Float: Signed + Primitive {
1415     /// Returns the NaN value.
1416     fn nan() -> Self;
1417     /// Returns the infinite value.
1418     fn infinity() -> Self;
1419     /// Returns the negative infinite value.
1420     fn neg_infinity() -> Self;
1421     /// Returns -0.0.
1422     fn neg_zero() -> Self;
1423
1424     /// Returns true if this value is NaN and false otherwise.
1425     fn is_nan(self) -> bool;
1426     /// Returns true if this value is positive infinity or negative infinity and
1427     /// false otherwise.
1428     fn is_infinite(self) -> bool;
1429     /// Returns true if this number is neither infinite nor NaN.
1430     fn is_finite(self) -> bool;
1431     /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1432     fn is_normal(self) -> bool;
1433     /// Returns the category that this number falls into.
1434     fn classify(self) -> FPCategory;
1435
1436     // FIXME (#5527): These should be associated constants
1437
1438     /// Returns the number of binary digits of mantissa that this type supports.
1439     fn mantissa_digits(unused_self: Option<Self>) -> uint;
1440     /// Returns the number of base-10 digits of precision that this type supports.
1441     fn digits(unused_self: Option<Self>) -> uint;
1442     /// Returns the difference between 1.0 and the smallest representable number larger than 1.0.
1443     fn epsilon() -> Self;
1444     /// Returns the minimum binary exponent that this type can represent.
1445     fn min_exp(unused_self: Option<Self>) -> int;
1446     /// Returns the maximum binary exponent that this type can represent.
1447     fn max_exp(unused_self: Option<Self>) -> int;
1448     /// Returns the minimum base-10 exponent that this type can represent.
1449     fn min_10_exp(unused_self: Option<Self>) -> int;
1450     /// Returns the maximum base-10 exponent that this type can represent.
1451     fn max_10_exp(unused_self: Option<Self>) -> int;
1452     /// Returns the smallest normalized positive number that this type can represent.
1453     fn min_pos_value(unused_self: Option<Self>) -> Self;
1454
1455     /// Returns the mantissa, exponent and sign as integers, respectively.
1456     fn integer_decode(self) -> (u64, i16, i8);
1457
1458     /// Return the largest integer less than or equal to a number.
1459     fn floor(self) -> Self;
1460     /// Return the smallest integer greater than or equal to a number.
1461     fn ceil(self) -> Self;
1462     /// Return the nearest integer to a number. Round half-way cases away from
1463     /// `0.0`.
1464     fn round(self) -> Self;
1465     /// Return the integer part of a number.
1466     fn trunc(self) -> Self;
1467     /// Return the fractional part of a number.
1468     fn fract(self) -> Self;
1469
1470     /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1471     /// error. This produces a more accurate result with better performance than
1472     /// a separate multiplication operation followed by an add.
1473     fn mul_add(self, a: Self, b: Self) -> Self;
1474     /// Take the reciprocal (inverse) of a number, `1/x`.
1475     fn recip(self) -> Self;
1476
1477     /// Raise a number to an integer power.
1478     ///
1479     /// Using this function is generally faster than using `powf`
1480     fn powi(self, n: i32) -> Self;
1481     /// Raise a number to a floating point power.
1482     fn powf(self, n: Self) -> Self;
1483
1484     /// sqrt(2.0).
1485     fn sqrt2() -> Self;
1486     /// 1.0 / sqrt(2.0).
1487     fn frac_1_sqrt2() -> Self;
1488
1489     /// Take the square root of a number.
1490     fn sqrt(self) -> Self;
1491     /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1492     fn rsqrt(self) -> Self;
1493
1494     // FIXME (#5527): These should be associated constants
1495
1496     /// Archimedes' constant.
1497     fn pi() -> Self;
1498     /// 2.0 * pi.
1499     fn two_pi() -> Self;
1500     /// pi / 2.0.
1501     fn frac_pi_2() -> Self;
1502     /// pi / 3.0.
1503     fn frac_pi_3() -> Self;
1504     /// pi / 4.0.
1505     fn frac_pi_4() -> Self;
1506     /// pi / 6.0.
1507     fn frac_pi_6() -> Self;
1508     /// pi / 8.0.
1509     fn frac_pi_8() -> Self;
1510     /// 1.0 / pi.
1511     fn frac_1_pi() -> Self;
1512     /// 2.0 / pi.
1513     fn frac_2_pi() -> Self;
1514     /// 2.0 / sqrt(pi).
1515     fn frac_2_sqrtpi() -> Self;
1516
1517     /// Euler's number.
1518     fn e() -> Self;
1519     /// log2(e).
1520     fn log2_e() -> Self;
1521     /// log10(e).
1522     fn log10_e() -> Self;
1523     /// ln(2.0).
1524     fn ln_2() -> Self;
1525     /// ln(10.0).
1526     fn ln_10() -> Self;
1527
1528     /// Returns `e^(self)`, (the exponential function).
1529     fn exp(self) -> Self;
1530     /// Returns 2 raised to the power of the number, `2^(self)`.
1531     fn exp2(self) -> Self;
1532     /// Returns the natural logarithm of the number.
1533     fn ln(self) -> Self;
1534     /// Returns the logarithm of the number with respect to an arbitrary base.
1535     fn log(self, base: Self) -> Self;
1536     /// Returns the base 2 logarithm of the number.
1537     fn log2(self) -> Self;
1538     /// Returns the base 10 logarithm of the number.
1539     fn log10(self) -> Self;
1540
1541     /// Convert radians to degrees.
1542     fn to_degrees(self) -> Self;
1543     /// Convert degrees to radians.
1544     fn to_radians(self) -> Self;
1545 }