]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
bfbb2ded0782dbf4e177d35b00cca42e70e581e2
[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 use slice::SliceExt;
28
29 /// Provides intentionally-wrapped arithmetic on `T`.
30 ///
31 /// Operations like `+` on `u32` values is intended to never overflow,
32 /// and in some debug configurations overflow is detected and results
33 /// in a panic. While most arithmetic falls into this category, some
34 /// code explicitly expects and relies upon modular arithmetic (e.g.,
35 /// hashing).
36 ///
37 /// Wrapping arithmetic can be achieved either through methods like
38 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
39 /// all standard arithmetic operations on the underlying value are
40 /// intended to have wrapping semantics.
41 #[stable(feature = "rust1", since = "1.0.0")]
42 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)]
43 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
44
45 pub mod wrapping;
46 pub mod flt2dec;
47
48 /// Types that have a "zero" value.
49 ///
50 /// This trait is intended for use in conjunction with `Add`, as an identity:
51 /// `x + T::zero() == x`.
52 #[unstable(feature = "zero_one",
53            reason = "unsure of placement, wants to use associated constants")]
54 pub trait Zero {
55     /// The "zero" (usually, additive identity) for this type.
56     fn zero() -> Self;
57 }
58
59 /// Types that have a "one" value.
60 ///
61 /// This trait is intended for use in conjunction with `Mul`, as an identity:
62 /// `x * T::one() == x`.
63 #[unstable(feature = "zero_one",
64            reason = "unsure of placement, wants to use associated constants")]
65 pub trait One {
66     /// The "one" (usually, multiplicative identity) for this type.
67     fn one() -> Self;
68 }
69
70 macro_rules! zero_one_impl {
71     ($($t:ty)*) => ($(
72         impl Zero for $t {
73             #[inline]
74             fn zero() -> Self { 0 }
75         }
76         impl One for $t {
77             #[inline]
78             fn one() -> Self { 1 }
79         }
80     )*)
81 }
82 zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
83
84 macro_rules! zero_one_impl_float {
85     ($($t:ty)*) => ($(
86         impl Zero for $t {
87             #[inline]
88             fn zero() -> Self { 0.0 }
89         }
90         impl One for $t {
91             #[inline]
92             fn one() -> Self { 1.0 }
93         }
94     )*)
95 }
96 zero_one_impl_float! { f32 f64 }
97
98 macro_rules! checked_op {
99     ($U:ty, $op:path, $x:expr, $y:expr) => {{
100         let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
101         if overflowed { None } else { Some(result as Self) }
102     }}
103 }
104
105 /// Swapping a single byte is a no-op. This is marked as `unsafe` for
106 /// consistency with the other `bswap` intrinsics.
107 unsafe fn bswap8(x: u8) -> u8 { x }
108
109 // `Int` + `SignedInt` implemented for signed integers
110 macro_rules! int_impl {
111     ($ActualT:ty, $UnsignedT:ty, $BITS:expr,
112      $add_with_overflow:path,
113      $sub_with_overflow:path,
114      $mul_with_overflow:path) => {
115         /// Returns the smallest value that can be represented by this integer type.
116         #[stable(feature = "rust1", since = "1.0.0")]
117         #[inline]
118         pub fn min_value() -> Self {
119             (-1 as Self) << ($BITS - 1)
120         }
121
122         /// Returns the largest value that can be represented by this integer type.
123         #[stable(feature = "rust1", since = "1.0.0")]
124         #[inline]
125         pub fn max_value() -> Self {
126             let min = Self::min_value(); !min
127         }
128
129         /// Converts a string slice in a given base to an integer.
130         ///
131         /// Leading and trailing whitespace represent an error.
132         ///
133         /// # Examples
134         ///
135         /// ```
136         /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
137         /// ```
138         #[stable(feature = "rust1", since = "1.0.0")]
139         #[allow(deprecated)]
140         pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
141             from_str_radix(src, radix)
142         }
143
144         /// Returns the number of ones in the binary representation of `self`.
145         ///
146         /// # Examples
147         ///
148         /// ```rust
149         /// let n = 0b01001100u8;
150         ///
151         /// assert_eq!(n.count_ones(), 3);
152         /// ```
153         #[stable(feature = "rust1", since = "1.0.0")]
154         #[inline]
155         pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
156
157         /// Returns the number of zeros in the binary representation of `self`.
158         ///
159         /// # Examples
160         ///
161         /// ```rust
162         /// let n = 0b01001100u8;
163         ///
164         /// assert_eq!(n.count_zeros(), 5);
165         /// ```
166         #[stable(feature = "rust1", since = "1.0.0")]
167         #[inline]
168         pub fn count_zeros(self) -> u32 {
169             (!self).count_ones()
170         }
171
172         /// Returns the number of leading zeros in the binary representation
173         /// of `self`.
174         ///
175         /// # Examples
176         ///
177         /// ```rust
178         /// let n = 0b0101000u16;
179         ///
180         /// assert_eq!(n.leading_zeros(), 10);
181         /// ```
182         #[stable(feature = "rust1", since = "1.0.0")]
183         #[inline]
184         pub fn leading_zeros(self) -> u32 {
185             (self as $UnsignedT).leading_zeros()
186         }
187
188         /// Returns the number of trailing zeros in the binary representation
189         /// of `self`.
190         ///
191         /// # Examples
192         ///
193         /// ```rust
194         /// let n = 0b0101000u16;
195         ///
196         /// assert_eq!(n.trailing_zeros(), 3);
197         /// ```
198         #[stable(feature = "rust1", since = "1.0.0")]
199         #[inline]
200         pub fn trailing_zeros(self) -> u32 {
201             (self as $UnsignedT).trailing_zeros()
202         }
203
204         /// Shifts the bits to the left by a specified amount, `n`,
205         /// wrapping the truncated bits to the end of the resulting integer.
206         ///
207         /// # Examples
208         ///
209         /// ```rust
210         /// let n = 0x0123456789ABCDEFu64;
211         /// let m = 0x3456789ABCDEF012u64;
212         ///
213         /// assert_eq!(n.rotate_left(12), m);
214         /// ```
215         #[stable(feature = "rust1", since = "1.0.0")]
216         #[inline]
217         pub fn rotate_left(self, n: u32) -> Self {
218             (self as $UnsignedT).rotate_left(n) as Self
219         }
220
221         /// Shifts the bits to the right by a specified amount, `n`,
222         /// wrapping the truncated bits to the beginning of the resulting
223         /// integer.
224         ///
225         /// # Examples
226         ///
227         /// ```rust
228         /// let n = 0x0123456789ABCDEFu64;
229         /// let m = 0xDEF0123456789ABCu64;
230         ///
231         /// assert_eq!(n.rotate_right(12), m);
232         /// ```
233         #[stable(feature = "rust1", since = "1.0.0")]
234         #[inline]
235         pub fn rotate_right(self, n: u32) -> Self {
236             (self as $UnsignedT).rotate_right(n) as Self
237         }
238
239         /// Reverses the byte order of the integer.
240         ///
241         /// # Examples
242         ///
243         /// ```rust
244         /// let n = 0x0123456789ABCDEFu64;
245         /// let m = 0xEFCDAB8967452301u64;
246         ///
247         /// assert_eq!(n.swap_bytes(), m);
248         /// ```
249         #[stable(feature = "rust1", since = "1.0.0")]
250         #[inline]
251         pub fn swap_bytes(self) -> Self {
252             (self as $UnsignedT).swap_bytes() as Self
253         }
254
255         /// Converts an integer from big endian to the target's endianness.
256         ///
257         /// On big endian this is a no-op. On little endian the bytes are
258         /// swapped.
259         ///
260         /// # Examples
261         ///
262         /// ```rust
263         /// let n = 0x0123456789ABCDEFu64;
264         ///
265         /// if cfg!(target_endian = "big") {
266         ///     assert_eq!(u64::from_be(n), n)
267         /// } else {
268         ///     assert_eq!(u64::from_be(n), n.swap_bytes())
269         /// }
270         /// ```
271         #[stable(feature = "rust1", since = "1.0.0")]
272         #[inline]
273         pub fn from_be(x: Self) -> Self {
274             if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
275         }
276
277         /// Converts an integer from little endian to the target's endianness.
278         ///
279         /// On little endian this is a no-op. On big endian the bytes are
280         /// swapped.
281         ///
282         /// # Examples
283         ///
284         /// ```rust
285         /// let n = 0x0123456789ABCDEFu64;
286         ///
287         /// if cfg!(target_endian = "little") {
288         ///     assert_eq!(u64::from_le(n), n)
289         /// } else {
290         ///     assert_eq!(u64::from_le(n), n.swap_bytes())
291         /// }
292         /// ```
293         #[stable(feature = "rust1", since = "1.0.0")]
294         #[inline]
295         pub fn from_le(x: Self) -> Self {
296             if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
297         }
298
299         /// Converts `self` to big endian from the target's endianness.
300         ///
301         /// On big endian this is a no-op. On little endian the bytes are
302         /// swapped.
303         ///
304         /// # Examples
305         ///
306         /// ```rust
307         /// let n = 0x0123456789ABCDEFu64;
308         ///
309         /// if cfg!(target_endian = "big") {
310         ///     assert_eq!(n.to_be(), n)
311         /// } else {
312         ///     assert_eq!(n.to_be(), n.swap_bytes())
313         /// }
314         /// ```
315         #[stable(feature = "rust1", since = "1.0.0")]
316         #[inline]
317         pub fn to_be(self) -> Self { // or not to be?
318             if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
319         }
320
321         /// Converts `self` to little endian from the target's endianness.
322         ///
323         /// On little endian this is a no-op. On big endian the bytes are
324         /// swapped.
325         ///
326         /// # Examples
327         ///
328         /// ```rust
329         /// let n = 0x0123456789ABCDEFu64;
330         ///
331         /// if cfg!(target_endian = "little") {
332         ///     assert_eq!(n.to_le(), n)
333         /// } else {
334         ///     assert_eq!(n.to_le(), n.swap_bytes())
335         /// }
336         /// ```
337         #[stable(feature = "rust1", since = "1.0.0")]
338         #[inline]
339         pub fn to_le(self) -> Self {
340             if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
341         }
342
343         /// Checked integer addition. Computes `self + other`, returning `None`
344         /// if overflow occurred.
345         ///
346         /// # Examples
347         ///
348         /// ```rust
349         /// assert_eq!(5u16.checked_add(65530), Some(65535));
350         /// assert_eq!(6u16.checked_add(65530), None);
351         /// ```
352         #[stable(feature = "rust1", since = "1.0.0")]
353         #[inline]
354         pub fn checked_add(self, other: Self) -> Option<Self> {
355             checked_op!($ActualT, $add_with_overflow, self, other)
356         }
357
358         /// Checked integer subtraction. Computes `self - other`, returning
359         /// `None` if underflow occurred.
360         ///
361         /// # Examples
362         ///
363         /// ```rust
364         /// assert_eq!((-127i8).checked_sub(1), Some(-128));
365         /// assert_eq!((-128i8).checked_sub(1), None);
366         /// ```
367         #[stable(feature = "rust1", since = "1.0.0")]
368         #[inline]
369         pub fn checked_sub(self, other: Self) -> Option<Self> {
370             checked_op!($ActualT, $sub_with_overflow, self, other)
371         }
372
373         /// Checked integer multiplication. Computes `self * other`, returning
374         /// `None` if underflow or overflow occurred.
375         ///
376         /// # Examples
377         ///
378         /// ```rust
379         /// assert_eq!(5u8.checked_mul(51), Some(255));
380         /// assert_eq!(5u8.checked_mul(52), None);
381         /// ```
382         #[stable(feature = "rust1", since = "1.0.0")]
383         #[inline]
384         pub fn checked_mul(self, other: Self) -> Option<Self> {
385             checked_op!($ActualT, $mul_with_overflow, self, other)
386         }
387
388         /// Checked integer division. Computes `self / other`, returning `None`
389         /// if `other == 0` or the operation results in underflow or overflow.
390         ///
391         /// # Examples
392         ///
393         /// ```rust
394         /// assert_eq!((-127i8).checked_div(-1), Some(127));
395         /// assert_eq!((-128i8).checked_div(-1), None);
396         /// assert_eq!((1i8).checked_div(0), None);
397         /// ```
398         #[stable(feature = "rust1", since = "1.0.0")]
399         #[inline]
400         pub fn checked_div(self, v: Self) -> Option<Self> {
401             match v {
402                 0   => None,
403                -1 if self == Self::min_value()
404                     => None,
405                 v   => Some(self / v),
406             }
407         }
408
409         /// Saturating integer addition. Computes `self + other`, saturating at
410         /// the numeric bounds instead of overflowing.
411         #[stable(feature = "rust1", since = "1.0.0")]
412         #[inline]
413         pub fn saturating_add(self, other: Self) -> Self {
414             match self.checked_add(other) {
415                 Some(x)                       => x,
416                 None if other >= Self::zero() => Self::max_value(),
417                 None => Self::min_value(),
418             }
419         }
420
421         /// Saturating integer subtraction. Computes `self - other`, saturating
422         /// at the numeric bounds instead of overflowing.
423         #[stable(feature = "rust1", since = "1.0.0")]
424         #[inline]
425         pub fn saturating_sub(self, other: Self) -> Self {
426             match self.checked_sub(other) {
427                 Some(x)                      => x,
428                 None if other >= Self::zero() => Self::min_value(),
429                 None => Self::max_value(),
430             }
431         }
432
433         /// Wrapping (modular) addition. Computes `self + other`,
434         /// wrapping around at the boundary of the type.
435         #[stable(feature = "rust1", since = "1.0.0")]
436         #[inline]
437         pub fn wrapping_add(self, rhs: Self) -> Self {
438             unsafe {
439                 intrinsics::overflowing_add(self, rhs)
440             }
441         }
442
443         /// Wrapping (modular) subtraction. Computes `self - other`,
444         /// wrapping around at the boundary of the type.
445         #[stable(feature = "rust1", since = "1.0.0")]
446         #[inline]
447         pub fn wrapping_sub(self, rhs: Self) -> Self {
448             unsafe {
449                 intrinsics::overflowing_sub(self, rhs)
450             }
451         }
452
453         /// Wrapping (modular) multiplication. Computes `self *
454         /// other`, wrapping around at the boundary of the type.
455         #[stable(feature = "rust1", since = "1.0.0")]
456         #[inline]
457         pub fn wrapping_mul(self, rhs: Self) -> Self {
458             unsafe {
459                 intrinsics::overflowing_mul(self, rhs)
460             }
461         }
462
463         /// Wrapping (modular) division. Computes `self / other`,
464         /// wrapping around at the boundary of the type.
465         ///
466         /// The only case where such wrapping can occur is when one
467         /// divides `MIN / -1` on a signed type (where `MIN` is the
468         /// negative minimal value for the type); this is equivalent
469         /// to `-MIN`, a positive value that is too large to represent
470         /// in the type. In such a case, this function returns `MIN`
471         /// itself.
472         #[stable(feature = "num_wrapping", since = "1.2.0")]
473         #[inline(always)]
474         pub fn wrapping_div(self, rhs: Self) -> Self {
475             self.overflowing_div(rhs).0
476         }
477
478         /// Wrapping (modular) remainder. Computes `self % other`,
479         /// wrapping around at the boundary of the type.
480         ///
481         /// Such wrap-around never actually occurs mathematically;
482         /// implementation artifacts make `x % y` illegal for `MIN /
483         /// -1` on a signed type illegal (where `MIN` is the negative
484         /// minimal value). In such a case, this function returns `0`.
485         #[stable(feature = "num_wrapping", since = "1.2.0")]
486         #[inline(always)]
487         pub fn wrapping_rem(self, rhs: Self) -> Self {
488             self.overflowing_rem(rhs).0
489         }
490
491         /// Wrapping (modular) negation. Computes `-self`,
492         /// wrapping around at the boundary of the type.
493         ///
494         /// The only case where such wrapping can occur is when one
495         /// negates `MIN` on a signed type (where `MIN` is the
496         /// negative minimal value for the type); this is a positive
497         /// value that is too large to represent in the type. In such
498         /// a case, this function returns `MIN` itself.
499         #[stable(feature = "num_wrapping", since = "1.2.0")]
500         #[inline(always)]
501         pub fn wrapping_neg(self) -> Self {
502             self.overflowing_neg().0
503         }
504
505         /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
506         /// where `mask` removes any high-order bits of `rhs` that
507         /// would cause the shift to exceed the bitwidth of the type.
508         #[stable(feature = "num_wrapping", since = "1.2.0")]
509         #[inline(always)]
510         pub fn wrapping_shl(self, rhs: u32) -> Self {
511             self.overflowing_shl(rhs).0
512         }
513
514         /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
515         /// where `mask` removes any high-order bits of `rhs` that
516         /// would cause the shift to exceed the bitwidth of the type.
517         #[stable(feature = "num_wrapping", since = "1.2.0")]
518         #[inline(always)]
519         pub fn wrapping_shr(self, rhs: u32) -> Self {
520             self.overflowing_shr(rhs).0
521         }
522
523         /// Raises self to the power of `exp`, using exponentiation by squaring.
524         ///
525         /// # Examples
526         ///
527         /// ```
528         /// let x: i32 = 2; // or any other integer type
529         ///
530         /// assert_eq!(x.pow(4), 16);
531         /// ```
532         #[stable(feature = "rust1", since = "1.0.0")]
533         #[inline]
534         pub fn pow(self, mut exp: u32) -> Self {
535             let mut base = self;
536             let mut acc = Self::one();
537
538             let mut prev_base = self;
539             let mut base_oflo = false;
540             while exp > 0 {
541                 if (exp & 1) == 1 {
542                     if base_oflo {
543                         // ensure overflow occurs in the same manner it
544                         // would have otherwise (i.e. signal any exception
545                         // it would have otherwise).
546                         acc = acc * (prev_base * prev_base);
547                     } else {
548                         acc = acc * base;
549                     }
550                 }
551                 prev_base = base;
552                 let (new_base, new_base_oflo) = base.overflowing_mul(base);
553                 base = new_base;
554                 base_oflo = new_base_oflo;
555                 exp /= 2;
556             }
557             acc
558         }
559
560         /// Computes the absolute value of `self`.
561         ///
562         /// # Overflow behavior
563         ///
564         /// The absolute value of `i32::min_value()` cannot be represented as an
565         /// `i32`, and attempting to calculate it will cause an overflow. This
566         /// means that code in debug mode will trigger a panic on this case and
567         /// optimized code will return `i32::min_value()` without a panic.
568         #[stable(feature = "rust1", since = "1.0.0")]
569         #[inline]
570         pub fn abs(self) -> Self {
571             if self.is_negative() {
572                 // Note that the #[inline] above means that the overflow
573                 // semantics of this negation depend on the crate we're being
574                 // inlined into.
575                 -self
576             } else {
577                 self
578             }
579         }
580
581         /// Returns a number representing sign of `self`.
582         ///
583         /// - `0` if the number is zero
584         /// - `1` if the number is positive
585         /// - `-1` if the number is negative
586         #[stable(feature = "rust1", since = "1.0.0")]
587         #[inline]
588         pub fn signum(self) -> Self {
589             match self {
590                 n if n > 0 =>  1,
591                 0          =>  0,
592                 _          => -1,
593             }
594         }
595
596         /// Returns `true` if `self` is positive and `false` if the number
597         /// is zero or negative.
598         #[stable(feature = "rust1", since = "1.0.0")]
599         #[inline]
600         pub fn is_positive(self) -> bool { self > 0 }
601
602         /// Returns `true` if `self` is negative and `false` if the number
603         /// is zero or positive.
604         #[stable(feature = "rust1", since = "1.0.0")]
605         #[inline]
606         pub fn is_negative(self) -> bool { self < 0 }
607     }
608 }
609
610 #[lang = "i8"]
611 impl i8 {
612     int_impl! { i8, u8, 8,
613         intrinsics::i8_add_with_overflow,
614         intrinsics::i8_sub_with_overflow,
615         intrinsics::i8_mul_with_overflow }
616 }
617
618 #[lang = "i16"]
619 impl i16 {
620     int_impl! { i16, u16, 16,
621         intrinsics::i16_add_with_overflow,
622         intrinsics::i16_sub_with_overflow,
623         intrinsics::i16_mul_with_overflow }
624 }
625
626 #[lang = "i32"]
627 impl i32 {
628     int_impl! { i32, u32, 32,
629         intrinsics::i32_add_with_overflow,
630         intrinsics::i32_sub_with_overflow,
631         intrinsics::i32_mul_with_overflow }
632 }
633
634 #[lang = "i64"]
635 impl i64 {
636     int_impl! { i64, u64, 64,
637         intrinsics::i64_add_with_overflow,
638         intrinsics::i64_sub_with_overflow,
639         intrinsics::i64_mul_with_overflow }
640 }
641
642 #[cfg(target_pointer_width = "32")]
643 #[lang = "isize"]
644 impl isize {
645     int_impl! { i32, u32, 32,
646         intrinsics::i32_add_with_overflow,
647         intrinsics::i32_sub_with_overflow,
648         intrinsics::i32_mul_with_overflow }
649 }
650
651 #[cfg(target_pointer_width = "64")]
652 #[lang = "isize"]
653 impl isize {
654     int_impl! { i64, u64, 64,
655         intrinsics::i64_add_with_overflow,
656         intrinsics::i64_sub_with_overflow,
657         intrinsics::i64_mul_with_overflow }
658 }
659
660 // `Int` + `UnsignedInt` implemented for signed integers
661 macro_rules! uint_impl {
662     ($ActualT:ty, $BITS:expr,
663      $ctpop:path,
664      $ctlz:path,
665      $cttz:path,
666      $bswap:path,
667      $add_with_overflow:path,
668      $sub_with_overflow:path,
669      $mul_with_overflow:path) => {
670         /// Returns the smallest value that can be represented by this integer type.
671         #[stable(feature = "rust1", since = "1.0.0")]
672         #[inline]
673         pub fn min_value() -> Self { 0 }
674
675         /// Returns the largest value that can be represented by this integer type.
676         #[stable(feature = "rust1", since = "1.0.0")]
677         #[inline]
678         pub fn max_value() -> Self { !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<Self, 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) -> Self {
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) -> Self {
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) -> Self {
826             unsafe { $bswap(self as $ActualT) as Self }
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: Self) -> Self {
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: Self) -> Self {
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) -> Self { // 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) -> Self {
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: Self) -> Option<Self> {
929             checked_op!($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: Self) -> Option<Self> {
944             checked_op!($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: Self) -> Option<Self> {
959             checked_op!($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: Self) -> Option<Self> {
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: Self) -> Self {
986             match self.checked_add(other) {
987                 Some(x)                       => x,
988                 None if other >= Self::zero() => Self::max_value(),
989                 None => Self::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: Self) -> Self {
998             match self.checked_sub(other) {
999                 Some(x)                       => x,
1000                 None if other >= Self::zero() => Self::min_value(),
1001                 None => Self::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: Self) -> Self {
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: Self) -> Self {
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: Self) -> Self {
1030             unsafe {
1031                 intrinsics::overflowing_mul(self, rhs)
1032             }
1033         }
1034
1035         /// Wrapping (modular) division. Computes `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         #[stable(feature = "num_wrapping", since = "1.2.0")]
1045         #[inline(always)]
1046         pub fn wrapping_div(self, rhs: Self) -> Self {
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         #[stable(feature = "num_wrapping", since = "1.2.0")]
1058         #[inline(always)]
1059         pub fn wrapping_rem(self, rhs: Self) -> Self {
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         #[stable(feature = "num_wrapping", since = "1.2.0")]
1072         #[inline(always)]
1073         pub fn wrapping_neg(self) -> Self {
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         #[stable(feature = "num_wrapping", since = "1.2.0")]
1081         #[inline(always)]
1082         pub fn wrapping_shl(self, rhs: u32) -> Self {
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         #[stable(feature = "num_wrapping", since = "1.2.0")]
1090         #[inline(always)]
1091         pub fn wrapping_shr(self, rhs: u32) -> Self {
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) -> Self {
1105             let mut base = self;
1106             let mut acc = Self::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` if and only if `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(Self::one())) & self == Self::zero() &&
1135                 !(self == Self::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) -> Self {
1143             let bits = size_of::<Self>() * 8;
1144             let one: Self = Self::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<Self> {
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, 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, 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, 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, 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! { 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! { 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 #[unstable(feature = "core_float",
1266            reason = "stable interface is via `impl f{32,64}` in later crates")]
1267 pub trait Float {
1268     /// Returns the NaN value.
1269     fn nan() -> Self;
1270     /// Returns the infinite value.
1271     fn infinity() -> Self;
1272     /// Returns the negative infinite value.
1273     fn neg_infinity() -> Self;
1274     /// Returns -0.0.
1275     fn neg_zero() -> Self;
1276     /// Returns 0.0.
1277     fn zero() -> Self;
1278     /// Returns 1.0.
1279     fn one() -> Self;
1280     /// Parses the string `s` with the radix `r` as a float.
1281     fn from_str_radix(s: &str, r: u32) -> Result<Self, ParseFloatError>;
1282
1283     /// Returns true if this value is NaN and false otherwise.
1284     fn is_nan(self) -> bool;
1285     /// Returns true if this value is positive infinity or negative infinity and
1286     /// false otherwise.
1287     fn is_infinite(self) -> bool;
1288     /// Returns true if this number is neither infinite nor NaN.
1289     fn is_finite(self) -> bool;
1290     /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1291     fn is_normal(self) -> bool;
1292     /// Returns the category that this number falls into.
1293     fn classify(self) -> FpCategory;
1294
1295     /// Returns the mantissa, exponent and sign as integers, respectively.
1296     fn integer_decode(self) -> (u64, i16, i8);
1297
1298     /// Return the largest integer less than or equal to a number.
1299     fn floor(self) -> Self;
1300     /// Return the smallest integer greater than or equal to a number.
1301     fn ceil(self) -> Self;
1302     /// Return the nearest integer to a number. Round half-way cases away from
1303     /// `0.0`.
1304     fn round(self) -> Self;
1305     /// Return the integer part of a number.
1306     fn trunc(self) -> Self;
1307     /// Return the fractional part of a number.
1308     fn fract(self) -> Self;
1309
1310     /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1311     /// number is `Float::nan()`.
1312     fn abs(self) -> Self;
1313     /// Returns a number that represents the sign of `self`.
1314     ///
1315     /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1316     /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1317     /// - `Float::nan()` if the number is `Float::nan()`
1318     fn signum(self) -> Self;
1319     /// Returns `true` if `self` is positive, including `+0.0` and
1320     /// `Float::infinity()`.
1321     fn is_positive(self) -> bool;
1322     /// Returns `true` if `self` is negative, including `-0.0` and
1323     /// `Float::neg_infinity()`.
1324     fn is_negative(self) -> bool;
1325
1326     /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1327     /// error. This produces a more accurate result with better performance than
1328     /// a separate multiplication operation followed by an add.
1329     fn mul_add(self, a: Self, b: Self) -> Self;
1330     /// Take the reciprocal (inverse) of a number, `1/x`.
1331     fn recip(self) -> Self;
1332
1333     /// Raise a number to an integer power.
1334     ///
1335     /// Using this function is generally faster than using `powf`
1336     fn powi(self, n: i32) -> Self;
1337     /// Raise a number to a floating point power.
1338     fn powf(self, n: Self) -> Self;
1339
1340     /// Take the square root of a number.
1341     ///
1342     /// Returns NaN if `self` is a negative number.
1343     fn sqrt(self) -> Self;
1344     /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1345     fn rsqrt(self) -> Self;
1346
1347     /// Returns `e^(self)`, (the exponential function).
1348     fn exp(self) -> Self;
1349     /// Returns 2 raised to the power of the number, `2^(self)`.
1350     fn exp2(self) -> Self;
1351     /// Returns the natural logarithm of the number.
1352     fn ln(self) -> Self;
1353     /// Returns the logarithm of the number with respect to an arbitrary base.
1354     fn log(self, base: Self) -> Self;
1355     /// Returns the base 2 logarithm of the number.
1356     fn log2(self) -> Self;
1357     /// Returns the base 10 logarithm of the number.
1358     fn log10(self) -> Self;
1359
1360     /// Convert radians to degrees.
1361     fn to_degrees(self) -> Self;
1362     /// Convert degrees to radians.
1363     fn to_radians(self) -> Self;
1364 }
1365
1366 macro_rules! from_str_float_impl {
1367     ($t:ty) => {
1368         #[stable(feature = "rust1", since = "1.0.0")]
1369         impl FromStr for $t {
1370             type Err = ParseFloatError;
1371
1372             /// Converts a string in base 10 to a float.
1373             /// Accepts an optional decimal exponent.
1374             ///
1375             /// This function accepts strings such as
1376             ///
1377             /// * '3.14'
1378             /// * '-3.14'
1379             /// * '2.5E10', or equivalently, '2.5e10'
1380             /// * '2.5E-10'
1381             /// * '.' (understood as 0)
1382             /// * '5.'
1383             /// * '.5', or, equivalently,  '0.5'
1384             /// * 'inf', '-inf', 'NaN'
1385             ///
1386             /// Leading and trailing whitespace represent an error.
1387             ///
1388             /// # Arguments
1389             ///
1390             /// * src - A string
1391             ///
1392             /// # Return value
1393             ///
1394             /// `Err(ParseFloatError)` if the string did not represent a valid
1395             /// number.  Otherwise, `Ok(n)` where `n` is the floating-point
1396             /// number represented by `src`.
1397             #[inline]
1398             #[allow(deprecated)]
1399             fn from_str(src: &str) -> Result<Self, ParseFloatError> {
1400                 Self::from_str_radix(src, 10)
1401             }
1402         }
1403     }
1404 }
1405 from_str_float_impl!(f32);
1406 from_str_float_impl!(f64);
1407
1408 macro_rules! from_str_radix_int_impl {
1409     ($($t:ty)*) => {$(
1410         #[stable(feature = "rust1", since = "1.0.0")]
1411         #[allow(deprecated)]
1412         impl FromStr for $t {
1413             type Err = ParseIntError;
1414             fn from_str(src: &str) -> Result<Self, ParseIntError> {
1415                 from_str_radix(src, 10)
1416             }
1417         }
1418     )*}
1419 }
1420 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
1421
1422 #[doc(hidden)]
1423 trait FromStrRadixHelper: PartialOrd + Copy {
1424     fn min_value() -> Self;
1425     fn from_u32(u: u32) -> Self;
1426     fn checked_mul(&self, other: u32) -> Option<Self>;
1427     fn checked_sub(&self, other: u32) -> Option<Self>;
1428     fn checked_add(&self, other: u32) -> Option<Self>;
1429 }
1430
1431 macro_rules! doit {
1432     ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
1433         fn min_value() -> Self { Self::min_value() }
1434         fn from_u32(u: u32) -> Self { u as Self }
1435         fn checked_mul(&self, other: u32) -> Option<Self> {
1436             Self::checked_mul(*self, other as Self)
1437         }
1438         fn checked_sub(&self, other: u32) -> Option<Self> {
1439             Self::checked_sub(*self, other as Self)
1440         }
1441         fn checked_add(&self, other: u32) -> Option<Self> {
1442             Self::checked_add(*self, other as Self)
1443         }
1444     })*)
1445 }
1446 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1447
1448 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
1449                                          -> Result<T, ParseIntError> {
1450     use self::IntErrorKind::*;
1451     use self::ParseIntError as PIE;
1452
1453     assert!(radix >= 2 && radix <= 36,
1454            "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1455            radix);
1456
1457     if src.is_empty() {
1458         return Err(PIE { kind: Empty });
1459     }
1460
1461     let is_signed_ty = T::from_u32(0) > T::min_value();
1462
1463     // all valid digits are ascii, so we will just iterate over the utf8 bytes
1464     // and cast them to chars. .to_digit() will safely return None for anything
1465     // other than a valid ascii digit for a the given radix, including the first-byte
1466     // of multi-byte sequences
1467     let src = src.as_bytes();
1468
1469     match (src[0], &src[1..])  {
1470         (b'-', digits) if digits.is_empty() => Err(PIE { kind: Empty }),
1471         (b'-', digits) if is_signed_ty => {
1472             // The number is negative
1473             let mut result = T::from_u32(0);
1474             for &c in digits {
1475                 let x = match (c as char).to_digit(radix) {
1476                     Some(x) => x,
1477                     None => return Err(PIE { kind: InvalidDigit }),
1478                 };
1479                 result = match result.checked_mul(radix) {
1480                     Some(result) => result,
1481                     None => return Err(PIE { kind: Underflow }),
1482                 };
1483                 result = match result.checked_sub(x) {
1484                     Some(result) => result,
1485                     None => return Err(PIE { kind: Underflow }),
1486                 };
1487             }
1488             Ok(result)
1489         },
1490         (c, digits) => {
1491             // The number is signed
1492             let mut result = match (c as char).to_digit(radix) {
1493                 Some(x) => T::from_u32(x),
1494                 None => return Err(PIE { kind: InvalidDigit }),
1495             };
1496             for &c in digits {
1497                 let x = match (c as char).to_digit(radix) {
1498                     Some(x) => x,
1499                     None => return Err(PIE { kind: InvalidDigit }),
1500                 };
1501                 result = match result.checked_mul(radix) {
1502                     Some(result) => result,
1503                     None => return Err(PIE { kind: Overflow }),
1504                 };
1505                 result = match result.checked_add(x) {
1506                     Some(result) => result,
1507                     None => return Err(PIE { kind: Overflow }),
1508                 };
1509             }
1510             Ok(result)
1511         }
1512     }
1513 }
1514
1515 /// An error which can be returned when parsing an integer.
1516 #[derive(Debug, Clone, PartialEq)]
1517 #[stable(feature = "rust1", since = "1.0.0")]
1518 pub struct ParseIntError { kind: IntErrorKind }
1519
1520 #[derive(Debug, Clone, PartialEq)]
1521 enum IntErrorKind {
1522     Empty,
1523     InvalidDigit,
1524     Overflow,
1525     Underflow,
1526 }
1527
1528 impl ParseIntError {
1529     #[unstable(feature = "int_error_internals",
1530                reason = "available through Error trait and this method should \
1531                          not be exposed publicly")]
1532     #[doc(hidden)]
1533     pub fn __description(&self) -> &str {
1534         match self.kind {
1535             IntErrorKind::Empty => "cannot parse integer from empty string",
1536             IntErrorKind::InvalidDigit => "invalid digit found in string",
1537             IntErrorKind::Overflow => "number too large to fit in target type",
1538             IntErrorKind::Underflow => "number too small to fit in target type",
1539         }
1540     }
1541 }
1542
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 impl fmt::Display for ParseIntError {
1545     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1546         self.__description().fmt(f)
1547     }
1548 }
1549
1550 /// An error which can be returned when parsing a float.
1551 #[derive(Debug, Clone, PartialEq)]
1552 #[stable(feature = "rust1", since = "1.0.0")]
1553 pub struct ParseFloatError {
1554     #[doc(hidden)]
1555     #[unstable(feature = "float_error_internals",
1556                reason = "should not be exposed publicly")]
1557     pub __kind: FloatErrorKind
1558 }
1559
1560 #[derive(Debug, Clone, PartialEq)]
1561 #[unstable(feature = "float_error_internals",
1562            reason = "should not be exposed publicly")]
1563 #[doc(hidden)]
1564 pub enum FloatErrorKind {
1565     Empty,
1566     Invalid,
1567 }
1568
1569 impl ParseFloatError {
1570     #[doc(hidden)]
1571     pub fn __description(&self) -> &str {
1572         match self.__kind {
1573             FloatErrorKind::Empty => "cannot parse float from empty string",
1574             FloatErrorKind::Invalid => "invalid float literal",
1575         }
1576     }
1577 }
1578
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 impl fmt::Display for ParseFloatError {
1581     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1582         self.__description().fmt(f)
1583     }
1584 }