]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
run rustfmt on libcore/num folder
[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
15 use convert::TryFrom;
16 use fmt;
17 use intrinsics;
18 use mem::size_of;
19 use str::FromStr;
20
21 /// Provides intentionally-wrapped arithmetic on `T`.
22 ///
23 /// Operations like `+` on `u32` values is intended to never overflow,
24 /// and in some debug configurations overflow is detected and results
25 /// in a panic. While most arithmetic falls into this category, some
26 /// code explicitly expects and relies upon modular arithmetic (e.g.,
27 /// hashing).
28 ///
29 /// Wrapping arithmetic can be achieved either through methods like
30 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
31 /// all standard arithmetic operations on the underlying value are
32 /// intended to have wrapping semantics.
33 ///
34 /// # Examples
35 ///
36 /// ```
37 /// use std::num::Wrapping;
38 ///
39 /// let zero = Wrapping(0u32);
40 /// let one = Wrapping(1u32);
41 ///
42 /// assert_eq!(std::u32::MAX, (zero - one).0);
43 /// ```
44 #[stable(feature = "rust1", since = "1.0.0")]
45 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
46 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
47                        pub T);
48
49 #[stable(feature = "rust1", since = "1.0.0")]
50 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
51     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52         self.0.fmt(f)
53     }
54 }
55
56 #[stable(feature = "wrapping_display", since = "1.10.0")]
57 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
58     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59         self.0.fmt(f)
60     }
61 }
62
63 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
64 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
65     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66         self.0.fmt(f)
67     }
68 }
69
70 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
71 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
72     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
73         self.0.fmt(f)
74     }
75 }
76
77 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
78 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
79     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
80         self.0.fmt(f)
81     }
82 }
83
84 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
85 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
86     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
87         self.0.fmt(f)
88     }
89 }
90
91 mod wrapping;
92
93 // All these modules are technically private and only exposed for libcoretest:
94 pub mod flt2dec;
95 pub mod dec2flt;
96 pub mod bignum;
97 pub mod diy_float;
98
99 /// Types that have a "zero" value.
100 ///
101 /// This trait is intended for use in conjunction with `Add`, as an identity:
102 /// `x + T::zero() == x`.
103 #[unstable(feature = "zero_one",
104            reason = "unsure of placement, wants to use associated constants",
105            issue = "27739")]
106 #[rustc_deprecated(since = "1.11.0", reason = "no longer used for \
107                                                Iterator::sum")]
108 pub trait Zero: Sized {
109     /// The "zero" (usually, additive identity) for this type.
110     fn zero() -> Self;
111 }
112
113 /// Types that have a "one" value.
114 ///
115 /// This trait is intended for use in conjunction with `Mul`, as an identity:
116 /// `x * T::one() == x`.
117 #[unstable(feature = "zero_one",
118            reason = "unsure of placement, wants to use associated constants",
119            issue = "27739")]
120 #[rustc_deprecated(since = "1.11.0", reason = "no longer used for \
121                                                Iterator::product")]
122 pub trait One: Sized {
123     /// The "one" (usually, multiplicative identity) for this type.
124     fn one() -> Self;
125 }
126
127 macro_rules! zero_one_impl {
128     ($($t:ty)*) => ($(
129         #[unstable(feature = "zero_one",
130                    reason = "unsure of placement, wants to use associated constants",
131                    issue = "27739")]
132         #[allow(deprecated)]
133         impl Zero for $t {
134             #[inline]
135             fn zero() -> Self { 0 }
136         }
137         #[unstable(feature = "zero_one",
138                    reason = "unsure of placement, wants to use associated constants",
139                    issue = "27739")]
140         #[allow(deprecated)]
141         impl One for $t {
142             #[inline]
143             fn one() -> Self { 1 }
144         }
145     )*)
146 }
147 zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
148
149 macro_rules! zero_one_impl_float {
150     ($($t:ty)*) => ($(
151         #[unstable(feature = "zero_one",
152                    reason = "unsure of placement, wants to use associated constants",
153                    issue = "27739")]
154         #[allow(deprecated)]
155         impl Zero for $t {
156             #[inline]
157             fn zero() -> Self { 0.0 }
158         }
159         #[unstable(feature = "zero_one",
160                    reason = "unsure of placement, wants to use associated constants",
161                    issue = "27739")]
162         #[allow(deprecated)]
163         impl One for $t {
164             #[inline]
165             fn one() -> Self { 1.0 }
166         }
167     )*)
168 }
169 zero_one_impl_float! { f32 f64 }
170
171 macro_rules! checked_op {
172     ($U:ty, $op:path, $x:expr, $y:expr) => {{
173         let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
174         if overflowed { None } else { Some(result as Self) }
175     }}
176 }
177
178 // `Int` + `SignedInt` implemented for signed integers
179 macro_rules! int_impl {
180     ($ActualT:ident, $UnsignedT:ty, $BITS:expr,
181      $add_with_overflow:path,
182      $sub_with_overflow:path,
183      $mul_with_overflow:path) => {
184         /// Returns the smallest value that can be represented by this integer type.
185         ///
186         /// # Examples
187         ///
188         /// ```
189         /// assert_eq!(i8::min_value(), -128);
190         /// ```
191         #[stable(feature = "rust1", since = "1.0.0")]
192         #[inline]
193         pub const fn min_value() -> Self {
194             (-1 as Self) << ($BITS - 1)
195         }
196
197         /// Returns the largest value that can be represented by this integer type.
198         ///
199         /// # Examples
200         ///
201         /// ```
202         /// assert_eq!(i8::max_value(), 127);
203         /// ```
204         #[stable(feature = "rust1", since = "1.0.0")]
205         #[inline]
206         pub const fn max_value() -> Self {
207             !Self::min_value()
208         }
209
210         /// Converts a string slice in a given base to an integer.
211         ///
212         /// Leading and trailing whitespace represent an error.
213         ///
214         /// # Examples
215         ///
216         /// Basic usage:
217         ///
218         /// ```
219         /// assert_eq!(i32::from_str_radix("A", 16), Ok(10));
220         /// ```
221         #[stable(feature = "rust1", since = "1.0.0")]
222         pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
223             from_str_radix(src, radix)
224         }
225
226         /// Returns the number of ones in the binary representation of `self`.
227         ///
228         /// # Examples
229         ///
230         /// Basic usage:
231         ///
232         /// ```
233         /// let n = -0b1000_0000i8;
234         ///
235         /// assert_eq!(n.count_ones(), 1);
236         /// ```
237         #[stable(feature = "rust1", since = "1.0.0")]
238         #[inline]
239         pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
240
241         /// Returns the number of zeros in the binary representation of `self`.
242         ///
243         /// # Examples
244         ///
245         /// Basic usage:
246         ///
247         /// ```
248         /// let n = -0b1000_0000i8;
249         ///
250         /// assert_eq!(n.count_zeros(), 7);
251         /// ```
252         #[stable(feature = "rust1", since = "1.0.0")]
253         #[inline]
254         pub fn count_zeros(self) -> u32 {
255             (!self).count_ones()
256         }
257
258         /// Returns the number of leading zeros in the binary representation
259         /// of `self`.
260         ///
261         /// # Examples
262         ///
263         /// Basic usage:
264         ///
265         /// ```
266         /// let n = -1i16;
267         ///
268         /// assert_eq!(n.leading_zeros(), 0);
269         /// ```
270         #[stable(feature = "rust1", since = "1.0.0")]
271         #[inline]
272         pub fn leading_zeros(self) -> u32 {
273             (self as $UnsignedT).leading_zeros()
274         }
275
276         /// Returns the number of trailing zeros in the binary representation
277         /// of `self`.
278         ///
279         /// # Examples
280         ///
281         /// Basic usage:
282         ///
283         /// ```
284         /// let n = -4i8;
285         ///
286         /// assert_eq!(n.trailing_zeros(), 2);
287         /// ```
288         #[stable(feature = "rust1", since = "1.0.0")]
289         #[inline]
290         pub fn trailing_zeros(self) -> u32 {
291             (self as $UnsignedT).trailing_zeros()
292         }
293
294         /// Shifts the bits to the left by a specified amount, `n`,
295         /// wrapping the truncated bits to the end of the resulting integer.
296         ///
297         /// Please note this isn't the same operation as `<<`!
298         ///
299         /// # Examples
300         ///
301         /// Basic usage:
302         ///
303         /// ```
304         /// let n = 0x0123456789ABCDEFi64;
305         /// let m = -0x76543210FEDCBA99i64;
306         ///
307         /// assert_eq!(n.rotate_left(32), m);
308         /// ```
309         #[stable(feature = "rust1", since = "1.0.0")]
310         #[inline]
311         pub fn rotate_left(self, n: u32) -> Self {
312             (self as $UnsignedT).rotate_left(n) as Self
313         }
314
315         /// Shifts the bits to the right by a specified amount, `n`,
316         /// wrapping the truncated bits to the beginning of the resulting
317         /// integer.
318         ///
319         /// Please note this isn't the same operation as `>>`!
320         ///
321         /// # Examples
322         ///
323         /// Basic usage:
324         ///
325         /// ```
326         /// let n = 0x0123456789ABCDEFi64;
327         /// let m = -0xFEDCBA987654322i64;
328         ///
329         /// assert_eq!(n.rotate_right(4), m);
330         /// ```
331         #[stable(feature = "rust1", since = "1.0.0")]
332         #[inline]
333         pub fn rotate_right(self, n: u32) -> Self {
334             (self as $UnsignedT).rotate_right(n) as Self
335         }
336
337         /// Reverses the byte order of the integer.
338         ///
339         /// # Examples
340         ///
341         /// Basic usage:
342         ///
343         /// ```
344         /// let n =  0x0123456789ABCDEFi64;
345         /// let m = -0x1032547698BADCFFi64;
346         ///
347         /// assert_eq!(n.swap_bytes(), m);
348         /// ```
349         #[stable(feature = "rust1", since = "1.0.0")]
350         #[inline]
351         pub fn swap_bytes(self) -> Self {
352             (self as $UnsignedT).swap_bytes() as Self
353         }
354
355         /// Converts an integer from big endian to the target's endianness.
356         ///
357         /// On big endian this is a no-op. On little endian the bytes are
358         /// swapped.
359         ///
360         /// # Examples
361         ///
362         /// Basic usage:
363         ///
364         /// ```
365         /// let n = 0x0123456789ABCDEFi64;
366         ///
367         /// if cfg!(target_endian = "big") {
368         ///     assert_eq!(i64::from_be(n), n)
369         /// } else {
370         ///     assert_eq!(i64::from_be(n), n.swap_bytes())
371         /// }
372         /// ```
373         #[stable(feature = "rust1", since = "1.0.0")]
374         #[inline]
375         pub fn from_be(x: Self) -> Self {
376             if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
377         }
378
379         /// Converts an integer from little endian to the target's endianness.
380         ///
381         /// On little endian this is a no-op. On big endian the bytes are
382         /// swapped.
383         ///
384         /// # Examples
385         ///
386         /// Basic usage:
387         ///
388         /// ```
389         /// let n = 0x0123456789ABCDEFi64;
390         ///
391         /// if cfg!(target_endian = "little") {
392         ///     assert_eq!(i64::from_le(n), n)
393         /// } else {
394         ///     assert_eq!(i64::from_le(n), n.swap_bytes())
395         /// }
396         /// ```
397         #[stable(feature = "rust1", since = "1.0.0")]
398         #[inline]
399         pub fn from_le(x: Self) -> Self {
400             if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
401         }
402
403         /// Converts `self` to big endian from the target's endianness.
404         ///
405         /// On big endian this is a no-op. On little endian the bytes are
406         /// swapped.
407         ///
408         /// # Examples
409         ///
410         /// Basic usage:
411         ///
412         /// ```
413         /// let n = 0x0123456789ABCDEFi64;
414         ///
415         /// if cfg!(target_endian = "big") {
416         ///     assert_eq!(n.to_be(), n)
417         /// } else {
418         ///     assert_eq!(n.to_be(), n.swap_bytes())
419         /// }
420         /// ```
421         #[stable(feature = "rust1", since = "1.0.0")]
422         #[inline]
423         pub fn to_be(self) -> Self { // or not to be?
424             if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
425         }
426
427         /// Converts `self` to little endian from the target's endianness.
428         ///
429         /// On little endian this is a no-op. On big endian the bytes are
430         /// swapped.
431         ///
432         /// # Examples
433         ///
434         /// Basic usage:
435         ///
436         /// ```
437         /// let n = 0x0123456789ABCDEFi64;
438         ///
439         /// if cfg!(target_endian = "little") {
440         ///     assert_eq!(n.to_le(), n)
441         /// } else {
442         ///     assert_eq!(n.to_le(), n.swap_bytes())
443         /// }
444         /// ```
445         #[stable(feature = "rust1", since = "1.0.0")]
446         #[inline]
447         pub fn to_le(self) -> Self {
448             if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
449         }
450
451         /// Checked integer addition. Computes `self + other`, returning `None`
452         /// if overflow occurred.
453         ///
454         /// # Examples
455         ///
456         /// Basic usage:
457         ///
458         /// ```
459         /// assert_eq!(7i16.checked_add(32760), Some(32767));
460         /// assert_eq!(8i16.checked_add(32760), None);
461         /// ```
462         #[stable(feature = "rust1", since = "1.0.0")]
463         #[inline]
464         pub fn checked_add(self, other: Self) -> Option<Self> {
465             let (a, b) = self.overflowing_add(other);
466             if b {None} else {Some(a)}
467         }
468
469         /// Checked integer subtraction. Computes `self - other`, returning
470         /// `None` if underflow occurred.
471         ///
472         /// # Examples
473         ///
474         /// Basic usage:
475         ///
476         /// ```
477         /// assert_eq!((-127i8).checked_sub(1), Some(-128));
478         /// assert_eq!((-128i8).checked_sub(1), None);
479         /// ```
480         #[stable(feature = "rust1", since = "1.0.0")]
481         #[inline]
482         pub fn checked_sub(self, other: Self) -> Option<Self> {
483             let (a, b) = self.overflowing_sub(other);
484             if b {None} else {Some(a)}
485         }
486
487         /// Checked integer multiplication. Computes `self * other`, returning
488         /// `None` if underflow or overflow occurred.
489         ///
490         /// # Examples
491         ///
492         /// Basic usage:
493         ///
494         /// ```
495         /// assert_eq!(6i8.checked_mul(21), Some(126));
496         /// assert_eq!(6i8.checked_mul(22), None);
497         /// ```
498         #[stable(feature = "rust1", since = "1.0.0")]
499         #[inline]
500         pub fn checked_mul(self, other: Self) -> Option<Self> {
501             let (a, b) = self.overflowing_mul(other);
502             if b {None} else {Some(a)}
503         }
504
505         /// Checked integer division. Computes `self / other`, returning `None`
506         /// if `other == 0` or the operation results in underflow or overflow.
507         ///
508         /// # Examples
509         ///
510         /// Basic usage:
511         ///
512         /// ```
513         /// assert_eq!((-127i8).checked_div(-1), Some(127));
514         /// assert_eq!((-128i8).checked_div(-1), None);
515         /// assert_eq!((1i8).checked_div(0), None);
516         /// ```
517         #[stable(feature = "rust1", since = "1.0.0")]
518         #[inline]
519         pub fn checked_div(self, other: Self) -> Option<Self> {
520             if other == 0 || (self == Self::min_value() && other == -1) {
521                 None
522             } else {
523                 Some(unsafe { intrinsics::unchecked_div(self, other) })
524             }
525         }
526
527         /// Checked integer remainder. Computes `self % other`, returning `None`
528         /// if `other == 0` or the operation results in underflow or overflow.
529         ///
530         /// # Examples
531         ///
532         /// Basic usage:
533         ///
534         /// ```
535         /// use std::i32;
536         ///
537         /// assert_eq!(5i32.checked_rem(2), Some(1));
538         /// assert_eq!(5i32.checked_rem(0), None);
539         /// assert_eq!(i32::MIN.checked_rem(-1), None);
540         /// ```
541         #[stable(feature = "wrapping", since = "1.7.0")]
542         #[inline]
543         pub fn checked_rem(self, other: Self) -> Option<Self> {
544             if other == 0 || (self == Self::min_value() && other == -1) {
545                 None
546             } else {
547                 Some(unsafe { intrinsics::unchecked_rem(self, other) })
548             }
549         }
550
551         /// Checked negation. Computes `-self`, returning `None` if `self ==
552         /// MIN`.
553         ///
554         /// # Examples
555         ///
556         /// Basic usage:
557         ///
558         /// ```
559         /// use std::i32;
560         ///
561         /// assert_eq!(5i32.checked_neg(), Some(-5));
562         /// assert_eq!(i32::MIN.checked_neg(), None);
563         /// ```
564         #[stable(feature = "wrapping", since = "1.7.0")]
565         #[inline]
566         pub fn checked_neg(self) -> Option<Self> {
567             let (a, b) = self.overflowing_neg();
568             if b {None} else {Some(a)}
569         }
570
571         /// Checked shift left. Computes `self << rhs`, returning `None`
572         /// if `rhs` is larger than or equal to the number of bits in `self`.
573         ///
574         /// # Examples
575         ///
576         /// Basic usage:
577         ///
578         /// ```
579         /// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
580         /// assert_eq!(0x10i32.checked_shl(33), None);
581         /// ```
582         #[stable(feature = "wrapping", since = "1.7.0")]
583         #[inline]
584         pub fn checked_shl(self, rhs: u32) -> Option<Self> {
585             let (a, b) = self.overflowing_shl(rhs);
586             if b {None} else {Some(a)}
587         }
588
589         /// Checked shift right. Computes `self >> rhs`, returning `None`
590         /// if `rhs` is larger than or equal to the number of bits in `self`.
591         ///
592         /// # Examples
593         ///
594         /// Basic usage:
595         ///
596         /// ```
597         /// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
598         /// assert_eq!(0x10i32.checked_shr(33), None);
599         /// ```
600         #[stable(feature = "wrapping", since = "1.7.0")]
601         #[inline]
602         pub fn checked_shr(self, rhs: u32) -> Option<Self> {
603             let (a, b) = self.overflowing_shr(rhs);
604             if b {None} else {Some(a)}
605         }
606
607         /// Checked absolute value. Computes `self.abs()`, returning `None` if
608         /// `self == MIN`.
609         ///
610         /// # Examples
611         ///
612         /// Basic usage:
613         ///
614         /// ```
615         /// use std::i32;
616         ///
617         /// assert_eq!((-5i32).checked_abs(), Some(5));
618         /// assert_eq!(i32::MIN.checked_abs(), None);
619         /// ```
620         #[stable(feature = "no_panic_abs", since = "1.13.0")]
621         #[inline]
622         pub fn checked_abs(self) -> Option<Self> {
623             if self.is_negative() {
624                 self.checked_neg()
625             } else {
626                 Some(self)
627             }
628         }
629
630         /// Saturating integer addition. Computes `self + other`, saturating at
631         /// the numeric bounds instead of overflowing.
632         ///
633         /// # Examples
634         ///
635         /// Basic usage:
636         ///
637         /// ```
638         /// assert_eq!(100i8.saturating_add(1), 101);
639         /// assert_eq!(100i8.saturating_add(127), 127);
640         /// ```
641         #[stable(feature = "rust1", since = "1.0.0")]
642         #[inline]
643         pub fn saturating_add(self, other: Self) -> Self {
644             match self.checked_add(other) {
645                 Some(x) => x,
646                 None if other >= 0 => Self::max_value(),
647                 None => Self::min_value(),
648             }
649         }
650
651         /// Saturating integer subtraction. Computes `self - other`, saturating
652         /// at the numeric bounds instead of overflowing.
653         ///
654         /// # Examples
655         ///
656         /// Basic usage:
657         ///
658         /// ```
659         /// assert_eq!(100i8.saturating_sub(127), -27);
660         /// assert_eq!((-100i8).saturating_sub(127), -128);
661         /// ```
662         #[stable(feature = "rust1", since = "1.0.0")]
663         #[inline]
664         pub fn saturating_sub(self, other: Self) -> Self {
665             match self.checked_sub(other) {
666                 Some(x) => x,
667                 None if other >= 0 => Self::min_value(),
668                 None => Self::max_value(),
669             }
670         }
671
672         /// Saturating integer multiplication. Computes `self * other`,
673         /// saturating at the numeric bounds instead of overflowing.
674         ///
675         /// # Examples
676         ///
677         /// Basic usage:
678         ///
679         /// ```
680         /// use std::i32;
681         ///
682         /// assert_eq!(100i32.saturating_mul(127), 12700);
683         /// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
684         /// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
685         /// ```
686         #[stable(feature = "wrapping", since = "1.7.0")]
687         #[inline]
688         pub fn saturating_mul(self, other: Self) -> Self {
689             self.checked_mul(other).unwrap_or_else(|| {
690                 if (self < 0 && other < 0) || (self > 0 && other > 0) {
691                     Self::max_value()
692                 } else {
693                     Self::min_value()
694                 }
695             })
696         }
697
698         /// Wrapping (modular) addition. Computes `self + other`,
699         /// wrapping around at the boundary of the type.
700         ///
701         /// # Examples
702         ///
703         /// Basic usage:
704         ///
705         /// ```
706         /// assert_eq!(100i8.wrapping_add(27), 127);
707         /// assert_eq!(100i8.wrapping_add(127), -29);
708         /// ```
709         #[stable(feature = "rust1", since = "1.0.0")]
710         #[inline]
711         pub fn wrapping_add(self, rhs: Self) -> Self {
712             unsafe {
713                 intrinsics::overflowing_add(self, rhs)
714             }
715         }
716
717         /// Wrapping (modular) subtraction. Computes `self - other`,
718         /// wrapping around at the boundary of the type.
719         ///
720         /// # Examples
721         ///
722         /// Basic usage:
723         ///
724         /// ```
725         /// assert_eq!(0i8.wrapping_sub(127), -127);
726         /// assert_eq!((-2i8).wrapping_sub(127), 127);
727         /// ```
728         #[stable(feature = "rust1", since = "1.0.0")]
729         #[inline]
730         pub fn wrapping_sub(self, rhs: Self) -> Self {
731             unsafe {
732                 intrinsics::overflowing_sub(self, rhs)
733             }
734         }
735
736         /// Wrapping (modular) multiplication. Computes `self *
737         /// other`, wrapping around at the boundary of the type.
738         ///
739         /// # Examples
740         ///
741         /// Basic usage:
742         ///
743         /// ```
744         /// assert_eq!(10i8.wrapping_mul(12), 120);
745         /// assert_eq!(11i8.wrapping_mul(12), -124);
746         /// ```
747         #[stable(feature = "rust1", since = "1.0.0")]
748         #[inline]
749         pub fn wrapping_mul(self, rhs: Self) -> Self {
750             unsafe {
751                 intrinsics::overflowing_mul(self, rhs)
752             }
753         }
754
755         /// Wrapping (modular) division. Computes `self / other`,
756         /// wrapping around at the boundary of the type.
757         ///
758         /// The only case where such wrapping can occur is when one
759         /// divides `MIN / -1` on a signed type (where `MIN` is the
760         /// negative minimal value for the type); this is equivalent
761         /// to `-MIN`, a positive value that is too large to represent
762         /// in the type. In such a case, this function returns `MIN`
763         /// itself.
764         ///
765         /// # Panics
766         ///
767         /// This function will panic if `rhs` is 0.
768         ///
769         /// # Examples
770         ///
771         /// Basic usage:
772         ///
773         /// ```
774         /// assert_eq!(100u8.wrapping_div(10), 10);
775         /// assert_eq!((-128i8).wrapping_div(-1), -128);
776         /// ```
777         #[stable(feature = "num_wrapping", since = "1.2.0")]
778         #[inline(always)]
779         pub fn wrapping_div(self, rhs: Self) -> Self {
780             self.overflowing_div(rhs).0
781         }
782
783         /// Wrapping (modular) remainder. Computes `self % other`,
784         /// wrapping around at the boundary of the type.
785         ///
786         /// Such wrap-around never actually occurs mathematically;
787         /// implementation artifacts make `x % y` invalid for `MIN /
788         /// -1` on a signed type (where `MIN` is the negative
789         /// minimal value). In such a case, this function returns `0`.
790         ///
791         /// # Panics
792         ///
793         /// This function will panic if `rhs` is 0.
794         ///
795         /// # Examples
796         ///
797         /// Basic usage:
798         ///
799         /// ```
800         /// assert_eq!(100i8.wrapping_rem(10), 0);
801         /// assert_eq!((-128i8).wrapping_rem(-1), 0);
802         /// ```
803         #[stable(feature = "num_wrapping", since = "1.2.0")]
804         #[inline(always)]
805         pub fn wrapping_rem(self, rhs: Self) -> Self {
806             self.overflowing_rem(rhs).0
807         }
808
809         /// Wrapping (modular) negation. Computes `-self`,
810         /// wrapping around at the boundary of the type.
811         ///
812         /// The only case where such wrapping can occur is when one
813         /// negates `MIN` on a signed type (where `MIN` is the
814         /// negative minimal value for the type); this is a positive
815         /// value that is too large to represent in the type. In such
816         /// a case, this function returns `MIN` itself.
817         ///
818         /// # Examples
819         ///
820         /// Basic usage:
821         ///
822         /// ```
823         /// assert_eq!(100i8.wrapping_neg(), -100);
824         /// assert_eq!((-128i8).wrapping_neg(), -128);
825         /// ```
826         #[stable(feature = "num_wrapping", since = "1.2.0")]
827         #[inline(always)]
828         pub fn wrapping_neg(self) -> Self {
829             self.overflowing_neg().0
830         }
831
832         /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
833         /// where `mask` removes any high-order bits of `rhs` that
834         /// would cause the shift to exceed the bitwidth of the type.
835         ///
836         /// Note that this is *not* the same as a rotate-left; the
837         /// RHS of a wrapping shift-left is restricted to the range
838         /// of the type, rather than the bits shifted out of the LHS
839         /// being returned to the other end. The primitive integer
840         /// types all implement a `rotate_left` function, which may
841         /// be what you want instead.
842         ///
843         /// # Examples
844         ///
845         /// Basic usage:
846         ///
847         /// ```
848         /// assert_eq!((-1i8).wrapping_shl(7), -128);
849         /// assert_eq!((-1i8).wrapping_shl(8), -1);
850         /// ```
851         #[stable(feature = "num_wrapping", since = "1.2.0")]
852         #[inline(always)]
853         pub fn wrapping_shl(self, rhs: u32) -> Self {
854             self.overflowing_shl(rhs).0
855         }
856
857         /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
858         /// where `mask` removes any high-order bits of `rhs` that
859         /// would cause the shift to exceed the bitwidth of the type.
860         ///
861         /// Note that this is *not* the same as a rotate-right; the
862         /// RHS of a wrapping shift-right is restricted to the range
863         /// of the type, rather than the bits shifted out of the LHS
864         /// being returned to the other end. The primitive integer
865         /// types all implement a `rotate_right` function, which may
866         /// be what you want instead.
867         ///
868         /// # Examples
869         ///
870         /// Basic usage:
871         ///
872         /// ```
873         /// assert_eq!((-128i8).wrapping_shr(7), -1);
874         /// assert_eq!((-128i8).wrapping_shr(8), -128);
875         /// ```
876         #[stable(feature = "num_wrapping", since = "1.2.0")]
877         #[inline(always)]
878         pub fn wrapping_shr(self, rhs: u32) -> Self {
879             self.overflowing_shr(rhs).0
880         }
881
882         /// Wrapping (modular) absolute value. Computes `self.abs()`,
883         /// wrapping around at the boundary of the type.
884         ///
885         /// The only case where such wrapping can occur is when one takes
886         /// the absolute value of the negative minimal value for the type
887         /// this is a positive value that is too large to represent in the
888         /// type. In such a case, this function returns `MIN` itself.
889         ///
890         /// # Examples
891         ///
892         /// Basic usage:
893         ///
894         /// ```
895         /// assert_eq!(100i8.wrapping_abs(), 100);
896         /// assert_eq!((-100i8).wrapping_abs(), 100);
897         /// assert_eq!((-128i8).wrapping_abs(), -128);
898         /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
899         /// ```
900         #[stable(feature = "no_panic_abs", since = "1.13.0")]
901         #[inline(always)]
902         pub fn wrapping_abs(self) -> Self {
903             if self.is_negative() {
904                 self.wrapping_neg()
905             } else {
906                 self
907             }
908         }
909
910         /// Calculates `self` + `rhs`
911         ///
912         /// Returns a tuple of the addition along with a boolean indicating
913         /// whether an arithmetic overflow would occur. If an overflow would
914         /// have occurred then the wrapped value is returned.
915         ///
916         /// # Examples
917         ///
918         /// Basic usage
919         ///
920         /// ```
921         /// use std::i32;
922         ///
923         /// assert_eq!(5i32.overflowing_add(2), (7, false));
924         /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
925         /// ```
926         #[inline]
927         #[stable(feature = "wrapping", since = "1.7.0")]
928         pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
929             unsafe {
930                 let (a, b) = $add_with_overflow(self as $ActualT,
931                                                 rhs as $ActualT);
932                 (a as Self, b)
933             }
934         }
935
936         /// Calculates `self` - `rhs`
937         ///
938         /// Returns a tuple of the subtraction along with a boolean indicating
939         /// whether an arithmetic overflow would occur. If an overflow would
940         /// have occurred then the wrapped value is returned.
941         ///
942         /// # Examples
943         ///
944         /// Basic usage
945         ///
946         /// ```
947         /// use std::i32;
948         ///
949         /// assert_eq!(5i32.overflowing_sub(2), (3, false));
950         /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
951         /// ```
952         #[inline]
953         #[stable(feature = "wrapping", since = "1.7.0")]
954         pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
955             unsafe {
956                 let (a, b) = $sub_with_overflow(self as $ActualT,
957                                                 rhs as $ActualT);
958                 (a as Self, b)
959             }
960         }
961
962         /// Calculates the multiplication of `self` and `rhs`.
963         ///
964         /// Returns a tuple of the multiplication along with a boolean
965         /// indicating whether an arithmetic overflow would occur. If an
966         /// overflow would have occurred then the wrapped value is returned.
967         ///
968         /// # Examples
969         ///
970         /// Basic usage
971         ///
972         /// ```
973         /// assert_eq!(5i32.overflowing_mul(2), (10, false));
974         /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
975         /// ```
976         #[inline]
977         #[stable(feature = "wrapping", since = "1.7.0")]
978         pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
979             unsafe {
980                 let (a, b) = $mul_with_overflow(self as $ActualT,
981                                                 rhs as $ActualT);
982                 (a as Self, b)
983             }
984         }
985
986         /// Calculates the divisor when `self` is divided by `rhs`.
987         ///
988         /// Returns a tuple of the divisor along with a boolean indicating
989         /// whether an arithmetic overflow would occur. If an overflow would
990         /// occur then self is returned.
991         ///
992         /// # Panics
993         ///
994         /// This function will panic if `rhs` is 0.
995         ///
996         /// # Examples
997         ///
998         /// Basic usage
999         ///
1000         /// ```
1001         /// use std::i32;
1002         ///
1003         /// assert_eq!(5i32.overflowing_div(2), (2, false));
1004         /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
1005         /// ```
1006         #[inline]
1007         #[stable(feature = "wrapping", since = "1.7.0")]
1008         pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1009             if self == Self::min_value() && rhs == -1 {
1010                 (self, true)
1011             } else {
1012                 (self / rhs, false)
1013             }
1014         }
1015
1016         /// Calculates the remainder when `self` is divided by `rhs`.
1017         ///
1018         /// Returns a tuple of the remainder after dividing along with a boolean
1019         /// indicating whether an arithmetic overflow would occur. If an
1020         /// overflow would occur then 0 is returned.
1021         ///
1022         /// # Panics
1023         ///
1024         /// This function will panic if `rhs` is 0.
1025         ///
1026         /// # Examples
1027         ///
1028         /// Basic usage
1029         ///
1030         /// ```
1031         /// use std::i32;
1032         ///
1033         /// assert_eq!(5i32.overflowing_rem(2), (1, false));
1034         /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
1035         /// ```
1036         #[inline]
1037         #[stable(feature = "wrapping", since = "1.7.0")]
1038         pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1039             if self == Self::min_value() && rhs == -1 {
1040                 (0, true)
1041             } else {
1042                 (self % rhs, false)
1043             }
1044         }
1045
1046         /// Negates self, overflowing if this is equal to the minimum value.
1047         ///
1048         /// Returns a tuple of the negated version of self along with a boolean
1049         /// indicating whether an overflow happened. If `self` is the minimum
1050         /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
1051         /// value will be returned again and `true` will be returned for an
1052         /// overflow happening.
1053         ///
1054         /// # Examples
1055         ///
1056         /// Basic usage
1057         ///
1058         /// ```
1059         /// use std::i32;
1060         ///
1061         /// assert_eq!(2i32.overflowing_neg(), (-2, false));
1062         /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
1063         /// ```
1064         #[inline]
1065         #[stable(feature = "wrapping", since = "1.7.0")]
1066         pub fn overflowing_neg(self) -> (Self, bool) {
1067             if self == Self::min_value() {
1068                 (Self::min_value(), true)
1069             } else {
1070                 (-self, false)
1071             }
1072         }
1073
1074         /// Shifts self left by `rhs` bits.
1075         ///
1076         /// Returns a tuple of the shifted version of self along with a boolean
1077         /// indicating whether the shift value was larger than or equal to the
1078         /// number of bits. If the shift value is too large, then value is
1079         /// masked (N-1) where N is the number of bits, and this value is then
1080         /// used to perform the shift.
1081         ///
1082         /// # Examples
1083         ///
1084         /// Basic usage
1085         ///
1086         /// ```
1087         /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
1088         /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
1089         /// ```
1090         #[inline]
1091         #[stable(feature = "wrapping", since = "1.7.0")]
1092         pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1093             (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1094         }
1095
1096         /// Shifts self right by `rhs` bits.
1097         ///
1098         /// Returns a tuple of the shifted version of self along with a boolean
1099         /// indicating whether the shift value was larger than or equal to the
1100         /// number of bits. If the shift value is too large, then value is
1101         /// masked (N-1) where N is the number of bits, and this value is then
1102         /// used to perform the shift.
1103         ///
1104         /// # Examples
1105         ///
1106         /// Basic usage
1107         ///
1108         /// ```
1109         /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
1110         /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1111         /// ```
1112         #[inline]
1113         #[stable(feature = "wrapping", since = "1.7.0")]
1114         pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1115             (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1116         }
1117
1118         /// Computes the absolute value of `self`.
1119         ///
1120         /// Returns a tuple of the absolute version of self along with a
1121         /// boolean indicating whether an overflow happened. If self is the
1122         /// minimum value (e.g. i32::MIN for values of type i32), then the
1123         /// minimum value will be returned again and true will be returned for
1124         /// an overflow happening.
1125         ///
1126         /// # Examples
1127         ///
1128         /// Basic usage:
1129         ///
1130         /// ```
1131         /// assert_eq!(10i8.overflowing_abs(), (10,false));
1132         /// assert_eq!((-10i8).overflowing_abs(), (10,false));
1133         /// assert_eq!((-128i8).overflowing_abs(), (-128,true));
1134         /// ```
1135         #[stable(feature = "no_panic_abs", since = "1.13.0")]
1136         #[inline]
1137         pub fn overflowing_abs(self) -> (Self, bool) {
1138             if self.is_negative() {
1139                 self.overflowing_neg()
1140             } else {
1141                 (self, false)
1142             }
1143         }
1144
1145         /// Raises self to the power of `exp`, using exponentiation by squaring.
1146         ///
1147         /// # Examples
1148         ///
1149         /// Basic usage:
1150         ///
1151         /// ```
1152         /// let x: i32 = 2; // or any other integer type
1153         ///
1154         /// assert_eq!(x.pow(4), 16);
1155         /// ```
1156         #[stable(feature = "rust1", since = "1.0.0")]
1157         #[inline]
1158         #[rustc_inherit_overflow_checks]
1159         pub fn pow(self, mut exp: u32) -> Self {
1160             let mut base = self;
1161             let mut acc = 1;
1162
1163             while exp > 1 {
1164                 if (exp & 1) == 1 {
1165                     acc = acc * base;
1166                 }
1167                 exp /= 2;
1168                 base = base * base;
1169             }
1170
1171             // Deal with the final bit of the exponent separately, since
1172             // squaring the base afterwards is not necessary and may cause a
1173             // needless overflow.
1174             if exp == 1 {
1175                 acc = acc * base;
1176             }
1177
1178             acc
1179         }
1180
1181         /// Computes the absolute value of `self`.
1182         ///
1183         /// # Overflow behavior
1184         ///
1185         /// The absolute value of `i32::min_value()` cannot be represented as an
1186         /// `i32`, and attempting to calculate it will cause an overflow. This
1187         /// means that code in debug mode will trigger a panic on this case and
1188         /// optimized code will return `i32::min_value()` without a panic.
1189         ///
1190         /// # Examples
1191         ///
1192         /// Basic usage:
1193         ///
1194         /// ```
1195         /// assert_eq!(10i8.abs(), 10);
1196         /// assert_eq!((-10i8).abs(), 10);
1197         /// ```
1198         #[stable(feature = "rust1", since = "1.0.0")]
1199         #[inline]
1200         #[rustc_inherit_overflow_checks]
1201         pub fn abs(self) -> Self {
1202             if self.is_negative() {
1203                 // Note that the #[inline] above means that the overflow
1204                 // semantics of this negation depend on the crate we're being
1205                 // inlined into.
1206                 -self
1207             } else {
1208                 self
1209             }
1210         }
1211
1212         /// Returns a number representing sign of `self`.
1213         ///
1214         /// - `0` if the number is zero
1215         /// - `1` if the number is positive
1216         /// - `-1` if the number is negative
1217         ///
1218         /// # Examples
1219         ///
1220         /// Basic usage:
1221         ///
1222         /// ```
1223         /// assert_eq!(10i8.signum(), 1);
1224         /// assert_eq!(0i8.signum(), 0);
1225         /// assert_eq!((-10i8).signum(), -1);
1226         /// ```
1227         #[stable(feature = "rust1", since = "1.0.0")]
1228         #[inline]
1229         pub fn signum(self) -> Self {
1230             match self {
1231                 n if n > 0 =>  1,
1232                 0          =>  0,
1233                 _          => -1,
1234             }
1235         }
1236
1237         /// Returns `true` if `self` is positive and `false` if the number
1238         /// is zero or negative.
1239         ///
1240         /// # Examples
1241         ///
1242         /// Basic usage:
1243         ///
1244         /// ```
1245         /// assert!(10i8.is_positive());
1246         /// assert!(!(-10i8).is_positive());
1247         /// ```
1248         #[stable(feature = "rust1", since = "1.0.0")]
1249         #[inline]
1250         pub fn is_positive(self) -> bool { self > 0 }
1251
1252         /// Returns `true` if `self` is negative and `false` if the number
1253         /// is zero or positive.
1254         ///
1255         /// # Examples
1256         ///
1257         /// Basic usage:
1258         ///
1259         /// ```
1260         /// assert!((-10i8).is_negative());
1261         /// assert!(!10i8.is_negative());
1262         /// ```
1263         #[stable(feature = "rust1", since = "1.0.0")]
1264         #[inline]
1265         pub fn is_negative(self) -> bool { self < 0 }
1266     }
1267 }
1268
1269 #[lang = "i8"]
1270 impl i8 {
1271     int_impl! { i8, u8, 8,
1272         intrinsics::add_with_overflow,
1273         intrinsics::sub_with_overflow,
1274         intrinsics::mul_with_overflow }
1275 }
1276
1277 #[lang = "i16"]
1278 impl i16 {
1279     int_impl! { i16, u16, 16,
1280         intrinsics::add_with_overflow,
1281         intrinsics::sub_with_overflow,
1282         intrinsics::mul_with_overflow }
1283 }
1284
1285 #[lang = "i32"]
1286 impl i32 {
1287     int_impl! { i32, u32, 32,
1288         intrinsics::add_with_overflow,
1289         intrinsics::sub_with_overflow,
1290         intrinsics::mul_with_overflow }
1291 }
1292
1293 #[lang = "i64"]
1294 impl i64 {
1295     int_impl! { i64, u64, 64,
1296         intrinsics::add_with_overflow,
1297         intrinsics::sub_with_overflow,
1298         intrinsics::mul_with_overflow }
1299 }
1300
1301 #[cfg(target_pointer_width = "16")]
1302 #[lang = "isize"]
1303 impl isize {
1304     int_impl! { i16, u16, 16,
1305         intrinsics::add_with_overflow,
1306         intrinsics::sub_with_overflow,
1307         intrinsics::mul_with_overflow }
1308 }
1309
1310 #[cfg(target_pointer_width = "32")]
1311 #[lang = "isize"]
1312 impl isize {
1313     int_impl! { i32, u32, 32,
1314         intrinsics::add_with_overflow,
1315         intrinsics::sub_with_overflow,
1316         intrinsics::mul_with_overflow }
1317 }
1318
1319 #[cfg(target_pointer_width = "64")]
1320 #[lang = "isize"]
1321 impl isize {
1322     int_impl! { i64, u64, 64,
1323         intrinsics::add_with_overflow,
1324         intrinsics::sub_with_overflow,
1325         intrinsics::mul_with_overflow }
1326 }
1327
1328 // `Int` + `UnsignedInt` implemented for unsigned integers
1329 macro_rules! uint_impl {
1330     ($ActualT:ty, $BITS:expr,
1331      $ctpop:path,
1332      $ctlz:path,
1333      $cttz:path,
1334      $bswap:path,
1335      $add_with_overflow:path,
1336      $sub_with_overflow:path,
1337      $mul_with_overflow:path) => {
1338         /// Returns the smallest value that can be represented by this integer type.
1339         ///
1340         /// # Examples
1341         ///
1342         /// ```
1343         /// assert_eq!(u8::min_value(), 0);
1344         /// ```
1345         #[stable(feature = "rust1", since = "1.0.0")]
1346         #[inline]
1347         pub const fn min_value() -> Self { 0 }
1348
1349         /// Returns the largest value that can be represented by this integer type.
1350         ///
1351         /// # Examples
1352         ///
1353         /// ```
1354         /// assert_eq!(u8::max_value(), 255);
1355         /// ```
1356         #[stable(feature = "rust1", since = "1.0.0")]
1357         #[inline]
1358         pub const fn max_value() -> Self { !0 }
1359
1360         /// Converts a string slice in a given base to an integer.
1361         ///
1362         /// Leading and trailing whitespace represent an error.
1363         ///
1364         /// # Examples
1365         ///
1366         /// Basic usage:
1367         ///
1368         /// ```
1369         /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
1370         /// ```
1371         #[stable(feature = "rust1", since = "1.0.0")]
1372         pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1373             from_str_radix(src, radix)
1374         }
1375
1376         /// Returns the number of ones in the binary representation of `self`.
1377         ///
1378         /// # Examples
1379         ///
1380         /// Basic usage:
1381         ///
1382         /// ```
1383         /// let n = 0b01001100u8;
1384         ///
1385         /// assert_eq!(n.count_ones(), 3);
1386         /// ```
1387         #[stable(feature = "rust1", since = "1.0.0")]
1388         #[inline]
1389         pub fn count_ones(self) -> u32 {
1390             unsafe { $ctpop(self as $ActualT) as u32 }
1391         }
1392
1393         /// Returns the number of zeros in the binary representation of `self`.
1394         ///
1395         /// # Examples
1396         ///
1397         /// Basic usage:
1398         ///
1399         /// ```
1400         /// let n = 0b01001100u8;
1401         ///
1402         /// assert_eq!(n.count_zeros(), 5);
1403         /// ```
1404         #[stable(feature = "rust1", since = "1.0.0")]
1405         #[inline]
1406         pub fn count_zeros(self) -> u32 {
1407             (!self).count_ones()
1408         }
1409
1410         /// Returns the number of leading zeros in the binary representation
1411         /// of `self`.
1412         ///
1413         /// # Examples
1414         ///
1415         /// Basic usage:
1416         ///
1417         /// ```
1418         /// let n = 0b0101000u16;
1419         ///
1420         /// assert_eq!(n.leading_zeros(), 10);
1421         /// ```
1422         #[stable(feature = "rust1", since = "1.0.0")]
1423         #[inline]
1424         pub fn leading_zeros(self) -> u32 {
1425             unsafe { $ctlz(self as $ActualT) as u32 }
1426         }
1427
1428         /// Returns the number of trailing zeros in the binary representation
1429         /// of `self`.
1430         ///
1431         /// # Examples
1432         ///
1433         /// Basic usage:
1434         ///
1435         /// ```
1436         /// let n = 0b0101000u16;
1437         ///
1438         /// assert_eq!(n.trailing_zeros(), 3);
1439         /// ```
1440         #[stable(feature = "rust1", since = "1.0.0")]
1441         #[inline]
1442         pub fn trailing_zeros(self) -> u32 {
1443             // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1444             // emits two conditional moves on x86_64. By promoting the value to
1445             // u16 and setting bit 8, we get better code without any conditional
1446             // operations.
1447             // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1448             // pending, remove this workaround once LLVM generates better code
1449             // for cttz8.
1450             unsafe {
1451                 if $BITS == 8 {
1452                     intrinsics::cttz(self as u16 | 0x100) as u32
1453                 } else {
1454                     intrinsics::cttz(self) as u32
1455                 }
1456             }
1457         }
1458
1459         /// Shifts the bits to the left by a specified amount, `n`,
1460         /// wrapping the truncated bits to the end of the resulting integer.
1461         ///
1462         /// Please note this isn't the same operation as `<<`!
1463         ///
1464         /// # Examples
1465         ///
1466         /// Basic usage:
1467         ///
1468         /// ```
1469         /// let n = 0x0123456789ABCDEFu64;
1470         /// let m = 0x3456789ABCDEF012u64;
1471         ///
1472         /// assert_eq!(n.rotate_left(12), m);
1473         /// ```
1474         #[stable(feature = "rust1", since = "1.0.0")]
1475         #[inline]
1476         pub fn rotate_left(self, n: u32) -> Self {
1477             // Protect against undefined behaviour for over-long bit shifts
1478             let n = n % $BITS;
1479             (self << n) | (self >> (($BITS - n) % $BITS))
1480         }
1481
1482         /// Shifts the bits to the right by a specified amount, `n`,
1483         /// wrapping the truncated bits to the beginning of the resulting
1484         /// integer.
1485         ///
1486         /// Please note this isn't the same operation as `>>`!
1487         ///
1488         /// # Examples
1489         ///
1490         /// Basic usage:
1491         ///
1492         /// ```
1493         /// let n = 0x0123456789ABCDEFu64;
1494         /// let m = 0xDEF0123456789ABCu64;
1495         ///
1496         /// assert_eq!(n.rotate_right(12), m);
1497         /// ```
1498         #[stable(feature = "rust1", since = "1.0.0")]
1499         #[inline]
1500         pub fn rotate_right(self, n: u32) -> Self {
1501             // Protect against undefined behaviour for over-long bit shifts
1502             let n = n % $BITS;
1503             (self >> n) | (self << (($BITS - n) % $BITS))
1504         }
1505
1506         /// Reverses the byte order of the integer.
1507         ///
1508         /// # Examples
1509         ///
1510         /// Basic usage:
1511         ///
1512         /// ```
1513         /// let n = 0x0123456789ABCDEFu64;
1514         /// let m = 0xEFCDAB8967452301u64;
1515         ///
1516         /// assert_eq!(n.swap_bytes(), m);
1517         /// ```
1518         #[stable(feature = "rust1", since = "1.0.0")]
1519         #[inline]
1520         pub fn swap_bytes(self) -> Self {
1521             unsafe { $bswap(self as $ActualT) as Self }
1522         }
1523
1524         /// Converts an integer from big endian to the target's endianness.
1525         ///
1526         /// On big endian this is a no-op. On little endian the bytes are
1527         /// swapped.
1528         ///
1529         /// # Examples
1530         ///
1531         /// Basic usage:
1532         ///
1533         /// ```
1534         /// let n = 0x0123456789ABCDEFu64;
1535         ///
1536         /// if cfg!(target_endian = "big") {
1537         ///     assert_eq!(u64::from_be(n), n)
1538         /// } else {
1539         ///     assert_eq!(u64::from_be(n), n.swap_bytes())
1540         /// }
1541         /// ```
1542         #[stable(feature = "rust1", since = "1.0.0")]
1543         #[inline]
1544         pub fn from_be(x: Self) -> Self {
1545             if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1546         }
1547
1548         /// Converts an integer from little endian to the target's endianness.
1549         ///
1550         /// On little endian this is a no-op. On big endian the bytes are
1551         /// swapped.
1552         ///
1553         /// # Examples
1554         ///
1555         /// Basic usage:
1556         ///
1557         /// ```
1558         /// let n = 0x0123456789ABCDEFu64;
1559         ///
1560         /// if cfg!(target_endian = "little") {
1561         ///     assert_eq!(u64::from_le(n), n)
1562         /// } else {
1563         ///     assert_eq!(u64::from_le(n), n.swap_bytes())
1564         /// }
1565         /// ```
1566         #[stable(feature = "rust1", since = "1.0.0")]
1567         #[inline]
1568         pub fn from_le(x: Self) -> Self {
1569             if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1570         }
1571
1572         /// Converts `self` to big endian from the target's endianness.
1573         ///
1574         /// On big endian this is a no-op. On little endian the bytes are
1575         /// swapped.
1576         ///
1577         /// # Examples
1578         ///
1579         /// Basic usage:
1580         ///
1581         /// ```
1582         /// let n = 0x0123456789ABCDEFu64;
1583         ///
1584         /// if cfg!(target_endian = "big") {
1585         ///     assert_eq!(n.to_be(), n)
1586         /// } else {
1587         ///     assert_eq!(n.to_be(), n.swap_bytes())
1588         /// }
1589         /// ```
1590         #[stable(feature = "rust1", since = "1.0.0")]
1591         #[inline]
1592         pub fn to_be(self) -> Self { // or not to be?
1593             if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1594         }
1595
1596         /// Converts `self` to little endian from the target's endianness.
1597         ///
1598         /// On little endian this is a no-op. On big endian the bytes are
1599         /// swapped.
1600         ///
1601         /// # Examples
1602         ///
1603         /// Basic usage:
1604         ///
1605         /// ```
1606         /// let n = 0x0123456789ABCDEFu64;
1607         ///
1608         /// if cfg!(target_endian = "little") {
1609         ///     assert_eq!(n.to_le(), n)
1610         /// } else {
1611         ///     assert_eq!(n.to_le(), n.swap_bytes())
1612         /// }
1613         /// ```
1614         #[stable(feature = "rust1", since = "1.0.0")]
1615         #[inline]
1616         pub fn to_le(self) -> Self {
1617             if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1618         }
1619
1620         /// Checked integer addition. Computes `self + other`, returning `None`
1621         /// if overflow occurred.
1622         ///
1623         /// # Examples
1624         ///
1625         /// Basic usage:
1626         ///
1627         /// ```
1628         /// assert_eq!(5u16.checked_add(65530), Some(65535));
1629         /// assert_eq!(6u16.checked_add(65530), None);
1630         /// ```
1631         #[stable(feature = "rust1", since = "1.0.0")]
1632         #[inline]
1633         pub fn checked_add(self, other: Self) -> Option<Self> {
1634             let (a, b) = self.overflowing_add(other);
1635             if b {None} else {Some(a)}
1636         }
1637
1638         /// Checked integer subtraction. Computes `self - other`, returning
1639         /// `None` if underflow occurred.
1640         ///
1641         /// # Examples
1642         ///
1643         /// Basic usage:
1644         ///
1645         /// ```
1646         /// assert_eq!(1u8.checked_sub(1), Some(0));
1647         /// assert_eq!(0u8.checked_sub(1), None);
1648         /// ```
1649         #[stable(feature = "rust1", since = "1.0.0")]
1650         #[inline]
1651         pub fn checked_sub(self, other: Self) -> Option<Self> {
1652             let (a, b) = self.overflowing_sub(other);
1653             if b {None} else {Some(a)}
1654         }
1655
1656         /// Checked integer multiplication. Computes `self * other`, returning
1657         /// `None` if underflow or overflow occurred.
1658         ///
1659         /// # Examples
1660         ///
1661         /// Basic usage:
1662         ///
1663         /// ```
1664         /// assert_eq!(5u8.checked_mul(51), Some(255));
1665         /// assert_eq!(5u8.checked_mul(52), None);
1666         /// ```
1667         #[stable(feature = "rust1", since = "1.0.0")]
1668         #[inline]
1669         pub fn checked_mul(self, other: Self) -> Option<Self> {
1670             let (a, b) = self.overflowing_mul(other);
1671             if b {None} else {Some(a)}
1672         }
1673
1674         /// Checked integer division. Computes `self / other`, returning `None`
1675         /// if `other == 0` or the operation results in underflow or overflow.
1676         ///
1677         /// # Examples
1678         ///
1679         /// Basic usage:
1680         ///
1681         /// ```
1682         /// assert_eq!(128u8.checked_div(2), Some(64));
1683         /// assert_eq!(1u8.checked_div(0), None);
1684         /// ```
1685         #[stable(feature = "rust1", since = "1.0.0")]
1686         #[inline]
1687         pub fn checked_div(self, other: Self) -> Option<Self> {
1688             match other {
1689                 0 => None,
1690                 other => Some(unsafe { intrinsics::unchecked_div(self, other) }),
1691             }
1692         }
1693
1694         /// Checked integer remainder. Computes `self % other`, returning `None`
1695         /// if `other == 0` or the operation results in underflow or overflow.
1696         ///
1697         /// # Examples
1698         ///
1699         /// Basic usage:
1700         ///
1701         /// ```
1702         /// assert_eq!(5u32.checked_rem(2), Some(1));
1703         /// assert_eq!(5u32.checked_rem(0), None);
1704         /// ```
1705         #[stable(feature = "wrapping", since = "1.7.0")]
1706         #[inline]
1707         pub fn checked_rem(self, other: Self) -> Option<Self> {
1708             if other == 0 {
1709                 None
1710             } else {
1711                 Some(unsafe { intrinsics::unchecked_rem(self, other) })
1712             }
1713         }
1714
1715         /// Checked negation. Computes `-self`, returning `None` unless `self ==
1716         /// 0`.
1717         ///
1718         /// Note that negating any positive integer will overflow.
1719         ///
1720         /// # Examples
1721         ///
1722         /// Basic usage:
1723         ///
1724         /// ```
1725         /// assert_eq!(0u32.checked_neg(), Some(0));
1726         /// assert_eq!(1u32.checked_neg(), None);
1727         /// ```
1728         #[stable(feature = "wrapping", since = "1.7.0")]
1729         #[inline]
1730         pub fn checked_neg(self) -> Option<Self> {
1731             let (a, b) = self.overflowing_neg();
1732             if b {None} else {Some(a)}
1733         }
1734
1735         /// Checked shift left. Computes `self << rhs`, returning `None`
1736         /// if `rhs` is larger than or equal to the number of bits in `self`.
1737         ///
1738         /// # Examples
1739         ///
1740         /// Basic usage:
1741         ///
1742         /// ```
1743         /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1744         /// assert_eq!(0x10u32.checked_shl(33), None);
1745         /// ```
1746         #[stable(feature = "wrapping", since = "1.7.0")]
1747         #[inline]
1748         pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1749             let (a, b) = self.overflowing_shl(rhs);
1750             if b {None} else {Some(a)}
1751         }
1752
1753         /// Checked shift right. Computes `self >> rhs`, returning `None`
1754         /// if `rhs` is larger than or equal to the number of bits in `self`.
1755         ///
1756         /// # Examples
1757         ///
1758         /// Basic usage:
1759         ///
1760         /// ```
1761         /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1762         /// assert_eq!(0x10u32.checked_shr(33), None);
1763         /// ```
1764         #[stable(feature = "wrapping", since = "1.7.0")]
1765         #[inline]
1766         pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1767             let (a, b) = self.overflowing_shr(rhs);
1768             if b {None} else {Some(a)}
1769         }
1770
1771         /// Saturating integer addition. Computes `self + other`, saturating at
1772         /// the numeric bounds instead of overflowing.
1773         ///
1774         /// # Examples
1775         ///
1776         /// Basic usage:
1777         ///
1778         /// ```
1779         /// assert_eq!(100u8.saturating_add(1), 101);
1780         /// assert_eq!(200u8.saturating_add(127), 255);
1781         /// ```
1782         #[stable(feature = "rust1", since = "1.0.0")]
1783         #[inline]
1784         pub fn saturating_add(self, other: Self) -> Self {
1785             match self.checked_add(other) {
1786                 Some(x) => x,
1787                 None => Self::max_value(),
1788             }
1789         }
1790
1791         /// Saturating integer subtraction. Computes `self - other`, saturating
1792         /// at the numeric bounds instead of overflowing.
1793         ///
1794         /// # Examples
1795         ///
1796         /// Basic usage:
1797         ///
1798         /// ```
1799         /// assert_eq!(100u8.saturating_sub(27), 73);
1800         /// assert_eq!(13u8.saturating_sub(127), 0);
1801         /// ```
1802         #[stable(feature = "rust1", since = "1.0.0")]
1803         #[inline]
1804         pub fn saturating_sub(self, other: Self) -> Self {
1805             match self.checked_sub(other) {
1806                 Some(x) => x,
1807                 None => Self::min_value(),
1808             }
1809         }
1810
1811         /// Saturating integer multiplication. Computes `self * other`,
1812         /// saturating at the numeric bounds instead of overflowing.
1813         ///
1814         /// # Examples
1815         ///
1816         /// Basic usage:
1817         ///
1818         /// ```
1819         /// use std::u32;
1820         ///
1821         /// assert_eq!(100u32.saturating_mul(127), 12700);
1822         /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1823         /// ```
1824         #[stable(feature = "wrapping", since = "1.7.0")]
1825         #[inline]
1826         pub fn saturating_mul(self, other: Self) -> Self {
1827             self.checked_mul(other).unwrap_or(Self::max_value())
1828         }
1829
1830         /// Wrapping (modular) addition. Computes `self + other`,
1831         /// wrapping around at the boundary of the type.
1832         ///
1833         /// # Examples
1834         ///
1835         /// Basic usage:
1836         ///
1837         /// ```
1838         /// assert_eq!(200u8.wrapping_add(55), 255);
1839         /// assert_eq!(200u8.wrapping_add(155), 99);
1840         /// ```
1841         #[stable(feature = "rust1", since = "1.0.0")]
1842         #[inline]
1843         pub fn wrapping_add(self, rhs: Self) -> Self {
1844             unsafe {
1845                 intrinsics::overflowing_add(self, rhs)
1846             }
1847         }
1848
1849         /// Wrapping (modular) subtraction. Computes `self - other`,
1850         /// wrapping around at the boundary of the type.
1851         ///
1852         /// # Examples
1853         ///
1854         /// Basic usage:
1855         ///
1856         /// ```
1857         /// assert_eq!(100u8.wrapping_sub(100), 0);
1858         /// assert_eq!(100u8.wrapping_sub(155), 201);
1859         /// ```
1860         #[stable(feature = "rust1", since = "1.0.0")]
1861         #[inline]
1862         pub fn wrapping_sub(self, rhs: Self) -> Self {
1863             unsafe {
1864                 intrinsics::overflowing_sub(self, rhs)
1865             }
1866         }
1867
1868         /// Wrapping (modular) multiplication. Computes `self *
1869         /// other`, wrapping around at the boundary of the type.
1870         ///
1871         /// # Examples
1872         ///
1873         /// Basic usage:
1874         ///
1875         /// ```
1876         /// assert_eq!(10u8.wrapping_mul(12), 120);
1877         /// assert_eq!(25u8.wrapping_mul(12), 44);
1878         /// ```
1879         #[stable(feature = "rust1", since = "1.0.0")]
1880         #[inline]
1881         pub fn wrapping_mul(self, rhs: Self) -> Self {
1882             unsafe {
1883                 intrinsics::overflowing_mul(self, rhs)
1884             }
1885         }
1886
1887         /// Wrapping (modular) division. Computes `self / other`.
1888         /// Wrapped division on unsigned types is just normal division.
1889         /// There's no way wrapping could ever happen.
1890         /// This function exists, so that all operations
1891         /// are accounted for in the wrapping operations.
1892         ///
1893         /// # Examples
1894         ///
1895         /// Basic usage:
1896         ///
1897         /// ```
1898         /// assert_eq!(100u8.wrapping_div(10), 10);
1899         /// ```
1900         #[stable(feature = "num_wrapping", since = "1.2.0")]
1901         #[inline(always)]
1902         pub fn wrapping_div(self, rhs: Self) -> Self {
1903             self / rhs
1904         }
1905
1906         /// Wrapping (modular) remainder. Computes `self % other`.
1907         /// Wrapped remainder calculation on unsigned types is
1908         /// just the regular remainder calculation.
1909         /// There's no way wrapping could ever happen.
1910         /// This function exists, so that all operations
1911         /// are accounted for in the wrapping operations.
1912         ///
1913         /// # Examples
1914         ///
1915         /// Basic usage:
1916         ///
1917         /// ```
1918         /// assert_eq!(100u8.wrapping_rem(10), 0);
1919         /// ```
1920         #[stable(feature = "num_wrapping", since = "1.2.0")]
1921         #[inline(always)]
1922         pub fn wrapping_rem(self, rhs: Self) -> Self {
1923             self % rhs
1924         }
1925
1926         /// Wrapping (modular) negation. Computes `-self`,
1927         /// wrapping around at the boundary of the type.
1928         ///
1929         /// Since unsigned types do not have negative equivalents
1930         /// all applications of this function will wrap (except for `-0`).
1931         /// For values smaller than the corresponding signed type's maximum
1932         /// the result is the same as casting the corresponding signed value.
1933         /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1934         /// `MAX` is the corresponding signed type's maximum.
1935         ///
1936         /// # Examples
1937         ///
1938         /// Basic usage:
1939         ///
1940         /// ```
1941         /// assert_eq!(100u8.wrapping_neg(), 156);
1942         /// assert_eq!(0u8.wrapping_neg(), 0);
1943         /// assert_eq!(180u8.wrapping_neg(), 76);
1944         /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1945         /// ```
1946         #[stable(feature = "num_wrapping", since = "1.2.0")]
1947         #[inline(always)]
1948         pub fn wrapping_neg(self) -> Self {
1949             self.overflowing_neg().0
1950         }
1951
1952         /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1953         /// where `mask` removes any high-order bits of `rhs` that
1954         /// would cause the shift to exceed the bitwidth of the type.
1955         ///
1956         /// Note that this is *not* the same as a rotate-left; the
1957         /// RHS of a wrapping shift-left is restricted to the range
1958         /// of the type, rather than the bits shifted out of the LHS
1959         /// being returned to the other end. The primitive integer
1960         /// types all implement a `rotate_left` function, which may
1961         /// be what you want instead.
1962         ///
1963         /// # Examples
1964         ///
1965         /// Basic usage:
1966         ///
1967         /// ```
1968         /// assert_eq!(1u8.wrapping_shl(7), 128);
1969         /// assert_eq!(1u8.wrapping_shl(8), 1);
1970         /// ```
1971         #[stable(feature = "num_wrapping", since = "1.2.0")]
1972         #[inline(always)]
1973         pub fn wrapping_shl(self, rhs: u32) -> Self {
1974             self.overflowing_shl(rhs).0
1975         }
1976
1977         /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1978         /// where `mask` removes any high-order bits of `rhs` that
1979         /// would cause the shift to exceed the bitwidth of the type.
1980         ///
1981         /// Note that this is *not* the same as a rotate-right; the
1982         /// RHS of a wrapping shift-right is restricted to the range
1983         /// of the type, rather than the bits shifted out of the LHS
1984         /// being returned to the other end. The primitive integer
1985         /// types all implement a `rotate_right` function, which may
1986         /// be what you want instead.
1987         ///
1988         /// # Examples
1989         ///
1990         /// Basic usage:
1991         ///
1992         /// ```
1993         /// assert_eq!(128u8.wrapping_shr(7), 1);
1994         /// assert_eq!(128u8.wrapping_shr(8), 128);
1995         /// ```
1996         #[stable(feature = "num_wrapping", since = "1.2.0")]
1997         #[inline(always)]
1998         pub fn wrapping_shr(self, rhs: u32) -> Self {
1999             self.overflowing_shr(rhs).0
2000         }
2001
2002         /// Calculates `self` + `rhs`
2003         ///
2004         /// Returns a tuple of the addition along with a boolean indicating
2005         /// whether an arithmetic overflow would occur. If an overflow would
2006         /// have occurred then the wrapped value is returned.
2007         ///
2008         /// # Examples
2009         ///
2010         /// Basic usage
2011         ///
2012         /// ```
2013         /// use std::u32;
2014         ///
2015         /// assert_eq!(5u32.overflowing_add(2), (7, false));
2016         /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
2017         /// ```
2018         #[inline]
2019         #[stable(feature = "wrapping", since = "1.7.0")]
2020         pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2021             unsafe {
2022                 let (a, b) = $add_with_overflow(self as $ActualT,
2023                                                 rhs as $ActualT);
2024                 (a as Self, b)
2025             }
2026         }
2027
2028         /// Calculates `self` - `rhs`
2029         ///
2030         /// Returns a tuple of the subtraction along with a boolean indicating
2031         /// whether an arithmetic overflow would occur. If an overflow would
2032         /// have occurred then the wrapped value is returned.
2033         ///
2034         /// # Examples
2035         ///
2036         /// Basic usage
2037         ///
2038         /// ```
2039         /// use std::u32;
2040         ///
2041         /// assert_eq!(5u32.overflowing_sub(2), (3, false));
2042         /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
2043         /// ```
2044         #[inline]
2045         #[stable(feature = "wrapping", since = "1.7.0")]
2046         pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2047             unsafe {
2048                 let (a, b) = $sub_with_overflow(self as $ActualT,
2049                                                 rhs as $ActualT);
2050                 (a as Self, b)
2051             }
2052         }
2053
2054         /// Calculates the multiplication of `self` and `rhs`.
2055         ///
2056         /// Returns a tuple of the multiplication along with a boolean
2057         /// indicating whether an arithmetic overflow would occur. If an
2058         /// overflow would have occurred then the wrapped value is returned.
2059         ///
2060         /// # Examples
2061         ///
2062         /// Basic usage
2063         ///
2064         /// ```
2065         /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2066         /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2067         /// ```
2068         #[inline]
2069         #[stable(feature = "wrapping", since = "1.7.0")]
2070         pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2071             unsafe {
2072                 let (a, b) = $mul_with_overflow(self as $ActualT,
2073                                                 rhs as $ActualT);
2074                 (a as Self, b)
2075             }
2076         }
2077
2078         /// Calculates the divisor when `self` is divided by `rhs`.
2079         ///
2080         /// Returns a tuple of the divisor along with a boolean indicating
2081         /// whether an arithmetic overflow would occur. Note that for unsigned
2082         /// integers overflow never occurs, so the second value is always
2083         /// `false`.
2084         ///
2085         /// # Panics
2086         ///
2087         /// This function will panic if `rhs` is 0.
2088         ///
2089         /// # Examples
2090         ///
2091         /// Basic usage
2092         ///
2093         /// ```
2094         /// assert_eq!(5u32.overflowing_div(2), (2, false));
2095         /// ```
2096         #[inline]
2097         #[stable(feature = "wrapping", since = "1.7.0")]
2098         pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2099             (self / rhs, false)
2100         }
2101
2102         /// Calculates the remainder when `self` is divided by `rhs`.
2103         ///
2104         /// Returns a tuple of the remainder after dividing along with a boolean
2105         /// indicating whether an arithmetic overflow would occur. Note that for
2106         /// unsigned integers overflow never occurs, so the second value is
2107         /// always `false`.
2108         ///
2109         /// # Panics
2110         ///
2111         /// This function will panic if `rhs` is 0.
2112         ///
2113         /// # Examples
2114         ///
2115         /// Basic usage
2116         ///
2117         /// ```
2118         /// assert_eq!(5u32.overflowing_rem(2), (1, false));
2119         /// ```
2120         #[inline]
2121         #[stable(feature = "wrapping", since = "1.7.0")]
2122         pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2123             (self % rhs, false)
2124         }
2125
2126         /// Negates self in an overflowing fashion.
2127         ///
2128         /// Returns `!self + 1` using wrapping operations to return the value
2129         /// that represents the negation of this unsigned value. Note that for
2130         /// positive unsigned values overflow always occurs, but negating 0 does
2131         /// not overflow.
2132         ///
2133         /// # Examples
2134         ///
2135         /// Basic usage
2136         ///
2137         /// ```
2138         /// assert_eq!(0u32.overflowing_neg(), (0, false));
2139         /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
2140         /// ```
2141         #[inline]
2142         #[stable(feature = "wrapping", since = "1.7.0")]
2143         pub fn overflowing_neg(self) -> (Self, bool) {
2144             ((!self).wrapping_add(1), self != 0)
2145         }
2146
2147         /// Shifts self left by `rhs` bits.
2148         ///
2149         /// Returns a tuple of the shifted version of self along with a boolean
2150         /// indicating whether the shift value was larger than or equal to the
2151         /// number of bits. If the shift value is too large, then value is
2152         /// masked (N-1) where N is the number of bits, and this value is then
2153         /// used to perform the shift.
2154         ///
2155         /// # Examples
2156         ///
2157         /// Basic usage
2158         ///
2159         /// ```
2160         /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
2161         /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
2162         /// ```
2163         #[inline]
2164         #[stable(feature = "wrapping", since = "1.7.0")]
2165         pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2166             (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
2167         }
2168
2169         /// Shifts self right by `rhs` bits.
2170         ///
2171         /// Returns a tuple of the shifted version of self along with a boolean
2172         /// indicating whether the shift value was larger than or equal to the
2173         /// number of bits. If the shift value is too large, then value is
2174         /// masked (N-1) where N is the number of bits, and this value is then
2175         /// used to perform the shift.
2176         ///
2177         /// # Examples
2178         ///
2179         /// Basic usage
2180         ///
2181         /// ```
2182         /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
2183         /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2184         /// ```
2185         #[inline]
2186         #[stable(feature = "wrapping", since = "1.7.0")]
2187         pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2188             (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
2189         }
2190
2191         /// Raises self to the power of `exp`, using exponentiation by squaring.
2192         ///
2193         /// # Examples
2194         ///
2195         /// Basic usage:
2196         ///
2197         /// ```
2198         /// assert_eq!(2u32.pow(4), 16);
2199         /// ```
2200         #[stable(feature = "rust1", since = "1.0.0")]
2201         #[inline]
2202         #[rustc_inherit_overflow_checks]
2203         pub fn pow(self, mut exp: u32) -> Self {
2204             let mut base = self;
2205             let mut acc = 1;
2206
2207             while exp > 1 {
2208                 if (exp & 1) == 1 {
2209                     acc = acc * base;
2210                 }
2211                 exp /= 2;
2212                 base = base * base;
2213             }
2214
2215             // Deal with the final bit of the exponent separately, since
2216             // squaring the base afterwards is not necessary and may cause a
2217             // needless overflow.
2218             if exp == 1 {
2219                 acc = acc * base;
2220             }
2221
2222             acc
2223         }
2224
2225         /// Returns `true` if and only if `self == 2^k` for some `k`.
2226         ///
2227         /// # Examples
2228         ///
2229         /// Basic usage:
2230         ///
2231         /// ```
2232         /// assert!(16u8.is_power_of_two());
2233         /// assert!(!10u8.is_power_of_two());
2234         /// ```
2235         #[stable(feature = "rust1", since = "1.0.0")]
2236         #[inline]
2237         pub fn is_power_of_two(self) -> bool {
2238             (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2239         }
2240
2241         /// Returns the smallest power of two greater than or equal to `self`.
2242         /// Unspecified behavior on overflow.
2243         ///
2244         /// # Examples
2245         ///
2246         /// Basic usage:
2247         ///
2248         /// ```
2249         /// assert_eq!(2u8.next_power_of_two(), 2);
2250         /// assert_eq!(3u8.next_power_of_two(), 4);
2251         /// ```
2252         #[stable(feature = "rust1", since = "1.0.0")]
2253         #[inline]
2254         pub fn next_power_of_two(self) -> Self {
2255             let bits = size_of::<Self>() * 8;
2256             let one: Self = 1;
2257             one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
2258         }
2259
2260         /// Returns the smallest power of two greater than or equal to `n`. If
2261         /// the next power of two is greater than the type's maximum value,
2262         /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2263         ///
2264         /// # Examples
2265         ///
2266         /// Basic usage:
2267         ///
2268         /// ```
2269         /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2270         /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2271         /// assert_eq!(200u8.checked_next_power_of_two(), None);
2272         /// ```
2273         #[stable(feature = "rust1", since = "1.0.0")]
2274         pub fn checked_next_power_of_two(self) -> Option<Self> {
2275             let npot = self.next_power_of_two();
2276             if npot >= self {
2277                 Some(npot)
2278             } else {
2279                 None
2280             }
2281         }
2282     }
2283 }
2284
2285 #[lang = "u8"]
2286 impl u8 {
2287     uint_impl! { u8, 8,
2288         intrinsics::ctpop,
2289         intrinsics::ctlz,
2290         intrinsics::cttz,
2291         intrinsics::bswap,
2292         intrinsics::add_with_overflow,
2293         intrinsics::sub_with_overflow,
2294         intrinsics::mul_with_overflow }
2295 }
2296
2297 #[lang = "u16"]
2298 impl u16 {
2299     uint_impl! { u16, 16,
2300         intrinsics::ctpop,
2301         intrinsics::ctlz,
2302         intrinsics::cttz,
2303         intrinsics::bswap,
2304         intrinsics::add_with_overflow,
2305         intrinsics::sub_with_overflow,
2306         intrinsics::mul_with_overflow }
2307 }
2308
2309 #[lang = "u32"]
2310 impl u32 {
2311     uint_impl! { u32, 32,
2312         intrinsics::ctpop,
2313         intrinsics::ctlz,
2314         intrinsics::cttz,
2315         intrinsics::bswap,
2316         intrinsics::add_with_overflow,
2317         intrinsics::sub_with_overflow,
2318         intrinsics::mul_with_overflow }
2319 }
2320
2321 #[lang = "u64"]
2322 impl u64 {
2323     uint_impl! { u64, 64,
2324         intrinsics::ctpop,
2325         intrinsics::ctlz,
2326         intrinsics::cttz,
2327         intrinsics::bswap,
2328         intrinsics::add_with_overflow,
2329         intrinsics::sub_with_overflow,
2330         intrinsics::mul_with_overflow }
2331 }
2332
2333 #[cfg(target_pointer_width = "16")]
2334 #[lang = "usize"]
2335 impl usize {
2336     uint_impl! { u16, 16,
2337         intrinsics::ctpop,
2338         intrinsics::ctlz,
2339         intrinsics::cttz,
2340         intrinsics::bswap,
2341         intrinsics::add_with_overflow,
2342         intrinsics::sub_with_overflow,
2343         intrinsics::mul_with_overflow }
2344 }
2345 #[cfg(target_pointer_width = "32")]
2346 #[lang = "usize"]
2347 impl usize {
2348     uint_impl! { u32, 32,
2349         intrinsics::ctpop,
2350         intrinsics::ctlz,
2351         intrinsics::cttz,
2352         intrinsics::bswap,
2353         intrinsics::add_with_overflow,
2354         intrinsics::sub_with_overflow,
2355         intrinsics::mul_with_overflow }
2356 }
2357
2358 #[cfg(target_pointer_width = "64")]
2359 #[lang = "usize"]
2360 impl usize {
2361     uint_impl! { u64, 64,
2362         intrinsics::ctpop,
2363         intrinsics::ctlz,
2364         intrinsics::cttz,
2365         intrinsics::bswap,
2366         intrinsics::add_with_overflow,
2367         intrinsics::sub_with_overflow,
2368         intrinsics::mul_with_overflow }
2369 }
2370
2371 /// A classification of floating point numbers.
2372 ///
2373 /// This `enum` is used as the return type for [`f32::classify()`] and [`f64::classify()`]. See
2374 /// their documentation for more.
2375 ///
2376 /// [`f32::classify()`]: ../../std/primitive.f32.html#method.classify
2377 /// [`f64::classify()`]: ../../std/primitive.f64.html#method.classify
2378 ///
2379 /// # Examples
2380 ///
2381 /// ```
2382 /// use std::num::FpCategory;
2383 /// use std::f32;
2384 ///
2385 /// let num = 12.4_f32;
2386 /// let inf = f32::INFINITY;
2387 /// let zero = 0f32;
2388 /// let sub: f32 = 1.1754942e-38;
2389 /// let nan = f32::NAN;
2390 ///
2391 /// assert_eq!(num.classify(), FpCategory::Normal);
2392 /// assert_eq!(inf.classify(), FpCategory::Infinite);
2393 /// assert_eq!(zero.classify(), FpCategory::Zero);
2394 /// assert_eq!(nan.classify(), FpCategory::Nan);
2395 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
2396 /// ```
2397 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2398 #[stable(feature = "rust1", since = "1.0.0")]
2399 pub enum FpCategory {
2400     /// "Not a Number", often obtained by dividing by zero.
2401     #[stable(feature = "rust1", since = "1.0.0")]
2402     Nan,
2403
2404     /// Positive or negative infinity.
2405     #[stable(feature = "rust1", since = "1.0.0")]
2406     Infinite,
2407
2408     /// Positive or negative zero.
2409     #[stable(feature = "rust1", since = "1.0.0")]
2410     Zero,
2411
2412     /// De-normalized floating point representation (less precise than `Normal`).
2413     #[stable(feature = "rust1", since = "1.0.0")]
2414     Subnormal,
2415
2416     /// A regular floating point number.
2417     #[stable(feature = "rust1", since = "1.0.0")]
2418     Normal,
2419 }
2420
2421 /// A built-in floating point number.
2422 #[doc(hidden)]
2423 #[unstable(feature = "core_float",
2424            reason = "stable interface is via `impl f{32,64}` in later crates",
2425            issue = "32110")]
2426 pub trait Float: Sized {
2427     /// Returns the NaN value.
2428     #[unstable(feature = "float_extras", reason = "needs removal",
2429                issue = "27752")]
2430     #[rustc_deprecated(since = "1.11.0",
2431                        reason = "never really came to fruition and easily \
2432                                  implementable outside the standard library")]
2433     fn nan() -> Self;
2434     /// Returns the infinite value.
2435     #[unstable(feature = "float_extras", reason = "needs removal",
2436                issue = "27752")]
2437     #[rustc_deprecated(since = "1.11.0",
2438                        reason = "never really came to fruition and easily \
2439                                  implementable outside the standard library")]
2440     fn infinity() -> Self;
2441     /// Returns the negative infinite value.
2442     #[unstable(feature = "float_extras", reason = "needs removal",
2443                issue = "27752")]
2444     #[rustc_deprecated(since = "1.11.0",
2445                        reason = "never really came to fruition and easily \
2446                                  implementable outside the standard library")]
2447     fn neg_infinity() -> Self;
2448     /// Returns -0.0.
2449     #[unstable(feature = "float_extras", reason = "needs removal",
2450                issue = "27752")]
2451     #[rustc_deprecated(since = "1.11.0",
2452                        reason = "never really came to fruition and easily \
2453                                  implementable outside the standard library")]
2454     fn neg_zero() -> Self;
2455     /// Returns 0.0.
2456     #[unstable(feature = "float_extras", reason = "needs removal",
2457                issue = "27752")]
2458     #[rustc_deprecated(since = "1.11.0",
2459                        reason = "never really came to fruition and easily \
2460                                  implementable outside the standard library")]
2461     fn zero() -> Self;
2462     /// Returns 1.0.
2463     #[unstable(feature = "float_extras", reason = "needs removal",
2464                issue = "27752")]
2465     #[rustc_deprecated(since = "1.11.0",
2466                        reason = "never really came to fruition and easily \
2467                                  implementable outside the standard library")]
2468     fn one() -> Self;
2469
2470     /// Returns true if this value is NaN and false otherwise.
2471     #[stable(feature = "core", since = "1.6.0")]
2472     fn is_nan(self) -> bool;
2473     /// Returns true if this value is positive infinity or negative infinity and
2474     /// false otherwise.
2475     #[stable(feature = "core", since = "1.6.0")]
2476     fn is_infinite(self) -> bool;
2477     /// Returns true if this number is neither infinite nor NaN.
2478     #[stable(feature = "core", since = "1.6.0")]
2479     fn is_finite(self) -> bool;
2480     /// Returns true if this number is neither zero, infinite, denormal, or NaN.
2481     #[stable(feature = "core", since = "1.6.0")]
2482     fn is_normal(self) -> bool;
2483     /// Returns the category that this number falls into.
2484     #[stable(feature = "core", since = "1.6.0")]
2485     fn classify(self) -> FpCategory;
2486
2487     /// Returns the mantissa, exponent and sign as integers, respectively.
2488     #[unstable(feature = "float_extras", reason = "signature is undecided",
2489                issue = "27752")]
2490     #[rustc_deprecated(since = "1.11.0",
2491                        reason = "never really came to fruition and easily \
2492                                  implementable outside the standard library")]
2493     fn integer_decode(self) -> (u64, i16, i8);
2494
2495     /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2496     /// number is `Float::nan()`.
2497     #[stable(feature = "core", since = "1.6.0")]
2498     fn abs(self) -> Self;
2499     /// Returns a number that represents the sign of `self`.
2500     ///
2501     /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2502     /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2503     /// - `Float::nan()` if the number is `Float::nan()`
2504     #[stable(feature = "core", since = "1.6.0")]
2505     fn signum(self) -> Self;
2506
2507     /// Returns `true` if `self` is positive, including `+0.0` and
2508     /// `Float::infinity()`.
2509     #[stable(feature = "core", since = "1.6.0")]
2510     fn is_sign_positive(self) -> bool;
2511     /// Returns `true` if `self` is negative, including `-0.0` and
2512     /// `Float::neg_infinity()`.
2513     #[stable(feature = "core", since = "1.6.0")]
2514     fn is_sign_negative(self) -> bool;
2515
2516     /// Take the reciprocal (inverse) of a number, `1/x`.
2517     #[stable(feature = "core", since = "1.6.0")]
2518     fn recip(self) -> Self;
2519
2520     /// Raise a number to an integer power.
2521     ///
2522     /// Using this function is generally faster than using `powf`
2523     #[stable(feature = "core", since = "1.6.0")]
2524     fn powi(self, n: i32) -> Self;
2525
2526     /// Convert radians to degrees.
2527     #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2528     fn to_degrees(self) -> Self;
2529     /// Convert degrees to radians.
2530     #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2531     fn to_radians(self) -> Self;
2532 }
2533
2534 macro_rules! from_str_radix_int_impl {
2535     ($($t:ty)*) => {$(
2536         #[stable(feature = "rust1", since = "1.0.0")]
2537         impl FromStr for $t {
2538             type Err = ParseIntError;
2539             fn from_str(src: &str) -> Result<Self, ParseIntError> {
2540                 from_str_radix(src, 10)
2541             }
2542         }
2543     )*}
2544 }
2545 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
2546
2547 /// The error type returned when a checked integral type conversion fails.
2548 #[unstable(feature = "try_from", issue = "33417")]
2549 #[derive(Debug, Copy, Clone)]
2550 pub struct TryFromIntError(());
2551
2552 impl TryFromIntError {
2553     #[unstable(feature = "int_error_internals",
2554                reason = "available through Error trait and this method should \
2555                          not be exposed publicly",
2556                issue = "0")]
2557     #[doc(hidden)]
2558     pub fn __description(&self) -> &str {
2559         "out of range integral type conversion attempted"
2560     }
2561 }
2562
2563 #[unstable(feature = "try_from", issue = "33417")]
2564 impl fmt::Display for TryFromIntError {
2565     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2566         self.__description().fmt(fmt)
2567     }
2568 }
2569
2570 macro_rules! same_sign_from_int_impl {
2571     ($storage:ty, $target:ty, $($source:ty),*) => {$(
2572         #[unstable(feature = "try_from", issue = "33417")]
2573         impl TryFrom<$source> for $target {
2574             type Err = TryFromIntError;
2575
2576             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2577                 let min = <$target as FromStrRadixHelper>::min_value() as $storage;
2578                 let max = <$target as FromStrRadixHelper>::max_value() as $storage;
2579                 if u as $storage < min || u as $storage > max {
2580                     Err(TryFromIntError(()))
2581                 } else {
2582                     Ok(u as $target)
2583                 }
2584             }
2585         }
2586     )*}
2587 }
2588
2589 same_sign_from_int_impl!(u64, u8, u8, u16, u32, u64, usize);
2590 same_sign_from_int_impl!(i64, i8, i8, i16, i32, i64, isize);
2591 same_sign_from_int_impl!(u64, u16, u8, u16, u32, u64, usize);
2592 same_sign_from_int_impl!(i64, i16, i8, i16, i32, i64, isize);
2593 same_sign_from_int_impl!(u64, u32, u8, u16, u32, u64, usize);
2594 same_sign_from_int_impl!(i64, i32, i8, i16, i32, i64, isize);
2595 same_sign_from_int_impl!(u64, u64, u8, u16, u32, u64, usize);
2596 same_sign_from_int_impl!(i64, i64, i8, i16, i32, i64, isize);
2597 same_sign_from_int_impl!(u64, usize, u8, u16, u32, u64, usize);
2598 same_sign_from_int_impl!(i64, isize, i8, i16, i32, i64, isize);
2599
2600 macro_rules! cross_sign_from_int_impl {
2601     ($unsigned:ty, $($signed:ty),*) => {$(
2602         #[unstable(feature = "try_from", issue = "33417")]
2603         impl TryFrom<$unsigned> for $signed {
2604             type Err = TryFromIntError;
2605
2606             fn try_from(u: $unsigned) -> Result<$signed, TryFromIntError> {
2607                 let max = <$signed as FromStrRadixHelper>::max_value() as u64;
2608                 if u as u64 > max {
2609                     Err(TryFromIntError(()))
2610                 } else {
2611                     Ok(u as $signed)
2612                 }
2613             }
2614         }
2615
2616         #[unstable(feature = "try_from", issue = "33417")]
2617         impl TryFrom<$signed> for $unsigned {
2618             type Err = TryFromIntError;
2619
2620             fn try_from(u: $signed) -> Result<$unsigned, TryFromIntError> {
2621                 let max = <$unsigned as FromStrRadixHelper>::max_value() as u64;
2622                 if u < 0 || u as u64 > max {
2623                     Err(TryFromIntError(()))
2624                 } else {
2625                     Ok(u as $unsigned)
2626                 }
2627             }
2628         }
2629     )*}
2630 }
2631
2632 cross_sign_from_int_impl!(u8, i8, i16, i32, i64, isize);
2633 cross_sign_from_int_impl!(u16, i8, i16, i32, i64, isize);
2634 cross_sign_from_int_impl!(u32, i8, i16, i32, i64, isize);
2635 cross_sign_from_int_impl!(u64, i8, i16, i32, i64, isize);
2636 cross_sign_from_int_impl!(usize, i8, i16, i32, i64, isize);
2637
2638 #[doc(hidden)]
2639 trait FromStrRadixHelper: PartialOrd + Copy {
2640     fn min_value() -> Self;
2641     fn max_value() -> Self;
2642     fn from_u32(u: u32) -> Self;
2643     fn checked_mul(&self, other: u32) -> Option<Self>;
2644     fn checked_sub(&self, other: u32) -> Option<Self>;
2645     fn checked_add(&self, other: u32) -> Option<Self>;
2646 }
2647
2648 macro_rules! doit {
2649     ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
2650         fn min_value() -> Self { Self::min_value() }
2651         fn max_value() -> Self { Self::max_value() }
2652         fn from_u32(u: u32) -> Self { u as Self }
2653         fn checked_mul(&self, other: u32) -> Option<Self> {
2654             Self::checked_mul(*self, other as Self)
2655         }
2656         fn checked_sub(&self, other: u32) -> Option<Self> {
2657             Self::checked_sub(*self, other as Self)
2658         }
2659         fn checked_add(&self, other: u32) -> Option<Self> {
2660             Self::checked_add(*self, other as Self)
2661         }
2662     })*)
2663 }
2664 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
2665
2666 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
2667     use self::IntErrorKind::*;
2668     use self::ParseIntError as PIE;
2669
2670     assert!(radix >= 2 && radix <= 36,
2671            "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2672            radix);
2673
2674     if src.is_empty() {
2675         return Err(PIE { kind: Empty });
2676     }
2677
2678     let is_signed_ty = T::from_u32(0) > T::min_value();
2679
2680     // all valid digits are ascii, so we will just iterate over the utf8 bytes
2681     // and cast them to chars. .to_digit() will safely return None for anything
2682     // other than a valid ascii digit for the given radix, including the first-byte
2683     // of multi-byte sequences
2684     let src = src.as_bytes();
2685
2686     let (is_positive, digits) = match src[0] {
2687         b'+' => (true, &src[1..]),
2688         b'-' if is_signed_ty => (false, &src[1..]),
2689         _ => (true, src),
2690     };
2691
2692     if digits.is_empty() {
2693         return Err(PIE { kind: Empty });
2694     }
2695
2696     let mut result = T::from_u32(0);
2697     if is_positive {
2698         // The number is positive
2699         for &c in digits {
2700             let x = match (c as char).to_digit(radix) {
2701                 Some(x) => x,
2702                 None => return Err(PIE { kind: InvalidDigit }),
2703             };
2704             result = match result.checked_mul(radix) {
2705                 Some(result) => result,
2706                 None => return Err(PIE { kind: Overflow }),
2707             };
2708             result = match result.checked_add(x) {
2709                 Some(result) => result,
2710                 None => return Err(PIE { kind: Overflow }),
2711             };
2712         }
2713     } else {
2714         // The number is negative
2715         for &c in digits {
2716             let x = match (c as char).to_digit(radix) {
2717                 Some(x) => x,
2718                 None => return Err(PIE { kind: InvalidDigit }),
2719             };
2720             result = match result.checked_mul(radix) {
2721                 Some(result) => result,
2722                 None => return Err(PIE { kind: Underflow }),
2723             };
2724             result = match result.checked_sub(x) {
2725                 Some(result) => result,
2726                 None => return Err(PIE { kind: Underflow }),
2727             };
2728         }
2729     }
2730     Ok(result)
2731 }
2732
2733 /// An error which can be returned when parsing an integer.
2734 ///
2735 /// This error is used as the error type for the `from_str_radix()` functions
2736 /// on the primitive integer types, such as [`i8::from_str_radix()`].
2737 ///
2738 /// [`i8::from_str_radix()`]: ../../std/primitive.i8.html#method.from_str_radix
2739 #[derive(Debug, Clone, PartialEq, Eq)]
2740 #[stable(feature = "rust1", since = "1.0.0")]
2741 pub struct ParseIntError {
2742     kind: IntErrorKind,
2743 }
2744
2745 #[derive(Debug, Clone, PartialEq, Eq)]
2746 enum IntErrorKind {
2747     Empty,
2748     InvalidDigit,
2749     Overflow,
2750     Underflow,
2751 }
2752
2753 impl ParseIntError {
2754     #[unstable(feature = "int_error_internals",
2755                reason = "available through Error trait and this method should \
2756                          not be exposed publicly",
2757                issue = "0")]
2758     #[doc(hidden)]
2759     pub fn __description(&self) -> &str {
2760         match self.kind {
2761             IntErrorKind::Empty => "cannot parse integer from empty string",
2762             IntErrorKind::InvalidDigit => "invalid digit found in string",
2763             IntErrorKind::Overflow => "number too large to fit in target type",
2764             IntErrorKind::Underflow => "number too small to fit in target type",
2765         }
2766     }
2767 }
2768
2769 #[stable(feature = "rust1", since = "1.0.0")]
2770 impl fmt::Display for ParseIntError {
2771     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2772         self.__description().fmt(f)
2773     }
2774 }
2775
2776 #[stable(feature = "rust1", since = "1.0.0")]
2777 pub use num::dec2flt::ParseFloatError;
2778
2779 // Conversion traits for primitive integer and float types
2780 // Conversions T -> T are covered by a blanket impl and therefore excluded
2781 // Some conversions from and to usize/isize are not implemented due to portability concerns
2782 macro_rules! impl_from {
2783     ($Small: ty, $Large: ty) => {
2784         #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
2785         impl From<$Small> for $Large {
2786             #[inline]
2787             fn from(small: $Small) -> $Large {
2788                 small as $Large
2789             }
2790         }
2791     }
2792 }
2793
2794 // Unsigned -> Unsigned
2795 impl_from! { u8, u16 }
2796 impl_from! { u8, u32 }
2797 impl_from! { u8, u64 }
2798 impl_from! { u8, usize }
2799 impl_from! { u16, u32 }
2800 impl_from! { u16, u64 }
2801 impl_from! { u32, u64 }
2802
2803 // Signed -> Signed
2804 impl_from! { i8, i16 }
2805 impl_from! { i8, i32 }
2806 impl_from! { i8, i64 }
2807 impl_from! { i8, isize }
2808 impl_from! { i16, i32 }
2809 impl_from! { i16, i64 }
2810 impl_from! { i32, i64 }
2811
2812 // Unsigned -> Signed
2813 impl_from! { u8, i16 }
2814 impl_from! { u8, i32 }
2815 impl_from! { u8, i64 }
2816 impl_from! { u16, i32 }
2817 impl_from! { u16, i64 }
2818 impl_from! { u32, i64 }
2819
2820 // Note: integers can only be represented with full precision in a float if
2821 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2822 // Lossy float conversions are not implemented at this time.
2823
2824 // Signed -> Float
2825 impl_from! { i8, f32 }
2826 impl_from! { i8, f64 }
2827 impl_from! { i16, f32 }
2828 impl_from! { i16, f64 }
2829 impl_from! { i32, f64 }
2830
2831 // Unsigned -> Float
2832 impl_from! { u8, f32 }
2833 impl_from! { u8, f64 }
2834 impl_from! { u16, f32 }
2835 impl_from! { u16, f64 }
2836 impl_from! { u32, f64 }
2837
2838 // Float -> Float
2839 impl_from! { f32, f64 }