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