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