]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
Auto merge of #31461 - jseyfried:remove_import_resolutions, r=nrc
[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 pub 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!(u32::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 = 0b01001100u8;
167         ///
168         /// assert_eq!(n.count_ones(), 3);
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 = 0b01001100u8;
182         ///
183         /// assert_eq!(n.count_zeros(), 5);
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 = 0b0101000u16;
200         ///
201         /// assert_eq!(n.leading_zeros(), 10);
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 = 0b0101000u16;
218         ///
219         /// assert_eq!(n.trailing_zeros(), 3);
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 = 0x0123456789ABCDEFu64;
236         /// let m = 0x3456789ABCDEF012u64;
237         ///
238         /// assert_eq!(n.rotate_left(12), 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 = 0x0123456789ABCDEFu64;
256         /// let m = 0xDEF0123456789ABCu64;
257         ///
258         /// assert_eq!(n.rotate_right(12), 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 = 0x0123456789ABCDEFu64;
274         /// let m = 0xEFCDAB8967452301u64;
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 = 0x0123456789ABCDEFu64;
295         ///
296         /// if cfg!(target_endian = "big") {
297         ///     assert_eq!(u64::from_be(n), n)
298         /// } else {
299         ///     assert_eq!(u64::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 = 0x0123456789ABCDEFu64;
319         ///
320         /// if cfg!(target_endian = "little") {
321         ///     assert_eq!(u64::from_le(n), n)
322         /// } else {
323         ///     assert_eq!(u64::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 = 0x0123456789ABCDEFu64;
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 = 0x0123456789ABCDEFu64;
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!(5u16.checked_add(65530), Some(65535));
389         /// assert_eq!(6u16.checked_add(65530), 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!(5u8.checked_mul(51), Some(255));
425         /// assert_eq!(5u8.checked_mul(52), 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         /// # Examples
745         ///
746         /// Basic usage:
747         ///
748         /// ```
749         /// assert_eq!(1u8.wrapping_shl(7), 128);
750         /// assert_eq!(1u8.wrapping_shl(8), 1);
751         /// ```
752         #[stable(feature = "num_wrapping", since = "1.2.0")]
753         #[inline(always)]
754         pub fn wrapping_shl(self, rhs: u32) -> Self {
755             self.overflowing_shl(rhs).0
756         }
757
758         /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
759         /// where `mask` removes any high-order bits of `rhs` that
760         /// would cause the shift to exceed the bitwidth of the type.
761         ///
762         /// # Examples
763         ///
764         /// Basic usage:
765         ///
766         /// ```
767         /// assert_eq!(128u8.wrapping_shr(7), 1);
768         /// assert_eq!(128u8.wrapping_shr(8), 128);
769         /// ```
770         #[stable(feature = "num_wrapping", since = "1.2.0")]
771         #[inline(always)]
772         pub fn wrapping_shr(self, rhs: u32) -> Self {
773             self.overflowing_shr(rhs).0
774         }
775
776         /// Calculates `self` + `rhs`
777         ///
778         /// Returns a tuple of the addition along with a boolean indicating
779         /// whether an arithmetic overflow would occur. If an overflow would
780         /// have occurred then the wrapped value is returned.
781         ///
782         /// # Examples
783         ///
784         /// Basic usage
785         ///
786         /// ```
787         /// use std::i32;
788         ///
789         /// assert_eq!(5i32.overflowing_add(2), (7, false));
790         /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
791         /// ```
792         #[inline]
793         #[stable(feature = "wrapping", since = "1.7.0")]
794         pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
795             unsafe {
796                 let (a, b) = $add_with_overflow(self as $ActualT,
797                                                 rhs as $ActualT);
798                 (a as Self, b)
799             }
800         }
801
802         /// Calculates `self` - `rhs`
803         ///
804         /// Returns a tuple of the subtraction along with a boolean indicating
805         /// whether an arithmetic overflow would occur. If an overflow would
806         /// have occurred then the wrapped value is returned.
807         ///
808         /// # Examples
809         ///
810         /// Basic usage
811         ///
812         /// ```
813         /// use std::i32;
814         ///
815         /// assert_eq!(5i32.overflowing_sub(2), (3, false));
816         /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
817         /// ```
818         #[inline]
819         #[stable(feature = "wrapping", since = "1.7.0")]
820         pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
821             unsafe {
822                 let (a, b) = $sub_with_overflow(self as $ActualT,
823                                                 rhs as $ActualT);
824                 (a as Self, b)
825             }
826         }
827
828         /// Calculates the multiplication of `self` and `rhs`.
829         ///
830         /// Returns a tuple of the multiplication along with a boolean
831         /// indicating whether an arithmetic overflow would occur. If an
832         /// overflow would have occurred then the wrapped value is returned.
833         ///
834         /// # Examples
835         ///
836         /// Basic usage
837         ///
838         /// ```
839         /// assert_eq!(5i32.overflowing_mul(2), (10, false));
840         /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
841         /// ```
842         #[inline]
843         #[stable(feature = "wrapping", since = "1.7.0")]
844         pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
845             unsafe {
846                 let (a, b) = $mul_with_overflow(self as $ActualT,
847                                                 rhs as $ActualT);
848                 (a as Self, b)
849             }
850         }
851
852         /// Calculates the divisor when `self` is divided by `rhs`.
853         ///
854         /// Returns a tuple of the divisor along with a boolean indicating
855         /// whether an arithmetic overflow would occur. If an overflow would
856         /// occur then self is returned.
857         ///
858         /// # Panics
859         ///
860         /// This function will panic if `rhs` is 0.
861         ///
862         /// # Examples
863         ///
864         /// Basic usage
865         ///
866         /// ```
867         /// use std::i32;
868         ///
869         /// assert_eq!(5i32.overflowing_div(2), (2, false));
870         /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
871         /// ```
872         #[inline]
873         #[stable(feature = "wrapping", since = "1.7.0")]
874         pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
875             if self == Self::min_value() && rhs == -1 {
876                 (self, true)
877             } else {
878                 (self / rhs, false)
879             }
880         }
881
882         /// Calculates the remainder when `self` is divided by `rhs`.
883         ///
884         /// Returns a tuple of the remainder after dividing along with a boolean
885         /// indicating whether an arithmetic overflow would occur. If an
886         /// overflow would occur then 0 is returned.
887         ///
888         /// # Panics
889         ///
890         /// This function will panic if `rhs` is 0.
891         ///
892         /// # Examples
893         ///
894         /// Basic usage
895         ///
896         /// ```
897         /// use std::i32;
898         ///
899         /// assert_eq!(5i32.overflowing_rem(2), (1, false));
900         /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
901         /// ```
902         #[inline]
903         #[stable(feature = "wrapping", since = "1.7.0")]
904         pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
905             if self == Self::min_value() && rhs == -1 {
906                 (0, true)
907             } else {
908                 (self % rhs, false)
909             }
910         }
911
912         /// Negates self, overflowing if this is equal to the minimum value.
913         ///
914         /// Returns a tuple of the negated version of self along with a boolean
915         /// indicating whether an overflow happened. If `self` is the minimum
916         /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
917         /// value will be returned again and `true` will be returned for an
918         /// overflow happening.
919         ///
920         /// # Examples
921         ///
922         /// Basic usage
923         ///
924         /// ```
925         /// use std::i32;
926         ///
927         /// assert_eq!(2i32.overflowing_neg(), (-2, false));
928         /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
929         /// ```
930         #[inline]
931         #[stable(feature = "wrapping", since = "1.7.0")]
932         pub fn overflowing_neg(self) -> (Self, bool) {
933             if self == Self::min_value() {
934                 (Self::min_value(), true)
935             } else {
936                 (-self, false)
937             }
938         }
939
940         /// Shifts self left by `rhs` bits.
941         ///
942         /// Returns a tuple of the shifted version of self along with a boolean
943         /// indicating whether the shift value was larger than or equal to the
944         /// number of bits. If the shift value is too large, then value is
945         /// masked (N-1) where N is the number of bits, and this value is then
946         /// used to perform the shift.
947         ///
948         /// # Examples
949         ///
950         /// Basic usage
951         ///
952         /// ```
953         /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
954         /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
955         /// ```
956         #[inline]
957         #[stable(feature = "wrapping", since = "1.7.0")]
958         pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
959             (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
960         }
961
962         /// Shifts self right by `rhs` bits.
963         ///
964         /// Returns a tuple of the shifted version of self along with a boolean
965         /// indicating whether the shift value was larger than or equal to the
966         /// number of bits. If the shift value is too large, then value is
967         /// masked (N-1) where N is the number of bits, and this value is then
968         /// used to perform the shift.
969         ///
970         /// # Examples
971         ///
972         /// Basic usage
973         ///
974         /// ```
975         /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
976         /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
977         /// ```
978         #[inline]
979         #[stable(feature = "wrapping", since = "1.7.0")]
980         pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
981             (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
982         }
983
984         /// Raises self to the power of `exp`, using exponentiation by squaring.
985         ///
986         /// # Examples
987         ///
988         /// Basic usage:
989         ///
990         /// ```
991         /// let x: i32 = 2; // or any other integer type
992         ///
993         /// assert_eq!(x.pow(4), 16);
994         /// ```
995         #[stable(feature = "rust1", since = "1.0.0")]
996         #[inline]
997         pub fn pow(self, mut exp: u32) -> Self {
998             let mut base = self;
999             let mut acc = Self::one();
1000
1001             while exp > 1 {
1002                 if (exp & 1) == 1 {
1003                     acc = acc * base;
1004                 }
1005                 exp /= 2;
1006                 base = base * base;
1007             }
1008
1009             // Deal with the final bit of the exponent separately, since
1010             // squaring the base afterwards is not necessary and may cause a
1011             // needless overflow.
1012             if exp == 1 {
1013                 acc = acc * base;
1014             }
1015
1016             acc
1017         }
1018
1019         /// Computes the absolute value of `self`.
1020         ///
1021         /// # Overflow behavior
1022         ///
1023         /// The absolute value of `i32::min_value()` cannot be represented as an
1024         /// `i32`, and attempting to calculate it will cause an overflow. This
1025         /// means that code in debug mode will trigger a panic on this case and
1026         /// optimized code will return `i32::min_value()` without a panic.
1027         ///
1028         /// # Examples
1029         ///
1030         /// Basic usage:
1031         ///
1032         /// ```
1033         /// assert_eq!(10i8.abs(), 10);
1034         /// assert_eq!((-10i8).abs(), 10);
1035         /// ```
1036         #[stable(feature = "rust1", since = "1.0.0")]
1037         #[inline]
1038         pub fn abs(self) -> Self {
1039             if self.is_negative() {
1040                 // Note that the #[inline] above means that the overflow
1041                 // semantics of this negation depend on the crate we're being
1042                 // inlined into.
1043                 -self
1044             } else {
1045                 self
1046             }
1047         }
1048
1049         /// Returns a number representing sign of `self`.
1050         ///
1051         /// - `0` if the number is zero
1052         /// - `1` if the number is positive
1053         /// - `-1` if the number is negative
1054         ///
1055         /// # Examples
1056         ///
1057         /// Basic usage:
1058         ///
1059         /// ```
1060         /// assert_eq!(10i8.signum(), 1);
1061         /// assert_eq!(0i8.signum(), 0);
1062         /// assert_eq!((-10i8).signum(), -1);
1063         /// ```
1064         #[stable(feature = "rust1", since = "1.0.0")]
1065         #[inline]
1066         pub fn signum(self) -> Self {
1067             match self {
1068                 n if n > 0 =>  1,
1069                 0          =>  0,
1070                 _          => -1,
1071             }
1072         }
1073
1074         /// Returns `true` if `self` is positive and `false` if the number
1075         /// is zero or negative.
1076         ///
1077         /// # Examples
1078         ///
1079         /// Basic usage:
1080         ///
1081         /// ```
1082         /// assert!(10i8.is_positive());
1083         /// assert!(!(-10i8).is_positive());
1084         /// ```
1085         #[stable(feature = "rust1", since = "1.0.0")]
1086         #[inline]
1087         pub fn is_positive(self) -> bool { self > 0 }
1088
1089         /// Returns `true` if `self` is negative and `false` if the number
1090         /// is zero or positive.
1091         ///
1092         /// # Examples
1093         ///
1094         /// Basic usage:
1095         ///
1096         /// ```
1097         /// assert!((-10i8).is_negative());
1098         /// assert!(!10i8.is_negative());
1099         /// ```
1100         #[stable(feature = "rust1", since = "1.0.0")]
1101         #[inline]
1102         pub fn is_negative(self) -> bool { self < 0 }
1103     }
1104 }
1105
1106 #[lang = "i8"]
1107 impl i8 {
1108     int_impl! { i8, u8, 8,
1109         intrinsics::add_with_overflow,
1110         intrinsics::sub_with_overflow,
1111         intrinsics::mul_with_overflow }
1112 }
1113
1114 #[lang = "i16"]
1115 impl i16 {
1116     int_impl! { i16, u16, 16,
1117         intrinsics::add_with_overflow,
1118         intrinsics::sub_with_overflow,
1119         intrinsics::mul_with_overflow }
1120 }
1121
1122 #[lang = "i32"]
1123 impl i32 {
1124     int_impl! { i32, u32, 32,
1125         intrinsics::add_with_overflow,
1126         intrinsics::sub_with_overflow,
1127         intrinsics::mul_with_overflow }
1128 }
1129
1130 #[lang = "i64"]
1131 impl i64 {
1132     int_impl! { i64, u64, 64,
1133         intrinsics::add_with_overflow,
1134         intrinsics::sub_with_overflow,
1135         intrinsics::mul_with_overflow }
1136 }
1137
1138 #[cfg(target_pointer_width = "32")]
1139 #[lang = "isize"]
1140 impl isize {
1141     int_impl! { i32, u32, 32,
1142         intrinsics::add_with_overflow,
1143         intrinsics::sub_with_overflow,
1144         intrinsics::mul_with_overflow }
1145 }
1146
1147 #[cfg(target_pointer_width = "64")]
1148 #[lang = "isize"]
1149 impl isize {
1150     int_impl! { i64, u64, 64,
1151         intrinsics::add_with_overflow,
1152         intrinsics::sub_with_overflow,
1153         intrinsics::mul_with_overflow }
1154 }
1155
1156 // `Int` + `UnsignedInt` implemented for unsigned integers
1157 macro_rules! uint_impl {
1158     ($ActualT:ty, $BITS:expr,
1159      $ctpop:path,
1160      $ctlz:path,
1161      $cttz:path,
1162      $bswap:path,
1163      $add_with_overflow:path,
1164      $sub_with_overflow:path,
1165      $mul_with_overflow:path) => {
1166         /// Returns the smallest value that can be represented by this integer type.
1167         #[stable(feature = "rust1", since = "1.0.0")]
1168         #[inline]
1169         pub const fn min_value() -> Self { 0 }
1170
1171         /// Returns the largest value that can be represented by this integer type.
1172         #[stable(feature = "rust1", since = "1.0.0")]
1173         #[inline]
1174         pub const fn max_value() -> Self { !0 }
1175
1176         /// Converts a string slice in a given base to an integer.
1177         ///
1178         /// Leading and trailing whitespace represent an error.
1179         ///
1180         /// # Arguments
1181         ///
1182         /// * src - A string slice
1183         /// * radix - The base to use. Must lie in the range [2 .. 36]
1184         ///
1185         /// # Return value
1186         ///
1187         /// `Err(ParseIntError)` if the string did not represent a valid number.
1188         /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
1189         #[stable(feature = "rust1", since = "1.0.0")]
1190         pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1191             from_str_radix(src, radix)
1192         }
1193
1194         /// Returns the number of ones in the binary representation of `self`.
1195         ///
1196         /// # Examples
1197         ///
1198         /// Basic usage:
1199         ///
1200         /// ```
1201         /// let n = 0b01001100u8;
1202         ///
1203         /// assert_eq!(n.count_ones(), 3);
1204         /// ```
1205         #[stable(feature = "rust1", since = "1.0.0")]
1206         #[inline]
1207         pub fn count_ones(self) -> u32 {
1208             unsafe { $ctpop(self as $ActualT) as u32 }
1209         }
1210
1211         /// Returns the number of zeros in the binary representation of `self`.
1212         ///
1213         /// # Examples
1214         ///
1215         /// Basic usage:
1216         ///
1217         /// ```
1218         /// let n = 0b01001100u8;
1219         ///
1220         /// assert_eq!(n.count_zeros(), 5);
1221         /// ```
1222         #[stable(feature = "rust1", since = "1.0.0")]
1223         #[inline]
1224         pub fn count_zeros(self) -> u32 {
1225             (!self).count_ones()
1226         }
1227
1228         /// Returns the number of leading zeros in the binary representation
1229         /// of `self`.
1230         ///
1231         /// # Examples
1232         ///
1233         /// Basic usage:
1234         ///
1235         /// ```
1236         /// let n = 0b0101000u16;
1237         ///
1238         /// assert_eq!(n.leading_zeros(), 10);
1239         /// ```
1240         #[stable(feature = "rust1", since = "1.0.0")]
1241         #[inline]
1242         pub fn leading_zeros(self) -> u32 {
1243             unsafe { $ctlz(self as $ActualT) as u32 }
1244         }
1245
1246         /// Returns the number of trailing zeros in the binary representation
1247         /// of `self`.
1248         ///
1249         /// # Examples
1250         ///
1251         /// Basic usage:
1252         ///
1253         /// ```
1254         /// let n = 0b0101000u16;
1255         ///
1256         /// assert_eq!(n.trailing_zeros(), 3);
1257         /// ```
1258         #[stable(feature = "rust1", since = "1.0.0")]
1259         #[inline]
1260         pub fn trailing_zeros(self) -> u32 {
1261             // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1262             // emits two conditional moves on x86_64. By promoting the value to
1263             // u16 and setting bit 8, we get better code without any conditional
1264             // operations.
1265             // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1266             // pending, remove this workaround once LLVM generates better code
1267             // for cttz8.
1268             unsafe {
1269                 if $BITS == 8 {
1270                     intrinsics::cttz(self as u16 | 0x100) as u32
1271                 } else {
1272                     intrinsics::cttz(self) as u32
1273                 }
1274             }
1275         }
1276
1277         /// Shifts the bits to the left by a specified amount, `n`,
1278         /// wrapping the truncated bits to the end of the resulting integer.
1279         ///
1280         /// # Examples
1281         ///
1282         /// Basic usage:
1283         ///
1284         /// ```
1285         /// let n = 0x0123456789ABCDEFu64;
1286         /// let m = 0x3456789ABCDEF012u64;
1287         ///
1288         /// assert_eq!(n.rotate_left(12), m);
1289         /// ```
1290         #[stable(feature = "rust1", since = "1.0.0")]
1291         #[inline]
1292         pub fn rotate_left(self, n: u32) -> Self {
1293             // Protect against undefined behaviour for over-long bit shifts
1294             let n = n % $BITS;
1295             (self << n) | (self >> (($BITS - n) % $BITS))
1296         }
1297
1298         /// Shifts the bits to the right by a specified amount, `n`,
1299         /// wrapping the truncated bits to the beginning of the resulting
1300         /// integer.
1301         ///
1302         /// # Examples
1303         ///
1304         /// Basic usage:
1305         ///
1306         /// ```
1307         /// let n = 0x0123456789ABCDEFu64;
1308         /// let m = 0xDEF0123456789ABCu64;
1309         ///
1310         /// assert_eq!(n.rotate_right(12), m);
1311         /// ```
1312         #[stable(feature = "rust1", since = "1.0.0")]
1313         #[inline]
1314         pub fn rotate_right(self, n: u32) -> Self {
1315             // Protect against undefined behaviour for over-long bit shifts
1316             let n = n % $BITS;
1317             (self >> n) | (self << (($BITS - n) % $BITS))
1318         }
1319
1320         /// Reverses the byte order of the integer.
1321         ///
1322         /// # Examples
1323         ///
1324         /// Basic usage:
1325         ///
1326         /// ```
1327         /// let n = 0x0123456789ABCDEFu64;
1328         /// let m = 0xEFCDAB8967452301u64;
1329         ///
1330         /// assert_eq!(n.swap_bytes(), m);
1331         /// ```
1332         #[stable(feature = "rust1", since = "1.0.0")]
1333         #[inline]
1334         pub fn swap_bytes(self) -> Self {
1335             unsafe { $bswap(self as $ActualT) as Self }
1336         }
1337
1338         /// Converts an integer from big endian to the target's endianness.
1339         ///
1340         /// On big endian this is a no-op. On little endian the bytes are
1341         /// swapped.
1342         ///
1343         /// # Examples
1344         ///
1345         /// Basic usage:
1346         ///
1347         /// ```
1348         /// let n = 0x0123456789ABCDEFu64;
1349         ///
1350         /// if cfg!(target_endian = "big") {
1351         ///     assert_eq!(u64::from_be(n), n)
1352         /// } else {
1353         ///     assert_eq!(u64::from_be(n), n.swap_bytes())
1354         /// }
1355         /// ```
1356         #[stable(feature = "rust1", since = "1.0.0")]
1357         #[inline]
1358         pub fn from_be(x: Self) -> Self {
1359             if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1360         }
1361
1362         /// Converts an integer from little endian to the target's endianness.
1363         ///
1364         /// On little endian this is a no-op. On big endian the bytes are
1365         /// swapped.
1366         ///
1367         /// # Examples
1368         ///
1369         /// Basic usage:
1370         ///
1371         /// ```
1372         /// let n = 0x0123456789ABCDEFu64;
1373         ///
1374         /// if cfg!(target_endian = "little") {
1375         ///     assert_eq!(u64::from_le(n), n)
1376         /// } else {
1377         ///     assert_eq!(u64::from_le(n), n.swap_bytes())
1378         /// }
1379         /// ```
1380         #[stable(feature = "rust1", since = "1.0.0")]
1381         #[inline]
1382         pub fn from_le(x: Self) -> Self {
1383             if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1384         }
1385
1386         /// Converts `self` to big endian from the target's endianness.
1387         ///
1388         /// On big endian this is a no-op. On little endian the bytes are
1389         /// swapped.
1390         ///
1391         /// # Examples
1392         ///
1393         /// Basic usage:
1394         ///
1395         /// ```
1396         /// let n = 0x0123456789ABCDEFu64;
1397         ///
1398         /// if cfg!(target_endian = "big") {
1399         ///     assert_eq!(n.to_be(), n)
1400         /// } else {
1401         ///     assert_eq!(n.to_be(), n.swap_bytes())
1402         /// }
1403         /// ```
1404         #[stable(feature = "rust1", since = "1.0.0")]
1405         #[inline]
1406         pub fn to_be(self) -> Self { // or not to be?
1407             if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1408         }
1409
1410         /// Converts `self` to little endian from the target's endianness.
1411         ///
1412         /// On little endian this is a no-op. On big endian the bytes are
1413         /// swapped.
1414         ///
1415         /// # Examples
1416         ///
1417         /// Basic usage:
1418         ///
1419         /// ```
1420         /// let n = 0x0123456789ABCDEFu64;
1421         ///
1422         /// if cfg!(target_endian = "little") {
1423         ///     assert_eq!(n.to_le(), n)
1424         /// } else {
1425         ///     assert_eq!(n.to_le(), n.swap_bytes())
1426         /// }
1427         /// ```
1428         #[stable(feature = "rust1", since = "1.0.0")]
1429         #[inline]
1430         pub fn to_le(self) -> Self {
1431             if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1432         }
1433
1434         /// Checked integer addition. Computes `self + other`, returning `None`
1435         /// if overflow occurred.
1436         ///
1437         /// # Examples
1438         ///
1439         /// Basic usage:
1440         ///
1441         /// ```
1442         /// assert_eq!(5u16.checked_add(65530), Some(65535));
1443         /// assert_eq!(6u16.checked_add(65530), None);
1444         /// ```
1445         #[stable(feature = "rust1", since = "1.0.0")]
1446         #[inline]
1447         pub fn checked_add(self, other: Self) -> Option<Self> {
1448             let (a, b) = self.overflowing_add(other);
1449             if b {None} else {Some(a)}
1450         }
1451
1452         /// Checked integer subtraction. Computes `self - other`, returning
1453         /// `None` if underflow occurred.
1454         ///
1455         /// # Examples
1456         ///
1457         /// Basic usage:
1458         ///
1459         /// ```
1460         /// assert_eq!(1u8.checked_sub(1), Some(0));
1461         /// assert_eq!(0u8.checked_sub(1), None);
1462         /// ```
1463         #[stable(feature = "rust1", since = "1.0.0")]
1464         #[inline]
1465         pub fn checked_sub(self, other: Self) -> Option<Self> {
1466             let (a, b) = self.overflowing_sub(other);
1467             if b {None} else {Some(a)}
1468         }
1469
1470         /// Checked integer multiplication. Computes `self * other`, returning
1471         /// `None` if underflow or overflow occurred.
1472         ///
1473         /// # Examples
1474         ///
1475         /// Basic usage:
1476         ///
1477         /// ```
1478         /// assert_eq!(5u8.checked_mul(51), Some(255));
1479         /// assert_eq!(5u8.checked_mul(52), None);
1480         /// ```
1481         #[stable(feature = "rust1", since = "1.0.0")]
1482         #[inline]
1483         pub fn checked_mul(self, other: Self) -> Option<Self> {
1484             let (a, b) = self.overflowing_mul(other);
1485             if b {None} else {Some(a)}
1486         }
1487
1488         /// Checked integer division. Computes `self / other`, returning `None`
1489         /// if `other == 0` or the operation results in underflow or overflow.
1490         ///
1491         /// # Examples
1492         ///
1493         /// Basic usage:
1494         ///
1495         /// ```
1496         /// assert_eq!(128u8.checked_div(2), Some(64));
1497         /// assert_eq!(1u8.checked_div(0), None);
1498         /// ```
1499         #[stable(feature = "rust1", since = "1.0.0")]
1500         #[inline]
1501         pub fn checked_div(self, other: Self) -> Option<Self> {
1502             match other {
1503                 0 => None,
1504                 other => Some(self / other),
1505             }
1506         }
1507
1508         /// Checked integer remainder. Computes `self % other`, returning `None`
1509         /// if `other == 0` or the operation results in underflow or overflow.
1510         ///
1511         /// # Examples
1512         ///
1513         /// Basic usage:
1514         ///
1515         /// ```
1516         /// assert_eq!(5u32.checked_rem(2), Some(1));
1517         /// assert_eq!(5u32.checked_rem(0), None);
1518         /// ```
1519         #[stable(feature = "wrapping", since = "1.7.0")]
1520         #[inline]
1521         pub fn checked_rem(self, other: Self) -> Option<Self> {
1522             if other == 0 {
1523                 None
1524             } else {
1525                 Some(self % other)
1526             }
1527         }
1528
1529         /// Checked negation. Computes `-self`, returning `None` unless `self ==
1530         /// 0`.
1531         ///
1532         /// Note that negating any positive integer will overflow.
1533         ///
1534         /// # Examples
1535         ///
1536         /// Basic usage:
1537         ///
1538         /// ```
1539         /// assert_eq!(0u32.checked_neg(), Some(0));
1540         /// assert_eq!(1u32.checked_neg(), None);
1541         /// ```
1542         #[stable(feature = "wrapping", since = "1.7.0")]
1543         #[inline]
1544         pub fn checked_neg(self) -> Option<Self> {
1545             let (a, b) = self.overflowing_neg();
1546             if b {None} else {Some(a)}
1547         }
1548
1549         /// Checked shift left. Computes `self << rhs`, returning `None`
1550         /// if `rhs` is larger than or equal to the number of bits in `self`.
1551         ///
1552         /// # Examples
1553         ///
1554         /// Basic usage:
1555         ///
1556         /// ```
1557         /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1558         /// assert_eq!(0x10u32.checked_shl(33), None);
1559         /// ```
1560         #[stable(feature = "wrapping", since = "1.7.0")]
1561         #[inline]
1562         pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1563             let (a, b) = self.overflowing_shl(rhs);
1564             if b {None} else {Some(a)}
1565         }
1566
1567         /// Checked shift right. Computes `self >> rhs`, returning `None`
1568         /// if `rhs` is larger than or equal to the number of bits in `self`.
1569         ///
1570         /// # Examples
1571         ///
1572         /// Basic usage:
1573         ///
1574         /// ```
1575         /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1576         /// assert_eq!(0x10u32.checked_shr(33), None);
1577         /// ```
1578         #[stable(feature = "wrapping", since = "1.7.0")]
1579         #[inline]
1580         pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1581             let (a, b) = self.overflowing_shr(rhs);
1582             if b {None} else {Some(a)}
1583         }
1584
1585         /// Saturating integer addition. Computes `self + other`, saturating at
1586         /// the numeric bounds instead of overflowing.
1587         ///
1588         /// # Examples
1589         ///
1590         /// Basic usage:
1591         ///
1592         /// ```
1593         /// assert_eq!(100u8.saturating_add(1), 101);
1594         /// assert_eq!(200u8.saturating_add(127), 255);
1595         /// ```
1596         #[stable(feature = "rust1", since = "1.0.0")]
1597         #[inline]
1598         pub fn saturating_add(self, other: Self) -> Self {
1599             match self.checked_add(other) {
1600                 Some(x) => x,
1601                 None => Self::max_value(),
1602             }
1603         }
1604
1605         /// Saturating integer subtraction. Computes `self - other`, saturating
1606         /// at the numeric bounds instead of overflowing.
1607         ///
1608         /// # Examples
1609         ///
1610         /// Basic usage:
1611         ///
1612         /// ```
1613         /// assert_eq!(100u8.saturating_sub(27), 73);
1614         /// assert_eq!(13u8.saturating_sub(127), 0);
1615         /// ```
1616         #[stable(feature = "rust1", since = "1.0.0")]
1617         #[inline]
1618         pub fn saturating_sub(self, other: Self) -> Self {
1619             match self.checked_sub(other) {
1620                 Some(x) => x,
1621                 None => Self::min_value(),
1622             }
1623         }
1624
1625         /// Saturating integer multiplication. Computes `self * other`,
1626         /// saturating at the numeric bounds instead of overflowing.
1627         ///
1628         /// # Examples
1629         ///
1630         /// Basic usage:
1631         ///
1632         /// ```
1633         /// use std::u32;
1634         ///
1635         /// assert_eq!(100u32.saturating_mul(127), 12700);
1636         /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1637         /// ```
1638         #[stable(feature = "wrapping", since = "1.7.0")]
1639         #[inline]
1640         pub fn saturating_mul(self, other: Self) -> Self {
1641             self.checked_mul(other).unwrap_or(Self::max_value())
1642         }
1643
1644         /// Wrapping (modular) addition. Computes `self + other`,
1645         /// wrapping around at the boundary of the type.
1646         ///
1647         /// # Examples
1648         ///
1649         /// Basic usage:
1650         ///
1651         /// ```
1652         /// assert_eq!(200u8.wrapping_add(55), 255);
1653         /// assert_eq!(200u8.wrapping_add(155), 99);
1654         /// ```
1655         #[stable(feature = "rust1", since = "1.0.0")]
1656         #[inline]
1657         pub fn wrapping_add(self, rhs: Self) -> Self {
1658             unsafe {
1659                 intrinsics::overflowing_add(self, rhs)
1660             }
1661         }
1662
1663         /// Wrapping (modular) subtraction. Computes `self - other`,
1664         /// wrapping around at the boundary of the type.
1665         ///
1666         /// # Examples
1667         ///
1668         /// Basic usage:
1669         ///
1670         /// ```
1671         /// assert_eq!(100u8.wrapping_sub(100), 0);
1672         /// assert_eq!(100u8.wrapping_sub(155), 201);
1673         /// ```
1674         #[stable(feature = "rust1", since = "1.0.0")]
1675         #[inline]
1676         pub fn wrapping_sub(self, rhs: Self) -> Self {
1677             unsafe {
1678                 intrinsics::overflowing_sub(self, rhs)
1679             }
1680         }
1681
1682         /// Wrapping (modular) multiplication. Computes `self *
1683         /// other`, wrapping around at the boundary of the type.
1684         ///
1685         /// # Examples
1686         ///
1687         /// Basic usage:
1688         ///
1689         /// ```
1690         /// assert_eq!(10u8.wrapping_mul(12), 120);
1691         /// assert_eq!(25u8.wrapping_mul(12), 44);
1692         /// ```
1693         #[stable(feature = "rust1", since = "1.0.0")]
1694         #[inline]
1695         pub fn wrapping_mul(self, rhs: Self) -> Self {
1696             unsafe {
1697                 intrinsics::overflowing_mul(self, rhs)
1698             }
1699         }
1700
1701         /// Wrapping (modular) division. Computes `self / other`.
1702         /// Wrapped division on unsigned types is just normal division.
1703         /// There's no way wrapping could ever happen.
1704         /// This function exists, so that all operations
1705         /// are accounted for in the wrapping operations.
1706         ///
1707         /// # Examples
1708         ///
1709         /// Basic usage:
1710         ///
1711         /// ```
1712         /// assert_eq!(100u8.wrapping_div(10), 10);
1713         /// ```
1714         #[stable(feature = "num_wrapping", since = "1.2.0")]
1715         #[inline(always)]
1716         pub fn wrapping_div(self, rhs: Self) -> Self {
1717             self / rhs
1718         }
1719
1720         /// Wrapping (modular) remainder. Computes `self % other`.
1721         /// Wrapped remainder calculation on unsigned types is
1722         /// just the regular remainder calculation.
1723         /// There's no way wrapping could ever happen.
1724         /// This function exists, so that all operations
1725         /// are accounted for in the wrapping operations.
1726         ///
1727         /// # Examples
1728         ///
1729         /// Basic usage:
1730         ///
1731         /// ```
1732         /// assert_eq!(100i8.wrapping_rem(10), 0);
1733         /// ```
1734         #[stable(feature = "num_wrapping", since = "1.2.0")]
1735         #[inline(always)]
1736         pub fn wrapping_rem(self, rhs: Self) -> Self {
1737             self % rhs
1738         }
1739
1740         /// Wrapping (modular) negation. Computes `-self`,
1741         /// wrapping around at the boundary of the type.
1742         ///
1743         /// Since unsigned types do not have negative equivalents
1744         /// all applications of this function will wrap (except for `-0`).
1745         /// For values smaller than the corresponding signed type's maximum
1746         /// the result is the same as casting the corresponding signed value.
1747         /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1748         /// `MAX` is the corresponding signed type's maximum.
1749         ///
1750         /// # Examples
1751         ///
1752         /// Basic usage:
1753         ///
1754         /// ```
1755         /// assert_eq!(100u8.wrapping_neg(), 156);
1756         /// assert_eq!(0u8.wrapping_neg(), 0);
1757         /// assert_eq!(180u8.wrapping_neg(), 76);
1758         /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1759         /// ```
1760         #[stable(feature = "num_wrapping", since = "1.2.0")]
1761         #[inline(always)]
1762         pub fn wrapping_neg(self) -> Self {
1763             self.overflowing_neg().0
1764         }
1765
1766         /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1767         /// where `mask` removes any high-order bits of `rhs` that
1768         /// would cause the shift to exceed the bitwidth of the type.
1769         ///
1770         /// # Examples
1771         ///
1772         /// Basic usage:
1773         ///
1774         /// ```
1775         /// assert_eq!(1u8.wrapping_shl(7), 128);
1776         /// assert_eq!(1u8.wrapping_shl(8), 1);
1777         /// ```
1778         #[stable(feature = "num_wrapping", since = "1.2.0")]
1779         #[inline(always)]
1780         pub fn wrapping_shl(self, rhs: u32) -> Self {
1781             self.overflowing_shl(rhs).0
1782         }
1783
1784         /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1785         /// where `mask` removes any high-order bits of `rhs` that
1786         /// would cause the shift to exceed the bitwidth of the type.
1787         ///
1788         /// # Examples
1789         ///
1790         /// Basic usage:
1791         ///
1792         /// ```
1793         /// assert_eq!(128u8.wrapping_shr(7), 1);
1794         /// assert_eq!(128u8.wrapping_shr(8), 128);
1795         /// ```
1796         #[stable(feature = "num_wrapping", since = "1.2.0")]
1797         #[inline(always)]
1798         pub fn wrapping_shr(self, rhs: u32) -> Self {
1799             self.overflowing_shr(rhs).0
1800         }
1801
1802         /// Calculates `self` + `rhs`
1803         ///
1804         /// Returns a tuple of the addition along with a boolean indicating
1805         /// whether an arithmetic overflow would occur. If an overflow would
1806         /// have occurred then the wrapped value is returned.
1807         ///
1808         /// # Examples
1809         ///
1810         /// Basic usage
1811         ///
1812         /// ```
1813         /// use std::u32;
1814         ///
1815         /// assert_eq!(5u32.overflowing_add(2), (7, false));
1816         /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
1817         /// ```
1818         #[inline]
1819         #[stable(feature = "wrapping", since = "1.7.0")]
1820         pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1821             unsafe {
1822                 let (a, b) = $add_with_overflow(self as $ActualT,
1823                                                 rhs as $ActualT);
1824                 (a as Self, b)
1825             }
1826         }
1827
1828         /// Calculates `self` - `rhs`
1829         ///
1830         /// Returns a tuple of the subtraction along with a boolean indicating
1831         /// whether an arithmetic overflow would occur. If an overflow would
1832         /// have occurred then the wrapped value is returned.
1833         ///
1834         /// # Examples
1835         ///
1836         /// Basic usage
1837         ///
1838         /// ```
1839         /// use std::u32;
1840         ///
1841         /// assert_eq!(5u32.overflowing_sub(2), (3, false));
1842         /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
1843         /// ```
1844         #[inline]
1845         #[stable(feature = "wrapping", since = "1.7.0")]
1846         pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1847             unsafe {
1848                 let (a, b) = $sub_with_overflow(self as $ActualT,
1849                                                 rhs as $ActualT);
1850                 (a as Self, b)
1851             }
1852         }
1853
1854         /// Calculates the multiplication of `self` and `rhs`.
1855         ///
1856         /// Returns a tuple of the multiplication along with a boolean
1857         /// indicating whether an arithmetic overflow would occur. If an
1858         /// overflow would have occurred then the wrapped value is returned.
1859         ///
1860         /// # Examples
1861         ///
1862         /// Basic usage
1863         ///
1864         /// ```
1865         /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1866         /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1867         /// ```
1868         #[inline]
1869         #[stable(feature = "wrapping", since = "1.7.0")]
1870         pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1871             unsafe {
1872                 let (a, b) = $mul_with_overflow(self as $ActualT,
1873                                                 rhs as $ActualT);
1874                 (a as Self, b)
1875             }
1876         }
1877
1878         /// Calculates the divisor when `self` is divided by `rhs`.
1879         ///
1880         /// Returns a tuple of the divisor along with a boolean indicating
1881         /// whether an arithmetic overflow would occur. Note that for unsigned
1882         /// integers overflow never occurs, so the second value is always
1883         /// `false`.
1884         ///
1885         /// # Panics
1886         ///
1887         /// This function will panic if `rhs` is 0.
1888         ///
1889         /// # Examples
1890         ///
1891         /// Basic usage
1892         ///
1893         /// ```
1894         /// assert_eq!(5u32.overflowing_div(2), (2, false));
1895         /// ```
1896         #[inline]
1897         #[stable(feature = "wrapping", since = "1.7.0")]
1898         pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1899             (self / rhs, false)
1900         }
1901
1902         /// Calculates the remainder when `self` is divided by `rhs`.
1903         ///
1904         /// Returns a tuple of the remainder after dividing along with a boolean
1905         /// indicating whether an arithmetic overflow would occur. Note that for
1906         /// unsigned integers overflow never occurs, so the second value is
1907         /// always `false`.
1908         ///
1909         /// # Panics
1910         ///
1911         /// This function will panic if `rhs` is 0.
1912         ///
1913         /// # Examples
1914         ///
1915         /// Basic usage
1916         ///
1917         /// ```
1918         /// assert_eq!(5u32.overflowing_rem(2), (1, false));
1919         /// ```
1920         #[inline]
1921         #[stable(feature = "wrapping", since = "1.7.0")]
1922         pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1923             (self % rhs, false)
1924         }
1925
1926         /// Negates self in an overflowing fashion.
1927         ///
1928         /// Returns `!self + 1` using wrapping operations to return the value
1929         /// that represents the negation of this unsigned value. Note that for
1930         /// positive unsigned values overflow always occurs, but negating 0 does
1931         /// not overflow.
1932         ///
1933         /// # Examples
1934         ///
1935         /// Basic usage
1936         ///
1937         /// ```
1938         /// assert_eq!(0u32.overflowing_neg(), (0, false));
1939         /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
1940         /// ```
1941         #[inline]
1942         #[stable(feature = "wrapping", since = "1.7.0")]
1943         pub fn overflowing_neg(self) -> (Self, bool) {
1944             ((!self).wrapping_add(1), self != 0)
1945         }
1946
1947         /// Shifts self left by `rhs` bits.
1948         ///
1949         /// Returns a tuple of the shifted version of self along with a boolean
1950         /// indicating whether the shift value was larger than or equal to the
1951         /// number of bits. If the shift value is too large, then value is
1952         /// masked (N-1) where N is the number of bits, and this value is then
1953         /// used to perform the shift.
1954         ///
1955         /// # Examples
1956         ///
1957         /// Basic usage
1958         ///
1959         /// ```
1960         /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
1961         /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
1962         /// ```
1963         #[inline]
1964         #[stable(feature = "wrapping", since = "1.7.0")]
1965         pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1966             (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1967         }
1968
1969         /// Shifts self right by `rhs` bits.
1970         ///
1971         /// Returns a tuple of the shifted version of self along with a boolean
1972         /// indicating whether the shift value was larger than or equal to the
1973         /// number of bits. If the shift value is too large, then value is
1974         /// masked (N-1) where N is the number of bits, and this value is then
1975         /// used to perform the shift.
1976         ///
1977         /// # Examples
1978         ///
1979         /// Basic usage
1980         ///
1981         /// ```
1982         /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
1983         /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
1984         /// ```
1985         #[inline]
1986         #[stable(feature = "wrapping", since = "1.7.0")]
1987         pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1988             (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1989         }
1990
1991         /// Raises self to the power of `exp`, using exponentiation by squaring.
1992         ///
1993         /// # Examples
1994         ///
1995         /// Basic usage:
1996         ///
1997         /// ```
1998         /// assert_eq!(2u32.pow(4), 16);
1999         /// ```
2000         #[stable(feature = "rust1", since = "1.0.0")]
2001         #[inline]
2002         pub fn pow(self, mut exp: u32) -> Self {
2003             let mut base = self;
2004             let mut acc = Self::one();
2005
2006             let mut prev_base = self;
2007             let mut base_oflo = false;
2008             while exp > 0 {
2009                 if (exp & 1) == 1 {
2010                     if base_oflo {
2011                         // ensure overflow occurs in the same manner it
2012                         // would have otherwise (i.e. signal any exception
2013                         // it would have otherwise).
2014                         acc = acc * (prev_base * prev_base);
2015                     } else {
2016                         acc = acc * base;
2017                     }
2018                 }
2019                 prev_base = base;
2020                 let (new_base, new_base_oflo) = base.overflowing_mul(base);
2021                 base = new_base;
2022                 base_oflo = new_base_oflo;
2023                 exp /= 2;
2024             }
2025             acc
2026         }
2027
2028         /// Returns `true` if and only if `self == 2^k` for some `k`.
2029         ///
2030         /// # Examples
2031         ///
2032         /// Basic usage:
2033         ///
2034         /// ```
2035         /// assert!(16u8.is_power_of_two());
2036         /// assert!(!10u8.is_power_of_two());
2037         /// ```
2038         #[stable(feature = "rust1", since = "1.0.0")]
2039         #[inline]
2040         pub fn is_power_of_two(self) -> bool {
2041             (self.wrapping_sub(Self::one())) & self == Self::zero() &&
2042                 !(self == Self::zero())
2043         }
2044
2045         /// Returns the smallest power of two greater than or equal to `self`.
2046         /// Unspecified behavior on overflow.
2047         ///
2048         /// # Examples
2049         ///
2050         /// Basic usage:
2051         ///
2052         /// ```
2053         /// assert_eq!(2u8.next_power_of_two(), 2);
2054         /// assert_eq!(3u8.next_power_of_two(), 4);
2055         /// ```
2056         #[stable(feature = "rust1", since = "1.0.0")]
2057         #[inline]
2058         pub fn next_power_of_two(self) -> Self {
2059             let bits = size_of::<Self>() * 8;
2060             let one: Self = Self::one();
2061             one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
2062         }
2063
2064         /// Returns the smallest power of two greater than or equal to `n`. If
2065         /// the next power of two is greater than the type's maximum value,
2066         /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2067         ///
2068         /// # Examples
2069         ///
2070         /// Basic usage:
2071         ///
2072         /// ```
2073         /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2074         /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2075         /// assert_eq!(200u8.checked_next_power_of_two(), None);
2076         /// ```
2077         #[stable(feature = "rust1", since = "1.0.0")]
2078         pub fn checked_next_power_of_two(self) -> Option<Self> {
2079             let npot = self.next_power_of_two();
2080             if npot >= self {
2081                 Some(npot)
2082             } else {
2083                 None
2084             }
2085         }
2086     }
2087 }
2088
2089 #[lang = "u8"]
2090 impl u8 {
2091     uint_impl! { u8, 8,
2092         intrinsics::ctpop,
2093         intrinsics::ctlz,
2094         intrinsics::cttz,
2095         intrinsics::bswap,
2096         intrinsics::add_with_overflow,
2097         intrinsics::sub_with_overflow,
2098         intrinsics::mul_with_overflow }
2099 }
2100
2101 #[lang = "u16"]
2102 impl u16 {
2103     uint_impl! { u16, 16,
2104         intrinsics::ctpop,
2105         intrinsics::ctlz,
2106         intrinsics::cttz,
2107         intrinsics::bswap,
2108         intrinsics::add_with_overflow,
2109         intrinsics::sub_with_overflow,
2110         intrinsics::mul_with_overflow }
2111 }
2112
2113 #[lang = "u32"]
2114 impl u32 {
2115     uint_impl! { u32, 32,
2116         intrinsics::ctpop,
2117         intrinsics::ctlz,
2118         intrinsics::cttz,
2119         intrinsics::bswap,
2120         intrinsics::add_with_overflow,
2121         intrinsics::sub_with_overflow,
2122         intrinsics::mul_with_overflow }
2123 }
2124
2125 #[lang = "u64"]
2126 impl u64 {
2127     uint_impl! { u64, 64,
2128         intrinsics::ctpop,
2129         intrinsics::ctlz,
2130         intrinsics::cttz,
2131         intrinsics::bswap,
2132         intrinsics::add_with_overflow,
2133         intrinsics::sub_with_overflow,
2134         intrinsics::mul_with_overflow }
2135 }
2136
2137 #[cfg(target_pointer_width = "32")]
2138 #[lang = "usize"]
2139 impl usize {
2140     uint_impl! { u32, 32,
2141         intrinsics::ctpop,
2142         intrinsics::ctlz,
2143         intrinsics::cttz,
2144         intrinsics::bswap,
2145         intrinsics::add_with_overflow,
2146         intrinsics::sub_with_overflow,
2147         intrinsics::mul_with_overflow }
2148 }
2149
2150 #[cfg(target_pointer_width = "64")]
2151 #[lang = "usize"]
2152 impl usize {
2153     uint_impl! { u64, 64,
2154         intrinsics::ctpop,
2155         intrinsics::ctlz,
2156         intrinsics::cttz,
2157         intrinsics::bswap,
2158         intrinsics::add_with_overflow,
2159         intrinsics::sub_with_overflow,
2160         intrinsics::mul_with_overflow }
2161 }
2162
2163 /// A classification of floating point numbers.
2164 ///
2165 /// This `enum` is used as the return type for [`f32::classify()`] and [`f64::classify()`]. See
2166 /// their documentation for more.
2167 ///
2168 /// [`f32::classify()`]: ../primitive.f32.html#method.classify
2169 /// [`f64::classify()`]: ../primitive.f64.html#method.classify
2170 #[derive(Copy, Clone, PartialEq, Debug)]
2171 #[stable(feature = "rust1", since = "1.0.0")]
2172 pub enum FpCategory {
2173     /// "Not a Number", often obtained by dividing by zero
2174     #[stable(feature = "rust1", since = "1.0.0")]
2175     Nan,
2176
2177     /// Positive or negative infinity
2178     #[stable(feature = "rust1", since = "1.0.0")]
2179     Infinite ,
2180
2181     /// Positive or negative zero
2182     #[stable(feature = "rust1", since = "1.0.0")]
2183     Zero,
2184
2185     /// De-normalized floating point representation (less precise than `Normal`)
2186     #[stable(feature = "rust1", since = "1.0.0")]
2187     Subnormal,
2188
2189     /// A regular floating point number
2190     #[stable(feature = "rust1", since = "1.0.0")]
2191     Normal,
2192 }
2193
2194 /// A built-in floating point number.
2195 #[doc(hidden)]
2196 #[unstable(feature = "core_float",
2197            reason = "stable interface is via `impl f{32,64}` in later crates",
2198            issue = "27702")]
2199 pub trait Float: Sized {
2200     /// Returns the NaN value.
2201     #[unstable(feature = "float_extras", reason = "needs removal",
2202                issue = "27752")]
2203     fn nan() -> Self;
2204     /// Returns the infinite value.
2205     #[unstable(feature = "float_extras", reason = "needs removal",
2206                issue = "27752")]
2207     fn infinity() -> Self;
2208     /// Returns the negative infinite value.
2209     #[unstable(feature = "float_extras", reason = "needs removal",
2210                issue = "27752")]
2211     fn neg_infinity() -> Self;
2212     /// Returns -0.0.
2213     #[unstable(feature = "float_extras", reason = "needs removal",
2214                issue = "27752")]
2215     fn neg_zero() -> Self;
2216     /// Returns 0.0.
2217     #[unstable(feature = "float_extras", reason = "needs removal",
2218                issue = "27752")]
2219     fn zero() -> Self;
2220     /// Returns 1.0.
2221     #[unstable(feature = "float_extras", reason = "needs removal",
2222                issue = "27752")]
2223     fn one() -> Self;
2224
2225     /// Returns true if this value is NaN and false otherwise.
2226     #[stable(feature = "core", since = "1.6.0")]
2227     fn is_nan(self) -> bool;
2228     /// Returns true if this value is positive infinity or negative infinity and
2229     /// false otherwise.
2230     #[stable(feature = "core", since = "1.6.0")]
2231     fn is_infinite(self) -> bool;
2232     /// Returns true if this number is neither infinite nor NaN.
2233     #[stable(feature = "core", since = "1.6.0")]
2234     fn is_finite(self) -> bool;
2235     /// Returns true if this number is neither zero, infinite, denormal, or NaN.
2236     #[stable(feature = "core", since = "1.6.0")]
2237     fn is_normal(self) -> bool;
2238     /// Returns the category that this number falls into.
2239     #[stable(feature = "core", since = "1.6.0")]
2240     fn classify(self) -> FpCategory;
2241
2242     /// Returns the mantissa, exponent and sign as integers, respectively.
2243     #[unstable(feature = "float_extras", reason = "signature is undecided",
2244                issue = "27752")]
2245     fn integer_decode(self) -> (u64, i16, i8);
2246
2247     /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2248     /// number is `Float::nan()`.
2249     #[stable(feature = "core", since = "1.6.0")]
2250     fn abs(self) -> Self;
2251     /// Returns a number that represents the sign of `self`.
2252     ///
2253     /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2254     /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2255     /// - `Float::nan()` if the number is `Float::nan()`
2256     #[stable(feature = "core", since = "1.6.0")]
2257     fn signum(self) -> Self;
2258
2259     /// Returns `true` if `self` is positive, including `+0.0` and
2260     /// `Float::infinity()`.
2261     #[stable(feature = "core", since = "1.6.0")]
2262     fn is_sign_positive(self) -> bool;
2263     /// Returns `true` if `self` is negative, including `-0.0` and
2264     /// `Float::neg_infinity()`.
2265     #[stable(feature = "core", since = "1.6.0")]
2266     fn is_sign_negative(self) -> bool;
2267
2268     /// Take the reciprocal (inverse) of a number, `1/x`.
2269     #[stable(feature = "core", since = "1.6.0")]
2270     fn recip(self) -> Self;
2271
2272     /// Raise a number to an integer power.
2273     ///
2274     /// Using this function is generally faster than using `powf`
2275     #[stable(feature = "core", since = "1.6.0")]
2276     fn powi(self, n: i32) -> Self;
2277
2278     /// Convert radians to degrees.
2279     #[unstable(feature = "float_extras", reason = "desirability is unclear",
2280                issue = "27752")]
2281     fn to_degrees(self) -> Self;
2282     /// Convert degrees to radians.
2283     #[unstable(feature = "float_extras", reason = "desirability is unclear",
2284                issue = "27752")]
2285     fn to_radians(self) -> Self;
2286 }
2287
2288 macro_rules! from_str_radix_int_impl {
2289     ($($t:ty)*) => {$(
2290         #[stable(feature = "rust1", since = "1.0.0")]
2291         impl FromStr for $t {
2292             type Err = ParseIntError;
2293             fn from_str(src: &str) -> Result<Self, ParseIntError> {
2294                 from_str_radix(src, 10)
2295             }
2296         }
2297     )*}
2298 }
2299 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
2300
2301 #[doc(hidden)]
2302 trait FromStrRadixHelper: PartialOrd + Copy {
2303     fn min_value() -> Self;
2304     fn from_u32(u: u32) -> Self;
2305     fn checked_mul(&self, other: u32) -> Option<Self>;
2306     fn checked_sub(&self, other: u32) -> Option<Self>;
2307     fn checked_add(&self, other: u32) -> Option<Self>;
2308 }
2309
2310 macro_rules! doit {
2311     ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
2312         fn min_value() -> Self { Self::min_value() }
2313         fn from_u32(u: u32) -> Self { u as Self }
2314         fn checked_mul(&self, other: u32) -> Option<Self> {
2315             Self::checked_mul(*self, other as Self)
2316         }
2317         fn checked_sub(&self, other: u32) -> Option<Self> {
2318             Self::checked_sub(*self, other as Self)
2319         }
2320         fn checked_add(&self, other: u32) -> Option<Self> {
2321             Self::checked_add(*self, other as Self)
2322         }
2323     })*)
2324 }
2325 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
2326
2327 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
2328                                          -> Result<T, ParseIntError> {
2329     use self::IntErrorKind::*;
2330     use self::ParseIntError as PIE;
2331
2332     assert!(radix >= 2 && radix <= 36,
2333            "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2334            radix);
2335
2336     if src.is_empty() {
2337         return Err(PIE { kind: Empty });
2338     }
2339
2340     let is_signed_ty = T::from_u32(0) > T::min_value();
2341
2342     // all valid digits are ascii, so we will just iterate over the utf8 bytes
2343     // and cast them to chars. .to_digit() will safely return None for anything
2344     // other than a valid ascii digit for the given radix, including the first-byte
2345     // of multi-byte sequences
2346     let src = src.as_bytes();
2347
2348     let (is_positive, digits) = match src[0] {
2349         b'+' => (true, &src[1..]),
2350         b'-' if is_signed_ty => (false, &src[1..]),
2351         _ => (true, src)
2352     };
2353
2354     if digits.is_empty() {
2355         return Err(PIE { kind: Empty });
2356     }
2357
2358     let mut result = T::from_u32(0);
2359     if is_positive {
2360         // The number is positive
2361         for &c in digits {
2362             let x = match (c as char).to_digit(radix) {
2363                 Some(x) => x,
2364                 None => return Err(PIE { kind: InvalidDigit }),
2365             };
2366             result = match result.checked_mul(radix) {
2367                 Some(result) => result,
2368                 None => return Err(PIE { kind: Overflow }),
2369             };
2370             result = match result.checked_add(x) {
2371                 Some(result) => result,
2372                 None => return Err(PIE { kind: Overflow }),
2373             };
2374         }
2375     } else {
2376         // The number is negative
2377         for &c in digits {
2378             let x = match (c as char).to_digit(radix) {
2379                 Some(x) => x,
2380                 None => return Err(PIE { kind: InvalidDigit }),
2381             };
2382             result = match result.checked_mul(radix) {
2383                 Some(result) => result,
2384                 None => return Err(PIE { kind: Underflow }),
2385             };
2386             result = match result.checked_sub(x) {
2387                 Some(result) => result,
2388                 None => return Err(PIE { kind: Underflow }),
2389             };
2390         }
2391     }
2392     Ok(result)
2393 }
2394
2395 /// An error which can be returned when parsing an integer.
2396 ///
2397 /// This error is used as the error type for the `from_str_radix()` functions
2398 /// on the primitive integer types, such as [`i8::from_str_radix()`].
2399 ///
2400 /// [`i8::from_str_radix()`]: ../std/primitive.i8.html#method.from_str_radix
2401 #[derive(Debug, Clone, PartialEq)]
2402 #[stable(feature = "rust1", since = "1.0.0")]
2403 pub struct ParseIntError { kind: IntErrorKind }
2404
2405 #[derive(Debug, Clone, PartialEq)]
2406 enum IntErrorKind {
2407     Empty,
2408     InvalidDigit,
2409     Overflow,
2410     Underflow,
2411 }
2412
2413 impl ParseIntError {
2414     #[unstable(feature = "int_error_internals",
2415                reason = "available through Error trait and this method should \
2416                          not be exposed publicly",
2417                issue = "0")]
2418     #[doc(hidden)]
2419     pub fn __description(&self) -> &str {
2420         match self.kind {
2421             IntErrorKind::Empty => "cannot parse integer from empty string",
2422             IntErrorKind::InvalidDigit => "invalid digit found in string",
2423             IntErrorKind::Overflow => "number too large to fit in target type",
2424             IntErrorKind::Underflow => "number too small to fit in target type",
2425         }
2426     }
2427 }
2428
2429 #[stable(feature = "rust1", since = "1.0.0")]
2430 impl fmt::Display for ParseIntError {
2431     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2432         self.__description().fmt(f)
2433     }
2434 }
2435
2436 #[stable(feature = "rust1", since = "1.0.0")]
2437 pub use num::dec2flt::ParseFloatError;
2438
2439 // Conversion traits for primitive integer and float types
2440 // Conversions T -> T are covered by a blanket impl and therefore excluded
2441 // Some conversions from and to usize/isize are not implemented due to portability concerns
2442 macro_rules! impl_from {
2443     ($Small: ty, $Large: ty) => {
2444         #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
2445         impl From<$Small> for $Large {
2446             #[inline]
2447             fn from(small: $Small) -> $Large {
2448                 small as $Large
2449             }
2450         }
2451     }
2452 }
2453
2454 // Unsigned -> Unsigned
2455 impl_from! { u8, u16 }
2456 impl_from! { u8, u32 }
2457 impl_from! { u8, u64 }
2458 impl_from! { u8, usize }
2459 impl_from! { u16, u32 }
2460 impl_from! { u16, u64 }
2461 impl_from! { u32, u64 }
2462
2463 // Signed -> Signed
2464 impl_from! { i8, i16 }
2465 impl_from! { i8, i32 }
2466 impl_from! { i8, i64 }
2467 impl_from! { i8, isize }
2468 impl_from! { i16, i32 }
2469 impl_from! { i16, i64 }
2470 impl_from! { i32, i64 }
2471
2472 // Unsigned -> Signed
2473 impl_from! { u8, i16 }
2474 impl_from! { u8, i32 }
2475 impl_from! { u8, i64 }
2476 impl_from! { u16, i32 }
2477 impl_from! { u16, i64 }
2478 impl_from! { u32, i64 }
2479
2480 // Note: integers can only be represented with full precision in a float if
2481 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2482 // Lossy float conversions are not implemented at this time.
2483
2484 // Signed -> Float
2485 impl_from! { i8, f32 }
2486 impl_from! { i8, f64 }
2487 impl_from! { i16, f32 }
2488 impl_from! { i16, f64 }
2489 impl_from! { i32, f64 }
2490
2491 // Unsigned -> Float
2492 impl_from! { u8, f32 }
2493 impl_from! { u8, f64 }
2494 impl_from! { u16, f32 }
2495 impl_from! { u16, f64 }
2496 impl_from! { u32, f64 }
2497
2498 // Float -> Float
2499 impl_from! { f32, f64 }