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