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