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