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