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