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