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