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