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