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