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