]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
core: Split apart the global `core` feature
[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 `floor(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         #[unstable(feature = "num_wrapping")]
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         #[unstable(feature = "num_wrapping")]
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         #[unstable(feature = "num_wrapping")]
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         #[unstable(feature = "num_wrapping")]
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         #[unstable(feature = "num_wrapping")]
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         pub fn min_value() -> Self { 0 }
672
673         /// Returns the largest value that can be represented by this integer type.
674         #[stable(feature = "rust1", since = "1.0.0")]
675         pub fn max_value() -> Self { !0 }
676
677         /// Converts a string slice in a given base to an integer.
678         ///
679         /// Leading and trailing whitespace represent an error.
680         ///
681         /// # Arguments
682         ///
683         /// * src - A string slice
684         /// * radix - The base to use. Must lie in the range [2 .. 36]
685         ///
686         /// # Return value
687         ///
688         /// `Err(ParseIntError)` if the string did not represent a valid number.
689         /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
690         #[stable(feature = "rust1", since = "1.0.0")]
691         #[allow(deprecated)]
692         pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
693             from_str_radix(src, radix)
694         }
695
696         /// Returns the number of ones in the binary representation of `self`.
697         ///
698         /// # Examples
699         ///
700         /// ```rust
701         /// let n = 0b01001100u8;
702         ///
703         /// assert_eq!(n.count_ones(), 3);
704         /// ```
705         #[stable(feature = "rust1", since = "1.0.0")]
706         #[inline]
707         pub fn count_ones(self) -> u32 {
708             unsafe { $ctpop(self as $ActualT) as u32 }
709         }
710
711         /// Returns the number of zeros in the binary representation of `self`.
712         ///
713         /// # Examples
714         ///
715         /// ```rust
716         /// let n = 0b01001100u8;
717         ///
718         /// assert_eq!(n.count_zeros(), 5);
719         /// ```
720         #[stable(feature = "rust1", since = "1.0.0")]
721         #[inline]
722         pub fn count_zeros(self) -> u32 {
723             (!self).count_ones()
724         }
725
726         /// Returns the number of leading zeros in the binary representation
727         /// of `self`.
728         ///
729         /// # Examples
730         ///
731         /// ```rust
732         /// let n = 0b0101000u16;
733         ///
734         /// assert_eq!(n.leading_zeros(), 10);
735         /// ```
736         #[stable(feature = "rust1", since = "1.0.0")]
737         #[inline]
738         pub fn leading_zeros(self) -> u32 {
739             unsafe { $ctlz(self as $ActualT) as u32 }
740         }
741
742         /// Returns the number of trailing zeros in the binary representation
743         /// of `self`.
744         ///
745         /// # Examples
746         ///
747         /// ```rust
748         /// let n = 0b0101000u16;
749         ///
750         /// assert_eq!(n.trailing_zeros(), 3);
751         /// ```
752         #[stable(feature = "rust1", since = "1.0.0")]
753         #[inline]
754         pub fn trailing_zeros(self) -> u32 {
755             // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
756             // emits two conditional moves on x86_64. By promoting the value to
757             // u16 and setting bit 8, we get better code without any conditional
758             // operations.
759             // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
760             // pending, remove this workaround once LLVM generates better code
761             // for cttz8.
762             unsafe {
763                 if $BITS == 8 {
764                     intrinsics::cttz16(self as u16 | 0x100) as u32
765                 } else {
766                     $cttz(self as $ActualT) as u32
767                 }
768             }
769         }
770
771         /// Shifts the bits to the left by a specified amount, `n`,
772         /// wrapping the truncated bits to the end of the resulting integer.
773         ///
774         /// # Examples
775         ///
776         /// ```rust
777         /// let n = 0x0123456789ABCDEFu64;
778         /// let m = 0x3456789ABCDEF012u64;
779         ///
780         /// assert_eq!(n.rotate_left(12), m);
781         /// ```
782         #[stable(feature = "rust1", since = "1.0.0")]
783         #[inline]
784         pub fn rotate_left(self, n: u32) -> Self {
785             // Protect against undefined behaviour for over-long bit shifts
786             let n = n % $BITS;
787             (self << n) | (self >> (($BITS - n) % $BITS))
788         }
789
790         /// Shifts the bits to the right by a specified amount, `n`,
791         /// wrapping the truncated bits to the beginning of the resulting
792         /// integer.
793         ///
794         /// # Examples
795         ///
796         /// ```rust
797         /// let n = 0x0123456789ABCDEFu64;
798         /// let m = 0xDEF0123456789ABCu64;
799         ///
800         /// assert_eq!(n.rotate_right(12), m);
801         /// ```
802         #[stable(feature = "rust1", since = "1.0.0")]
803         #[inline]
804         pub fn rotate_right(self, n: u32) -> Self {
805             // Protect against undefined behaviour for over-long bit shifts
806             let n = n % $BITS;
807             (self >> n) | (self << (($BITS - n) % $BITS))
808         }
809
810         /// Reverses the byte order of the integer.
811         ///
812         /// # Examples
813         ///
814         /// ```rust
815         /// let n = 0x0123456789ABCDEFu64;
816         /// let m = 0xEFCDAB8967452301u64;
817         ///
818         /// assert_eq!(n.swap_bytes(), m);
819         /// ```
820         #[stable(feature = "rust1", since = "1.0.0")]
821         #[inline]
822         pub fn swap_bytes(self) -> Self {
823             unsafe { $bswap(self as $ActualT) as Self }
824         }
825
826         /// Converts an integer from big endian to the target's endianness.
827         ///
828         /// On big endian this is a no-op. On little endian the bytes are
829         /// swapped.
830         ///
831         /// # Examples
832         ///
833         /// ```rust
834         /// let n = 0x0123456789ABCDEFu64;
835         ///
836         /// if cfg!(target_endian = "big") {
837         ///     assert_eq!(u64::from_be(n), n)
838         /// } else {
839         ///     assert_eq!(u64::from_be(n), n.swap_bytes())
840         /// }
841         /// ```
842         #[stable(feature = "rust1", since = "1.0.0")]
843         #[inline]
844         pub fn from_be(x: Self) -> Self {
845             if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
846         }
847
848         /// Converts an integer from little endian to the target's endianness.
849         ///
850         /// On little endian this is a no-op. On big endian the bytes are
851         /// swapped.
852         ///
853         /// # Examples
854         ///
855         /// ```rust
856         /// let n = 0x0123456789ABCDEFu64;
857         ///
858         /// if cfg!(target_endian = "little") {
859         ///     assert_eq!(u64::from_le(n), n)
860         /// } else {
861         ///     assert_eq!(u64::from_le(n), n.swap_bytes())
862         /// }
863         /// ```
864         #[stable(feature = "rust1", since = "1.0.0")]
865         #[inline]
866         pub fn from_le(x: Self) -> Self {
867             if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
868         }
869
870         /// Converts `self` to big endian from the target's endianness.
871         ///
872         /// On big endian this is a no-op. On little endian the bytes are
873         /// swapped.
874         ///
875         /// # Examples
876         ///
877         /// ```rust
878         /// let n = 0x0123456789ABCDEFu64;
879         ///
880         /// if cfg!(target_endian = "big") {
881         ///     assert_eq!(n.to_be(), n)
882         /// } else {
883         ///     assert_eq!(n.to_be(), n.swap_bytes())
884         /// }
885         /// ```
886         #[stable(feature = "rust1", since = "1.0.0")]
887         #[inline]
888         pub fn to_be(self) -> Self { // or not to be?
889             if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
890         }
891
892         /// Converts `self` to little endian from the target's endianness.
893         ///
894         /// On little endian this is a no-op. On big endian the bytes are
895         /// swapped.
896         ///
897         /// # Examples
898         ///
899         /// ```rust
900         /// let n = 0x0123456789ABCDEFu64;
901         ///
902         /// if cfg!(target_endian = "little") {
903         ///     assert_eq!(n.to_le(), n)
904         /// } else {
905         ///     assert_eq!(n.to_le(), n.swap_bytes())
906         /// }
907         /// ```
908         #[stable(feature = "rust1", since = "1.0.0")]
909         #[inline]
910         pub fn to_le(self) -> Self {
911             if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
912         }
913
914         /// Checked integer addition. Computes `self + other`, returning `None`
915         /// if overflow occurred.
916         ///
917         /// # Examples
918         ///
919         /// ```rust
920         /// assert_eq!(5u16.checked_add(65530), Some(65535));
921         /// assert_eq!(6u16.checked_add(65530), None);
922         /// ```
923         #[stable(feature = "rust1", since = "1.0.0")]
924         #[inline]
925         pub fn checked_add(self, other: Self) -> Option<Self> {
926             checked_op!($ActualT, $add_with_overflow, self, other)
927         }
928
929         /// Checked integer subtraction. Computes `self - other`, returning
930         /// `None` if underflow occurred.
931         ///
932         /// # Examples
933         ///
934         /// ```rust
935         /// assert_eq!((-127i8).checked_sub(1), Some(-128));
936         /// assert_eq!((-128i8).checked_sub(1), None);
937         /// ```
938         #[stable(feature = "rust1", since = "1.0.0")]
939         #[inline]
940         pub fn checked_sub(self, other: Self) -> Option<Self> {
941             checked_op!($ActualT, $sub_with_overflow, self, other)
942         }
943
944         /// Checked integer multiplication. Computes `self * other`, returning
945         /// `None` if underflow or overflow occurred.
946         ///
947         /// # Examples
948         ///
949         /// ```rust
950         /// assert_eq!(5u8.checked_mul(51), Some(255));
951         /// assert_eq!(5u8.checked_mul(52), None);
952         /// ```
953         #[stable(feature = "rust1", since = "1.0.0")]
954         #[inline]
955         pub fn checked_mul(self, other: Self) -> Option<Self> {
956             checked_op!($ActualT, $mul_with_overflow, self, other)
957         }
958
959         /// Checked integer division. Computes `self / other`, returning `None`
960         /// if `other == 0` or the operation results in underflow or overflow.
961         ///
962         /// # Examples
963         ///
964         /// ```rust
965         /// assert_eq!((-127i8).checked_div(-1), Some(127));
966         /// assert_eq!((-128i8).checked_div(-1), None);
967         /// assert_eq!((1i8).checked_div(0), None);
968         /// ```
969         #[stable(feature = "rust1", since = "1.0.0")]
970         #[inline]
971         pub fn checked_div(self, v: Self) -> Option<Self> {
972             match v {
973                 0 => None,
974                 v => Some(self / v),
975             }
976         }
977
978         /// Saturating integer addition. Computes `self + other`, saturating at
979         /// the numeric bounds instead of overflowing.
980         #[stable(feature = "rust1", since = "1.0.0")]
981         #[inline]
982         pub fn saturating_add(self, other: Self) -> Self {
983             match self.checked_add(other) {
984                 Some(x)                       => x,
985                 None if other >= Self::zero() => Self::max_value(),
986                 None => Self::min_value(),
987             }
988         }
989
990         /// Saturating integer subtraction. Computes `self - other`, saturating
991         /// at the numeric bounds instead of overflowing.
992         #[stable(feature = "rust1", since = "1.0.0")]
993         #[inline]
994         pub fn saturating_sub(self, other: Self) -> Self {
995             match self.checked_sub(other) {
996                 Some(x)                       => x,
997                 None if other >= Self::zero() => Self::min_value(),
998                 None => Self::max_value(),
999             }
1000         }
1001
1002         /// Wrapping (modular) addition. Computes `self + other`,
1003         /// wrapping around at the boundary of the type.
1004         #[stable(feature = "rust1", since = "1.0.0")]
1005         #[inline]
1006         pub fn wrapping_add(self, rhs: Self) -> Self {
1007             unsafe {
1008                 intrinsics::overflowing_add(self, rhs)
1009             }
1010         }
1011
1012         /// Wrapping (modular) subtraction. Computes `self - other`,
1013         /// wrapping around at the boundary of the type.
1014         #[stable(feature = "rust1", since = "1.0.0")]
1015         #[inline]
1016         pub fn wrapping_sub(self, rhs: Self) -> Self {
1017             unsafe {
1018                 intrinsics::overflowing_sub(self, rhs)
1019             }
1020         }
1021
1022         /// Wrapping (modular) multiplication. Computes `self *
1023         /// other`, wrapping around at the boundary of the type.
1024         #[stable(feature = "rust1", since = "1.0.0")]
1025         #[inline]
1026         pub fn wrapping_mul(self, rhs: Self) -> Self {
1027             unsafe {
1028                 intrinsics::overflowing_mul(self, rhs)
1029             }
1030         }
1031
1032         /// Wrapping (modular) division. Computes `floor(self / other)`,
1033         /// wrapping around at the boundary of the type.
1034         ///
1035         /// The only case where such wrapping can occur is when one
1036         /// divides `MIN / -1` on a signed type (where `MIN` is the
1037         /// negative minimal value for the type); this is equivalent
1038         /// to `-MIN`, a positive value that is too large to represent
1039         /// in the type. In such a case, this function returns `MIN`
1040         /// itself..
1041         #[unstable(feature = "num_wrapping")]
1042         #[inline(always)]
1043         pub fn wrapping_div(self, rhs: Self) -> Self {
1044             self.overflowing_div(rhs).0
1045         }
1046
1047         /// Wrapping (modular) remainder. Computes `self % other`,
1048         /// wrapping around at the boundary of the type.
1049         ///
1050         /// Such wrap-around never actually occurs mathematically;
1051         /// implementation artifacts make `x % y` illegal for `MIN /
1052         /// -1` on a signed type illegal (where `MIN` is the negative
1053         /// minimal value). In such a case, this function returns `0`.
1054         #[unstable(feature = "num_wrapping")]
1055         #[inline(always)]
1056         pub fn wrapping_rem(self, rhs: Self) -> Self {
1057             self.overflowing_rem(rhs).0
1058         }
1059
1060         /// Wrapping (modular) negation. Computes `-self`,
1061         /// wrapping around at the boundary of the type.
1062         ///
1063         /// The only case where such wrapping can occur is when one
1064         /// negates `MIN` on a signed type (where `MIN` is the
1065         /// negative minimal value for the type); this is a positive
1066         /// value that is too large to represent in the type. In such
1067         /// a case, this function returns `MIN` itself.
1068         #[unstable(feature = "num_wrapping")]
1069         #[inline(always)]
1070         pub fn wrapping_neg(self) -> Self {
1071             self.overflowing_neg().0
1072         }
1073
1074         /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1075         /// where `mask` removes any high-order bits of `rhs` that
1076         /// would cause the shift to exceed the bitwidth of the type.
1077         #[unstable(feature = "num_wrapping")]
1078         #[inline(always)]
1079         pub fn wrapping_shl(self, rhs: u32) -> Self {
1080             self.overflowing_shl(rhs).0
1081         }
1082
1083         /// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
1084         /// where `mask` removes any high-order bits of `rhs` that
1085         /// would cause the shift to exceed the bitwidth of the type.
1086         #[unstable(feature = "num_wrapping")]
1087         #[inline(always)]
1088         pub fn wrapping_shr(self, rhs: u32) -> Self {
1089             self.overflowing_shr(rhs).0
1090         }
1091
1092         /// Raises self to the power of `exp`, using exponentiation by squaring.
1093         ///
1094         /// # Examples
1095         ///
1096         /// ```rust
1097         /// assert_eq!(2i32.pow(4), 16);
1098         /// ```
1099         #[stable(feature = "rust1", since = "1.0.0")]
1100         #[inline]
1101         pub fn pow(self, mut exp: u32) -> Self {
1102             let mut base = self;
1103             let mut acc = Self::one();
1104
1105             let mut prev_base = self;
1106             let mut base_oflo = false;
1107             while exp > 0 {
1108                 if (exp & 1) == 1 {
1109                     if base_oflo {
1110                         // ensure overflow occurs in the same manner it
1111                         // would have otherwise (i.e. signal any exception
1112                         // it would have otherwise).
1113                         acc = acc * (prev_base * prev_base);
1114                     } else {
1115                         acc = acc * base;
1116                     }
1117                 }
1118                 prev_base = base;
1119                 let (new_base, new_base_oflo) = base.overflowing_mul(base);
1120                 base = new_base;
1121                 base_oflo = new_base_oflo;
1122                 exp /= 2;
1123             }
1124             acc
1125         }
1126
1127         /// Returns `true` iff `self == 2^k` for some `k`.
1128         #[stable(feature = "rust1", since = "1.0.0")]
1129         #[inline]
1130         pub fn is_power_of_two(self) -> bool {
1131             (self.wrapping_sub(Self::one())) & self == Self::zero() &&
1132                 !(self == Self::zero())
1133         }
1134
1135         /// Returns the smallest power of two greater than or equal to `self`.
1136         /// Unspecified behavior on overflow.
1137         #[stable(feature = "rust1", since = "1.0.0")]
1138         #[inline]
1139         pub fn next_power_of_two(self) -> Self {
1140             let bits = size_of::<Self>() * 8;
1141             let one: Self = Self::one();
1142             one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
1143         }
1144
1145         /// Returns the smallest power of two greater than or equal to `n`. If
1146         /// the next power of two is greater than the type's maximum value,
1147         /// `None` is returned, otherwise the power of two is wrapped in `Some`.
1148         #[stable(feature = "rust1", since = "1.0.0")]
1149         pub fn checked_next_power_of_two(self) -> Option<Self> {
1150             let npot = self.next_power_of_two();
1151             if npot >= self {
1152                 Some(npot)
1153             } else {
1154                 None
1155             }
1156         }
1157     }
1158 }
1159
1160 #[lang = "u8"]
1161 impl u8 {
1162     uint_impl! { u8, 8,
1163         intrinsics::ctpop8,
1164         intrinsics::ctlz8,
1165         intrinsics::cttz8,
1166         bswap8,
1167         intrinsics::u8_add_with_overflow,
1168         intrinsics::u8_sub_with_overflow,
1169         intrinsics::u8_mul_with_overflow }
1170 }
1171
1172 #[lang = "u16"]
1173 impl u16 {
1174     uint_impl! { u16, 16,
1175         intrinsics::ctpop16,
1176         intrinsics::ctlz16,
1177         intrinsics::cttz16,
1178         intrinsics::bswap16,
1179         intrinsics::u16_add_with_overflow,
1180         intrinsics::u16_sub_with_overflow,
1181         intrinsics::u16_mul_with_overflow }
1182 }
1183
1184 #[lang = "u32"]
1185 impl u32 {
1186     uint_impl! { u32, 32,
1187         intrinsics::ctpop32,
1188         intrinsics::ctlz32,
1189         intrinsics::cttz32,
1190         intrinsics::bswap32,
1191         intrinsics::u32_add_with_overflow,
1192         intrinsics::u32_sub_with_overflow,
1193         intrinsics::u32_mul_with_overflow }
1194 }
1195
1196
1197 #[lang = "u64"]
1198 impl u64 {
1199     uint_impl! { u64, 64,
1200         intrinsics::ctpop64,
1201         intrinsics::ctlz64,
1202         intrinsics::cttz64,
1203         intrinsics::bswap64,
1204         intrinsics::u64_add_with_overflow,
1205         intrinsics::u64_sub_with_overflow,
1206         intrinsics::u64_mul_with_overflow }
1207 }
1208
1209 #[cfg(target_pointer_width = "32")]
1210 #[lang = "usize"]
1211 impl usize {
1212     uint_impl! { u32, 32,
1213         intrinsics::ctpop32,
1214         intrinsics::ctlz32,
1215         intrinsics::cttz32,
1216         intrinsics::bswap32,
1217         intrinsics::u32_add_with_overflow,
1218         intrinsics::u32_sub_with_overflow,
1219         intrinsics::u32_mul_with_overflow }
1220 }
1221
1222 #[cfg(target_pointer_width = "64")]
1223 #[lang = "usize"]
1224 impl usize {
1225     uint_impl! { u64, 64,
1226         intrinsics::ctpop64,
1227         intrinsics::ctlz64,
1228         intrinsics::cttz64,
1229         intrinsics::bswap64,
1230         intrinsics::u64_add_with_overflow,
1231         intrinsics::u64_sub_with_overflow,
1232         intrinsics::u64_mul_with_overflow }
1233 }
1234
1235 /// Used for representing the classification of floating point numbers
1236 #[derive(Copy, Clone, PartialEq, Debug)]
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 pub enum FpCategory {
1239     /// "Not a Number", often obtained by dividing by zero
1240     #[stable(feature = "rust1", since = "1.0.0")]
1241     Nan,
1242
1243     /// Positive or negative infinity
1244     #[stable(feature = "rust1", since = "1.0.0")]
1245     Infinite ,
1246
1247     /// Positive or negative zero
1248     #[stable(feature = "rust1", since = "1.0.0")]
1249     Zero,
1250
1251     /// De-normalized floating point representation (less precise than `Normal`)
1252     #[stable(feature = "rust1", since = "1.0.0")]
1253     Subnormal,
1254
1255     /// A regular floating point number
1256     #[stable(feature = "rust1", since = "1.0.0")]
1257     Normal,
1258 }
1259
1260 /// A built-in floating point number.
1261 #[doc(hidden)]
1262 #[unstable(feature = "core_float",
1263            reason = "stable interface is via `impl f{32,64}` in later crates")]
1264 pub trait Float {
1265     /// Returns the NaN value.
1266     fn nan() -> Self;
1267     /// Returns the infinite value.
1268     fn infinity() -> Self;
1269     /// Returns the negative infinite value.
1270     fn neg_infinity() -> Self;
1271     /// Returns -0.0.
1272     fn neg_zero() -> Self;
1273     /// Returns 0.0.
1274     fn zero() -> Self;
1275     /// Returns 1.0.
1276     fn one() -> Self;
1277     /// Parses the string `s` with the radix `r` as a float.
1278     fn from_str_radix(s: &str, r: u32) -> Result<Self, ParseFloatError>;
1279
1280     /// Returns true if this value is NaN and false otherwise.
1281     fn is_nan(self) -> bool;
1282     /// Returns true if this value is positive infinity or negative infinity and
1283     /// false otherwise.
1284     fn is_infinite(self) -> bool;
1285     /// Returns true if this number is neither infinite nor NaN.
1286     fn is_finite(self) -> bool;
1287     /// Returns true if this number is neither zero, infinite, denormal, or NaN.
1288     fn is_normal(self) -> bool;
1289     /// Returns the category that this number falls into.
1290     fn classify(self) -> FpCategory;
1291
1292     /// Returns the mantissa, exponent and sign as integers, respectively.
1293     fn integer_decode(self) -> (u64, i16, i8);
1294
1295     /// Return the largest integer less than or equal to a number.
1296     fn floor(self) -> Self;
1297     /// Return the smallest integer greater than or equal to a number.
1298     fn ceil(self) -> Self;
1299     /// Return the nearest integer to a number. Round half-way cases away from
1300     /// `0.0`.
1301     fn round(self) -> Self;
1302     /// Return the integer part of a number.
1303     fn trunc(self) -> Self;
1304     /// Return the fractional part of a number.
1305     fn fract(self) -> Self;
1306
1307     /// Computes the absolute value of `self`. Returns `Float::nan()` if the
1308     /// number is `Float::nan()`.
1309     fn abs(self) -> Self;
1310     /// Returns a number that represents the sign of `self`.
1311     ///
1312     /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
1313     /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
1314     /// - `Float::nan()` if the number is `Float::nan()`
1315     fn signum(self) -> Self;
1316     /// Returns `true` if `self` is positive, including `+0.0` and
1317     /// `Float::infinity()`.
1318     fn is_positive(self) -> bool;
1319     /// Returns `true` if `self` is negative, including `-0.0` and
1320     /// `Float::neg_infinity()`.
1321     fn is_negative(self) -> bool;
1322
1323     /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1324     /// error. This produces a more accurate result with better performance than
1325     /// a separate multiplication operation followed by an add.
1326     fn mul_add(self, a: Self, b: Self) -> Self;
1327     /// Take the reciprocal (inverse) of a number, `1/x`.
1328     fn recip(self) -> Self;
1329
1330     /// Raise a number to an integer power.
1331     ///
1332     /// Using this function is generally faster than using `powf`
1333     fn powi(self, n: i32) -> Self;
1334     /// Raise a number to a floating point power.
1335     fn powf(self, n: Self) -> Self;
1336
1337     /// Take the square root of a number.
1338     ///
1339     /// Returns NaN if `self` is a negative number.
1340     fn sqrt(self) -> Self;
1341     /// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
1342     fn rsqrt(self) -> Self;
1343
1344     /// Returns `e^(self)`, (the exponential function).
1345     fn exp(self) -> Self;
1346     /// Returns 2 raised to the power of the number, `2^(self)`.
1347     fn exp2(self) -> Self;
1348     /// Returns the natural logarithm of the number.
1349     fn ln(self) -> Self;
1350     /// Returns the logarithm of the number with respect to an arbitrary base.
1351     fn log(self, base: Self) -> Self;
1352     /// Returns the base 2 logarithm of the number.
1353     fn log2(self) -> Self;
1354     /// Returns the base 10 logarithm of the number.
1355     fn log10(self) -> Self;
1356
1357     /// Convert radians to degrees.
1358     fn to_degrees(self) -> Self;
1359     /// Convert degrees to radians.
1360     fn to_radians(self) -> Self;
1361 }
1362
1363 macro_rules! from_str_float_impl {
1364     ($t:ty) => {
1365         #[stable(feature = "rust1", since = "1.0.0")]
1366         impl FromStr for $t {
1367             type Err = ParseFloatError;
1368
1369             /// Converts a string in base 10 to a float.
1370             /// Accepts an optional decimal exponent.
1371             ///
1372             /// This function accepts strings such as
1373             ///
1374             /// * '3.14'
1375             /// * '+3.14', equivalent to '3.14'
1376             /// * '-3.14'
1377             /// * '2.5E10', or equivalently, '2.5e10'
1378             /// * '2.5E-10'
1379             /// * '.' (understood as 0)
1380             /// * '5.'
1381             /// * '.5', or, equivalently,  '0.5'
1382             /// * '+inf', 'inf', '-inf', 'NaN'
1383             ///
1384             /// Leading and trailing whitespace represent an error.
1385             ///
1386             /// # Arguments
1387             ///
1388             /// * src - A string
1389             ///
1390             /// # Return value
1391             ///
1392             /// `Err(ParseFloatError)` if the string did not represent a valid
1393             /// number.  Otherwise, `Ok(n)` where `n` is the floating-point
1394             /// number represented by `src`.
1395             #[inline]
1396             #[allow(deprecated)]
1397             fn from_str(src: &str) -> Result<Self, ParseFloatError> {
1398                 Self::from_str_radix(src, 10)
1399             }
1400         }
1401     }
1402 }
1403 from_str_float_impl!(f32);
1404 from_str_float_impl!(f64);
1405
1406 macro_rules! from_str_radix_int_impl {
1407     ($($t:ty)*) => {$(
1408         #[stable(feature = "rust1", since = "1.0.0")]
1409         #[allow(deprecated)]
1410         impl FromStr for $t {
1411             type Err = ParseIntError;
1412             fn from_str(src: &str) -> Result<Self, ParseIntError> {
1413                 from_str_radix(src, 10)
1414             }
1415         }
1416     )*}
1417 }
1418 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
1419
1420 #[doc(hidden)]
1421 trait FromStrRadixHelper: PartialOrd + Copy {
1422     fn min_value() -> Self;
1423     fn from_u32(u: u32) -> Self;
1424     fn checked_mul(&self, other: u32) -> Option<Self>;
1425     fn checked_sub(&self, other: u32) -> Option<Self>;
1426     fn checked_add(&self, other: u32) -> Option<Self>;
1427 }
1428
1429 macro_rules! doit {
1430     ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
1431         fn min_value() -> Self { Self::min_value() }
1432         fn from_u32(u: u32) -> Self { u as Self }
1433         fn checked_mul(&self, other: u32) -> Option<Self> {
1434             Self::checked_mul(*self, other as Self)
1435         }
1436         fn checked_sub(&self, other: u32) -> Option<Self> {
1437             Self::checked_sub(*self, other as Self)
1438         }
1439         fn checked_add(&self, other: u32) -> Option<Self> {
1440             Self::checked_add(*self, other as Self)
1441         }
1442     })*)
1443 }
1444 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1445
1446 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
1447                                          -> Result<T, ParseIntError> {
1448     use self::IntErrorKind::*;
1449     use self::ParseIntError as PIE;
1450     assert!(radix >= 2 && radix <= 36,
1451            "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
1452            radix);
1453
1454     let is_signed_ty = T::from_u32(0) > T::min_value();
1455
1456     match src.slice_shift_char() {
1457         Some(('-', "")) => Err(PIE { kind: Empty }),
1458         Some(('-', src)) if is_signed_ty => {
1459             // The number is negative
1460             let mut result = T::from_u32(0);
1461             for c in src.chars() {
1462                 let x = match c.to_digit(radix) {
1463                     Some(x) => x,
1464                     None => return Err(PIE { kind: InvalidDigit }),
1465                 };
1466                 result = match result.checked_mul(radix) {
1467                     Some(result) => result,
1468                     None => return Err(PIE { kind: Underflow }),
1469                 };
1470                 result = match result.checked_sub(x) {
1471                     Some(result) => result,
1472                     None => return Err(PIE { kind: Underflow }),
1473                 };
1474             }
1475             Ok(result)
1476         },
1477         Some((_, _)) => {
1478             // The number is signed
1479             let mut result = T::from_u32(0);
1480             for c in src.chars() {
1481                 let x = match c.to_digit(radix) {
1482                     Some(x) => x,
1483                     None => return Err(PIE { kind: InvalidDigit }),
1484                 };
1485                 result = match result.checked_mul(radix) {
1486                     Some(result) => result,
1487                     None => return Err(PIE { kind: Overflow }),
1488                 };
1489                 result = match result.checked_add(x) {
1490                     Some(result) => result,
1491                     None => return Err(PIE { kind: Overflow }),
1492                 };
1493             }
1494             Ok(result)
1495         },
1496         None => Err(ParseIntError { kind: Empty }),
1497     }
1498 }
1499
1500 /// An error which can be returned when parsing an integer.
1501 #[derive(Debug, Clone, PartialEq)]
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 pub struct ParseIntError { kind: IntErrorKind }
1504
1505 #[derive(Debug, Clone, PartialEq)]
1506 enum IntErrorKind {
1507     Empty,
1508     InvalidDigit,
1509     Overflow,
1510     Underflow,
1511 }
1512
1513 impl ParseIntError {
1514     #[unstable(feature = "int_error_internals",
1515                reason = "available through Error trait and this method should \
1516                          not be exposed publicly")]
1517     pub fn description(&self) -> &str {
1518         match self.kind {
1519             IntErrorKind::Empty => "cannot parse integer from empty string",
1520             IntErrorKind::InvalidDigit => "invalid digit found in string",
1521             IntErrorKind::Overflow => "number too large to fit in target type",
1522             IntErrorKind::Underflow => "number too small to fit in target type",
1523         }
1524     }
1525 }
1526
1527 #[stable(feature = "rust1", since = "1.0.0")]
1528 impl fmt::Display for ParseIntError {
1529     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1530         self.description().fmt(f)
1531     }
1532 }
1533
1534 /// An error which can be returned when parsing a float.
1535 #[derive(Debug, Clone, PartialEq)]
1536 #[stable(feature = "rust1", since = "1.0.0")]
1537 pub struct ParseFloatError {
1538     #[doc(hidden)]
1539     #[unstable(feature = "float_error_internals",
1540                reason = "should not be exposed publicly")]
1541     pub __kind: FloatErrorKind
1542 }
1543
1544 #[derive(Debug, Clone, PartialEq)]
1545 #[unstable(feature = "float_error_internals",
1546            reason = "should not be exposed publicly")]
1547 pub enum FloatErrorKind {
1548     Empty,
1549     Invalid,
1550 }
1551
1552 impl ParseFloatError {
1553     #[doc(hidden)]
1554     pub fn __description(&self) -> &str {
1555         match self.__kind {
1556             FloatErrorKind::Empty => "cannot parse float from empty string",
1557             FloatErrorKind::Invalid => "invalid float literal",
1558         }
1559     }
1560 }
1561
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 impl fmt::Display for ParseFloatError {
1564     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1565         self.__description().fmt(f)
1566     }
1567 }