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