]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
eaa632be6d04c42fe749f39c1b5267fe945890de
[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 /// Numbers with a fixed binary representation.
380 pub trait Bitwise: Bounded
381                  + Not<Self>
382                  + BitAnd<Self,Self>
383                  + BitOr<Self,Self>
384                  + BitXor<Self,Self>
385                  + Shl<Self,Self>
386                  + Shr<Self,Self> {
387     /// Returns the number of ones in the binary representation of the number.
388     ///
389     /// # Example
390     ///
391     /// ```rust
392     /// use std::num::Bitwise;
393     ///
394     /// let n = 0b01001100u8;
395     /// assert_eq!(n.count_ones(), 3);
396     /// ```
397     fn count_ones(&self) -> Self;
398
399     /// Returns the number of zeros in the binary representation of the number.
400     ///
401     /// # Example
402     ///
403     /// ```rust
404     /// use std::num::Bitwise;
405     ///
406     /// let n = 0b01001100u8;
407     /// assert_eq!(n.count_zeros(), 5);
408     /// ```
409     #[inline]
410     fn count_zeros(&self) -> Self {
411         (!*self).count_ones()
412     }
413
414     /// Returns the number of leading zeros in the in the binary representation
415     /// of the number.
416     ///
417     /// # Example
418     ///
419     /// ```rust
420     /// use std::num::Bitwise;
421     ///
422     /// let n = 0b0101000u16;
423     /// assert_eq!(n.leading_zeros(), 10);
424     /// ```
425     fn leading_zeros(&self) -> Self;
426
427     /// Returns the number of trailing zeros in the in the binary representation
428     /// of the number.
429     ///
430     /// # Example
431     ///
432     /// ```rust
433     /// use std::num::Bitwise;
434     ///
435     /// let n = 0b0101000u16;
436     /// assert_eq!(n.trailing_zeros(), 3);
437     /// ```
438     fn trailing_zeros(&self) -> Self;
439
440     /// Reverses the byte order of a binary number.
441     ///
442     /// # Example
443     ///
444     /// ```rust
445     /// use std::num::Bitwise;
446     ///
447     /// let n = 0x0123456789ABCDEFu64;
448     /// let m = 0xEFCDAB8967452301u64;
449     /// assert_eq!(n.swap_bytes(), m);
450     /// ```
451     fn swap_bytes(&self) -> Self;
452
453     /// Shifts the bits to the left by a specified amount amount, `r`, wrapping
454     /// the truncated bits to the end of the resulting value.
455     ///
456     /// # Example
457     ///
458     /// ```rust
459     /// use std::num::Bitwise;
460     ///
461     /// let n = 0x0123456789ABCDEFu64;
462     /// let m = 0x3456789ABCDEF012u64;
463     /// assert_eq!(n.rotate_left(12), m);
464     /// ```
465     fn rotate_left(&self, r: uint) -> Self;
466
467     /// Shifts the bits to the right by a specified amount amount, `r`, wrapping
468     /// the truncated bits to the beginning of the resulting value.
469     ///
470     /// # Example
471     ///
472     /// ```rust
473     /// use std::num::Bitwise;
474     ///
475     /// let n = 0x0123456789ABCDEFu64;
476     /// let m = 0xDEF0123456789ABCu64;
477     /// assert_eq!(n.rotate_right(12), m);
478     /// ```
479     fn rotate_right(&self, r: uint) -> Self;
480 }
481
482 /// Swapping a single byte does nothing. This is unsafe to be consistent with
483 /// the other `bswap` intrinsics.
484 #[inline]
485 unsafe fn bswap8(x: u8) -> u8 { x }
486
487 macro_rules! bitwise_impl(
488     ($t:ty, $bits:expr, $co:ident, $lz:ident, $tz:ident, $bs:path) => {
489         impl Bitwise for $t {
490             #[inline]
491             fn count_ones(&self) -> $t { unsafe { intrinsics::$co(*self) } }
492
493             #[inline]
494             fn leading_zeros(&self) -> $t { unsafe { intrinsics::$lz(*self) } }
495
496             #[inline]
497             fn trailing_zeros(&self) -> $t { unsafe { intrinsics::$tz(*self) } }
498
499             #[inline]
500             fn swap_bytes(&self) -> $t { unsafe { $bs(*self) } }
501
502             #[inline]
503             fn rotate_left(&self, r: uint) -> $t {
504                 // Protect against undefined behaviour for overlong bit shifts
505                 let r = r % $bits;
506                 (*self << r) | (*self >> ($bits - r))
507             }
508
509             #[inline]
510             fn rotate_right(&self, r: uint) -> $t {
511                 // Protect against undefined behaviour for overlong bit shifts
512                 let r = r % $bits;
513                 (*self >> r) | (*self << ($bits - r))
514             }
515         }
516     }
517 )
518
519 macro_rules! bitwise_cast_impl(
520     ($t:ty, $t_cast:ty, $bits:expr,  $co:ident, $lz:ident, $tz:ident, $bs:path) => {
521         impl Bitwise for $t {
522             #[inline]
523             fn count_ones(&self) -> $t { unsafe { intrinsics::$co(*self as $t_cast) as $t } }
524
525             #[inline]
526             fn leading_zeros(&self) -> $t { unsafe { intrinsics::$lz(*self as $t_cast) as $t } }
527
528             #[inline]
529             fn trailing_zeros(&self) -> $t { unsafe { intrinsics::$tz(*self as $t_cast) as $t } }
530
531             #[inline]
532             fn swap_bytes(&self) -> $t { unsafe { $bs(*self as $t_cast) as $t } }
533
534             #[inline]
535             fn rotate_left(&self, r: uint) -> $t {
536                 // cast to prevent the sign bit from being corrupted
537                 (*self as $t_cast).rotate_left(r) as $t
538             }
539
540             #[inline]
541             fn rotate_right(&self, r: uint) -> $t {
542                 // cast to prevent the sign bit from being corrupted
543                 (*self as $t_cast).rotate_right(r) as $t
544             }
545         }
546     }
547 )
548
549 #[cfg(target_word_size = "32")]
550 bitwise_cast_impl!(uint, u32, 32, ctpop32, ctlz32, cttz32, intrinsics::bswap32)
551 #[cfg(target_word_size = "64")]
552 bitwise_cast_impl!(uint, u64, 64, ctpop64, ctlz64, cttz64, intrinsics::bswap64)
553
554 bitwise_impl!(u8, 8, ctpop8, ctlz8, cttz8, bswap8)
555 bitwise_impl!(u16, 16, ctpop16, ctlz16, cttz16, intrinsics::bswap16)
556 bitwise_impl!(u32, 32, ctpop32, ctlz32, cttz32, intrinsics::bswap32)
557 bitwise_impl!(u64, 64, ctpop64, ctlz64, cttz64, intrinsics::bswap64)
558
559 #[cfg(target_word_size = "32")]
560 bitwise_cast_impl!(int, u32, 32, ctpop32, ctlz32, cttz32, intrinsics::bswap32)
561 #[cfg(target_word_size = "64")]
562 bitwise_cast_impl!(int, u64, 64, ctpop64, ctlz64, cttz64, intrinsics::bswap64)
563
564 bitwise_cast_impl!(i8, u8, 8, ctpop8, ctlz8, cttz8, bswap8)
565 bitwise_cast_impl!(i16, u16, 16, ctpop16, ctlz16, cttz16, intrinsics::bswap16)
566 bitwise_cast_impl!(i32, u32, 32, ctpop32, ctlz32, cttz32, intrinsics::bswap32)
567 bitwise_cast_impl!(i64, u64, 64, ctpop64, ctlz64, cttz64, intrinsics::bswap64)
568
569 /// Specifies the available operations common to all of Rust's core numeric primitives.
570 /// These may not always make sense from a purely mathematical point of view, but
571 /// may be useful for systems programming.
572 pub trait Primitive: Copy
573                    + Clone
574                    + Num
575                    + NumCast
576                    + PartialOrd
577                    + Bounded {}
578
579 trait_impl!(Primitive for uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64)
580
581 /// A collection of traits relevant to primitive signed and unsigned integers
582 pub trait Int: Primitive
583              + Bitwise
584              + CheckedAdd
585              + CheckedSub
586              + CheckedMul
587              + CheckedDiv {}
588
589 trait_impl!(Int for uint u8 u16 u32 u64 int i8 i16 i32 i64)
590
591 /// Returns the smallest power of 2 greater than or equal to `n`.
592 #[inline]
593 pub fn next_power_of_two<T: Unsigned + Int>(n: T) -> T {
594     let halfbits: T = cast(size_of::<T>() * 4).unwrap();
595     let mut tmp: T = n - one();
596     let mut shift: T = one();
597     while shift <= halfbits {
598         tmp = tmp | (tmp >> shift);
599         shift = shift << one();
600     }
601     tmp + one()
602 }
603
604 // Returns `true` iff `n == 2^k` for some k.
605 #[inline]
606 pub fn is_power_of_two<T: Unsigned + Int>(n: T) -> bool {
607     (n - one()) & n == zero()
608 }
609
610 /// Returns the smallest power of 2 greater than or equal to `n`. If the next
611 /// power of two is greater than the type's maximum value, `None` is returned,
612 /// otherwise the power of 2 is wrapped in `Some`.
613 #[inline]
614 pub fn checked_next_power_of_two<T: Unsigned + Int>(n: T) -> Option<T> {
615     let halfbits: T = cast(size_of::<T>() * 4).unwrap();
616     let mut tmp: T = n - one();
617     let mut shift: T = one();
618     while shift <= halfbits {
619         tmp = tmp | (tmp >> shift);
620         shift = shift << one();
621     }
622     tmp.checked_add(&one())
623 }
624
625 /// A generic trait for converting a value to a number.
626 pub trait ToPrimitive {
627     /// Converts the value of `self` to an `int`.
628     #[inline]
629     fn to_int(&self) -> Option<int> {
630         self.to_i64().and_then(|x| x.to_int())
631     }
632
633     /// Converts the value of `self` to an `i8`.
634     #[inline]
635     fn to_i8(&self) -> Option<i8> {
636         self.to_i64().and_then(|x| x.to_i8())
637     }
638
639     /// Converts the value of `self` to an `i16`.
640     #[inline]
641     fn to_i16(&self) -> Option<i16> {
642         self.to_i64().and_then(|x| x.to_i16())
643     }
644
645     /// Converts the value of `self` to an `i32`.
646     #[inline]
647     fn to_i32(&self) -> Option<i32> {
648         self.to_i64().and_then(|x| x.to_i32())
649     }
650
651     /// Converts the value of `self` to an `i64`.
652     fn to_i64(&self) -> Option<i64>;
653
654     /// Converts the value of `self` to an `uint`.
655     #[inline]
656     fn to_uint(&self) -> Option<uint> {
657         self.to_u64().and_then(|x| x.to_uint())
658     }
659
660     /// Converts the value of `self` to an `u8`.
661     #[inline]
662     fn to_u8(&self) -> Option<u8> {
663         self.to_u64().and_then(|x| x.to_u8())
664     }
665
666     /// Converts the value of `self` to an `u16`.
667     #[inline]
668     fn to_u16(&self) -> Option<u16> {
669         self.to_u64().and_then(|x| x.to_u16())
670     }
671
672     /// Converts the value of `self` to an `u32`.
673     #[inline]
674     fn to_u32(&self) -> Option<u32> {
675         self.to_u64().and_then(|x| x.to_u32())
676     }
677
678     /// Converts the value of `self` to an `u64`.
679     #[inline]
680     fn to_u64(&self) -> Option<u64>;
681
682     /// Converts the value of `self` to an `f32`.
683     #[inline]
684     fn to_f32(&self) -> Option<f32> {
685         self.to_f64().and_then(|x| x.to_f32())
686     }
687
688     /// Converts the value of `self` to an `f64`.
689     #[inline]
690     fn to_f64(&self) -> Option<f64> {
691         self.to_i64().and_then(|x| x.to_f64())
692     }
693 }
694
695 macro_rules! impl_to_primitive_int_to_int(
696     ($SrcT:ty, $DstT:ty) => (
697         {
698             if size_of::<$SrcT>() <= size_of::<$DstT>() {
699                 Some(*self as $DstT)
700             } else {
701                 let n = *self as i64;
702                 let min_value: $DstT = Bounded::min_value();
703                 let max_value: $DstT = Bounded::max_value();
704                 if min_value as i64 <= n && n <= max_value as i64 {
705                     Some(*self as $DstT)
706                 } else {
707                     None
708                 }
709             }
710         }
711     )
712 )
713
714 macro_rules! impl_to_primitive_int_to_uint(
715     ($SrcT:ty, $DstT:ty) => (
716         {
717             let zero: $SrcT = Zero::zero();
718             let max_value: $DstT = Bounded::max_value();
719             if zero <= *self && *self as u64 <= max_value as u64 {
720                 Some(*self as $DstT)
721             } else {
722                 None
723             }
724         }
725     )
726 )
727
728 macro_rules! impl_to_primitive_int(
729     ($T:ty) => (
730         impl ToPrimitive for $T {
731             #[inline]
732             fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int) }
733             #[inline]
734             fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8) }
735             #[inline]
736             fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16) }
737             #[inline]
738             fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32) }
739             #[inline]
740             fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64) }
741
742             #[inline]
743             fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint) }
744             #[inline]
745             fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8) }
746             #[inline]
747             fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16) }
748             #[inline]
749             fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32) }
750             #[inline]
751             fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64) }
752
753             #[inline]
754             fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
755             #[inline]
756             fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
757         }
758     )
759 )
760
761 impl_to_primitive_int!(int)
762 impl_to_primitive_int!(i8)
763 impl_to_primitive_int!(i16)
764 impl_to_primitive_int!(i32)
765 impl_to_primitive_int!(i64)
766
767 macro_rules! impl_to_primitive_uint_to_int(
768     ($DstT:ty) => (
769         {
770             let max_value: $DstT = Bounded::max_value();
771             if *self as u64 <= max_value as u64 {
772                 Some(*self as $DstT)
773             } else {
774                 None
775             }
776         }
777     )
778 )
779
780 macro_rules! impl_to_primitive_uint_to_uint(
781     ($SrcT:ty, $DstT:ty) => (
782         {
783             if size_of::<$SrcT>() <= size_of::<$DstT>() {
784                 Some(*self as $DstT)
785             } else {
786                 let zero: $SrcT = Zero::zero();
787                 let max_value: $DstT = Bounded::max_value();
788                 if zero <= *self && *self as u64 <= max_value as u64 {
789                     Some(*self as $DstT)
790                 } else {
791                     None
792                 }
793             }
794         }
795     )
796 )
797
798 macro_rules! impl_to_primitive_uint(
799     ($T:ty) => (
800         impl ToPrimitive for $T {
801             #[inline]
802             fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int) }
803             #[inline]
804             fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8) }
805             #[inline]
806             fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16) }
807             #[inline]
808             fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32) }
809             #[inline]
810             fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64) }
811
812             #[inline]
813             fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint) }
814             #[inline]
815             fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8) }
816             #[inline]
817             fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16) }
818             #[inline]
819             fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32) }
820             #[inline]
821             fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64) }
822
823             #[inline]
824             fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
825             #[inline]
826             fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
827         }
828     )
829 )
830
831 impl_to_primitive_uint!(uint)
832 impl_to_primitive_uint!(u8)
833 impl_to_primitive_uint!(u16)
834 impl_to_primitive_uint!(u32)
835 impl_to_primitive_uint!(u64)
836
837 macro_rules! impl_to_primitive_float_to_float(
838     ($SrcT:ty, $DstT:ty) => (
839         if size_of::<$SrcT>() <= size_of::<$DstT>() {
840             Some(*self as $DstT)
841         } else {
842             let n = *self as f64;
843             let max_value: $SrcT = Bounded::max_value();
844             if -max_value as f64 <= n && n <= max_value as f64 {
845                 Some(*self as $DstT)
846             } else {
847                 None
848             }
849         }
850     )
851 )
852
853 macro_rules! impl_to_primitive_float(
854     ($T:ty) => (
855         impl ToPrimitive for $T {
856             #[inline]
857             fn to_int(&self) -> Option<int> { Some(*self as int) }
858             #[inline]
859             fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
860             #[inline]
861             fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
862             #[inline]
863             fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
864             #[inline]
865             fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
866
867             #[inline]
868             fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
869             #[inline]
870             fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
871             #[inline]
872             fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
873             #[inline]
874             fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
875             #[inline]
876             fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
877
878             #[inline]
879             fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32) }
880             #[inline]
881             fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64) }
882         }
883     )
884 )
885
886 impl_to_primitive_float!(f32)
887 impl_to_primitive_float!(f64)
888
889 /// A generic trait for converting a number to a value.
890 pub trait FromPrimitive {
891     /// Convert an `int` to return an optional value of this type. If the
892     /// value cannot be represented by this value, the `None` is returned.
893     #[inline]
894     fn from_int(n: int) -> Option<Self> {
895         FromPrimitive::from_i64(n as i64)
896     }
897
898     /// Convert an `i8` to return an optional value of this type. If the
899     /// type cannot be represented by this value, the `None` is returned.
900     #[inline]
901     fn from_i8(n: i8) -> Option<Self> {
902         FromPrimitive::from_i64(n as i64)
903     }
904
905     /// Convert an `i16` to return an optional value of this type. If the
906     /// type cannot be represented by this value, the `None` is returned.
907     #[inline]
908     fn from_i16(n: i16) -> Option<Self> {
909         FromPrimitive::from_i64(n as i64)
910     }
911
912     /// Convert an `i32` to return an optional value of this type. If the
913     /// type cannot be represented by this value, the `None` is returned.
914     #[inline]
915     fn from_i32(n: i32) -> Option<Self> {
916         FromPrimitive::from_i64(n as i64)
917     }
918
919     /// Convert an `i64` to return an optional value of this type. If the
920     /// type cannot be represented by this value, the `None` is returned.
921     fn from_i64(n: i64) -> Option<Self>;
922
923     /// Convert an `uint` to return an optional value of this type. If the
924     /// type cannot be represented by this value, the `None` is returned.
925     #[inline]
926     fn from_uint(n: uint) -> Option<Self> {
927         FromPrimitive::from_u64(n as u64)
928     }
929
930     /// Convert an `u8` to return an optional value of this type. If the
931     /// type cannot be represented by this value, the `None` is returned.
932     #[inline]
933     fn from_u8(n: u8) -> Option<Self> {
934         FromPrimitive::from_u64(n as u64)
935     }
936
937     /// Convert an `u16` to return an optional value of this type. If the
938     /// type cannot be represented by this value, the `None` is returned.
939     #[inline]
940     fn from_u16(n: u16) -> Option<Self> {
941         FromPrimitive::from_u64(n as u64)
942     }
943
944     /// Convert an `u32` to return an optional value of this type. If the
945     /// type cannot be represented by this value, the `None` is returned.
946     #[inline]
947     fn from_u32(n: u32) -> Option<Self> {
948         FromPrimitive::from_u64(n as u64)
949     }
950
951     /// Convert an `u64` to return an optional value of this type. If the
952     /// type cannot be represented by this value, the `None` is returned.
953     fn from_u64(n: u64) -> Option<Self>;
954
955     /// Convert a `f32` to return an optional value of this type. If the
956     /// type cannot be represented by this value, the `None` is returned.
957     #[inline]
958     fn from_f32(n: f32) -> Option<Self> {
959         FromPrimitive::from_f64(n as f64)
960     }
961
962     /// Convert a `f64` to return an optional value of this type. If the
963     /// type cannot be represented by this value, the `None` is returned.
964     #[inline]
965     fn from_f64(n: f64) -> Option<Self> {
966         FromPrimitive::from_i64(n as i64)
967     }
968 }
969
970 /// A utility function that just calls `FromPrimitive::from_int`.
971 pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
972     FromPrimitive::from_int(n)
973 }
974
975 /// A utility function that just calls `FromPrimitive::from_i8`.
976 pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> {
977     FromPrimitive::from_i8(n)
978 }
979
980 /// A utility function that just calls `FromPrimitive::from_i16`.
981 pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> {
982     FromPrimitive::from_i16(n)
983 }
984
985 /// A utility function that just calls `FromPrimitive::from_i32`.
986 pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> {
987     FromPrimitive::from_i32(n)
988 }
989
990 /// A utility function that just calls `FromPrimitive::from_i64`.
991 pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
992     FromPrimitive::from_i64(n)
993 }
994
995 /// A utility function that just calls `FromPrimitive::from_uint`.
996 pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
997     FromPrimitive::from_uint(n)
998 }
999
1000 /// A utility function that just calls `FromPrimitive::from_u8`.
1001 pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> {
1002     FromPrimitive::from_u8(n)
1003 }
1004
1005 /// A utility function that just calls `FromPrimitive::from_u16`.
1006 pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> {
1007     FromPrimitive::from_u16(n)
1008 }
1009
1010 /// A utility function that just calls `FromPrimitive::from_u32`.
1011 pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> {
1012     FromPrimitive::from_u32(n)
1013 }
1014
1015 /// A utility function that just calls `FromPrimitive::from_u64`.
1016 pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> {
1017     FromPrimitive::from_u64(n)
1018 }
1019
1020 /// A utility function that just calls `FromPrimitive::from_f32`.
1021 pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> {
1022     FromPrimitive::from_f32(n)
1023 }
1024
1025 /// A utility function that just calls `FromPrimitive::from_f64`.
1026 pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> {
1027     FromPrimitive::from_f64(n)
1028 }
1029
1030 macro_rules! impl_from_primitive(
1031     ($T:ty, $to_ty:expr) => (
1032         impl FromPrimitive for $T {
1033             #[inline] fn from_int(n: int) -> Option<$T> { $to_ty }
1034             #[inline] fn from_i8(n: i8) -> Option<$T> { $to_ty }
1035             #[inline] fn from_i16(n: i16) -> Option<$T> { $to_ty }
1036             #[inline] fn from_i32(n: i32) -> Option<$T> { $to_ty }
1037             #[inline] fn from_i64(n: i64) -> Option<$T> { $to_ty }
1038
1039             #[inline] fn from_uint(n: uint) -> Option<$T> { $to_ty }
1040             #[inline] fn from_u8(n: u8) -> Option<$T> { $to_ty }
1041             #[inline] fn from_u16(n: u16) -> Option<$T> { $to_ty }
1042             #[inline] fn from_u32(n: u32) -> Option<$T> { $to_ty }
1043             #[inline] fn from_u64(n: u64) -> Option<$T> { $to_ty }
1044
1045             #[inline] fn from_f32(n: f32) -> Option<$T> { $to_ty }
1046             #[inline] fn from_f64(n: f64) -> Option<$T> { $to_ty }
1047         }
1048     )
1049 )
1050
1051 impl_from_primitive!(int, n.to_int())
1052 impl_from_primitive!(i8, n.to_i8())
1053 impl_from_primitive!(i16, n.to_i16())
1054 impl_from_primitive!(i32, n.to_i32())
1055 impl_from_primitive!(i64, n.to_i64())
1056 impl_from_primitive!(uint, n.to_uint())
1057 impl_from_primitive!(u8, n.to_u8())
1058 impl_from_primitive!(u16, n.to_u16())
1059 impl_from_primitive!(u32, n.to_u32())
1060 impl_from_primitive!(u64, n.to_u64())
1061 impl_from_primitive!(f32, n.to_f32())
1062 impl_from_primitive!(f64, n.to_f64())
1063
1064 /// Cast from one machine scalar to another.
1065 ///
1066 /// # Example
1067 ///
1068 /// ```
1069 /// use std::num;
1070 ///
1071 /// let twenty: f32 = num::cast(0x14).unwrap();
1072 /// assert_eq!(twenty, 20f32);
1073 /// ```
1074 ///
1075 #[inline]
1076 pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
1077     NumCast::from(n)
1078 }
1079
1080 /// An interface for casting between machine scalars.
1081 pub trait NumCast: ToPrimitive {
1082     /// Creates a number from another value that can be converted into a primitive via the
1083     /// `ToPrimitive` trait.
1084     fn from<T: ToPrimitive>(n: T) -> Option<Self>;
1085 }
1086
1087 macro_rules! impl_num_cast(
1088     ($T:ty, $conv:ident) => (
1089         impl NumCast for $T {
1090             #[inline]
1091             fn from<N: ToPrimitive>(n: N) -> Option<$T> {
1092                 // `$conv` could be generated using `concat_idents!`, but that
1093                 // macro seems to be broken at the moment
1094                 n.$conv()
1095             }
1096         }
1097     )
1098 )
1099
1100 impl_num_cast!(u8,    to_u8)
1101 impl_num_cast!(u16,   to_u16)
1102 impl_num_cast!(u32,   to_u32)
1103 impl_num_cast!(u64,   to_u64)
1104 impl_num_cast!(uint,  to_uint)
1105 impl_num_cast!(i8,    to_i8)
1106 impl_num_cast!(i16,   to_i16)
1107 impl_num_cast!(i32,   to_i32)
1108 impl_num_cast!(i64,   to_i64)
1109 impl_num_cast!(int,   to_int)
1110 impl_num_cast!(f32,   to_f32)
1111 impl_num_cast!(f64,   to_f64)
1112
1113 /// Saturating math operations
1114 pub trait Saturating {
1115     /// Saturating addition operator.
1116     /// Returns a+b, saturating at the numeric bounds instead of overflowing.
1117     fn saturating_add(self, v: Self) -> Self;
1118
1119     /// Saturating subtraction operator.
1120     /// Returns a-b, saturating at the numeric bounds instead of overflowing.
1121     fn saturating_sub(self, v: Self) -> Self;
1122 }
1123
1124 impl<T: CheckedAdd + CheckedSub + Zero + PartialOrd + Bounded> Saturating for T {
1125     #[inline]
1126     fn saturating_add(self, v: T) -> T {
1127         match self.checked_add(&v) {
1128             Some(x) => x,
1129             None => if v >= Zero::zero() {
1130                 Bounded::max_value()
1131             } else {
1132                 Bounded::min_value()
1133             }
1134         }
1135     }
1136
1137     #[inline]
1138     fn saturating_sub(self, v: T) -> T {
1139         match self.checked_sub(&v) {
1140             Some(x) => x,
1141             None => if v >= Zero::zero() {
1142                 Bounded::min_value()
1143             } else {
1144                 Bounded::max_value()
1145             }
1146         }
1147     }
1148 }
1149
1150 /// Performs addition that returns `None` instead of wrapping around on overflow.
1151 pub trait CheckedAdd: Add<Self, Self> {
1152     /// Adds two numbers, checking for overflow. If overflow happens, `None` is returned.
1153     fn checked_add(&self, v: &Self) -> Option<Self>;
1154 }
1155
1156 macro_rules! checked_impl(
1157     ($trait_name:ident, $method:ident, $t:ty, $op:path) => {
1158         impl $trait_name for $t {
1159             #[inline]
1160             fn $method(&self, v: &$t) -> Option<$t> {
1161                 unsafe {
1162                     let (x, y) = $op(*self, *v);
1163                     if y { None } else { Some(x) }
1164                 }
1165             }
1166         }
1167     }
1168 )
1169 macro_rules! checked_cast_impl(
1170     ($trait_name:ident, $method:ident, $t:ty, $cast:ty, $op:path) => {
1171         impl $trait_name for $t {
1172             #[inline]
1173             fn $method(&self, v: &$t) -> Option<$t> {
1174                 unsafe {
1175                     let (x, y) = $op(*self as $cast, *v as $cast);
1176                     if y { None } else { Some(x as $t) }
1177                 }
1178             }
1179         }
1180     }
1181 )
1182
1183 #[cfg(target_word_size = "32")]
1184 checked_cast_impl!(CheckedAdd, checked_add, uint, u32, intrinsics::u32_add_with_overflow)
1185 #[cfg(target_word_size = "64")]
1186 checked_cast_impl!(CheckedAdd, checked_add, uint, u64, intrinsics::u64_add_with_overflow)
1187
1188 checked_impl!(CheckedAdd, checked_add, u8,  intrinsics::u8_add_with_overflow)
1189 checked_impl!(CheckedAdd, checked_add, u16, intrinsics::u16_add_with_overflow)
1190 checked_impl!(CheckedAdd, checked_add, u32, intrinsics::u32_add_with_overflow)
1191 checked_impl!(CheckedAdd, checked_add, u64, intrinsics::u64_add_with_overflow)
1192
1193 #[cfg(target_word_size = "32")]
1194 checked_cast_impl!(CheckedAdd, checked_add, int, i32, intrinsics::i32_add_with_overflow)
1195 #[cfg(target_word_size = "64")]
1196 checked_cast_impl!(CheckedAdd, checked_add, int, i64, intrinsics::i64_add_with_overflow)
1197
1198 checked_impl!(CheckedAdd, checked_add, i8,  intrinsics::i8_add_with_overflow)
1199 checked_impl!(CheckedAdd, checked_add, i16, intrinsics::i16_add_with_overflow)
1200 checked_impl!(CheckedAdd, checked_add, i32, intrinsics::i32_add_with_overflow)
1201 checked_impl!(CheckedAdd, checked_add, i64, intrinsics::i64_add_with_overflow)
1202
1203 /// Performs subtraction that returns `None` instead of wrapping around on underflow.
1204 pub trait CheckedSub: Sub<Self, Self> {
1205     /// Subtracts two numbers, checking for underflow. If underflow happens, `None` is returned.
1206     fn checked_sub(&self, v: &Self) -> Option<Self>;
1207 }
1208
1209 #[cfg(target_word_size = "32")]
1210 checked_cast_impl!(CheckedSub, checked_sub, uint, u32, intrinsics::u32_sub_with_overflow)
1211 #[cfg(target_word_size = "64")]
1212 checked_cast_impl!(CheckedSub, checked_sub, uint, u64, intrinsics::u64_sub_with_overflow)
1213
1214 checked_impl!(CheckedSub, checked_sub, u8,  intrinsics::u8_sub_with_overflow)
1215 checked_impl!(CheckedSub, checked_sub, u16, intrinsics::u16_sub_with_overflow)
1216 checked_impl!(CheckedSub, checked_sub, u32, intrinsics::u32_sub_with_overflow)
1217 checked_impl!(CheckedSub, checked_sub, u64, intrinsics::u64_sub_with_overflow)
1218
1219 #[cfg(target_word_size = "32")]
1220 checked_cast_impl!(CheckedSub, checked_sub, int, i32, intrinsics::i32_sub_with_overflow)
1221 #[cfg(target_word_size = "64")]
1222 checked_cast_impl!(CheckedSub, checked_sub, int, i64, intrinsics::i64_sub_with_overflow)
1223
1224 checked_impl!(CheckedSub, checked_sub, i8,  intrinsics::i8_sub_with_overflow)
1225 checked_impl!(CheckedSub, checked_sub, i16, intrinsics::i16_sub_with_overflow)
1226 checked_impl!(CheckedSub, checked_sub, i32, intrinsics::i32_sub_with_overflow)
1227 checked_impl!(CheckedSub, checked_sub, i64, intrinsics::i64_sub_with_overflow)
1228
1229 /// Performs multiplication that returns `None` instead of wrapping around on underflow or
1230 /// overflow.
1231 pub trait CheckedMul: Mul<Self, Self> {
1232     /// Multiplies two numbers, checking for underflow or overflow. If underflow or overflow
1233     /// happens, `None` is returned.
1234     fn checked_mul(&self, v: &Self) -> Option<Self>;
1235 }
1236
1237 #[cfg(target_word_size = "32")]
1238 checked_cast_impl!(CheckedMul, checked_mul, uint, u32, intrinsics::u32_mul_with_overflow)
1239 #[cfg(target_word_size = "64")]
1240 checked_cast_impl!(CheckedMul, checked_mul, uint, u64, intrinsics::u64_mul_with_overflow)
1241
1242 checked_impl!(CheckedMul, checked_mul, u8,  intrinsics::u8_mul_with_overflow)
1243 checked_impl!(CheckedMul, checked_mul, u16, intrinsics::u16_mul_with_overflow)
1244 checked_impl!(CheckedMul, checked_mul, u32, intrinsics::u32_mul_with_overflow)
1245 checked_impl!(CheckedMul, checked_mul, u64, intrinsics::u64_mul_with_overflow)
1246
1247 #[cfg(target_word_size = "32")]
1248 checked_cast_impl!(CheckedMul, checked_mul, int, i32, intrinsics::i32_mul_with_overflow)
1249 #[cfg(target_word_size = "64")]
1250 checked_cast_impl!(CheckedMul, checked_mul, int, i64, intrinsics::i64_mul_with_overflow)
1251
1252 checked_impl!(CheckedMul, checked_mul, i8,  intrinsics::i8_mul_with_overflow)
1253 checked_impl!(CheckedMul, checked_mul, i16, intrinsics::i16_mul_with_overflow)
1254 checked_impl!(CheckedMul, checked_mul, i32, intrinsics::i32_mul_with_overflow)
1255 checked_impl!(CheckedMul, checked_mul, i64, intrinsics::i64_mul_with_overflow)
1256
1257 /// Performs division that returns `None` instead of wrapping around on underflow or overflow.
1258 pub trait CheckedDiv: Div<Self, Self> {
1259     /// Divides two numbers, checking for underflow or overflow. If underflow or overflow happens,
1260     /// `None` is returned.
1261     fn checked_div(&self, v: &Self) -> Option<Self>;
1262 }
1263
1264 macro_rules! checkeddiv_int_impl(
1265     ($t:ty, $min:expr) => {
1266         impl CheckedDiv for $t {
1267             #[inline]
1268             fn checked_div(&self, v: &$t) -> Option<$t> {
1269                 if *v == 0 || (*self == $min && *v == -1) {
1270                     None
1271                 } else {
1272                     Some(self / *v)
1273                 }
1274             }
1275         }
1276     }
1277 )
1278
1279 checkeddiv_int_impl!(int, int::MIN)
1280 checkeddiv_int_impl!(i8, i8::MIN)
1281 checkeddiv_int_impl!(i16, i16::MIN)
1282 checkeddiv_int_impl!(i32, i32::MIN)
1283 checkeddiv_int_impl!(i64, i64::MIN)
1284
1285 macro_rules! checkeddiv_uint_impl(
1286     ($($t:ty)*) => ($(
1287         impl CheckedDiv for $t {
1288             #[inline]
1289             fn checked_div(&self, v: &$t) -> Option<$t> {
1290                 if *v == 0 {
1291                     None
1292                 } else {
1293                     Some(self / *v)
1294                 }
1295             }
1296         }
1297     )*)
1298 )
1299
1300 checkeddiv_uint_impl!(uint u8 u16 u32 u64)
1301
1302 /// Helper function for testing numeric operations
1303 #[cfg(test)]
1304 pub fn test_num<T:Num + NumCast + ::std::fmt::Show>(ten: T, two: T) {
1305     assert_eq!(ten.add(&two),  cast(12).unwrap());
1306     assert_eq!(ten.sub(&two),  cast(8).unwrap());
1307     assert_eq!(ten.mul(&two),  cast(20).unwrap());
1308     assert_eq!(ten.div(&two),  cast(5).unwrap());
1309     assert_eq!(ten.rem(&two),  cast(0).unwrap());
1310
1311     assert_eq!(ten.add(&two),  ten + two);
1312     assert_eq!(ten.sub(&two),  ten - two);
1313     assert_eq!(ten.mul(&two),  ten * two);
1314     assert_eq!(ten.div(&two),  ten / two);
1315     assert_eq!(ten.rem(&two),  ten % two);
1316 }
1317
1318 /// Used for representing the classification of floating point numbers
1319 #[deriving(PartialEq, Show)]
1320 pub enum FPCategory {
1321     /// "Not a Number", often obtained by dividing by zero
1322     FPNaN,
1323     /// Positive or negative infinity
1324     FPInfinite ,
1325     /// Positive or negative zero
1326     FPZero,
1327     /// De-normalized floating point representation (less precise than `FPNormal`)
1328     FPSubnormal,
1329     /// A regular floating point number
1330     FPNormal,
1331 }
1332
1333 /// Operations on primitive floating point numbers.
1334 // FIXME(#5527): In a future version of Rust, many of these functions will
1335 //               become constants.
1336 //
1337 // FIXME(#8888): Several of these functions have a parameter named
1338 //               `unused_self`. Removing it requires #8888 to be fixed.
1339 pub trait Float: Signed + Primitive {
1340     /// Returns the NaN value.
1341     fn nan() -> Self;
1342     /// Returns the infinite value.
1343     fn infinity() -> Self;
1344     /// Returns the negative infinite value.
1345     fn neg_infinity() -> Self;
1346     /// Returns -0.0.
1347     fn neg_zero() -> Self;
1348
1349     /// Returns true if this value is NaN and false otherwise.
1350     fn is_nan(self) -> bool;
1351     /// Returns true if this value is positive infinity or negative infinity and
1352     /// false otherwise.
1353     fn is_infinite(self) -> bool;
1354     /// Returns true if this number is neither infinite nor NaN.
1355     fn is_finite(self) -> bool;
1356     /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1357     fn is_normal(self) -> bool;
1358     /// Returns the category that this number falls into.
1359     fn classify(self) -> FPCategory;
1360
1361     // FIXME (#5527): These should be associated constants
1362
1363     /// Returns the number of binary digits of mantissa that this type supports.
1364     fn mantissa_digits(unused_self: Option<Self>) -> uint;
1365     /// Returns the number of base-10 digits of precision that this type supports.
1366     fn digits(unused_self: Option<Self>) -> uint;
1367     /// Returns the difference between 1.0 and the smallest representable number larger than 1.0.
1368     fn epsilon() -> Self;
1369     /// Returns the minimum binary exponent that this type can represent.
1370     fn min_exp(unused_self: Option<Self>) -> int;
1371     /// Returns the maximum binary exponent that this type can represent.
1372     fn max_exp(unused_self: Option<Self>) -> int;
1373     /// Returns the minimum base-10 exponent that this type can represent.
1374     fn min_10_exp(unused_self: Option<Self>) -> int;
1375     /// Returns the maximum base-10 exponent that this type can represent.
1376     fn max_10_exp(unused_self: Option<Self>) -> int;
1377     /// Returns the smallest normalized positive number that this type can represent.
1378     fn min_pos_value(unused_self: Option<Self>) -> Self;
1379
1380     /// Returns the mantissa, exponent and sign as integers, respectively.
1381     fn integer_decode(self) -> (u64, i16, i8);
1382
1383     /// Return the largest integer less than or equal to a number.
1384     fn floor(self) -> Self;
1385     /// Return the smallest integer greater than or equal to a number.
1386     fn ceil(self) -> Self;
1387     /// Return the nearest integer to a number. Round half-way cases away from
1388     /// `0.0`.
1389     fn round(self) -> Self;
1390     /// Return the integer part of a number.
1391     fn trunc(self) -> Self;
1392     /// Return the fractional part of a number.
1393     fn fract(self) -> Self;
1394
1395     /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1396     /// error. This produces a more accurate result with better performance than
1397     /// a separate multiplication operation followed by an add.
1398     fn mul_add(self, a: Self, b: Self) -> Self;
1399     /// Take the reciprocal (inverse) of a number, `1/x`.
1400     fn recip(self) -> Self;
1401
1402     /// Raise a number to an integer power.
1403     ///
1404     /// Using this function is generally faster than using `powf`
1405     fn powi(self, n: i32) -> Self;
1406     /// Raise a number to a floating point power.
1407     fn powf(self, n: Self) -> Self;
1408
1409     /// sqrt(2.0).
1410     fn sqrt2() -> Self;
1411     /// 1.0 / sqrt(2.0).
1412     fn frac_1_sqrt2() -> Self;
1413
1414     /// Take the square root of a number.
1415     fn sqrt(self) -> Self;
1416     /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1417     fn rsqrt(self) -> Self;
1418
1419     // FIXME (#5527): These should be associated constants
1420
1421     /// Archimedes' constant.
1422     fn pi() -> Self;
1423     /// 2.0 * pi.
1424     fn two_pi() -> Self;
1425     /// pi / 2.0.
1426     fn frac_pi_2() -> Self;
1427     /// pi / 3.0.
1428     fn frac_pi_3() -> Self;
1429     /// pi / 4.0.
1430     fn frac_pi_4() -> Self;
1431     /// pi / 6.0.
1432     fn frac_pi_6() -> Self;
1433     /// pi / 8.0.
1434     fn frac_pi_8() -> Self;
1435     /// 1.0 / pi.
1436     fn frac_1_pi() -> Self;
1437     /// 2.0 / pi.
1438     fn frac_2_pi() -> Self;
1439     /// 2.0 / sqrt(pi).
1440     fn frac_2_sqrtpi() -> Self;
1441
1442     /// Euler's number.
1443     fn e() -> Self;
1444     /// log2(e).
1445     fn log2_e() -> Self;
1446     /// log10(e).
1447     fn log10_e() -> Self;
1448     /// ln(2.0).
1449     fn ln_2() -> Self;
1450     /// ln(10.0).
1451     fn ln_10() -> Self;
1452
1453     /// Returns `e^(self)`, (the exponential function).
1454     fn exp(self) -> Self;
1455     /// Returns 2 raised to the power of the number, `2^(self)`.
1456     fn exp2(self) -> Self;
1457     /// Returns the natural logarithm of the number.
1458     fn ln(self) -> Self;
1459     /// Returns the logarithm of the number with respect to an arbitrary base.
1460     fn log(self, base: Self) -> Self;
1461     /// Returns the base 2 logarithm of the number.
1462     fn log2(self) -> Self;
1463     /// Returns the base 10 logarithm of the number.
1464     fn log10(self) -> Self;
1465
1466     /// Convert radians to degrees.
1467     fn to_degrees(self) -> Self;
1468     /// Convert degrees to radians.
1469     fn to_radians(self) -> Self;
1470 }