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