]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
011830ddb7882d65da98c0c14b481cf6700e32ac
[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 the built-in numeric types.
12
13 #![stable(feature = "rust1", since = "1.0.0")]
14 #![allow(missing_docs)]
15
16 use self::wrapping::OverflowingOps;
17
18 use char::CharExt;
19 use cmp::{Eq, PartialOrd};
20 use fmt;
21 use intrinsics;
22 use marker::Copy;
23 use mem::size_of;
24 use option::Option::{self, Some, None};
25 use result::Result::{self, Ok, Err};
26 use str::{FromStr, StrExt};
27
28 /// Provides intentionally-wrapped arithmetic on `T`.
29 ///
30 /// Operations like `+` on `u32` values is intended to never overflow,
31 /// and in some debug configurations overflow is detected and results
32 /// in a panic. While most arithmetic falls into this category, some
33 /// code explicitly expects and relies upon modular arithmetic (e.g.,
34 /// hashing).
35 ///
36 /// Wrapping arithmetic can be achieved either through methods like
37 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
38 /// all standard arithmetic operations on the underlying value are
39 /// intended to have wrapping semantics.
40 #[stable(feature = "rust1", since = "1.0.0")]
41 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)]
42 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
43
44 #[unstable(feature = "core", reason = "may be removed or relocated")]
45 pub mod wrapping;
46
47 #[unstable(feature = "core", reason = "internal routines only exposed for testing")]
48 pub mod flt2dec;
49
50 /// Types that have a "zero" value.
51 ///
52 /// This trait is intended for use in conjunction with `Add`, as an identity:
53 /// `x + T::zero() == x`.
54 #[unstable(feature = "zero_one",
55            reason = "unsure of placement, wants to use associated constants")]
56 pub trait Zero {
57     /// The "zero" (usually, additive identity) for this type.
58     fn zero() -> Self;
59 }
60
61 /// Types that have a "one" value.
62 ///
63 /// This trait is intended for use in conjunction with `Mul`, as an identity:
64 /// `x * T::one() == x`.
65 #[unstable(feature = "zero_one",
66            reason = "unsure of placement, wants to use associated constants")]
67 pub trait One {
68     /// The "one" (usually, multiplicative identity) for this type.
69     fn one() -> Self;
70 }
71
72 macro_rules! zero_one_impl {
73     ($($t:ty)*) => ($(
74         impl Zero for $t {
75             #[inline]
76             fn zero() -> $t { 0 }
77         }
78         impl One for $t {
79             #[inline]
80             fn one() -> $t { 1 }
81         }
82     )*)
83 }
84 zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
85
86 macro_rules! zero_one_impl_float {
87     ($($t:ty)*) => ($(
88         impl Zero for $t {
89             #[inline]
90             fn zero() -> $t { 0.0 }
91         }
92         impl One for $t {
93             #[inline]
94             fn one() -> $t { 1.0 }
95         }
96     )*)
97 }
98 zero_one_impl_float! { f32 f64 }
99
100 macro_rules! checked_op {
101     ($T:ty, $U:ty, $op:path, $x:expr, $y:expr) => {{
102         let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
103         if overflowed { None } else { Some(result as $T) }
104     }}
105 }
106
107 /// Swapping a single byte is a no-op. This is marked as `unsafe` for
108 /// consistency with the other `bswap` intrinsics.
109 unsafe fn bswap8(x: u8) -> u8 { x }
110
111 // `Int` + `SignedInt` implemented for signed integers
112 macro_rules! int_impl {
113     ($T:ident = $ActualT:ty, $UnsignedT:ty, $BITS:expr,
114      $add_with_overflow:path,
115      $sub_with_overflow:path,
116      $mul_with_overflow:path) => {
117         /// Returns the smallest value that can be represented by this integer type.
118         #[stable(feature = "rust1", since = "1.0.0")]
119         #[inline]
120         pub fn min_value() -> $T {
121             (-1 as $T) << ($BITS - 1)
122         }
123
124         /// Returns the largest value that can be represented by this integer type.
125         #[stable(feature = "rust1", since = "1.0.0")]
126         #[inline]
127         pub fn max_value() -> $T {
128             let min = $T::min_value(); !min
129         }
130
131         /// Converts a string slice in a given base to an integer.
132         ///
133         /// Leading and trailing whitespace represent an error.
134         ///
135         /// # Arguments
136         ///
137         /// * src - A string slice
138         /// * radix - The base to use. Must lie in the range [2 .. 36]
139         ///
140         /// # Return value
141         ///
142         /// `Err(ParseIntError)` if the string did not represent a valid number.
143         /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
144         #[stable(feature = "rust1", since = "1.0.0")]
145         #[allow(deprecated)]
146         pub fn from_str_radix(src: &str, radix: u32) -> Result<$T, ParseIntError> {
147             from_str_radix(src, radix)
148         }
149
150         /// Returns the number of ones in the binary representation of `self`.
151         ///
152         /// # Examples
153         ///
154         /// ```rust
155         /// let n = 0b01001100u8;
156         ///
157         /// assert_eq!(n.count_ones(), 3);
158         /// ```
159         #[stable(feature = "rust1", since = "1.0.0")]
160         #[inline]
161         pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
162
163         /// Returns the number of zeros in the binary representation of `self`.
164         ///
165         /// # Examples
166         ///
167         /// ```rust
168         /// let n = 0b01001100u8;
169         ///
170         /// assert_eq!(n.count_zeros(), 5);
171         /// ```
172         #[stable(feature = "rust1", since = "1.0.0")]
173         #[inline]
174         pub fn count_zeros(self) -> u32 {
175             (!self).count_ones()
176         }
177
178         /// Returns the number of leading zeros in the binary representation
179         /// of `self`.
180         ///
181         /// # Examples
182         ///
183         /// ```rust
184         /// let n = 0b0101000u16;
185         ///
186         /// assert_eq!(n.leading_zeros(), 10);
187         /// ```
188         #[stable(feature = "rust1", since = "1.0.0")]
189         #[inline]
190         pub fn leading_zeros(self) -> u32 {
191             (self as $UnsignedT).leading_zeros()
192         }
193
194         /// Returns the number of trailing zeros in the binary representation
195         /// of `self`.
196         ///
197         /// # Examples
198         ///
199         /// ```rust
200         /// let n = 0b0101000u16;
201         ///
202         /// assert_eq!(n.trailing_zeros(), 3);
203         /// ```
204         #[stable(feature = "rust1", since = "1.0.0")]
205         #[inline]
206         pub fn trailing_zeros(self) -> u32 {
207             (self as $UnsignedT).trailing_zeros()
208         }
209
210         /// Shifts the bits to the left by a specified amount, `n`,
211         /// wrapping the truncated bits to the end of the resulting integer.
212         ///
213         /// # Examples
214         ///
215         /// ```rust
216         /// let n = 0x0123456789ABCDEFu64;
217         /// let m = 0x3456789ABCDEF012u64;
218         ///
219         /// assert_eq!(n.rotate_left(12), m);
220         /// ```
221         #[stable(feature = "rust1", since = "1.0.0")]
222         #[inline]
223         pub fn rotate_left(self, n: u32) -> $T {
224             (self as $UnsignedT).rotate_left(n) as $T
225         }
226
227         /// Shifts the bits to the right by a specified amount, `n`,
228         /// wrapping the truncated bits to the beginning of the resulting
229         /// integer.
230         ///
231         /// # Examples
232         ///
233         /// ```rust
234         /// let n = 0x0123456789ABCDEFu64;
235         /// let m = 0xDEF0123456789ABCu64;
236         ///
237         /// assert_eq!(n.rotate_right(12), m);
238         /// ```
239         #[stable(feature = "rust1", since = "1.0.0")]
240         #[inline]
241         pub fn rotate_right(self, n: u32) -> $T {
242             (self as $UnsignedT).rotate_right(n) as $T
243         }
244
245         /// Reverses the byte order of the integer.
246         ///
247         /// # Examples
248         ///
249         /// ```rust
250         /// let n = 0x0123456789ABCDEFu64;
251         /// let m = 0xEFCDAB8967452301u64;
252         ///
253         /// assert_eq!(n.swap_bytes(), m);
254         /// ```
255         #[stable(feature = "rust1", since = "1.0.0")]
256         #[inline]
257         pub fn swap_bytes(self) -> $T {
258             (self as $UnsignedT).swap_bytes() as $T
259         }
260
261         /// Converts an integer from big endian to the target's endianness.
262         ///
263         /// On big endian this is a no-op. On little endian the bytes are
264         /// swapped.
265         ///
266         /// # Examples
267         ///
268         /// ```rust
269         /// let n = 0x0123456789ABCDEFu64;
270         ///
271         /// if cfg!(target_endian = "big") {
272         ///     assert_eq!(u64::from_be(n), n)
273         /// } else {
274         ///     assert_eq!(u64::from_be(n), n.swap_bytes())
275         /// }
276         /// ```
277         #[stable(feature = "rust1", since = "1.0.0")]
278         #[inline]
279         pub fn from_be(x: $T) -> $T {
280             if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
281         }
282
283         /// Converts an integer from little endian to the target's endianness.
284         ///
285         /// On little endian this is a no-op. On big endian the bytes are
286         /// swapped.
287         ///
288         /// # Examples
289         ///
290         /// ```rust
291         /// let n = 0x0123456789ABCDEFu64;
292         ///
293         /// if cfg!(target_endian = "little") {
294         ///     assert_eq!(u64::from_le(n), n)
295         /// } else {
296         ///     assert_eq!(u64::from_le(n), n.swap_bytes())
297         /// }
298         /// ```
299         #[stable(feature = "rust1", since = "1.0.0")]
300         #[inline]
301         pub fn from_le(x: $T) -> $T {
302             if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
303         }
304
305         /// Converts `self` to big endian from the target's endianness.
306         ///
307         /// On big endian this is a no-op. On little endian the bytes are
308         /// swapped.
309         ///
310         /// # Examples
311         ///
312         /// ```rust
313         /// let n = 0x0123456789ABCDEFu64;
314         ///
315         /// if cfg!(target_endian = "big") {
316         ///     assert_eq!(n.to_be(), n)
317         /// } else {
318         ///     assert_eq!(n.to_be(), n.swap_bytes())
319         /// }
320         /// ```
321         #[stable(feature = "rust1", since = "1.0.0")]
322         #[inline]
323         pub fn to_be(self) -> $T { // or not to be?
324             if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
325         }
326
327         /// Converts `self` to little endian from the target's endianness.
328         ///
329         /// On little endian this is a no-op. On big endian the bytes are
330         /// swapped.
331         ///
332         /// # Examples
333         ///
334         /// ```rust
335         /// let n = 0x0123456789ABCDEFu64;
336         ///
337         /// if cfg!(target_endian = "little") {
338         ///     assert_eq!(n.to_le(), n)
339         /// } else {
340         ///     assert_eq!(n.to_le(), n.swap_bytes())
341         /// }
342         /// ```
343         #[stable(feature = "rust1", since = "1.0.0")]
344         #[inline]
345         pub fn to_le(self) -> $T {
346             if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
347         }
348
349         /// Checked integer addition. Computes `self + other`, returning `None`
350         /// if overflow occurred.
351         ///
352         /// # Examples
353         ///
354         /// ```rust
355         /// assert_eq!(5u16.checked_add(65530), Some(65535));
356         /// assert_eq!(6u16.checked_add(65530), None);
357         /// ```
358         #[stable(feature = "rust1", since = "1.0.0")]
359         #[inline]
360         pub fn checked_add(self, other: $T) -> Option<$T> {
361             checked_op!($T, $ActualT, $add_with_overflow, self, other)
362         }
363
364         /// Checked integer subtraction. Computes `self - other`, returning
365         /// `None` if underflow occurred.
366         ///
367         /// # Examples
368         ///
369         /// ```rust
370         /// assert_eq!((-127i8).checked_sub(1), Some(-128));
371         /// assert_eq!((-128i8).checked_sub(1), None);
372         /// ```
373         #[stable(feature = "rust1", since = "1.0.0")]
374         #[inline]
375         pub fn checked_sub(self, other: $T) -> Option<$T> {
376             checked_op!($T, $ActualT, $sub_with_overflow, self, other)
377         }
378
379         /// Checked integer multiplication. Computes `self * other`, returning
380         /// `None` if underflow or overflow occurred.
381         ///
382         /// # Examples
383         ///
384         /// ```rust
385         /// assert_eq!(5u8.checked_mul(51), Some(255));
386         /// assert_eq!(5u8.checked_mul(52), None);
387         /// ```
388         #[stable(feature = "rust1", since = "1.0.0")]
389         #[inline]
390         pub fn checked_mul(self, other: $T) -> Option<$T> {
391             checked_op!($T, $ActualT, $mul_with_overflow, self, other)
392         }
393
394         /// Checked integer division. Computes `self / other`, returning `None`
395         /// if `other == 0` or the operation results in underflow or overflow.
396         ///
397         /// # Examples
398         ///
399         /// ```rust
400         /// assert_eq!((-127i8).checked_div(-1), Some(127));
401         /// assert_eq!((-128i8).checked_div(-1), None);
402         /// assert_eq!((1i8).checked_div(0), None);
403         /// ```
404         #[stable(feature = "rust1", since = "1.0.0")]
405         #[inline]
406         pub fn checked_div(self, v: $T) -> Option<$T> {
407             match v {
408                 0   => None,
409                -1 if self == <$T>::min_value()
410                     => None,
411                 v   => Some(self / v),
412             }
413         }
414
415         /// Saturating integer addition. Computes `self + other`, saturating at
416         /// the numeric bounds instead of overflowing.
417         #[stable(feature = "rust1", since = "1.0.0")]
418         #[inline]
419         pub fn saturating_add(self, other: $T) -> $T {
420             match self.checked_add(other) {
421                 Some(x)                       => x,
422                 None if other >= <$T as Zero>::zero() => <$T>::max_value(),
423                 None => <$T>::min_value(),
424             }
425         }
426
427         /// Saturating integer subtraction. Computes `self - other`, saturating
428         /// at the numeric bounds instead of overflowing.
429         #[stable(feature = "rust1", since = "1.0.0")]
430         #[inline]
431         pub fn saturating_sub(self, other: $T) -> $T {
432             match self.checked_sub(other) {
433                 Some(x)                      => x,
434                 None if other >= <$T as Zero>::zero() => <$T>::min_value(),
435                 None => <$T>::max_value(),
436             }
437         }
438
439         /// Wrapping (modular) addition. Computes `self + other`,
440         /// wrapping around at the boundary of the type.
441         #[stable(feature = "rust1", since = "1.0.0")]
442         #[inline]
443         pub fn wrapping_add(self, rhs: $T) -> $T {
444             unsafe {
445                 intrinsics::overflowing_add(self, rhs)
446             }
447         }
448
449         /// Wrapping (modular) subtraction. Computes `self - other`,
450         /// wrapping around at the boundary of the type.
451         #[stable(feature = "rust1", since = "1.0.0")]
452         #[inline]
453         pub fn wrapping_sub(self, rhs: $T) -> $T {
454             unsafe {
455                 intrinsics::overflowing_sub(self, rhs)
456             }
457         }
458
459         /// Wrapping (modular) multiplication. Computes `self *
460         /// other`, wrapping around at the boundary of the type.
461         #[stable(feature = "rust1", since = "1.0.0")]
462         #[inline]
463         pub fn wrapping_mul(self, rhs: $T) -> $T {
464             unsafe {
465                 intrinsics::overflowing_mul(self, rhs)
466             }
467         }
468
469         /// Wrapping (modular) division. Computes `floor(self / other)`,
470         /// wrapping around at the boundary of the type.
471         ///
472         /// The only case where such wrapping can occur is when one
473         /// divides `MIN / -1` on a signed type (where `MIN` is the
474         /// negative minimal value for the type); this is equivalent
475         /// to `-MIN`, a positive value that is too large to represent
476         /// in the type. In such a case, this function returns `MIN`
477         /// itself..
478         #[unstable(feature = "core", since = "1.0.0")]
479         #[inline(always)]
480         pub fn wrapping_div(self, rhs: $T) -> $T {
481             self.overflowing_div(rhs).0
482         }
483
484         /// Wrapping (modular) remainder. Computes `self % other`,
485         /// wrapping around at the boundary of the type.
486         ///
487         /// Such wrap-around never actually occurs mathematically;
488         /// implementation artifacts make `x % y` illegal for `MIN /
489         /// -1` on a signed type illegal (where `MIN` is the negative
490         /// minimal value). In such a case, this function returns `0`.
491         #[unstable(feature = "core", since = "1.0.0")]
492         #[inline(always)]
493         pub fn wrapping_rem(self, rhs: $T) -> $T {
494             self.overflowing_rem(rhs).0
495         }
496
497         /// Wrapping (modular) negation. Computes `-self`,
498         /// wrapping around at the boundary of the type.
499         ///
500         /// The only case where such wrapping can occur is when one
501         /// negates `MIN` on a signed type (where `MIN` is the
502         /// negative minimal value for the type); this is a positive
503         /// value that is too large to represent in the type. In such
504         /// a case, this function returns `MIN` itself.
505         #[unstable(feature = "core", since = "1.0.0")]
506         #[inline(always)]
507         pub fn wrapping_neg(self) -> $T {
508             self.overflowing_neg().0
509         }
510
511         /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
512         /// where `mask` removes any high-order bits of `rhs` that
513         /// would cause the shift to exceed the bitwidth of the type.
514         #[unstable(feature = "core", since = "1.0.0")]
515         #[inline(always)]
516         pub fn wrapping_shl(self, rhs: u32) -> $T {
517             self.overflowing_shl(rhs).0
518         }
519
520         /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
521         /// where `mask` removes any high-order bits of `rhs` that
522         /// would cause the shift to exceed the bitwidth of the type.
523         #[unstable(feature = "core", since = "1.0.0")]
524         #[inline(always)]
525         pub fn wrapping_shr(self, rhs: u32) -> $T {
526             self.overflowing_shr(rhs).0
527         }
528
529         /// Raises self to the power of `exp`, using exponentiation by squaring.
530         ///
531         /// # Examples
532         ///
533         /// ```
534         /// let x: i32 = 2; // or any other integer type
535         ///
536         /// assert_eq!(x.pow(4), 16);
537         /// ```
538         #[stable(feature = "rust1", since = "1.0.0")]
539         #[inline]
540         pub fn pow(self, mut exp: u32) -> $T {
541             let mut base = self;
542             let mut acc = <$T as One>::one();
543
544             let mut prev_base = self;
545             let mut base_oflo = false;
546             while exp > 0 {
547                 if (exp & 1) == 1 {
548                     if base_oflo {
549                         // ensure overflow occurs in the same manner it
550                         // would have otherwise (i.e. signal any exception
551                         // it would have otherwise).
552                         acc = acc * (prev_base * prev_base);
553                     } else {
554                         acc = acc * base;
555                     }
556                 }
557                 prev_base = base;
558                 let (new_base, new_base_oflo) = base.overflowing_mul(base);
559                 base = new_base;
560                 base_oflo = new_base_oflo;
561                 exp /= 2;
562             }
563             acc
564         }
565
566         /// Computes the absolute value of `self`. `Int::min_value()` will be
567         /// returned if the number is `Int::min_value()`.
568         #[stable(feature = "rust1", since = "1.0.0")]
569         #[inline]
570         pub fn abs(self) -> $T {
571             if self.is_negative() {
572                 self.wrapping_neg()
573             } else {
574                 self
575             }
576         }
577
578         /// Returns a number representing sign of `self`.
579         ///
580         /// - `0` if the number is zero
581         /// - `1` if the number is positive
582         /// - `-1` if the number is negative
583         #[stable(feature = "rust1", since = "1.0.0")]
584         #[inline]
585         pub fn signum(self) -> $T {
586             match self {
587                 n if n > 0 =>  1,
588                 0          =>  0,
589                 _          => -1,
590             }
591         }
592
593         /// Returns `true` if `self` is positive and `false` if the number
594         /// is zero or negative.
595         #[stable(feature = "rust1", since = "1.0.0")]
596         #[inline]
597         pub fn is_positive(self) -> bool { self > 0 }
598
599         /// Returns `true` if `self` is negative and `false` if the number
600         /// is zero or positive.
601         #[stable(feature = "rust1", since = "1.0.0")]
602         #[inline]
603         pub fn is_negative(self) -> bool { self < 0 }
604     }
605 }
606
607 #[lang = "i8"]
608 impl i8 {
609     int_impl! { i8 = i8, u8, 8,
610         intrinsics::i8_add_with_overflow,
611         intrinsics::i8_sub_with_overflow,
612         intrinsics::i8_mul_with_overflow }
613 }
614
615 #[lang = "i16"]
616 impl i16 {
617     int_impl! { i16 = i16, u16, 16,
618         intrinsics::i16_add_with_overflow,
619         intrinsics::i16_sub_with_overflow,
620         intrinsics::i16_mul_with_overflow }
621 }
622
623 #[lang = "i32"]
624 impl i32 {
625     int_impl! { i32 = i32, u32, 32,
626         intrinsics::i32_add_with_overflow,
627         intrinsics::i32_sub_with_overflow,
628         intrinsics::i32_mul_with_overflow }
629 }
630
631 #[lang = "i64"]
632 impl i64 {
633     int_impl! { i64 = i64, u64, 64,
634         intrinsics::i64_add_with_overflow,
635         intrinsics::i64_sub_with_overflow,
636         intrinsics::i64_mul_with_overflow }
637 }
638
639 #[cfg(target_pointer_width = "32")]
640 #[lang = "isize"]
641 impl isize {
642     int_impl! { isize = i32, u32, 32,
643         intrinsics::i32_add_with_overflow,
644         intrinsics::i32_sub_with_overflow,
645         intrinsics::i32_mul_with_overflow }
646 }
647
648 #[cfg(target_pointer_width = "64")]
649 #[lang = "isize"]
650 impl isize {
651     int_impl! { isize = i64, u64, 64,
652         intrinsics::i64_add_with_overflow,
653         intrinsics::i64_sub_with_overflow,
654         intrinsics::i64_mul_with_overflow }
655 }
656
657 // `Int` + `UnsignedInt` implemented for signed integers
658 macro_rules! uint_impl {
659     ($T:ty = $ActualT:ty, $BITS:expr,
660      $ctpop:path,
661      $ctlz:path,
662      $cttz:path,
663      $bswap:path,
664      $add_with_overflow:path,
665      $sub_with_overflow:path,
666      $mul_with_overflow:path) => {
667         /// Returns the smallest value that can be represented by this integer type.
668         #[stable(feature = "rust1", since = "1.0.0")]
669         pub fn min_value() -> $T { 0 }
670
671         /// Returns the largest value that can be represented by this integer type.
672         #[stable(feature = "rust1", since = "1.0.0")]
673         pub fn max_value() -> $T { !0 }
674
675         /// Converts a string slice in a given base to an integer.
676         ///
677         /// Leading and trailing whitespace represent an error.
678         ///
679         /// # Arguments
680         ///
681         /// * src - A string slice
682         /// * radix - The base to use. Must lie in the range [2 .. 36]
683         ///
684         /// # Return value
685         ///
686         /// `Err(ParseIntError)` if the string did not represent a valid number.
687         /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
688         #[stable(feature = "rust1", since = "1.0.0")]
689         #[allow(deprecated)]
690         pub fn from_str_radix(src: &str, radix: u32) -> Result<$T, ParseIntError> {
691             from_str_radix(src, radix)
692         }
693
694         /// Returns the number of ones in the binary representation of `self`.
695         ///
696         /// # Examples
697         ///
698         /// ```rust
699         /// let n = 0b01001100u8;
700         ///
701         /// assert_eq!(n.count_ones(), 3);
702         /// ```
703         #[stable(feature = "rust1", since = "1.0.0")]
704         #[inline]
705         pub fn count_ones(self) -> u32 {
706             unsafe { $ctpop(self as $ActualT) as u32 }
707         }
708
709         /// Returns the number of zeros in the binary representation of `self`.
710         ///
711         /// # Examples
712         ///
713         /// ```rust
714         /// let n = 0b01001100u8;
715         ///
716         /// assert_eq!(n.count_zeros(), 5);
717         /// ```
718         #[stable(feature = "rust1", since = "1.0.0")]
719         #[inline]
720         pub fn count_zeros(self) -> u32 {
721             (!self).count_ones()
722         }
723
724         /// Returns the number of leading zeros in the binary representation
725         /// of `self`.
726         ///
727         /// # Examples
728         ///
729         /// ```rust
730         /// let n = 0b0101000u16;
731         ///
732         /// assert_eq!(n.leading_zeros(), 10);
733         /// ```
734         #[stable(feature = "rust1", since = "1.0.0")]
735         #[inline]
736         pub fn leading_zeros(self) -> u32 {
737             unsafe { $ctlz(self as $ActualT) as u32 }
738         }
739
740         /// Returns the number of trailing zeros in the binary representation
741         /// of `self`.
742         ///
743         /// # Examples
744         ///
745         /// ```rust
746         /// let n = 0b0101000u16;
747         ///
748         /// assert_eq!(n.trailing_zeros(), 3);
749         /// ```
750         #[stable(feature = "rust1", since = "1.0.0")]
751         #[inline]
752         pub fn trailing_zeros(self) -> u32 {
753             // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
754             // emits two conditional moves on x86_64. By promoting the value to
755             // u16 and setting bit 8, we get better code without any conditional
756             // operations.
757             // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
758             // pending, remove this workaround once LLVM generates better code
759             // for cttz8.
760             unsafe {
761                 if $BITS == 8 {
762                     intrinsics::cttz16(self as u16 | 0x100) as u32
763                 } else {
764                     $cttz(self as $ActualT) as u32
765                 }
766             }
767         }
768
769         /// Shifts the bits to the left by a specified amount, `n`,
770         /// wrapping the truncated bits to the end of the resulting integer.
771         ///
772         /// # Examples
773         ///
774         /// ```rust
775         /// let n = 0x0123456789ABCDEFu64;
776         /// let m = 0x3456789ABCDEF012u64;
777         ///
778         /// assert_eq!(n.rotate_left(12), m);
779         /// ```
780         #[stable(feature = "rust1", since = "1.0.0")]
781         #[inline]
782         pub fn rotate_left(self, n: u32) -> $T {
783             // Protect against undefined behaviour for over-long bit shifts
784             let n = n % $BITS;
785             (self << n) | (self >> (($BITS - n) % $BITS))
786         }
787
788         /// Shifts the bits to the right by a specified amount, `n`,
789         /// wrapping the truncated bits to the beginning of the resulting
790         /// integer.
791         ///
792         /// # Examples
793         ///
794         /// ```rust
795         /// let n = 0x0123456789ABCDEFu64;
796         /// let m = 0xDEF0123456789ABCu64;
797         ///
798         /// assert_eq!(n.rotate_right(12), m);
799         /// ```
800         #[stable(feature = "rust1", since = "1.0.0")]
801         #[inline]
802         pub fn rotate_right(self, n: u32) -> $T {
803             // Protect against undefined behaviour for over-long bit shifts
804             let n = n % $BITS;
805             (self >> n) | (self << (($BITS - n) % $BITS))
806         }
807
808         /// Reverses the byte order of the integer.
809         ///
810         /// # Examples
811         ///
812         /// ```rust
813         /// let n = 0x0123456789ABCDEFu64;
814         /// let m = 0xEFCDAB8967452301u64;
815         ///
816         /// assert_eq!(n.swap_bytes(), m);
817         /// ```
818         #[stable(feature = "rust1", since = "1.0.0")]
819         #[inline]
820         pub fn swap_bytes(self) -> $T {
821             unsafe { $bswap(self as $ActualT) as $T }
822         }
823
824         /// Converts an integer from big endian to the target's endianness.
825         ///
826         /// On big endian this is a no-op. On little endian the bytes are
827         /// swapped.
828         ///
829         /// # Examples
830         ///
831         /// ```rust
832         /// let n = 0x0123456789ABCDEFu64;
833         ///
834         /// if cfg!(target_endian = "big") {
835         ///     assert_eq!(u64::from_be(n), n)
836         /// } else {
837         ///     assert_eq!(u64::from_be(n), n.swap_bytes())
838         /// }
839         /// ```
840         #[stable(feature = "rust1", since = "1.0.0")]
841         #[inline]
842         pub fn from_be(x: $T) -> $T {
843             if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
844         }
845
846         /// Converts an integer from little endian to the target's endianness.
847         ///
848         /// On little endian this is a no-op. On big endian the bytes are
849         /// swapped.
850         ///
851         /// # Examples
852         ///
853         /// ```rust
854         /// let n = 0x0123456789ABCDEFu64;
855         ///
856         /// if cfg!(target_endian = "little") {
857         ///     assert_eq!(u64::from_le(n), n)
858         /// } else {
859         ///     assert_eq!(u64::from_le(n), n.swap_bytes())
860         /// }
861         /// ```
862         #[stable(feature = "rust1", since = "1.0.0")]
863         #[inline]
864         pub fn from_le(x: $T) -> $T {
865             if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
866         }
867
868         /// Converts `self` to big endian from the target's endianness.
869         ///
870         /// On big endian this is a no-op. On little endian the bytes are
871         /// swapped.
872         ///
873         /// # Examples
874         ///
875         /// ```rust
876         /// let n = 0x0123456789ABCDEFu64;
877         ///
878         /// if cfg!(target_endian = "big") {
879         ///     assert_eq!(n.to_be(), n)
880         /// } else {
881         ///     assert_eq!(n.to_be(), n.swap_bytes())
882         /// }
883         /// ```
884         #[stable(feature = "rust1", since = "1.0.0")]
885         #[inline]
886         pub fn to_be(self) -> $T { // or not to be?
887             if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
888         }
889
890         /// Converts `self` to little endian from the target's endianness.
891         ///
892         /// On little endian this is a no-op. On big endian the bytes are
893         /// swapped.
894         ///
895         /// # Examples
896         ///
897         /// ```rust
898         /// let n = 0x0123456789ABCDEFu64;
899         ///
900         /// if cfg!(target_endian = "little") {
901         ///     assert_eq!(n.to_le(), n)
902         /// } else {
903         ///     assert_eq!(n.to_le(), n.swap_bytes())
904         /// }
905         /// ```
906         #[stable(feature = "rust1", since = "1.0.0")]
907         #[inline]
908         pub fn to_le(self) -> $T {
909             if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
910         }
911
912         /// Checked integer addition. Computes `self + other`, returning `None`
913         /// if overflow occurred.
914         ///
915         /// # Examples
916         ///
917         /// ```rust
918         /// assert_eq!(5u16.checked_add(65530), Some(65535));
919         /// assert_eq!(6u16.checked_add(65530), None);
920         /// ```
921         #[stable(feature = "rust1", since = "1.0.0")]
922         #[inline]
923         pub fn checked_add(self, other: $T) -> Option<$T> {
924             checked_op!($T, $ActualT, $add_with_overflow, self, other)
925         }
926
927         /// Checked integer subtraction. Computes `self - other`, returning
928         /// `None` if underflow occurred.
929         ///
930         /// # Examples
931         ///
932         /// ```rust
933         /// assert_eq!((-127i8).checked_sub(1), Some(-128));
934         /// assert_eq!((-128i8).checked_sub(1), None);
935         /// ```
936         #[stable(feature = "rust1", since = "1.0.0")]
937         #[inline]
938         pub fn checked_sub(self, other: $T) -> Option<$T> {
939             checked_op!($T, $ActualT, $sub_with_overflow, self, other)
940         }
941
942         /// Checked integer multiplication. Computes `self * other`, returning
943         /// `None` if underflow or overflow occurred.
944         ///
945         /// # Examples
946         ///
947         /// ```rust
948         /// assert_eq!(5u8.checked_mul(51), Some(255));
949         /// assert_eq!(5u8.checked_mul(52), None);
950         /// ```
951         #[stable(feature = "rust1", since = "1.0.0")]
952         #[inline]
953         pub fn checked_mul(self, other: $T) -> Option<$T> {
954             checked_op!($T, $ActualT, $mul_with_overflow, self, other)
955         }
956
957         /// Checked integer division. Computes `self / other`, returning `None`
958         /// if `other == 0` or the operation results in underflow or overflow.
959         ///
960         /// # Examples
961         ///
962         /// ```rust
963         /// assert_eq!((-127i8).checked_div(-1), Some(127));
964         /// assert_eq!((-128i8).checked_div(-1), None);
965         /// assert_eq!((1i8).checked_div(0), None);
966         /// ```
967         #[stable(feature = "rust1", since = "1.0.0")]
968         #[inline]
969         pub fn checked_div(self, v: $T) -> Option<$T> {
970             match v {
971                 0 => None,
972                 v => Some(self / v),
973             }
974         }
975
976         /// Saturating integer addition. Computes `self + other`, saturating at
977         /// the numeric bounds instead of overflowing.
978         #[stable(feature = "rust1", since = "1.0.0")]
979         #[inline]
980         pub fn saturating_add(self, other: $T) -> $T {
981             match self.checked_add(other) {
982                 Some(x)                       => x,
983                 None if other >= <$T as Zero>::zero() => <$T>::max_value(),
984                 None => <$T>::min_value(),
985             }
986         }
987
988         /// Saturating integer subtraction. Computes `self - other`, saturating
989         /// at the numeric bounds instead of overflowing.
990         #[stable(feature = "rust1", since = "1.0.0")]
991         #[inline]
992         pub fn saturating_sub(self, other: $T) -> $T {
993             match self.checked_sub(other) {
994                 Some(x)                       => x,
995                 None if other >= <$T as Zero>::zero() => <$T>::min_value(),
996                 None => <$T>::max_value(),
997             }
998         }
999
1000         /// Wrapping (modular) addition. Computes `self + other`,
1001         /// wrapping around at the boundary of the type.
1002         #[stable(feature = "rust1", since = "1.0.0")]
1003         #[inline]
1004         pub fn wrapping_add(self, rhs: $T) -> $T {
1005             unsafe {
1006                 intrinsics::overflowing_add(self, rhs)
1007             }
1008         }
1009
1010         /// Wrapping (modular) subtraction. Computes `self - other`,
1011         /// wrapping around at the boundary of the type.
1012         #[stable(feature = "rust1", since = "1.0.0")]
1013         #[inline]
1014         pub fn wrapping_sub(self, rhs: $T) -> $T {
1015             unsafe {
1016                 intrinsics::overflowing_sub(self, rhs)
1017             }
1018         }
1019
1020         /// Wrapping (modular) multiplication. Computes `self *
1021         /// other`, wrapping around at the boundary of the type.
1022         #[stable(feature = "rust1", since = "1.0.0")]
1023         #[inline]
1024         pub fn wrapping_mul(self, rhs: $T) -> $T {
1025             unsafe {
1026                 intrinsics::overflowing_mul(self, rhs)
1027             }
1028         }
1029
1030         /// Wrapping (modular) division. Computes `floor(self / other)`,
1031         /// wrapping around at the boundary of the type.
1032         ///
1033         /// The only case where such wrapping can occur is when one
1034         /// divides `MIN / -1` on a signed type (where `MIN` is the
1035         /// negative minimal value for the type); this is equivalent
1036         /// to `-MIN`, a positive value that is too large to represent
1037         /// in the type. In such a case, this function returns `MIN`
1038         /// itself..
1039         #[unstable(feature = "core", since = "1.0.0")]
1040         #[inline(always)]
1041         pub fn wrapping_div(self, rhs: $T) -> $T {
1042             self.overflowing_div(rhs).0
1043         }
1044
1045         /// Wrapping (modular) remainder. Computes `self % other`,
1046         /// wrapping around at the boundary of the type.
1047         ///
1048         /// Such wrap-around never actually occurs mathematically;
1049         /// implementation artifacts make `x % y` illegal for `MIN /
1050         /// -1` on a signed type illegal (where `MIN` is the negative
1051         /// minimal value). In such a case, this function returns `0`.
1052         #[unstable(feature = "core", since = "1.0.0")]
1053         #[inline(always)]
1054         pub fn wrapping_rem(self, rhs: $T) -> $T {
1055             self.overflowing_rem(rhs).0
1056         }
1057
1058         /// Wrapping (modular) negation. Computes `-self`,
1059         /// wrapping around at the boundary of the type.
1060         ///
1061         /// The only case where such wrapping can occur is when one
1062         /// negates `MIN` on a signed type (where `MIN` is the
1063         /// negative minimal value for the type); this is a positive
1064         /// value that is too large to represent in the type. In such
1065         /// a case, this function returns `MIN` itself.
1066         #[unstable(feature = "core", since = "1.0.0")]
1067         #[inline(always)]
1068         pub fn wrapping_neg(self) -> $T {
1069             self.overflowing_neg().0
1070         }
1071
1072         /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1073         /// where `mask` removes any high-order bits of `rhs` that
1074         /// would cause the shift to exceed the bitwidth of the type.
1075         #[unstable(feature = "core", since = "1.0.0")]
1076         #[inline(always)]
1077         pub fn wrapping_shl(self, rhs: u32) -> $T {
1078             self.overflowing_shl(rhs).0
1079         }
1080
1081         /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
1082         /// where `mask` removes any high-order bits of `rhs` that
1083         /// would cause the shift to exceed the bitwidth of the type.
1084         #[unstable(feature = "core", since = "1.0.0")]
1085         #[inline(always)]
1086         pub fn wrapping_shr(self, rhs: u32) -> $T {
1087             self.overflowing_shr(rhs).0
1088         }
1089
1090         /// Raises self to the power of `exp`, using exponentiation by squaring.
1091         ///
1092         /// # Examples
1093         ///
1094         /// ```rust
1095         /// assert_eq!(2i32.pow(4), 16);
1096         /// ```
1097         #[stable(feature = "rust1", since = "1.0.0")]
1098         #[inline]
1099         pub fn pow(self, mut exp: u32) -> $T {
1100             let mut base = self;
1101             let mut acc = <$T as One>::one();
1102
1103             let mut prev_base = self;
1104             let mut base_oflo = false;
1105             while exp > 0 {
1106                 if (exp & 1) == 1 {
1107                     if base_oflo {
1108                         // ensure overflow occurs in the same manner it
1109                         // would have otherwise (i.e. signal any exception
1110                         // it would have otherwise).
1111                         acc = acc * (prev_base * prev_base);
1112                     } else {
1113                         acc = acc * base;
1114                     }
1115                 }
1116                 prev_base = base;
1117                 let (new_base, new_base_oflo) = base.overflowing_mul(base);
1118                 base = new_base;
1119                 base_oflo = new_base_oflo;
1120                 exp /= 2;
1121             }
1122             acc
1123         }
1124
1125         /// Returns `true` iff `self == 2^k` for some `k`.
1126         #[stable(feature = "rust1", since = "1.0.0")]
1127         #[inline]
1128         pub fn is_power_of_two(self) -> bool {
1129             (self.wrapping_sub(<$T as One>::one())) & self == <$T as Zero>::zero() &&
1130                 !(self == <$T as Zero>::zero())
1131         }
1132
1133         /// Returns the smallest power of two greater than or equal to `self`.
1134         /// Unspecified behavior on overflow.
1135         #[stable(feature = "rust1", since = "1.0.0")]
1136         #[inline]
1137         pub fn next_power_of_two(self) -> $T {
1138             let bits = size_of::<$T>() * 8;
1139             let one: $T = <$T as One>::one();
1140             one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
1141         }
1142
1143         /// Returns the smallest power of two greater than or equal to `n`. If
1144         /// the next power of two is greater than the type's maximum value,
1145         /// `None` is returned, otherwise the power of two is wrapped in `Some`.
1146         #[stable(feature = "rust1", since = "1.0.0")]
1147         pub fn checked_next_power_of_two(self) -> Option<$T> {
1148             let npot = self.next_power_of_two();
1149             if npot >= self {
1150                 Some(npot)
1151             } else {
1152                 None
1153             }
1154         }
1155     }
1156 }
1157
1158 #[lang = "u8"]
1159 impl u8 {
1160     uint_impl! { u8 = u8, 8,
1161         intrinsics::ctpop8,
1162         intrinsics::ctlz8,
1163         intrinsics::cttz8,
1164         bswap8,
1165         intrinsics::u8_add_with_overflow,
1166         intrinsics::u8_sub_with_overflow,
1167         intrinsics::u8_mul_with_overflow }
1168 }
1169
1170 #[lang = "u16"]
1171 impl u16 {
1172     uint_impl! { u16 = u16, 16,
1173         intrinsics::ctpop16,
1174         intrinsics::ctlz16,
1175         intrinsics::cttz16,
1176         intrinsics::bswap16,
1177         intrinsics::u16_add_with_overflow,
1178         intrinsics::u16_sub_with_overflow,
1179         intrinsics::u16_mul_with_overflow }
1180 }
1181
1182 #[lang = "u32"]
1183 impl u32 {
1184     uint_impl! { u32 = u32, 32,
1185         intrinsics::ctpop32,
1186         intrinsics::ctlz32,
1187         intrinsics::cttz32,
1188         intrinsics::bswap32,
1189         intrinsics::u32_add_with_overflow,
1190         intrinsics::u32_sub_with_overflow,
1191         intrinsics::u32_mul_with_overflow }
1192 }
1193
1194
1195 #[lang = "u64"]
1196 impl u64 {
1197     uint_impl! { u64 = u64, 64,
1198         intrinsics::ctpop64,
1199         intrinsics::ctlz64,
1200         intrinsics::cttz64,
1201         intrinsics::bswap64,
1202         intrinsics::u64_add_with_overflow,
1203         intrinsics::u64_sub_with_overflow,
1204         intrinsics::u64_mul_with_overflow }
1205 }
1206
1207 #[cfg(target_pointer_width = "32")]
1208 #[lang = "usize"]
1209 impl usize {
1210     uint_impl! { usize = u32, 32,
1211         intrinsics::ctpop32,
1212         intrinsics::ctlz32,
1213         intrinsics::cttz32,
1214         intrinsics::bswap32,
1215         intrinsics::u32_add_with_overflow,
1216         intrinsics::u32_sub_with_overflow,
1217         intrinsics::u32_mul_with_overflow }
1218 }
1219
1220 #[cfg(target_pointer_width = "64")]
1221 #[lang = "usize"]
1222 impl usize {
1223     uint_impl! { usize = u64, 64,
1224         intrinsics::ctpop64,
1225         intrinsics::ctlz64,
1226         intrinsics::cttz64,
1227         intrinsics::bswap64,
1228         intrinsics::u64_add_with_overflow,
1229         intrinsics::u64_sub_with_overflow,
1230         intrinsics::u64_mul_with_overflow }
1231 }
1232
1233 /// Used for representing the classification of floating point numbers
1234 #[derive(Copy, Clone, PartialEq, Debug)]
1235 #[stable(feature = "rust1", since = "1.0.0")]
1236 pub enum FpCategory {
1237     /// "Not a Number", often obtained by dividing by zero
1238     #[stable(feature = "rust1", since = "1.0.0")]
1239     Nan,
1240
1241     /// Positive or negative infinity
1242     #[stable(feature = "rust1", since = "1.0.0")]
1243     Infinite ,
1244
1245     /// Positive or negative zero
1246     #[stable(feature = "rust1", since = "1.0.0")]
1247     Zero,
1248
1249     /// De-normalized floating point representation (less precise than `Normal`)
1250     #[stable(feature = "rust1", since = "1.0.0")]
1251     Subnormal,
1252
1253     /// A regular floating point number
1254     #[stable(feature = "rust1", since = "1.0.0")]
1255     Normal,
1256 }
1257
1258 /// A built-in floating point number.
1259 #[doc(hidden)]
1260 pub trait Float {
1261     /// Returns the NaN value.
1262     fn nan() -> Self;
1263     /// Returns the infinite value.
1264     fn infinity() -> Self;
1265     /// Returns the negative infinite value.
1266     fn neg_infinity() -> Self;
1267     /// Returns -0.0.
1268     fn neg_zero() -> Self;
1269     /// Returns 0.0.
1270     fn zero() -> Self;
1271     /// Returns 1.0.
1272     fn one() -> Self;
1273     /// Parses the string `s` with the radix `r` as a float.
1274     fn from_str_radix(s: &str, r: u32) -> Result<Self, ParseFloatError>;
1275
1276     /// Returns true if this value is NaN and false otherwise.
1277     fn is_nan(self) -> bool;
1278     /// Returns true if this value is positive infinity or negative infinity and
1279     /// false otherwise.
1280     fn is_infinite(self) -> bool;
1281     /// Returns true if this number is neither infinite nor NaN.
1282     fn is_finite(self) -> bool;
1283     /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1284     fn is_normal(self) -> bool;
1285     /// Returns the category that this number falls into.
1286     fn classify(self) -> FpCategory;
1287
1288     /// Returns the mantissa, exponent and sign as integers, respectively.
1289     fn integer_decode(self) -> (u64, i16, i8);
1290
1291     /// Return the largest integer less than or equal to a number.
1292     fn floor(self) -> Self;
1293     /// Return the smallest integer greater than or equal to a number.
1294     fn ceil(self) -> Self;
1295     /// Return the nearest integer to a number. Round half-way cases away from
1296     /// `0.0`.
1297     fn round(self) -> Self;
1298     /// Return the integer part of a number.
1299     fn trunc(self) -> Self;
1300     /// Return the fractional part of a number.
1301     fn fract(self) -> Self;
1302
1303     /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1304     /// number is `Float::nan()`.
1305     fn abs(self) -> Self;
1306     /// Returns a number that represents the sign of `self`.
1307     ///
1308     /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1309     /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1310     /// - `Float::nan()` if the number is `Float::nan()`
1311     fn signum(self) -> Self;
1312     /// Returns `true` if `self` is positive, including `+0.0` and
1313     /// `Float::infinity()`.
1314     fn is_positive(self) -> bool;
1315     /// Returns `true` if `self` is negative, including `-0.0` and
1316     /// `Float::neg_infinity()`.
1317     fn is_negative(self) -> bool;
1318
1319     /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1320     /// error. This produces a more accurate result with better performance than
1321     /// a separate multiplication operation followed by an add.
1322     fn mul_add(self, a: Self, b: Self) -> Self;
1323     /// Take the reciprocal (inverse) of a number, `1/x`.
1324     fn recip(self) -> Self;
1325
1326     /// Raise a number to an integer power.
1327     ///
1328     /// Using this function is generally faster than using `powf`
1329     fn powi(self, n: i32) -> Self;
1330     /// Raise a number to a floating point power.
1331     fn powf(self, n: Self) -> Self;
1332
1333     /// Take the square root of a number.
1334     ///
1335     /// Returns NaN if `self` is a negative number.
1336     fn sqrt(self) -> Self;
1337     /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1338     fn rsqrt(self) -> Self;
1339
1340     /// Returns `e^(self)`, (the exponential function).
1341     fn exp(self) -> Self;
1342     /// Returns 2 raised to the power of the number, `2^(self)`.
1343     fn exp2(self) -> Self;
1344     /// Returns the natural logarithm of the number.
1345     fn ln(self) -> Self;
1346     /// Returns the logarithm of the number with respect to an arbitrary base.
1347     fn log(self, base: Self) -> Self;
1348     /// Returns the base 2 logarithm of the number.
1349     fn log2(self) -> Self;
1350     /// Returns the base 10 logarithm of the number.
1351     fn log10(self) -> Self;
1352
1353     /// Convert radians to degrees.
1354     fn to_degrees(self) -> Self;
1355     /// Convert degrees to radians.
1356     fn to_radians(self) -> Self;
1357 }
1358
1359 macro_rules! from_str_float_impl {
1360     ($T:ident) => {
1361         #[stable(feature = "rust1", since = "1.0.0")]
1362         impl FromStr for $T {
1363             type Err = ParseFloatError;
1364
1365             /// Converts a string in base 10 to a float.
1366             /// Accepts an optional decimal exponent.
1367             ///
1368             /// This function accepts strings such as
1369             ///
1370             /// * '3.14'
1371             /// * '+3.14', equivalent to '3.14'
1372             /// * '-3.14'
1373             /// * '2.5E10', or equivalently, '2.5e10'
1374             /// * '2.5E-10'
1375             /// * '.' (understood as 0)
1376             /// * '5.'
1377             /// * '.5', or, equivalently,  '0.5'
1378             /// * '+inf', 'inf', '-inf', 'NaN'
1379             ///
1380             /// Leading and trailing whitespace represent an error.
1381             ///
1382             /// # Arguments
1383             ///
1384             /// * src - A string
1385             ///
1386             /// # Return value
1387             ///
1388             /// `Err(ParseFloatError)` if the string did not represent a valid
1389             /// number.  Otherwise, `Ok(n)` where `n` is the floating-point
1390             /// number represented by `src`.
1391             #[inline]
1392             #[allow(deprecated)]
1393             fn from_str(src: &str) -> Result<$T, ParseFloatError> {
1394                 $T::from_str_radix(src, 10)
1395             }
1396         }
1397     }
1398 }
1399 from_str_float_impl!(f32);
1400 from_str_float_impl!(f64);
1401
1402 macro_rules! from_str_radix_int_impl {
1403     ($($T:ident)*) => {$(
1404         #[stable(feature = "rust1", since = "1.0.0")]
1405         #[allow(deprecated)]
1406         impl FromStr for $T {
1407             type Err = ParseIntError;
1408             fn from_str(src: &str) -> Result<$T, ParseIntError> {
1409                 from_str_radix(src, 10)
1410             }
1411         }
1412     )*}
1413 }
1414 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
1415
1416 #[doc(hidden)]
1417 trait FromStrRadixHelper: PartialOrd + Copy {
1418     fn min_value() -> Self;
1419     fn from_u32(u: u32) -> Self;
1420     fn checked_mul(&self, other: u32) -> Option<Self>;
1421     fn checked_sub(&self, other: u32) -> Option<Self>;
1422     fn checked_add(&self, other: u32) -> Option<Self>;
1423 }
1424
1425 macro_rules! doit {
1426     ($($t:ident)*) => ($(impl FromStrRadixHelper for $t {
1427         fn min_value() -> Self { <$t>::min_value() }
1428         fn from_u32(u: u32) -> Self { u as $t }
1429         fn checked_mul(&self, other: u32) -> Option<Self> {
1430             <$t>::checked_mul(*self, other as $t)
1431         }
1432         fn checked_sub(&self, other: u32) -> Option<Self> {
1433             <$t>::checked_sub(*self, other as $t)
1434         }
1435         fn checked_add(&self, other: u32) -> Option<Self> {
1436             <$t>::checked_add(*self, other as $t)
1437         }
1438     })*)
1439 }
1440 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1441
1442 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
1443                                          -> Result<T, ParseIntError> {
1444     use self::IntErrorKind::*;
1445     use self::ParseIntError as PIE;
1446     assert!(radix >= 2 && radix <= 36,
1447            "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1448            radix);
1449
1450     let is_signed_ty = T::from_u32(0) > T::min_value();
1451
1452     match src.slice_shift_char() {
1453         Some(('-', "")) => Err(PIE { kind: Empty }),
1454         Some(('-', src)) if is_signed_ty => {
1455             // The number is negative
1456             let mut result = T::from_u32(0);
1457             for c in src.chars() {
1458                 let x = match c.to_digit(radix) {
1459                     Some(x) => x,
1460                     None => return Err(PIE { kind: InvalidDigit }),
1461                 };
1462                 result = match result.checked_mul(radix) {
1463                     Some(result) => result,
1464                     None => return Err(PIE { kind: Underflow }),
1465                 };
1466                 result = match result.checked_sub(x) {
1467                     Some(result) => result,
1468                     None => return Err(PIE { kind: Underflow }),
1469                 };
1470             }
1471             Ok(result)
1472         },
1473         Some((_, _)) => {
1474             // The number is signed
1475             let mut result = T::from_u32(0);
1476             for c in src.chars() {
1477                 let x = match c.to_digit(radix) {
1478                     Some(x) => x,
1479                     None => return Err(PIE { kind: InvalidDigit }),
1480                 };
1481                 result = match result.checked_mul(radix) {
1482                     Some(result) => result,
1483                     None => return Err(PIE { kind: Overflow }),
1484                 };
1485                 result = match result.checked_add(x) {
1486                     Some(result) => result,
1487                     None => return Err(PIE { kind: Overflow }),
1488                 };
1489             }
1490             Ok(result)
1491         },
1492         None => Err(ParseIntError { kind: Empty }),
1493     }
1494 }
1495
1496 /// An error which can be returned when parsing an integer.
1497 #[derive(Debug, Clone, PartialEq)]
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 pub struct ParseIntError { kind: IntErrorKind }
1500
1501 #[derive(Debug, Clone, PartialEq)]
1502 enum IntErrorKind {
1503     Empty,
1504     InvalidDigit,
1505     Overflow,
1506     Underflow,
1507 }
1508
1509 impl ParseIntError {
1510     #[unstable(feature = "core", reason = "available through Error trait")]
1511     pub fn description(&self) -> &str {
1512         match self.kind {
1513             IntErrorKind::Empty => "cannot parse integer from empty string",
1514             IntErrorKind::InvalidDigit => "invalid digit found in string",
1515             IntErrorKind::Overflow => "number too large to fit in target type",
1516             IntErrorKind::Underflow => "number too small to fit in target type",
1517         }
1518     }
1519 }
1520
1521 #[stable(feature = "rust1", since = "1.0.0")]
1522 impl fmt::Display for ParseIntError {
1523     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1524         self.description().fmt(f)
1525     }
1526 }
1527
1528 /// An error which can be returned when parsing a float.
1529 #[derive(Debug, Clone, PartialEq)]
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 pub struct ParseFloatError {
1532     #[doc(hidden)]
1533     pub __kind: FloatErrorKind
1534 }
1535
1536 #[derive(Debug, Clone, PartialEq)]
1537 pub enum FloatErrorKind {
1538     Empty,
1539     Invalid,
1540 }
1541
1542 impl ParseFloatError {
1543     #[doc(hidden)]
1544     pub fn __description(&self) -> &str {
1545         match self.__kind {
1546             FloatErrorKind::Empty => "cannot parse float from empty string",
1547             FloatErrorKind::Invalid => "invalid float literal",
1548         }
1549     }
1550 }
1551
1552 #[stable(feature = "rust1", since = "1.0.0")]
1553 impl fmt::Display for ParseFloatError {
1554     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1555         self.__description().fmt(f)
1556     }
1557 }