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