]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
3bc2861460e1455024c9e1dc06c58d3b8c2de2a7
[rust.git] / src / libcore / num / mod.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Numeric traits and functions for the built-in numeric types.
12
13 #![stable(feature = "rust1", since = "1.0.0")]
14
15 use convert::TryFrom;
16 use fmt;
17 use intrinsics;
18 use mem;
19 use nonzero::NonZero;
20 use ops;
21 use str::FromStr;
22
23 macro_rules! impl_nonzero_fmt {
24     ( ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
25         $(
26             #[stable(feature = "nonzero", since = "1.28.0")]
27             impl fmt::$Trait for $Ty {
28                 #[inline]
29                 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
30                     self.get().fmt(f)
31                 }
32             }
33         )+
34     }
35 }
36
37 macro_rules! nonzero_integers {
38     ( $( $Ty: ident($Int: ty); )+ ) => {
39         $(
40             /// An integer that is known not to equal zero.
41             ///
42             /// This enables some memory layout optimization.
43             /// For example, `Option<NonZeroU32>` is the same size as `u32`:
44             ///
45             /// ```rust
46             /// use std::mem::size_of;
47             /// assert_eq!(size_of::<Option<std::num::NonZeroU32>>(), size_of::<u32>());
48             /// ```
49             #[stable(feature = "nonzero", since = "1.28.0")]
50             #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
51             #[repr(transparent)]
52             pub struct $Ty(NonZero<$Int>);
53
54             impl $Ty {
55                 /// Create a non-zero without checking the value.
56                 ///
57                 /// # Safety
58                 ///
59                 /// The value must not be zero.
60                 #[stable(feature = "nonzero", since = "1.28.0")]
61                 #[inline]
62                 pub const unsafe fn new_unchecked(n: $Int) -> Self {
63                     $Ty(NonZero(n))
64                 }
65
66                 /// Create a non-zero if the given value is not zero.
67                 #[stable(feature = "nonzero", since = "1.28.0")]
68                 #[inline]
69                 pub fn new(n: $Int) -> Option<Self> {
70                     if n != 0 {
71                         Some($Ty(NonZero(n)))
72                     } else {
73                         None
74                     }
75                 }
76
77                 /// Returns the value as a primitive type.
78                 #[stable(feature = "nonzero", since = "1.28.0")]
79                 #[inline]
80                 pub fn get(self) -> $Int {
81                     self.0 .0
82                 }
83
84             }
85
86             impl_nonzero_fmt! {
87                 (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
88             }
89         )+
90     }
91 }
92
93 nonzero_integers! {
94     NonZeroU8(u8);
95     NonZeroU16(u16);
96     NonZeroU32(u32);
97     NonZeroU64(u64);
98     NonZeroU128(u128);
99     NonZeroUsize(usize);
100 }
101
102 /// Provides intentionally-wrapped arithmetic on `T`.
103 ///
104 /// Operations like `+` on `u32` values is intended to never overflow,
105 /// and in some debug configurations overflow is detected and results
106 /// in a panic. While most arithmetic falls into this category, some
107 /// code explicitly expects and relies upon modular arithmetic (e.g.,
108 /// hashing).
109 ///
110 /// Wrapping arithmetic can be achieved either through methods like
111 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
112 /// all standard arithmetic operations on the underlying value are
113 /// intended to have wrapping semantics.
114 ///
115 /// # Examples
116 ///
117 /// ```
118 /// use std::num::Wrapping;
119 ///
120 /// let zero = Wrapping(0u32);
121 /// let one = Wrapping(1u32);
122 ///
123 /// assert_eq!(std::u32::MAX, (zero - one).0);
124 /// ```
125 #[stable(feature = "rust1", since = "1.0.0")]
126 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
127 #[repr(transparent)]
128 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
129                        pub T);
130
131 #[stable(feature = "rust1", since = "1.0.0")]
132 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
133     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
134         self.0.fmt(f)
135     }
136 }
137
138 #[stable(feature = "wrapping_display", since = "1.10.0")]
139 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
140     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
141         self.0.fmt(f)
142     }
143 }
144
145 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
146 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
147     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
148         self.0.fmt(f)
149     }
150 }
151
152 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
153 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
154     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
155         self.0.fmt(f)
156     }
157 }
158
159 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
160 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
161     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
162         self.0.fmt(f)
163     }
164 }
165
166 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
167 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
168     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
169         self.0.fmt(f)
170     }
171 }
172
173 // All these modules are technically private and only exposed for coretests:
174 pub mod flt2dec;
175 pub mod dec2flt;
176 pub mod bignum;
177 pub mod diy_float;
178
179 macro_rules! doc_comment {
180     ($x:expr, $($tt:tt)*) => {
181         #[doc = $x]
182         $($tt)*
183     };
184 }
185
186 mod wrapping;
187
188 // `Int` + `SignedInt` implemented for signed integers
189 macro_rules! int_impl {
190     ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
191      $EndFeature:expr) => {
192         doc_comment! {
193             concat!("Returns the smallest value that can be represented by this integer type.
194
195 # Examples
196
197 Basic usage:
198
199 ```
200 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
201 $EndFeature, "
202 ```"),
203             #[stable(feature = "rust1", since = "1.0.0")]
204             #[inline]
205             pub const fn min_value() -> Self {
206                 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
207             }
208         }
209
210         doc_comment! {
211             concat!("Returns the largest value that can be represented by this integer type.
212
213 # Examples
214
215 Basic usage:
216
217 ```
218 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
219 $EndFeature, "
220 ```"),
221             #[stable(feature = "rust1", since = "1.0.0")]
222             #[inline]
223             pub const fn max_value() -> Self {
224                 !Self::min_value()
225             }
226         }
227
228         doc_comment! {
229             concat!("Converts a string slice in a given base to an integer.
230
231 The string is expected to be an optional `+` or `-` sign followed by digits.
232 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
233 depending on `radix`:
234
235  * `0-9`
236  * `a-z`
237  * `A-Z`
238
239 # Panics
240
241 This function panics if `radix` is not in the range from 2 to 36.
242
243 # Examples
244
245 Basic usage:
246
247 ```
248 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
249 $EndFeature, "
250 ```"),
251             #[stable(feature = "rust1", since = "1.0.0")]
252             pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
253                 from_str_radix(src, radix)
254             }
255         }
256
257         doc_comment! {
258             concat!("Returns the number of ones in the binary representation of `self`.
259
260 # Examples
261
262 Basic usage:
263
264 ```
265 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
266
267 assert_eq!(n.count_ones(), 1);",
268 $EndFeature, "
269 ```
270 "),
271             #[stable(feature = "rust1", since = "1.0.0")]
272             #[rustc_const_unstable(feature = "const_int_ops")]
273             #[inline]
274             pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
275         }
276
277         doc_comment! {
278             concat!("Returns the number of zeros in the binary representation of `self`.
279
280 # Examples
281
282 Basic usage:
283
284 ```
285 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
286 ```"),
287             #[stable(feature = "rust1", since = "1.0.0")]
288             #[rustc_const_unstable(feature = "const_int_ops")]
289             #[inline]
290             pub const fn count_zeros(self) -> u32 {
291                 (!self).count_ones()
292             }
293         }
294
295         doc_comment! {
296             concat!("Returns the number of leading zeros in the binary representation of `self`.
297
298 # Examples
299
300 Basic usage:
301
302 ```
303 ", $Feature, "let n = -1", stringify!($SelfT), ";
304
305 assert_eq!(n.leading_zeros(), 0);",
306 $EndFeature, "
307 ```"),
308             #[stable(feature = "rust1", since = "1.0.0")]
309             #[rustc_const_unstable(feature = "const_int_ops")]
310             #[inline]
311             pub const fn leading_zeros(self) -> u32 {
312                 (self as $UnsignedT).leading_zeros()
313             }
314         }
315
316         doc_comment! {
317             concat!("Returns the number of trailing zeros in the binary representation of `self`.
318
319 # Examples
320
321 Basic usage:
322
323 ```
324 ", $Feature, "let n = -4", stringify!($SelfT), ";
325
326 assert_eq!(n.trailing_zeros(), 2);",
327 $EndFeature, "
328 ```"),
329             #[stable(feature = "rust1", since = "1.0.0")]
330             #[rustc_const_unstable(feature = "const_int_ops")]
331             #[inline]
332             pub const fn trailing_zeros(self) -> u32 {
333                 (self as $UnsignedT).trailing_zeros()
334             }
335         }
336
337         /// Shifts the bits to the left by a specified amount, `n`,
338         /// wrapping the truncated bits to the end of the resulting integer.
339         ///
340         /// Please note this isn't the same operation as `<<`!
341         ///
342         /// # Examples
343         ///
344         /// Please note that this example is shared between integer types.
345         /// Which explains why `i64` is used here.
346         ///
347         /// Basic usage:
348         ///
349         /// ```
350         /// let n = 0x0123456789ABCDEFi64;
351         /// let m = -0x76543210FEDCBA99i64;
352         ///
353         /// assert_eq!(n.rotate_left(32), m);
354         /// ```
355         #[stable(feature = "rust1", since = "1.0.0")]
356         #[inline]
357         pub fn rotate_left(self, n: u32) -> Self {
358             (self as $UnsignedT).rotate_left(n) as Self
359         }
360
361         /// Shifts the bits to the right by a specified amount, `n`,
362         /// wrapping the truncated bits to the beginning of the resulting
363         /// integer.
364         ///
365         /// Please note this isn't the same operation as `>>`!
366         ///
367         /// # Examples
368         ///
369         /// Please note that this example is shared between integer types.
370         /// Which explains why `i64` is used here.
371         ///
372         /// Basic usage:
373         ///
374         /// ```
375         /// let n = 0x0123456789ABCDEFi64;
376         /// let m = -0xFEDCBA987654322i64;
377         ///
378         /// assert_eq!(n.rotate_right(4), m);
379         /// ```
380         #[stable(feature = "rust1", since = "1.0.0")]
381         #[inline]
382         pub fn rotate_right(self, n: u32) -> Self {
383             (self as $UnsignedT).rotate_right(n) as Self
384         }
385
386         /// Reverses the byte order of the integer.
387         ///
388         /// # Examples
389         ///
390         /// Please note that this example is shared between integer types.
391         /// Which explains why `i16` is used here.
392         ///
393         /// Basic usage:
394         ///
395         /// ```
396         /// let n: i16 = 0b0000000_01010101;
397         /// assert_eq!(n, 85);
398         ///
399         /// let m = n.swap_bytes();
400         ///
401         /// assert_eq!(m, 0b01010101_00000000);
402         /// assert_eq!(m, 21760);
403         /// ```
404         #[stable(feature = "rust1", since = "1.0.0")]
405         #[rustc_const_unstable(feature = "const_int_ops")]
406         #[inline]
407         pub const fn swap_bytes(self) -> Self {
408             (self as $UnsignedT).swap_bytes() as Self
409         }
410
411         /// Reverses the bit pattern of the integer.
412         ///
413         /// # Examples
414         ///
415         /// Please note that this example is shared between integer types.
416         /// Which explains why `i16` is used here.
417         ///
418         /// Basic usage:
419         ///
420         /// ```
421         /// #![feature(reverse_bits)]
422         ///
423         /// let n: i16 = 0b0000000_01010101;
424         /// assert_eq!(n, 85);
425         ///
426         /// let m = n.reverse_bits();
427         ///
428         /// assert_eq!(m as u16, 0b10101010_00000000);
429         /// assert_eq!(m, -22016);
430         /// ```
431         #[unstable(feature = "reverse_bits", issue = "48763")]
432         #[inline]
433         pub fn reverse_bits(self) -> Self {
434             (self as $UnsignedT).reverse_bits() as Self
435         }
436
437         doc_comment! {
438             concat!("Converts an integer from big endian to the target's endianness.
439
440 On big endian this is a no-op. On little endian the bytes are swapped.
441
442 # Examples
443
444 Basic usage:
445
446 ```
447 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
448
449 if cfg!(target_endian = \"big\") {
450     assert_eq!(", stringify!($SelfT), "::from_be(n), n)
451 } else {
452     assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
453 }",
454 $EndFeature, "
455 ```"),
456             #[stable(feature = "rust1", since = "1.0.0")]
457             #[rustc_const_unstable(feature = "const_int_ops")]
458             #[inline]
459             pub const fn from_be(x: Self) -> Self {
460                 #[cfg(target_endian = "big")]
461                 {
462                     x
463                 }
464                 #[cfg(not(target_endian = "big"))]
465                 {
466                     x.swap_bytes()
467                 }
468             }
469         }
470
471         doc_comment! {
472             concat!("Converts an integer from little endian to the target's endianness.
473
474 On little endian this is a no-op. On big endian the bytes are swapped.
475
476 # Examples
477
478 Basic usage:
479
480 ```
481 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
482
483 if cfg!(target_endian = \"little\") {
484     assert_eq!(", stringify!($SelfT), "::from_le(n), n)
485 } else {
486     assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
487 }",
488 $EndFeature, "
489 ```"),
490             #[stable(feature = "rust1", since = "1.0.0")]
491             #[rustc_const_unstable(feature = "const_int_ops")]
492             #[inline]
493             pub const fn from_le(x: Self) -> Self {
494                 #[cfg(target_endian = "little")]
495                 {
496                     x
497                 }
498                 #[cfg(not(target_endian = "little"))]
499                 {
500                     x.swap_bytes()
501                 }
502             }
503         }
504
505         doc_comment! {
506             concat!("Converts `self` to big endian from the target's endianness.
507
508 On big endian this is a no-op. On little endian the bytes are swapped.
509
510 # Examples
511
512 Basic usage:
513
514 ```
515 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
516
517 if cfg!(target_endian = \"big\") {
518     assert_eq!(n.to_be(), n)
519 } else {
520     assert_eq!(n.to_be(), n.swap_bytes())
521 }",
522 $EndFeature, "
523 ```"),
524             #[stable(feature = "rust1", since = "1.0.0")]
525             #[rustc_const_unstable(feature = "const_int_ops")]
526             #[inline]
527             pub const fn to_be(self) -> Self { // or not to be?
528                 #[cfg(target_endian = "big")]
529                 {
530                     self
531                 }
532                 #[cfg(not(target_endian = "big"))]
533                 {
534                     self.swap_bytes()
535                 }
536             }
537         }
538
539         doc_comment! {
540             concat!("Converts `self` to little endian from the target's endianness.
541
542 On little endian this is a no-op. On big endian the bytes are swapped.
543
544 # Examples
545
546 Basic usage:
547
548 ```
549 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
550
551 if cfg!(target_endian = \"little\") {
552     assert_eq!(n.to_le(), n)
553 } else {
554     assert_eq!(n.to_le(), n.swap_bytes())
555 }",
556 $EndFeature, "
557 ```"),
558             #[stable(feature = "rust1", since = "1.0.0")]
559             #[rustc_const_unstable(feature = "const_int_ops")]
560             #[inline]
561             pub const fn to_le(self) -> Self {
562                 #[cfg(target_endian = "little")]
563                 {
564                     self
565                 }
566                 #[cfg(not(target_endian = "little"))]
567                 {
568                     self.swap_bytes()
569                 }
570             }
571         }
572
573         doc_comment! {
574             concat!("Checked integer addition. Computes `self + rhs`, returning `None`
575 if overflow occurred.
576
577 # Examples
578
579 Basic usage:
580
581 ```
582 ", $Feature, "assert_eq!((", stringify!($SelfT),
583 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
584 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
585 $EndFeature, "
586 ```"),
587             #[stable(feature = "rust1", since = "1.0.0")]
588             #[inline]
589             pub fn checked_add(self, rhs: Self) -> Option<Self> {
590                 let (a, b) = self.overflowing_add(rhs);
591                 if b {None} else {Some(a)}
592             }
593         }
594
595         doc_comment! {
596             concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
597 overflow occurred.
598
599 # Examples
600
601 Basic usage:
602
603 ```
604 ", $Feature, "assert_eq!((", stringify!($SelfT),
605 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
606 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
607 $EndFeature, "
608 ```"),
609             #[stable(feature = "rust1", since = "1.0.0")]
610             #[inline]
611             pub fn checked_sub(self, rhs: Self) -> Option<Self> {
612                 let (a, b) = self.overflowing_sub(rhs);
613                 if b {None} else {Some(a)}
614             }
615         }
616
617         doc_comment! {
618             concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
619 overflow occurred.
620
621 # Examples
622
623 Basic usage:
624
625 ```
626 ", $Feature, "assert_eq!(", stringify!($SelfT),
627 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
628 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
629 $EndFeature, "
630 ```"),
631             #[stable(feature = "rust1", since = "1.0.0")]
632             #[inline]
633             pub fn checked_mul(self, rhs: Self) -> Option<Self> {
634                 let (a, b) = self.overflowing_mul(rhs);
635                 if b {None} else {Some(a)}
636             }
637         }
638
639         doc_comment! {
640             concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
641 or the division results in overflow.
642
643 # Examples
644
645 Basic usage:
646
647 ```
648 ", $Feature, "assert_eq!((", stringify!($SelfT),
649 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
650 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
651 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
652 $EndFeature, "
653 ```"),
654             #[stable(feature = "rust1", since = "1.0.0")]
655             #[inline]
656             pub fn checked_div(self, rhs: Self) -> Option<Self> {
657                 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
658                     None
659                 } else {
660                     Some(unsafe { intrinsics::unchecked_div(self, rhs) })
661                 }
662             }
663         }
664
665         doc_comment! {
666             concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`,
667 returning `None` if `rhs == 0` or the division results in overflow.
668
669 # Examples
670
671 Basic usage:
672
673 ```
674 #![feature(euclidean_division)]
675 assert_eq!((", stringify!($SelfT),
676 "::min_value() + 1).checked_div_euc(-1), Some(", stringify!($Max), "));
677 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euc(-1), None);
678 assert_eq!((1", stringify!($SelfT), ").checked_div_euc(0), None);
679 ```"),
680             #[unstable(feature = "euclidean_division", issue = "49048")]
681             #[inline]
682             pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
683                 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
684                     None
685                 } else {
686                     Some(self.div_euc(rhs))
687                 }
688             }
689         }
690
691         doc_comment! {
692             concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
693 `rhs == 0` or the division results in overflow.
694
695 # Examples
696
697 Basic usage:
698
699 ```
700 ", $Feature, "use std::", stringify!($SelfT), ";
701
702 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
703 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
704 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
705 $EndFeature, "
706 ```"),
707             #[stable(feature = "wrapping", since = "1.7.0")]
708             #[inline]
709             pub fn checked_rem(self, rhs: Self) -> Option<Self> {
710                 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
711                     None
712                 } else {
713                     Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
714                 }
715             }
716         }
717
718         doc_comment! {
719             concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None` if
720 `rhs == 0` or the division results in overflow.
721
722 # Examples
723
724 Basic usage:
725
726 ```
727 #![feature(euclidean_division)]
728 use std::", stringify!($SelfT), ";
729
730 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
731 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
732 assert_eq!(", stringify!($SelfT), "::MIN.checked_mod_euc(-1), None);
733 ```"),
734             #[unstable(feature = "euclidean_division", issue = "49048")]
735             #[inline]
736             pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
737                 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
738                     None
739                 } else {
740                     Some(self.mod_euc(rhs))
741                 }
742             }
743         }
744
745         doc_comment! {
746             concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
747
748 # Examples
749
750 Basic usage:
751
752 ```
753 ", $Feature, "use std::", stringify!($SelfT), ";
754
755 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
756 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
757 $EndFeature, "
758 ```"),
759             #[stable(feature = "wrapping", since = "1.7.0")]
760             #[inline]
761             pub fn checked_neg(self) -> Option<Self> {
762                 let (a, b) = self.overflowing_neg();
763                 if b {None} else {Some(a)}
764             }
765         }
766
767         doc_comment! {
768             concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
769 than or equal to the number of bits in `self`.
770
771 # Examples
772
773 Basic usage:
774
775 ```
776 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
777 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
778 $EndFeature, "
779 ```"),
780             #[stable(feature = "wrapping", since = "1.7.0")]
781             #[inline]
782             pub fn checked_shl(self, rhs: u32) -> Option<Self> {
783                 let (a, b) = self.overflowing_shl(rhs);
784                 if b {None} else {Some(a)}
785             }
786         }
787
788         doc_comment! {
789             concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
790 larger than or equal to the number of bits in `self`.
791
792 # Examples
793
794 Basic usage:
795
796 ```
797 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
798 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
799 $EndFeature, "
800 ```"),
801             #[stable(feature = "wrapping", since = "1.7.0")]
802             #[inline]
803             pub fn checked_shr(self, rhs: u32) -> Option<Self> {
804                 let (a, b) = self.overflowing_shr(rhs);
805                 if b {None} else {Some(a)}
806             }
807         }
808
809         doc_comment! {
810             concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
811 `self == MIN`.
812
813 # Examples
814
815 Basic usage:
816
817 ```
818 ", $Feature, "use std::", stringify!($SelfT), ";
819
820 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
821 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
822 $EndFeature, "
823 ```"),
824             #[stable(feature = "no_panic_abs", since = "1.13.0")]
825             #[inline]
826             pub fn checked_abs(self) -> Option<Self> {
827                 if self.is_negative() {
828                     self.checked_neg()
829                 } else {
830                     Some(self)
831                 }
832             }
833         }
834
835         doc_comment! {
836             concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
837 overflow occurred.
838
839 # Examples
840
841 Basic usage:
842
843 ```
844 #![feature(no_panic_pow)]
845 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
846 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
847 $EndFeature, "
848 ```"),
849
850             #[unstable(feature = "no_panic_pow", issue = "48320")]
851             #[inline]
852             pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
853                 let mut base = self;
854                 let mut acc: Self = 1;
855
856                 while exp > 1 {
857                     if (exp & 1) == 1 {
858                         acc = acc.checked_mul(base)?;
859                     }
860                     exp /= 2;
861                     base = base.checked_mul(base)?;
862                 }
863
864                 // Deal with the final bit of the exponent separately, since
865                 // squaring the base afterwards is not necessary and may cause a
866                 // needless overflow.
867                 if exp == 1 {
868                     acc = acc.checked_mul(base)?;
869                 }
870
871                 Some(acc)
872             }
873         }
874
875         doc_comment! {
876             concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
877 bounds instead of overflowing.
878
879 # Examples
880
881 Basic usage:
882
883 ```
884 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
885 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
886 "::max_value());",
887 $EndFeature, "
888 ```"),
889             #[stable(feature = "rust1", since = "1.0.0")]
890             #[inline]
891             pub fn saturating_add(self, rhs: Self) -> Self {
892                 match self.checked_add(rhs) {
893                     Some(x) => x,
894                     None if rhs >= 0 => Self::max_value(),
895                     None => Self::min_value(),
896                 }
897             }
898         }
899
900         doc_comment! {
901             concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
902 numeric bounds instead of overflowing.
903
904 # Examples
905
906 Basic usage:
907
908 ```
909 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
910 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
911 "::min_value());",
912 $EndFeature, "
913 ```"),
914             #[stable(feature = "rust1", since = "1.0.0")]
915             #[inline]
916             pub fn saturating_sub(self, rhs: Self) -> Self {
917                 match self.checked_sub(rhs) {
918                     Some(x) => x,
919                     None if rhs >= 0 => Self::min_value(),
920                     None => Self::max_value(),
921                 }
922             }
923         }
924
925         doc_comment! {
926             concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
927 numeric bounds instead of overflowing.
928
929 # Examples
930
931 Basic usage:
932
933 ```
934 ", $Feature, "use std::", stringify!($SelfT), ";
935
936 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
937 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
938 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
939 $EndFeature, "
940 ```"),
941             #[stable(feature = "wrapping", since = "1.7.0")]
942             #[inline]
943             pub fn saturating_mul(self, rhs: Self) -> Self {
944                 self.checked_mul(rhs).unwrap_or_else(|| {
945                     if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
946                         Self::max_value()
947                     } else {
948                         Self::min_value()
949                     }
950                 })
951             }
952         }
953
954         doc_comment! {
955             concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
956 saturating at the numeric bounds instead of overflowing.
957
958 # Examples
959
960 Basic usage:
961
962 ```
963 #![feature(no_panic_pow)]
964 ", $Feature, "use std::", stringify!($SelfT), ";
965
966 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
967 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
968 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
969 $EndFeature, "
970 ```"),
971             #[unstable(feature = "no_panic_pow", issue = "48320")]
972             #[inline]
973             pub fn saturating_pow(self, exp: u32) -> Self {
974                 match self.checked_pow(exp) {
975                     Some(x) => x,
976                     None if self < 0 && exp % 2 == 1 => Self::min_value(),
977                     None => Self::max_value(),
978                 }
979             }
980         }
981
982         doc_comment! {
983             concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
984 boundary of the type.
985
986 # Examples
987
988 Basic usage:
989
990 ```
991 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
992 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
993 "::min_value() + 1);",
994 $EndFeature, "
995 ```"),
996             #[stable(feature = "rust1", since = "1.0.0")]
997             #[inline]
998             pub fn wrapping_add(self, rhs: Self) -> Self {
999                 unsafe {
1000                     intrinsics::overflowing_add(self, rhs)
1001                 }
1002             }
1003         }
1004
1005         doc_comment! {
1006             concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1007 boundary of the type.
1008
1009 # Examples
1010
1011 Basic usage:
1012
1013 ```
1014 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1015 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1016 stringify!($SelfT), "::max_value());",
1017 $EndFeature, "
1018 ```"),
1019             #[stable(feature = "rust1", since = "1.0.0")]
1020             #[inline]
1021             pub fn wrapping_sub(self, rhs: Self) -> Self {
1022                 unsafe {
1023                     intrinsics::overflowing_sub(self, rhs)
1024                 }
1025             }
1026         }
1027
1028         doc_comment! {
1029             concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1030 the boundary of the type.
1031
1032 # Examples
1033
1034 Basic usage:
1035
1036 ```
1037 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1038 assert_eq!(11i8.wrapping_mul(12), -124);",
1039 $EndFeature, "
1040 ```"),
1041             #[stable(feature = "rust1", since = "1.0.0")]
1042             #[inline]
1043             pub fn wrapping_mul(self, rhs: Self) -> Self {
1044                 unsafe {
1045                     intrinsics::overflowing_mul(self, rhs)
1046                 }
1047             }
1048         }
1049
1050         doc_comment! {
1051             concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1052 boundary of the type.
1053
1054 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1055 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1056 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1057
1058 # Panics
1059
1060 This function will panic if `rhs` is 0.
1061
1062 # Examples
1063
1064 Basic usage:
1065
1066 ```
1067 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1068 assert_eq!((-128i8).wrapping_div(-1), -128);",
1069 $EndFeature, "
1070 ```"),
1071             #[stable(feature = "num_wrapping", since = "1.2.0")]
1072             #[inline]
1073             pub fn wrapping_div(self, rhs: Self) -> Self {
1074                 self.overflowing_div(rhs).0
1075             }
1076         }
1077
1078         doc_comment! {
1079             concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`,
1080 wrapping around at the boundary of the type.
1081
1082 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1083 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1084 type. In this case, this method returns `MIN` itself.
1085
1086 # Panics
1087
1088 This function will panic if `rhs` is 0.
1089
1090 # Examples
1091
1092 Basic usage:
1093
1094 ```
1095 #![feature(euclidean_division)]
1096 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
1097 assert_eq!((-128i8).wrapping_div_euc(-1), -128);
1098 ```"),
1099             #[unstable(feature = "euclidean_division", issue = "49048")]
1100             #[inline]
1101             pub fn wrapping_div_euc(self, rhs: Self) -> Self {
1102                 self.overflowing_div_euc(rhs).0
1103             }
1104         }
1105
1106         doc_comment! {
1107             concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1108 boundary of the type.
1109
1110 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1111 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1112 this function returns `0`.
1113
1114 # Panics
1115
1116 This function will panic if `rhs` is 0.
1117
1118 # Examples
1119
1120 Basic usage:
1121
1122 ```
1123 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1124 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1125 $EndFeature, "
1126 ```"),
1127             #[stable(feature = "num_wrapping", since = "1.2.0")]
1128             #[inline]
1129             pub fn wrapping_rem(self, rhs: Self) -> Self {
1130                 self.overflowing_rem(rhs).0
1131             }
1132         }
1133
1134         doc_comment! {
1135             concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`, wrapping around at the
1136 boundary of the type.
1137
1138 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1139 for the type). In this case, this method returns 0.
1140
1141 # Panics
1142
1143 This function will panic if `rhs` is 0.
1144
1145 # Examples
1146
1147 Basic usage:
1148
1149 ```
1150 #![feature(euclidean_division)]
1151 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
1152 assert_eq!((-128i8).wrapping_mod_euc(-1), 0);
1153 ```"),
1154             #[unstable(feature = "euclidean_division", issue = "49048")]
1155             #[inline]
1156             pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
1157                 self.overflowing_mod_euc(rhs).0
1158             }
1159         }
1160
1161         doc_comment! {
1162             concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1163 of the type.
1164
1165 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1166 is the negative minimal value for the type); this is a positive value that is too large to represent
1167 in the type. In such a case, this function returns `MIN` itself.
1168
1169 # Examples
1170
1171 Basic usage:
1172
1173 ```
1174 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1175 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1176 "::min_value());",
1177 $EndFeature, "
1178 ```"),
1179             #[stable(feature = "num_wrapping", since = "1.2.0")]
1180             #[inline]
1181             pub fn wrapping_neg(self) -> Self {
1182                 self.overflowing_neg().0
1183             }
1184         }
1185
1186         doc_comment! {
1187             concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1188 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1189
1190 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1191 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1192 The primitive integer types all implement a `rotate_left` function, which may be what you want
1193 instead.
1194
1195 # Examples
1196
1197 Basic usage:
1198
1199 ```
1200 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1201 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1202 $EndFeature, "
1203 ```"),
1204             #[stable(feature = "num_wrapping", since = "1.2.0")]
1205             #[inline]
1206             pub fn wrapping_shl(self, rhs: u32) -> Self {
1207                 unsafe {
1208                     intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1209                 }
1210             }
1211         }
1212
1213         doc_comment! {
1214             concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1215 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1216
1217 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1218 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1219 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1220 instead.
1221
1222 # Examples
1223
1224 Basic usage:
1225
1226 ```
1227 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1228 assert_eq!((-128i16).wrapping_shr(64), -128);",
1229 $EndFeature, "
1230 ```"),
1231             #[stable(feature = "num_wrapping", since = "1.2.0")]
1232             #[inline]
1233             pub fn wrapping_shr(self, rhs: u32) -> Self {
1234                 unsafe {
1235                     intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1236                 }
1237             }
1238         }
1239
1240         doc_comment! {
1241             concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1242 the boundary of the type.
1243
1244 The only case where such wrapping can occur is when one takes the absolute value of the negative
1245 minimal value for the type this is a positive value that is too large to represent in the type. In
1246 such a case, this function returns `MIN` itself.
1247
1248 # Examples
1249
1250 Basic usage:
1251
1252 ```
1253 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1254 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1255 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1256 "::min_value());
1257 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1258 $EndFeature, "
1259 ```"),
1260             #[stable(feature = "no_panic_abs", since = "1.13.0")]
1261             #[inline]
1262             pub fn wrapping_abs(self) -> Self {
1263                 if self.is_negative() {
1264                     self.wrapping_neg()
1265                 } else {
1266                     self
1267                 }
1268             }
1269         }
1270
1271         doc_comment! {
1272             concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1273 wrapping around at the boundary of the type.
1274
1275 # Examples
1276
1277 Basic usage:
1278
1279 ```
1280 #![feature(no_panic_pow)]
1281 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1282 assert_eq!(3i8.wrapping_pow(5), -13);
1283 assert_eq!(3i8.wrapping_pow(6), -39);",
1284 $EndFeature, "
1285 ```"),
1286             #[unstable(feature = "no_panic_pow", issue = "48320")]
1287             #[inline]
1288             pub fn wrapping_pow(self, mut exp: u32) -> Self {
1289                 let mut base = self;
1290                 let mut acc: Self = 1;
1291
1292                 while exp > 1 {
1293                     if (exp & 1) == 1 {
1294                         acc = acc.wrapping_mul(base);
1295                     }
1296                     exp /= 2;
1297                     base = base.wrapping_mul(base);
1298                 }
1299
1300                 // Deal with the final bit of the exponent separately, since
1301                 // squaring the base afterwards is not necessary and may cause a
1302                 // needless overflow.
1303                 if exp == 1 {
1304                     acc = acc.wrapping_mul(base);
1305                 }
1306
1307                 acc
1308             }
1309         }
1310
1311         doc_comment! {
1312             concat!("Calculates `self` + `rhs`
1313
1314 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1315 occur. If an overflow would have occurred then the wrapped value is returned.
1316
1317 # Examples
1318
1319 Basic usage:
1320
1321 ```
1322 ", $Feature, "use std::", stringify!($SelfT), ";
1323
1324 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1325 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1326 "::MIN, true));", $EndFeature, "
1327 ```"),
1328             #[inline]
1329             #[stable(feature = "wrapping", since = "1.7.0")]
1330             pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1331                 let (a, b) = unsafe {
1332                     intrinsics::add_with_overflow(self as $ActualT,
1333                                                   rhs as $ActualT)
1334                 };
1335                 (a as Self, b)
1336             }
1337         }
1338
1339         doc_comment! {
1340             concat!("Calculates `self` - `rhs`
1341
1342 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1343 would occur. If an overflow would have occurred then the wrapped value is returned.
1344
1345 # Examples
1346
1347 Basic usage:
1348
1349 ```
1350 ", $Feature, "use std::", stringify!($SelfT), ";
1351
1352 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1353 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1354 "::MAX, true));", $EndFeature, "
1355 ```"),
1356             #[inline]
1357             #[stable(feature = "wrapping", since = "1.7.0")]
1358             pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1359                 let (a, b) = unsafe {
1360                     intrinsics::sub_with_overflow(self as $ActualT,
1361                                                   rhs as $ActualT)
1362                 };
1363                 (a as Self, b)
1364             }
1365         }
1366
1367         doc_comment! {
1368             concat!("Calculates the multiplication of `self` and `rhs`.
1369
1370 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1371 would occur. If an overflow would have occurred then the wrapped value is returned.
1372
1373 # Examples
1374
1375 Basic usage:
1376
1377 ```
1378 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1379 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1380 $EndFeature, "
1381 ```"),
1382             #[inline]
1383             #[stable(feature = "wrapping", since = "1.7.0")]
1384             pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1385                 let (a, b) = unsafe {
1386                     intrinsics::mul_with_overflow(self as $ActualT,
1387                                                   rhs as $ActualT)
1388                 };
1389                 (a as Self, b)
1390             }
1391         }
1392
1393         doc_comment! {
1394             concat!("Calculates the divisor when `self` is divided by `rhs`.
1395
1396 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1397 occur. If an overflow would occur then self is returned.
1398
1399 # Panics
1400
1401 This function will panic if `rhs` is 0.
1402
1403 # Examples
1404
1405 Basic usage:
1406
1407 ```
1408 ", $Feature, "use std::", stringify!($SelfT), ";
1409
1410 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1411 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1412 "::MIN, true));",
1413 $EndFeature, "
1414 ```"),
1415             #[inline]
1416             #[stable(feature = "wrapping", since = "1.7.0")]
1417             pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1418                 if self == Self::min_value() && rhs == -1 {
1419                     (self, true)
1420                 } else {
1421                     (self / rhs, false)
1422                 }
1423             }
1424         }
1425
1426         doc_comment! {
1427             concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
1428
1429 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1430 occur. If an overflow would occur then `self` is returned.
1431
1432 # Panics
1433
1434 This function will panic if `rhs` is 0.
1435
1436 # Examples
1437
1438 Basic usage:
1439
1440 ```
1441 #![feature(euclidean_division)]
1442 use std::", stringify!($SelfT), ";
1443
1444 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
1445 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euc(-1), (", stringify!($SelfT),
1446 "::MIN, true));
1447 ```"),
1448             #[inline]
1449             #[unstable(feature = "euclidean_division", issue = "49048")]
1450             pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
1451                 if self == Self::min_value() && rhs == -1 {
1452                     (self, true)
1453                 } else {
1454                     (self.div_euc(rhs), false)
1455                 }
1456             }
1457         }
1458
1459         doc_comment! {
1460             concat!("Calculates the remainder when `self` is divided by `rhs`.
1461
1462 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1463 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1464
1465 # Panics
1466
1467 This function will panic if `rhs` is 0.
1468
1469 # Examples
1470
1471 Basic usage:
1472
1473 ```
1474 ", $Feature, "use std::", stringify!($SelfT), ";
1475
1476 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1477 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1478 $EndFeature, "
1479 ```"),
1480             #[inline]
1481             #[stable(feature = "wrapping", since = "1.7.0")]
1482             pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1483                 if self == Self::min_value() && rhs == -1 {
1484                     (0, true)
1485                 } else {
1486                     (self % rhs, false)
1487                 }
1488             }
1489         }
1490
1491
1492         doc_comment! {
1493             concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
1494
1495 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1496 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1497
1498 # Panics
1499
1500 This function will panic if `rhs` is 0.
1501
1502 # Examples
1503
1504 Basic usage:
1505
1506 ```
1507 #![feature(euclidean_division)]
1508 use std::", stringify!($SelfT), ";
1509
1510 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
1511 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_mod_euc(-1), (0, true));
1512 ```"),
1513             #[unstable(feature = "euclidean_division", issue = "49048")]
1514             #[inline]
1515             pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
1516                 if self == Self::min_value() && rhs == -1 {
1517                     (0, true)
1518                 } else {
1519                     (self.mod_euc(rhs), false)
1520                 }
1521             }
1522         }
1523
1524
1525         doc_comment! {
1526             concat!("Negates self, overflowing if this is equal to the minimum value.
1527
1528 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1529 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1530 minimum value will be returned again and `true` will be returned for an overflow happening.
1531
1532 # Examples
1533
1534 Basic usage:
1535
1536 ```
1537 ", $Feature, "use std::", stringify!($SelfT), ";
1538
1539 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1540 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1541 "::MIN, true));", $EndFeature, "
1542 ```"),
1543             #[inline]
1544             #[stable(feature = "wrapping", since = "1.7.0")]
1545             pub fn overflowing_neg(self) -> (Self, bool) {
1546                 if self == Self::min_value() {
1547                     (Self::min_value(), true)
1548                 } else {
1549                     (-self, false)
1550                 }
1551             }
1552         }
1553
1554         doc_comment! {
1555             concat!("Shifts self left by `rhs` bits.
1556
1557 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1558 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1559 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1560
1561 # Examples
1562
1563 Basic usage:
1564
1565 ```
1566 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1567 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1568 $EndFeature, "
1569 ```"),
1570             #[inline]
1571             #[stable(feature = "wrapping", since = "1.7.0")]
1572             pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1573                 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1574             }
1575         }
1576
1577         doc_comment! {
1578             concat!("Shifts self right by `rhs` bits.
1579
1580 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1581 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1582 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1583
1584 # Examples
1585
1586 Basic usage:
1587
1588 ```
1589 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1590 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1591 $EndFeature, "
1592 ```"),
1593             #[inline]
1594             #[stable(feature = "wrapping", since = "1.7.0")]
1595             pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1596                 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1597             }
1598         }
1599
1600         doc_comment! {
1601             concat!("Computes the absolute value of `self`.
1602
1603 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1604 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1605  ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1606 for an overflow happening.
1607
1608 # Examples
1609
1610 Basic usage:
1611
1612 ```
1613 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1614 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1615 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1616 "::min_value(), true));",
1617 $EndFeature, "
1618 ```"),
1619             #[stable(feature = "no_panic_abs", since = "1.13.0")]
1620             #[inline]
1621             pub fn overflowing_abs(self) -> (Self, bool) {
1622                 if self.is_negative() {
1623                     self.overflowing_neg()
1624                 } else {
1625                     (self, false)
1626                 }
1627             }
1628         }
1629
1630         doc_comment! {
1631             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1632
1633 Returns a tuple of the exponentiation along with a bool indicating
1634 whether an overflow happened.
1635
1636 # Examples
1637
1638 Basic usage:
1639
1640 ```
1641 #![feature(no_panic_pow)]
1642 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1643 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1644 $EndFeature, "
1645 ```"),
1646             #[unstable(feature = "no_panic_pow", issue = "48320")]
1647             #[inline]
1648             pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1649                 let mut base = self;
1650                 let mut acc: Self = 1;
1651                 let mut overflown = false;
1652                 // Scratch space for storing results of overflowing_mul.
1653                 let mut r;
1654
1655                 while exp > 1 {
1656                     if (exp & 1) == 1 {
1657                         r = acc.overflowing_mul(base);
1658                         acc = r.0;
1659                         overflown |= r.1;
1660                     }
1661                     exp /= 2;
1662                     r = base.overflowing_mul(base);
1663                     base = r.0;
1664                     overflown |= r.1;
1665                 }
1666
1667                 // Deal with the final bit of the exponent separately, since
1668                 // squaring the base afterwards is not necessary and may cause a
1669                 // needless overflow.
1670                 if exp == 1 {
1671                     r = acc.overflowing_mul(base);
1672                     acc = r.0;
1673                     overflown |= r.1;
1674                 }
1675
1676                 (acc, overflown)
1677             }
1678         }
1679
1680         doc_comment! {
1681             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1682
1683 # Examples
1684
1685 Basic usage:
1686
1687 ```
1688 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1689
1690 assert_eq!(x.pow(5), 32);",
1691 $EndFeature, "
1692 ```"),
1693             #[stable(feature = "rust1", since = "1.0.0")]
1694             #[inline]
1695             #[rustc_inherit_overflow_checks]
1696             pub fn pow(self, mut exp: u32) -> Self {
1697                 let mut base = self;
1698                 let mut acc = 1;
1699
1700                 while exp > 1 {
1701                     if (exp & 1) == 1 {
1702                         acc = acc * base;
1703                     }
1704                     exp /= 2;
1705                     base = base * base;
1706                 }
1707
1708                 // Deal with the final bit of the exponent separately, since
1709                 // squaring the base afterwards is not necessary and may cause a
1710                 // needless overflow.
1711                 if exp == 1 {
1712                     acc = acc * base;
1713                 }
1714
1715                 acc
1716             }
1717         }
1718
1719         doc_comment! {
1720             concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1721
1722 This computes the integer `n` such that `self = n * rhs + self.mod_euc(rhs)`.
1723 In other words, the result is `self / rhs` rounded to the integer `n`
1724 such that `self >= n * rhs`.
1725
1726 # Panics
1727
1728 This function will panic if `rhs` is 0.
1729
1730 # Examples
1731
1732 Basic usage:
1733
1734 ```
1735 #![feature(euclidean_division)]
1736 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1737 let b = 4;
1738
1739 assert_eq!(a.div_euc(b), 1); // 7 >= 4 * 1
1740 assert_eq!(a.div_euc(-b), -1); // 7 >= -4 * -1
1741 assert_eq!((-a).div_euc(b), -2); // -7 >= 4 * -2
1742 assert_eq!((-a).div_euc(-b), 2); // -7 >= -4 * 2
1743 ```"),
1744             #[unstable(feature = "euclidean_division", issue = "49048")]
1745             #[inline]
1746             #[rustc_inherit_overflow_checks]
1747             pub fn div_euc(self, rhs: Self) -> Self {
1748                 let q = self / rhs;
1749                 if self % rhs < 0 {
1750                     return if rhs > 0 { q - 1 } else { q + 1 }
1751                 }
1752                 q
1753             }
1754         }
1755
1756
1757         doc_comment! {
1758             concat!("Calculates the remainder `self mod rhs` by Euclidean division.
1759
1760 In particular, the result `n` satisfies `0 <= n < rhs.abs()`.
1761
1762 # Panics
1763
1764 This function will panic if `rhs` is 0.
1765
1766 # Examples
1767
1768 Basic usage:
1769
1770 ```
1771 #![feature(euclidean_division)]
1772 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1773 let b = 4;
1774
1775 assert_eq!(a.mod_euc(b), 3);
1776 assert_eq!((-a).mod_euc(b), 1);
1777 assert_eq!(a.mod_euc(-b), 3);
1778 assert_eq!((-a).mod_euc(-b), 1);
1779 ```"),
1780             #[unstable(feature = "euclidean_division", issue = "49048")]
1781             #[inline]
1782             #[rustc_inherit_overflow_checks]
1783             pub fn mod_euc(self, rhs: Self) -> Self {
1784                 let r = self % rhs;
1785                 if r < 0 {
1786                     if rhs < 0 {
1787                         r - rhs
1788                     } else {
1789                         r + rhs
1790                     }
1791                 } else {
1792                     r
1793                 }
1794             }
1795         }
1796
1797         doc_comment! {
1798             concat!("Computes the absolute value of `self`.
1799
1800 # Overflow behavior
1801
1802 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1803 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1804 code in debug mode will trigger a panic on this case and optimized code will return `",
1805 stringify!($SelfT), "::min_value()` without a panic.
1806
1807 # Examples
1808
1809 Basic usage:
1810
1811 ```
1812 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1813 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1814 $EndFeature, "
1815 ```"),
1816             #[stable(feature = "rust1", since = "1.0.0")]
1817             #[inline]
1818             #[rustc_inherit_overflow_checks]
1819             pub fn abs(self) -> Self {
1820                 if self.is_negative() {
1821                     // Note that the #[inline] above means that the overflow
1822                     // semantics of this negation depend on the crate we're being
1823                     // inlined into.
1824                     -self
1825                 } else {
1826                     self
1827                 }
1828             }
1829         }
1830
1831         doc_comment! {
1832             concat!("Returns a number representing sign of `self`.
1833
1834  - `0` if the number is zero
1835  - `1` if the number is positive
1836  - `-1` if the number is negative
1837
1838 # Examples
1839
1840 Basic usage:
1841
1842 ```
1843 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1844 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1845 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1846 $EndFeature, "
1847 ```"),
1848             #[stable(feature = "rust1", since = "1.0.0")]
1849             #[inline]
1850             pub fn signum(self) -> Self {
1851                 match self {
1852                     n if n > 0 =>  1,
1853                     0          =>  0,
1854                     _          => -1,
1855                 }
1856             }
1857         }
1858
1859         doc_comment! {
1860             concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1861 negative.
1862
1863 # Examples
1864
1865 Basic usage:
1866
1867 ```
1868 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1869 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1870 $EndFeature, "
1871 ```"),
1872             #[stable(feature = "rust1", since = "1.0.0")]
1873             #[inline]
1874             pub fn is_positive(self) -> bool { self > 0 }
1875         }
1876
1877         doc_comment! {
1878             concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1879 positive.
1880
1881 # Examples
1882
1883 Basic usage:
1884
1885 ```
1886 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1887 assert!(!10", stringify!($SelfT), ".is_negative());",
1888 $EndFeature, "
1889 ```"),
1890             #[stable(feature = "rust1", since = "1.0.0")]
1891             #[inline]
1892             pub fn is_negative(self) -> bool { self < 0 }
1893         }
1894
1895         /// Return the memory representation of this integer as a byte array.
1896         ///
1897         /// The target platform’s native endianness is used.
1898         /// Portable code likely wants to use this after [`to_be`] or [`to_le`].
1899         ///
1900         /// [`to_be`]: #method.to_be
1901         /// [`to_le`]: #method.to_le
1902         ///
1903         /// # Examples
1904         ///
1905         /// ```
1906         /// #![feature(int_to_from_bytes)]
1907         ///
1908         /// let bytes = i32::min_value().to_be().to_bytes();
1909         /// assert_eq!(bytes, [0x80, 0, 0, 0]);
1910         /// ```
1911         #[unstable(feature = "int_to_from_bytes", issue = "49792")]
1912         #[inline]
1913         pub fn to_bytes(self) -> [u8; mem::size_of::<Self>()] {
1914             unsafe { mem::transmute(self) }
1915         }
1916
1917         /// Create an integer value from its memory representation as a byte array.
1918         ///
1919         /// The target platform’s native endianness is used.
1920         /// Portable code likely wants to use [`from_be`] or [`from_le`] after this.
1921         ///
1922         /// [`from_be`]: #method.from_be
1923         /// [`from_le`]: #method.from_le
1924         ///
1925         /// # Examples
1926         ///
1927         /// ```
1928         /// #![feature(int_to_from_bytes)]
1929         ///
1930         /// let int = i32::from_be(i32::from_bytes([0x80, 0, 0, 0]));
1931         /// assert_eq!(int, i32::min_value());
1932         /// ```
1933         #[unstable(feature = "int_to_from_bytes", issue = "49792")]
1934         #[inline]
1935         pub fn from_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1936             unsafe { mem::transmute(bytes) }
1937         }
1938     }
1939 }
1940
1941 #[lang = "i8"]
1942 impl i8 {
1943     int_impl! { i8, i8, u8, 8, -128, 127, "", "" }
1944 }
1945
1946 #[lang = "i16"]
1947 impl i16 {
1948     int_impl! { i16, i16, u16, 16, -32768, 32767, "", "" }
1949 }
1950
1951 #[lang = "i32"]
1952 impl i32 {
1953     int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "" }
1954 }
1955
1956 #[lang = "i64"]
1957 impl i64 {
1958     int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1959 }
1960
1961 #[lang = "i128"]
1962 impl i128 {
1963     int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
1964         170141183460469231731687303715884105727, "", "" }
1965 }
1966
1967 #[cfg(target_pointer_width = "16")]
1968 #[lang = "isize"]
1969 impl isize {
1970     int_impl! { isize, i16, u16, 16, -32768, 32767, "", "" }
1971 }
1972
1973 #[cfg(target_pointer_width = "32")]
1974 #[lang = "isize"]
1975 impl isize {
1976     int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "" }
1977 }
1978
1979 #[cfg(target_pointer_width = "64")]
1980 #[lang = "isize"]
1981 impl isize {
1982     int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1983 }
1984
1985 // Emits the correct `cttz` call, depending on the size of the type.
1986 macro_rules! uint_cttz_call {
1987     // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1988     // emits two conditional moves on x86_64. By promoting the value to
1989     // u16 and setting bit 8, we get better code without any conditional
1990     // operations.
1991     // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1992     // pending, remove this workaround once LLVM generates better code
1993     // for cttz8.
1994     ($value:expr, 8) => { intrinsics::cttz($value as u16 | 0x100) };
1995     ($value:expr, $_BITS:expr) => { intrinsics::cttz($value) }
1996 }
1997
1998 // `Int` + `UnsignedInt` implemented for unsigned integers
1999 macro_rules! uint_impl {
2000     ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr) => {
2001         doc_comment! {
2002             concat!("Returns the smallest value that can be represented by this integer type.
2003
2004 # Examples
2005
2006 Basic usage:
2007
2008 ```
2009 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2010 ```"),
2011             #[stable(feature = "rust1", since = "1.0.0")]
2012             #[inline]
2013             pub const fn min_value() -> Self { 0 }
2014         }
2015
2016         doc_comment! {
2017             concat!("Returns the largest value that can be represented by this integer type.
2018
2019 # Examples
2020
2021 Basic usage:
2022
2023 ```
2024 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2025 stringify!($MaxV), ");", $EndFeature, "
2026 ```"),
2027             #[stable(feature = "rust1", since = "1.0.0")]
2028             #[inline]
2029             pub const fn max_value() -> Self { !0 }
2030         }
2031
2032         doc_comment! {
2033             concat!("Converts a string slice in a given base to an integer.
2034
2035 The string is expected to be an optional `+` sign
2036 followed by digits.
2037 Leading and trailing whitespace represent an error.
2038 Digits are a subset of these characters, depending on `radix`:
2039
2040 * `0-9`
2041 * `a-z`
2042 * `A-Z`
2043
2044 # Panics
2045
2046 This function panics if `radix` is not in the range from 2 to 36.
2047
2048 # Examples
2049
2050 Basic usage:
2051
2052 ```
2053 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2054 $EndFeature, "
2055 ```"),
2056             #[stable(feature = "rust1", since = "1.0.0")]
2057             pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2058                 from_str_radix(src, radix)
2059             }
2060         }
2061
2062         doc_comment! {
2063             concat!("Returns the number of ones in the binary representation of `self`.
2064
2065 # Examples
2066
2067 Basic usage:
2068
2069 ```
2070 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2071
2072 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2073 ```"),
2074             #[stable(feature = "rust1", since = "1.0.0")]
2075             #[rustc_const_unstable(feature = "const_int_ops")]
2076             #[inline]
2077             pub const fn count_ones(self) -> u32 {
2078                 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
2079             }
2080         }
2081
2082         doc_comment! {
2083             concat!("Returns the number of zeros in the binary representation of `self`.
2084
2085 # Examples
2086
2087 Basic usage:
2088
2089 ```
2090 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2091 ```"),
2092             #[stable(feature = "rust1", since = "1.0.0")]
2093             #[rustc_const_unstable(feature = "const_int_ops")]
2094             #[inline]
2095             pub const fn count_zeros(self) -> u32 {
2096                 (!self).count_ones()
2097             }
2098         }
2099
2100         doc_comment! {
2101             concat!("Returns the number of leading zeros in the binary representation of `self`.
2102
2103 # Examples
2104
2105 Basic usage:
2106
2107 ```
2108 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2109
2110 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2111 ```"),
2112             #[stable(feature = "rust1", since = "1.0.0")]
2113             #[rustc_const_unstable(feature = "const_int_ops")]
2114             #[inline]
2115             pub const fn leading_zeros(self) -> u32 {
2116                 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
2117             }
2118         }
2119
2120         doc_comment! {
2121             concat!("Returns the number of trailing zeros in the binary representation
2122 of `self`.
2123
2124 # Examples
2125
2126 Basic usage:
2127
2128 ```
2129 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2130
2131 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2132 ```"),
2133             #[stable(feature = "rust1", since = "1.0.0")]
2134             #[rustc_const_unstable(feature = "const_int_ops")]
2135             #[inline]
2136             pub const fn trailing_zeros(self) -> u32 {
2137                 unsafe { uint_cttz_call!(self, $BITS) as u32 }
2138             }
2139         }
2140
2141         /// Shifts the bits to the left by a specified amount, `n`,
2142         /// wrapping the truncated bits to the end of the resulting integer.
2143         ///
2144         /// Please note this isn't the same operation as `<<`!
2145         ///
2146         /// # Examples
2147         ///
2148         /// Basic usage:
2149         ///
2150         /// Please note that this example is shared between integer types.
2151         /// Which explains why `u64` is used here.
2152         ///
2153         /// ```
2154         /// let n = 0x0123456789ABCDEFu64;
2155         /// let m = 0x3456789ABCDEF012u64;
2156         ///
2157         /// assert_eq!(n.rotate_left(12), m);
2158         /// ```
2159         #[stable(feature = "rust1", since = "1.0.0")]
2160         #[inline]
2161         pub fn rotate_left(self, n: u32) -> Self {
2162             // Protect against undefined behaviour for over-long bit shifts
2163             let n = n % $BITS;
2164             (self << n) | (self >> (($BITS - n) % $BITS))
2165         }
2166
2167         /// Shifts the bits to the right by a specified amount, `n`,
2168         /// wrapping the truncated bits to the beginning of the resulting
2169         /// integer.
2170         ///
2171         /// Please note this isn't the same operation as `>>`!
2172         ///
2173         /// # Examples
2174         ///
2175         /// Basic usage:
2176         ///
2177         /// Please note that this example is shared between integer types.
2178         /// Which explains why `u64` is used here.
2179         ///
2180         /// ```
2181         /// let n = 0x0123456789ABCDEFu64;
2182         /// let m = 0xDEF0123456789ABCu64;
2183         ///
2184         /// assert_eq!(n.rotate_right(12), m);
2185         /// ```
2186         #[stable(feature = "rust1", since = "1.0.0")]
2187         #[inline]
2188         pub fn rotate_right(self, n: u32) -> Self {
2189             // Protect against undefined behaviour for over-long bit shifts
2190             let n = n % $BITS;
2191             (self >> n) | (self << (($BITS - n) % $BITS))
2192         }
2193
2194         /// Reverses the byte order of the integer.
2195         ///
2196         /// # Examples
2197         ///
2198         /// Basic usage:
2199         ///
2200         /// Please note that this example is shared between integer types.
2201         /// Which explains why `u16` is used here.
2202         ///
2203         /// ```
2204         /// let n: u16 = 0b0000000_01010101;
2205         /// assert_eq!(n, 85);
2206         ///
2207         /// let m = n.swap_bytes();
2208         ///
2209         /// assert_eq!(m, 0b01010101_00000000);
2210         /// assert_eq!(m, 21760);
2211         /// ```
2212         #[stable(feature = "rust1", since = "1.0.0")]
2213         #[rustc_const_unstable(feature = "const_int_ops")]
2214         #[inline]
2215         pub const fn swap_bytes(self) -> Self {
2216             unsafe { intrinsics::bswap(self as $ActualT) as Self }
2217         }
2218
2219         /// Reverses the bit pattern of the integer.
2220         ///
2221         /// # Examples
2222         ///
2223         /// Basic usage:
2224         ///
2225         /// Please note that this example is shared between integer types.
2226         /// Which explains why `u16` is used here.
2227         ///
2228         /// ```
2229         /// #![feature(reverse_bits)]
2230         ///
2231         /// let n: u16 = 0b0000000_01010101;
2232         /// assert_eq!(n, 85);
2233         ///
2234         /// let m = n.reverse_bits();
2235         ///
2236         /// assert_eq!(m, 0b10101010_00000000);
2237         /// assert_eq!(m, 43520);
2238         /// ```
2239         #[unstable(feature = "reverse_bits", issue = "48763")]
2240         #[inline]
2241         pub fn reverse_bits(self) -> Self {
2242             unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
2243         }
2244
2245         doc_comment! {
2246             concat!("Converts an integer from big endian to the target's endianness.
2247
2248 On big endian this is a no-op. On little endian the bytes are
2249 swapped.
2250
2251 # Examples
2252
2253 Basic usage:
2254
2255 ```
2256 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2257
2258 if cfg!(target_endian = \"big\") {
2259     assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2260 } else {
2261     assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2262 }", $EndFeature, "
2263 ```"),
2264             #[stable(feature = "rust1", since = "1.0.0")]
2265             #[rustc_const_unstable(feature = "const_int_ops")]
2266             #[inline]
2267             pub const fn from_be(x: Self) -> Self {
2268                 #[cfg(target_endian = "big")]
2269                 {
2270                     x
2271                 }
2272                 #[cfg(not(target_endian = "big"))]
2273                 {
2274                     x.swap_bytes()
2275                 }
2276             }
2277         }
2278
2279         doc_comment! {
2280             concat!("Converts an integer from little endian to the target's endianness.
2281
2282 On little endian this is a no-op. On big endian the bytes are
2283 swapped.
2284
2285 # Examples
2286
2287 Basic usage:
2288
2289 ```
2290 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2291
2292 if cfg!(target_endian = \"little\") {
2293     assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2294 } else {
2295     assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2296 }", $EndFeature, "
2297 ```"),
2298             #[stable(feature = "rust1", since = "1.0.0")]
2299             #[rustc_const_unstable(feature = "const_int_ops")]
2300             #[inline]
2301             pub const fn from_le(x: Self) -> Self {
2302                 #[cfg(target_endian = "little")]
2303                 {
2304                     x
2305                 }
2306                 #[cfg(not(target_endian = "little"))]
2307                 {
2308                     x.swap_bytes()
2309                 }
2310             }
2311         }
2312
2313         doc_comment! {
2314             concat!("Converts `self` to big endian from the target's endianness.
2315
2316 On big endian this is a no-op. On little endian the bytes are
2317 swapped.
2318
2319 # Examples
2320
2321 Basic usage:
2322
2323 ```
2324 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2325
2326 if cfg!(target_endian = \"big\") {
2327     assert_eq!(n.to_be(), n)
2328 } else {
2329     assert_eq!(n.to_be(), n.swap_bytes())
2330 }", $EndFeature, "
2331 ```"),
2332             #[stable(feature = "rust1", since = "1.0.0")]
2333             #[rustc_const_unstable(feature = "const_int_ops")]
2334             #[inline]
2335             pub const fn to_be(self) -> Self { // or not to be?
2336                 #[cfg(target_endian = "big")]
2337                 {
2338                     self
2339                 }
2340                 #[cfg(not(target_endian = "big"))]
2341                 {
2342                     self.swap_bytes()
2343                 }
2344             }
2345         }
2346
2347         doc_comment! {
2348             concat!("Converts `self` to little endian from the target's endianness.
2349
2350 On little endian this is a no-op. On big endian the bytes are
2351 swapped.
2352
2353 # Examples
2354
2355 Basic usage:
2356
2357 ```
2358 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2359
2360 if cfg!(target_endian = \"little\") {
2361     assert_eq!(n.to_le(), n)
2362 } else {
2363     assert_eq!(n.to_le(), n.swap_bytes())
2364 }", $EndFeature, "
2365 ```"),
2366             #[stable(feature = "rust1", since = "1.0.0")]
2367             #[rustc_const_unstable(feature = "const_int_ops")]
2368             #[inline]
2369             pub const fn to_le(self) -> Self {
2370                 #[cfg(target_endian = "little")]
2371                 {
2372                     self
2373                 }
2374                 #[cfg(not(target_endian = "little"))]
2375                 {
2376                     self.swap_bytes()
2377                 }
2378             }
2379         }
2380
2381         doc_comment! {
2382             concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2383 if overflow occurred.
2384
2385 # Examples
2386
2387 Basic usage:
2388
2389 ```
2390 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2391 "Some(", stringify!($SelfT), "::max_value() - 1));
2392 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2393 ```"),
2394             #[stable(feature = "rust1", since = "1.0.0")]
2395             #[inline]
2396             pub fn checked_add(self, rhs: Self) -> Option<Self> {
2397                 let (a, b) = self.overflowing_add(rhs);
2398                 if b {None} else {Some(a)}
2399             }
2400         }
2401
2402         doc_comment! {
2403             concat!("Checked integer subtraction. Computes `self - rhs`, returning
2404 `None` if overflow occurred.
2405
2406 # Examples
2407
2408 Basic usage:
2409
2410 ```
2411 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2412 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2413 ```"),
2414             #[stable(feature = "rust1", since = "1.0.0")]
2415             #[inline]
2416             pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2417                 let (a, b) = self.overflowing_sub(rhs);
2418                 if b {None} else {Some(a)}
2419             }
2420         }
2421
2422         doc_comment! {
2423             concat!("Checked integer multiplication. Computes `self * rhs`, returning
2424 `None` if overflow occurred.
2425
2426 # Examples
2427
2428 Basic usage:
2429
2430 ```
2431 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2432 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2433 ```"),
2434             #[stable(feature = "rust1", since = "1.0.0")]
2435             #[inline]
2436             pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2437                 let (a, b) = self.overflowing_mul(rhs);
2438                 if b {None} else {Some(a)}
2439             }
2440         }
2441
2442         doc_comment! {
2443             concat!("Checked integer division. Computes `self / rhs`, returning `None`
2444 if `rhs == 0`.
2445
2446 # Examples
2447
2448 Basic usage:
2449
2450 ```
2451 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2452 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2453 ```"),
2454             #[stable(feature = "rust1", since = "1.0.0")]
2455             #[inline]
2456             pub fn checked_div(self, rhs: Self) -> Option<Self> {
2457                 match rhs {
2458                     0 => None,
2459                     rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2460                 }
2461             }
2462         }
2463
2464         doc_comment! {
2465             concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`, returning `None`
2466 if `rhs == 0`.
2467
2468 # Examples
2469
2470 Basic usage:
2471
2472 ```
2473 #![feature(euclidean_division)]
2474 assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2475 assert_eq!(1", stringify!($SelfT), ".checked_div_euc(0), None);
2476 ```"),
2477             #[unstable(feature = "euclidean_division", issue = "49048")]
2478             #[inline]
2479             pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
2480                 if rhs == 0 {
2481                     None
2482                 } else {
2483                     Some(self.div_euc(rhs))
2484                 }
2485             }
2486         }
2487
2488
2489         doc_comment! {
2490             concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2491 if `rhs == 0`.
2492
2493 # Examples
2494
2495 Basic usage:
2496
2497 ```
2498 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2499 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2500 ```"),
2501             #[stable(feature = "wrapping", since = "1.7.0")]
2502             #[inline]
2503             pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2504                 if rhs == 0 {
2505                     None
2506                 } else {
2507                     Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2508                 }
2509             }
2510         }
2511
2512         doc_comment! {
2513             concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None`
2514 if `rhs == 0`.
2515
2516 # Examples
2517
2518 Basic usage:
2519
2520 ```
2521 #![feature(euclidean_division)]
2522 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
2523 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
2524 ```"),
2525             #[unstable(feature = "euclidean_division", issue = "49048")]
2526             #[inline]
2527             pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
2528                 if rhs == 0 {
2529                     None
2530                 } else {
2531                     Some(self.mod_euc(rhs))
2532                 }
2533             }
2534         }
2535
2536         doc_comment! {
2537             concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2538 0`.
2539
2540 Note that negating any positive integer will overflow.
2541
2542 # Examples
2543
2544 Basic usage:
2545
2546 ```
2547 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2548 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2549 ```"),
2550             #[stable(feature = "wrapping", since = "1.7.0")]
2551             #[inline]
2552             pub fn checked_neg(self) -> Option<Self> {
2553                 let (a, b) = self.overflowing_neg();
2554                 if b {None} else {Some(a)}
2555             }
2556         }
2557
2558         doc_comment! {
2559             concat!("Checked shift left. Computes `self << rhs`, returning `None`
2560 if `rhs` is larger than or equal to the number of bits in `self`.
2561
2562 # Examples
2563
2564 Basic usage:
2565
2566 ```
2567 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2568 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2569 ```"),
2570             #[stable(feature = "wrapping", since = "1.7.0")]
2571             #[inline]
2572             pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2573                 let (a, b) = self.overflowing_shl(rhs);
2574                 if b {None} else {Some(a)}
2575             }
2576         }
2577
2578         doc_comment! {
2579             concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2580 if `rhs` is larger than or equal to the number of bits in `self`.
2581
2582 # Examples
2583
2584 Basic usage:
2585
2586 ```
2587 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2588 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2589 ```"),
2590             #[stable(feature = "wrapping", since = "1.7.0")]
2591             #[inline]
2592             pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2593                 let (a, b) = self.overflowing_shr(rhs);
2594                 if b {None} else {Some(a)}
2595             }
2596         }
2597
2598         doc_comment! {
2599             concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2600 overflow occurred.
2601
2602 # Examples
2603
2604 Basic usage:
2605
2606 ```
2607 #![feature(no_panic_pow)]
2608 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2609 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2610 ```"),
2611             #[unstable(feature = "no_panic_pow", issue = "48320")]
2612             #[inline]
2613             pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2614                 let mut base = self;
2615                 let mut acc: Self = 1;
2616
2617                 while exp > 1 {
2618                     if (exp & 1) == 1 {
2619                         acc = acc.checked_mul(base)?;
2620                     }
2621                     exp /= 2;
2622                     base = base.checked_mul(base)?;
2623                 }
2624
2625                 // Deal with the final bit of the exponent separately, since
2626                 // squaring the base afterwards is not necessary and may cause a
2627                 // needless overflow.
2628                 if exp == 1 {
2629                     acc = acc.checked_mul(base)?;
2630                 }
2631
2632                 Some(acc)
2633             }
2634         }
2635
2636         doc_comment! {
2637             concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2638 the numeric bounds instead of overflowing.
2639
2640 # Examples
2641
2642 Basic usage:
2643
2644 ```
2645 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2646 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2647 ```"),
2648             #[stable(feature = "rust1", since = "1.0.0")]
2649             #[inline]
2650             pub fn saturating_add(self, rhs: Self) -> Self {
2651                 match self.checked_add(rhs) {
2652                     Some(x) => x,
2653                     None => Self::max_value(),
2654                 }
2655             }
2656         }
2657
2658         doc_comment! {
2659             concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2660 at the numeric bounds instead of overflowing.
2661
2662 # Examples
2663
2664 Basic usage:
2665
2666 ```
2667 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2668 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2669 ```"),
2670             #[stable(feature = "rust1", since = "1.0.0")]
2671             #[inline]
2672             pub fn saturating_sub(self, rhs: Self) -> Self {
2673                 match self.checked_sub(rhs) {
2674                     Some(x) => x,
2675                     None => Self::min_value(),
2676                 }
2677             }
2678         }
2679
2680         doc_comment! {
2681             concat!("Saturating integer multiplication. Computes `self * rhs`,
2682 saturating at the numeric bounds instead of overflowing.
2683
2684 # Examples
2685
2686 Basic usage:
2687
2688 ```
2689 ", $Feature, "use std::", stringify!($SelfT), ";
2690
2691 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2692 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2693 "::MAX);", $EndFeature, "
2694 ```"),
2695             #[stable(feature = "wrapping", since = "1.7.0")]
2696             #[inline]
2697             pub fn saturating_mul(self, rhs: Self) -> Self {
2698                 self.checked_mul(rhs).unwrap_or(Self::max_value())
2699             }
2700         }
2701
2702         doc_comment! {
2703             concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2704 saturating at the numeric bounds instead of overflowing.
2705
2706 # Examples
2707
2708 Basic usage:
2709
2710 ```
2711 #![feature(no_panic_pow)]
2712 ", $Feature, "use std::", stringify!($SelfT), ";
2713
2714 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2715 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2716 $EndFeature, "
2717 ```"),
2718             #[unstable(feature = "no_panic_pow", issue = "48320")]
2719             #[inline]
2720             pub fn saturating_pow(self, exp: u32) -> Self {
2721                 match self.checked_pow(exp) {
2722                     Some(x) => x,
2723                     None => Self::max_value(),
2724                 }
2725             }
2726         }
2727
2728         doc_comment! {
2729             concat!("Wrapping (modular) addition. Computes `self + rhs`,
2730 wrapping around at the boundary of the type.
2731
2732 # Examples
2733
2734 Basic usage:
2735
2736 ```
2737 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2738 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2739 $EndFeature, "
2740 ```"),
2741             #[stable(feature = "rust1", since = "1.0.0")]
2742             #[inline]
2743             pub fn wrapping_add(self, rhs: Self) -> Self {
2744                 unsafe {
2745                     intrinsics::overflowing_add(self, rhs)
2746                 }
2747             }
2748         }
2749
2750         doc_comment! {
2751             concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2752 wrapping around at the boundary of the type.
2753
2754 # Examples
2755
2756 Basic usage:
2757
2758 ```
2759 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2760 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2761 $EndFeature, "
2762 ```"),
2763             #[stable(feature = "rust1", since = "1.0.0")]
2764             #[inline]
2765             pub fn wrapping_sub(self, rhs: Self) -> Self {
2766                 unsafe {
2767                     intrinsics::overflowing_sub(self, rhs)
2768                 }
2769             }
2770         }
2771
2772         /// Wrapping (modular) multiplication. Computes `self *
2773         /// rhs`, wrapping around at the boundary of the type.
2774         ///
2775         /// # Examples
2776         ///
2777         /// Basic usage:
2778         ///
2779         /// Please note that this example is shared between integer types.
2780         /// Which explains why `u8` is used here.
2781         ///
2782         /// ```
2783         /// assert_eq!(10u8.wrapping_mul(12), 120);
2784         /// assert_eq!(25u8.wrapping_mul(12), 44);
2785         /// ```
2786         #[stable(feature = "rust1", since = "1.0.0")]
2787         #[inline]
2788         pub fn wrapping_mul(self, rhs: Self) -> Self {
2789             unsafe {
2790                 intrinsics::overflowing_mul(self, rhs)
2791             }
2792         }
2793
2794         doc_comment! {
2795             concat!("Wrapping (modular) division. Computes `self / rhs`.
2796 Wrapped division on unsigned types is just normal division.
2797 There's no way wrapping could ever happen.
2798 This function exists, so that all operations
2799 are accounted for in the wrapping operations.
2800
2801 # Examples
2802
2803 Basic usage:
2804
2805 ```
2806 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2807 ```"),
2808             #[stable(feature = "num_wrapping", since = "1.2.0")]
2809             #[inline]
2810             pub fn wrapping_div(self, rhs: Self) -> Self {
2811                 self / rhs
2812             }
2813         }
2814
2815         doc_comment! {
2816             concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`.
2817 Wrapped division on unsigned types is just normal division.
2818 There's no way wrapping could ever happen.
2819 This function exists, so that all operations
2820 are accounted for in the wrapping operations.
2821
2822 # Examples
2823
2824 Basic usage:
2825
2826 ```
2827 #![feature(euclidean_division)]
2828 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
2829 ```"),
2830             #[unstable(feature = "euclidean_division", issue = "49048")]
2831             #[inline]
2832             pub fn wrapping_div_euc(self, rhs: Self) -> Self {
2833                 self / rhs
2834             }
2835         }
2836
2837         doc_comment! {
2838             concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2839 Wrapped remainder calculation on unsigned types is
2840 just the regular remainder calculation.
2841 There's no way wrapping could ever happen.
2842 This function exists, so that all operations
2843 are accounted for in the wrapping operations.
2844
2845 # Examples
2846
2847 Basic usage:
2848
2849 ```
2850 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2851 ```"),
2852             #[stable(feature = "num_wrapping", since = "1.2.0")]
2853             #[inline]
2854             pub fn wrapping_rem(self, rhs: Self) -> Self {
2855                 self % rhs
2856             }
2857         }
2858
2859         doc_comment! {
2860             concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`.
2861 Wrapped modulo calculation on unsigned types is
2862 just the regular remainder calculation.
2863 There's no way wrapping could ever happen.
2864 This function exists, so that all operations
2865 are accounted for in the wrapping operations.
2866
2867 # Examples
2868
2869 Basic usage:
2870
2871 ```
2872 #![feature(euclidean_division)]
2873 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
2874 ```"),
2875             #[unstable(feature = "euclidean_division", issue = "49048")]
2876             #[inline]
2877             pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
2878                 self % rhs
2879             }
2880         }
2881
2882         /// Wrapping (modular) negation. Computes `-self`,
2883         /// wrapping around at the boundary of the type.
2884         ///
2885         /// Since unsigned types do not have negative equivalents
2886         /// all applications of this function will wrap (except for `-0`).
2887         /// For values smaller than the corresponding signed type's maximum
2888         /// the result is the same as casting the corresponding signed value.
2889         /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2890         /// `MAX` is the corresponding signed type's maximum.
2891         ///
2892         /// # Examples
2893         ///
2894         /// Basic usage:
2895         ///
2896         /// Please note that this example is shared between integer types.
2897         /// Which explains why `i8` is used here.
2898         ///
2899         /// ```
2900         /// assert_eq!(100i8.wrapping_neg(), -100);
2901         /// assert_eq!((-128i8).wrapping_neg(), -128);
2902         /// ```
2903         #[stable(feature = "num_wrapping", since = "1.2.0")]
2904         #[inline]
2905         pub fn wrapping_neg(self) -> Self {
2906             self.overflowing_neg().0
2907         }
2908
2909         doc_comment! {
2910             concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2911 where `mask` removes any high-order bits of `rhs` that
2912 would cause the shift to exceed the bitwidth of the type.
2913
2914 Note that this is *not* the same as a rotate-left; the
2915 RHS of a wrapping shift-left is restricted to the range
2916 of the type, rather than the bits shifted out of the LHS
2917 being returned to the other end. The primitive integer
2918 types all implement a `rotate_left` function, which may
2919 be what you want instead.
2920
2921 # Examples
2922
2923 Basic usage:
2924
2925 ```
2926 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2927 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2928 ```"),
2929             #[stable(feature = "num_wrapping", since = "1.2.0")]
2930             #[inline]
2931             pub fn wrapping_shl(self, rhs: u32) -> Self {
2932                 unsafe {
2933                     intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
2934                 }
2935             }
2936         }
2937
2938         doc_comment! {
2939             concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2940 where `mask` removes any high-order bits of `rhs` that
2941 would cause the shift to exceed the bitwidth of the type.
2942
2943 Note that this is *not* the same as a rotate-right; the
2944 RHS of a wrapping shift-right is restricted to the range
2945 of the type, rather than the bits shifted out of the LHS
2946 being returned to the other end. The primitive integer
2947 types all implement a `rotate_right` function, which may
2948 be what you want instead.
2949
2950 # Examples
2951
2952 Basic usage:
2953
2954 ```
2955 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
2956 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
2957 ```"),
2958             #[stable(feature = "num_wrapping", since = "1.2.0")]
2959             #[inline]
2960             pub fn wrapping_shr(self, rhs: u32) -> Self {
2961                 unsafe {
2962                     intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
2963                 }
2964             }
2965         }
2966
2967         doc_comment! {
2968             concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2969 wrapping around at the boundary of the type.
2970
2971 # Examples
2972
2973 Basic usage:
2974
2975 ```
2976 #![feature(no_panic_pow)]
2977 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
2978 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
2979 ```"),
2980             #[unstable(feature = "no_panic_pow", issue = "48320")]
2981             #[inline]
2982             pub fn wrapping_pow(self, mut exp: u32) -> Self {
2983                 let mut base = self;
2984                 let mut acc: Self = 1;
2985
2986                 while exp > 1 {
2987                     if (exp & 1) == 1 {
2988                         acc = acc.wrapping_mul(base);
2989                     }
2990                     exp /= 2;
2991                     base = base.wrapping_mul(base);
2992                 }
2993
2994                 // Deal with the final bit of the exponent separately, since
2995                 // squaring the base afterwards is not necessary and may cause a
2996                 // needless overflow.
2997                 if exp == 1 {
2998                     acc = acc.wrapping_mul(base);
2999                 }
3000
3001                 acc
3002             }
3003         }
3004
3005         doc_comment! {
3006             concat!("Calculates `self` + `rhs`
3007
3008 Returns a tuple of the addition along with a boolean indicating
3009 whether an arithmetic overflow would occur. If an overflow would
3010 have occurred then the wrapped value is returned.
3011
3012 # Examples
3013
3014 Basic usage
3015
3016 ```
3017 ", $Feature, "use std::", stringify!($SelfT), ";
3018
3019 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3020 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3021 ```"),
3022             #[inline]
3023             #[stable(feature = "wrapping", since = "1.7.0")]
3024             pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3025                 let (a, b) = unsafe {
3026                     intrinsics::add_with_overflow(self as $ActualT,
3027                                                   rhs as $ActualT)
3028                 };
3029                 (a as Self, b)
3030             }
3031         }
3032
3033         doc_comment! {
3034             concat!("Calculates `self` - `rhs`
3035
3036 Returns a tuple of the subtraction along with a boolean indicating
3037 whether an arithmetic overflow would occur. If an overflow would
3038 have occurred then the wrapped value is returned.
3039
3040 # Examples
3041
3042 Basic usage
3043
3044 ```
3045 ", $Feature, "use std::", stringify!($SelfT), ";
3046
3047 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3048 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3049 $EndFeature, "
3050 ```"),
3051             #[inline]
3052             #[stable(feature = "wrapping", since = "1.7.0")]
3053             pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3054                 let (a, b) = unsafe {
3055                     intrinsics::sub_with_overflow(self as $ActualT,
3056                                                   rhs as $ActualT)
3057                 };
3058                 (a as Self, b)
3059             }
3060         }
3061
3062         /// Calculates the multiplication of `self` and `rhs`.
3063         ///
3064         /// Returns a tuple of the multiplication along with a boolean
3065         /// indicating whether an arithmetic overflow would occur. If an
3066         /// overflow would have occurred then the wrapped value is returned.
3067         ///
3068         /// # Examples
3069         ///
3070         /// Basic usage:
3071         ///
3072         /// Please note that this example is shared between integer types.
3073         /// Which explains why `u32` is used here.
3074         ///
3075         /// ```
3076         /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3077         /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3078         /// ```
3079         #[inline]
3080         #[stable(feature = "wrapping", since = "1.7.0")]
3081         pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3082             let (a, b) = unsafe {
3083                 intrinsics::mul_with_overflow(self as $ActualT,
3084                                               rhs as $ActualT)
3085             };
3086             (a as Self, b)
3087         }
3088
3089         doc_comment! {
3090             concat!("Calculates the divisor when `self` is divided by `rhs`.
3091
3092 Returns a tuple of the divisor along with a boolean indicating
3093 whether an arithmetic overflow would occur. Note that for unsigned
3094 integers overflow never occurs, so the second value is always
3095 `false`.
3096
3097 # Panics
3098
3099 This function will panic if `rhs` is 0.
3100
3101 # Examples
3102
3103 Basic usage
3104
3105 ```
3106 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3107 ```"),
3108             #[inline]
3109             #[stable(feature = "wrapping", since = "1.7.0")]
3110             pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3111                 (self / rhs, false)
3112             }
3113         }
3114
3115         doc_comment! {
3116             concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
3117
3118 Returns a tuple of the divisor along with a boolean indicating
3119 whether an arithmetic overflow would occur. Note that for unsigned
3120 integers overflow never occurs, so the second value is always
3121 `false`.
3122
3123 # Panics
3124
3125 This function will panic if `rhs` is 0.
3126
3127 # Examples
3128
3129 Basic usage
3130
3131 ```
3132 #![feature(euclidean_division)]
3133 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
3134 ```"),
3135             #[inline]
3136             #[unstable(feature = "euclidean_division", issue = "49048")]
3137             pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
3138                 (self / rhs, false)
3139             }
3140         }
3141
3142         doc_comment! {
3143             concat!("Calculates the remainder when `self` is divided by `rhs`.
3144
3145 Returns a tuple of the remainder after dividing along with a boolean
3146 indicating whether an arithmetic overflow would occur. Note that for
3147 unsigned integers overflow never occurs, so the second value is
3148 always `false`.
3149
3150 # Panics
3151
3152 This function will panic if `rhs` is 0.
3153
3154 # Examples
3155
3156 Basic usage
3157
3158 ```
3159 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3160 ```"),
3161             #[inline]
3162             #[stable(feature = "wrapping", since = "1.7.0")]
3163             pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3164                 (self % rhs, false)
3165             }
3166         }
3167
3168         doc_comment! {
3169             concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
3170
3171 Returns a tuple of the modulo after dividing along with a boolean
3172 indicating whether an arithmetic overflow would occur. Note that for
3173 unsigned integers overflow never occurs, so the second value is
3174 always `false`.
3175
3176 # Panics
3177
3178 This function will panic if `rhs` is 0.
3179
3180 # Examples
3181
3182 Basic usage
3183
3184 ```
3185 #![feature(euclidean_division)]
3186 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
3187 ```"),
3188             #[inline]
3189             #[unstable(feature = "euclidean_division", issue = "49048")]
3190             pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
3191                 (self % rhs, false)
3192             }
3193         }
3194
3195         doc_comment! {
3196             concat!("Negates self in an overflowing fashion.
3197
3198 Returns `!self + 1` using wrapping operations to return the value
3199 that represents the negation of this unsigned value. Note that for
3200 positive unsigned values overflow always occurs, but negating 0 does
3201 not overflow.
3202
3203 # Examples
3204
3205 Basic usage
3206
3207 ```
3208 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3209 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3210 ", true));", $EndFeature, "
3211 ```"),
3212             #[inline]
3213             #[stable(feature = "wrapping", since = "1.7.0")]
3214             pub fn overflowing_neg(self) -> (Self, bool) {
3215                 ((!self).wrapping_add(1), self != 0)
3216             }
3217         }
3218
3219         doc_comment! {
3220             concat!("Shifts self left by `rhs` bits.
3221
3222 Returns a tuple of the shifted version of self along with a boolean
3223 indicating whether the shift value was larger than or equal to the
3224 number of bits. If the shift value is too large, then value is
3225 masked (N-1) where N is the number of bits, and this value is then
3226 used to perform the shift.
3227
3228 # Examples
3229
3230 Basic usage
3231
3232 ```
3233 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3234 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3235 ```"),
3236             #[inline]
3237             #[stable(feature = "wrapping", since = "1.7.0")]
3238             pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3239                 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3240             }
3241         }
3242
3243         doc_comment! {
3244             concat!("Shifts self right by `rhs` bits.
3245
3246 Returns a tuple of the shifted version of self along with a boolean
3247 indicating whether the shift value was larger than or equal to the
3248 number of bits. If the shift value is too large, then value is
3249 masked (N-1) where N is the number of bits, and this value is then
3250 used to perform the shift.
3251
3252 # Examples
3253
3254 Basic usage
3255
3256 ```
3257 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3258 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3259 ```"),
3260             #[inline]
3261             #[stable(feature = "wrapping", since = "1.7.0")]
3262             pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3263                 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3264             }
3265         }
3266
3267         doc_comment! {
3268             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3269
3270 Returns a tuple of the exponentiation along with a bool indicating
3271 whether an overflow happened.
3272
3273 # Examples
3274
3275 Basic usage:
3276
3277 ```
3278 #![feature(no_panic_pow)]
3279 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3280 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3281 ```"),
3282             #[unstable(feature = "no_panic_pow", issue = "48320")]
3283             #[inline]
3284             pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3285                 let mut base = self;
3286                 let mut acc: Self = 1;
3287                 let mut overflown = false;
3288                 // Scratch space for storing results of overflowing_mul.
3289                 let mut r;
3290
3291                 while exp > 1 {
3292                     if (exp & 1) == 1 {
3293                         r = acc.overflowing_mul(base);
3294                         acc = r.0;
3295                         overflown |= r.1;
3296                     }
3297                     exp /= 2;
3298                     r = base.overflowing_mul(base);
3299                     base = r.0;
3300                     overflown |= r.1;
3301                 }
3302
3303                 // Deal with the final bit of the exponent separately, since
3304                 // squaring the base afterwards is not necessary and may cause a
3305                 // needless overflow.
3306                 if exp == 1 {
3307                     r = acc.overflowing_mul(base);
3308                     acc = r.0;
3309                     overflown |= r.1;
3310                 }
3311
3312                 (acc, overflown)
3313             }
3314         }
3315
3316         doc_comment! {
3317             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3318
3319 # Examples
3320
3321 Basic usage:
3322
3323 ```
3324 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3325 ```"),
3326         #[stable(feature = "rust1", since = "1.0.0")]
3327         #[inline]
3328         #[rustc_inherit_overflow_checks]
3329         pub fn pow(self, mut exp: u32) -> Self {
3330             let mut base = self;
3331             let mut acc = 1;
3332
3333             while exp > 1 {
3334                 if (exp & 1) == 1 {
3335                     acc = acc * base;
3336                 }
3337                 exp /= 2;
3338                 base = base * base;
3339             }
3340
3341             // Deal with the final bit of the exponent separately, since
3342             // squaring the base afterwards is not necessary and may cause a
3343             // needless overflow.
3344             if exp == 1 {
3345                 acc = acc * base;
3346             }
3347
3348             acc
3349         }
3350     }
3351
3352             doc_comment! {
3353             concat!("Performs Euclidean division.
3354
3355 For unsigned types, this is just the same as `self / rhs`.
3356
3357 # Examples
3358
3359 Basic usage:
3360
3361 ```
3362 #![feature(euclidean_division)]
3363 assert_eq!(7", stringify!($SelfT), ".div_euc(4), 1); // or any other integer type
3364 ```"),
3365             #[unstable(feature = "euclidean_division", issue = "49048")]
3366             #[inline]
3367             #[rustc_inherit_overflow_checks]
3368             pub fn div_euc(self, rhs: Self) -> Self {
3369                 self / rhs
3370             }
3371         }
3372
3373
3374         doc_comment! {
3375             concat!("Calculates the remainder `self mod rhs` by Euclidean division.
3376
3377 For unsigned types, this is just the same as `self % rhs`.
3378
3379 # Examples
3380
3381 Basic usage:
3382
3383 ```
3384 #![feature(euclidean_division)]
3385 assert_eq!(7", stringify!($SelfT), ".mod_euc(4), 3); // or any other integer type
3386 ```"),
3387             #[unstable(feature = "euclidean_division", issue = "49048")]
3388             #[inline]
3389             #[rustc_inherit_overflow_checks]
3390             pub fn mod_euc(self, rhs: Self) -> Self {
3391                 self % rhs
3392             }
3393         }
3394
3395         doc_comment! {
3396             concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3397
3398 # Examples
3399
3400 Basic usage:
3401
3402 ```
3403 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3404 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3405 ```"),
3406             #[stable(feature = "rust1", since = "1.0.0")]
3407             #[inline]
3408             pub fn is_power_of_two(self) -> bool {
3409                 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3410             }
3411         }
3412
3413         // Returns one less than next power of two.
3414         // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3415         //
3416         // 8u8.one_less_than_next_power_of_two() == 7
3417         // 6u8.one_less_than_next_power_of_two() == 7
3418         //
3419         // This method cannot overflow, as in the `next_power_of_two`
3420         // overflow cases it instead ends up returning the maximum value
3421         // of the type, and can return 0 for 0.
3422         #[inline]
3423         fn one_less_than_next_power_of_two(self) -> Self {
3424             if self <= 1 { return 0; }
3425
3426             // Because `p > 0`, it cannot consist entirely of leading zeros.
3427             // That means the shift is always in-bounds, and some processors
3428             // (such as intel pre-haswell) have more efficient ctlz
3429             // intrinsics when the argument is non-zero.
3430             let p = self - 1;
3431             let z = unsafe { intrinsics::ctlz_nonzero(p) };
3432             <$SelfT>::max_value() >> z
3433         }
3434
3435         doc_comment! {
3436             concat!("Returns the smallest power of two greater than or equal to `self`.
3437
3438 When return value overflows (i.e. `self > (1 << (N-1))` for type
3439 `uN`), it panics in debug mode and return value is wrapped to 0 in
3440 release mode (the only situation in which method can return 0).
3441
3442 # Examples
3443
3444 Basic usage:
3445
3446 ```
3447 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3448 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3449 ```"),
3450             #[stable(feature = "rust1", since = "1.0.0")]
3451             #[inline]
3452             pub fn next_power_of_two(self) -> Self {
3453                 // Call the trait to get overflow checks
3454                 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3455             }
3456         }
3457
3458         doc_comment! {
3459             concat!("Returns the smallest power of two greater than or equal to `n`. If
3460 the next power of two is greater than the type's maximum value,
3461 `None` is returned, otherwise the power of two is wrapped in `Some`.
3462
3463 # Examples
3464
3465 Basic usage:
3466
3467 ```
3468 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3469 ".checked_next_power_of_two(), Some(2));
3470 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3471 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3472 $EndFeature, "
3473 ```"),
3474             #[stable(feature = "rust1", since = "1.0.0")]
3475             pub fn checked_next_power_of_two(self) -> Option<Self> {
3476                 self.one_less_than_next_power_of_two().checked_add(1)
3477             }
3478         }
3479
3480         doc_comment! {
3481             concat!("Returns the smallest power of two greater than or equal to `n`. If
3482 the next power of two is greater than the type's maximum value,
3483 the return value is wrapped to `0`.
3484
3485 # Examples
3486
3487 Basic usage:
3488
3489 ```
3490 #![feature(wrapping_next_power_of_two)]
3491 ", $Feature, "
3492 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3493 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3494 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3495 $EndFeature, "
3496 ```"),
3497             #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3498                        reason = "needs decision on wrapping behaviour")]
3499             pub fn wrapping_next_power_of_two(self) -> Self {
3500                 self.one_less_than_next_power_of_two().wrapping_add(1)
3501             }
3502         }
3503
3504         /// Return the memory representation of this integer as a byte array.
3505         ///
3506         /// The target platform’s native endianness is used.
3507         /// Portable code likely wants to use this after [`to_be`] or [`to_le`].
3508         ///
3509         /// [`to_be`]: #method.to_be
3510         /// [`to_le`]: #method.to_le
3511         ///
3512         /// # Examples
3513         ///
3514         /// ```
3515         /// #![feature(int_to_from_bytes)]
3516         ///
3517         /// let bytes = 0x1234_5678_u32.to_be().to_bytes();
3518         /// assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);
3519         /// ```
3520         #[unstable(feature = "int_to_from_bytes", issue = "49792")]
3521         #[inline]
3522         pub fn to_bytes(self) -> [u8; mem::size_of::<Self>()] {
3523             unsafe { mem::transmute(self) }
3524         }
3525
3526         /// Create an integer value from its memory representation as a byte array.
3527         ///
3528         /// The target platform’s native endianness is used.
3529         /// Portable code likely wants to use [`to_be`] or [`to_le`] after this.
3530         ///
3531         /// [`to_be`]: #method.to_be
3532         /// [`to_le`]: #method.to_le
3533         ///
3534         /// # Examples
3535         ///
3536         /// ```
3537         /// #![feature(int_to_from_bytes)]
3538         ///
3539         /// let int = u32::from_be(u32::from_bytes([0x12, 0x34, 0x56, 0x78]));
3540         /// assert_eq!(int, 0x1234_5678_u32);
3541         /// ```
3542         #[unstable(feature = "int_to_from_bytes", issue = "49792")]
3543         #[inline]
3544         pub fn from_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3545             unsafe { mem::transmute(bytes) }
3546         }
3547     }
3548 }
3549
3550 #[lang = "u8"]
3551 impl u8 {
3552     uint_impl! { u8, u8, 8, 255, "", "" }
3553
3554
3555     /// Checks if the value is within the ASCII range.
3556     ///
3557     /// # Examples
3558     ///
3559     /// ```
3560     /// let ascii = 97u8;
3561     /// let non_ascii = 150u8;
3562     ///
3563     /// assert!(ascii.is_ascii());
3564     /// assert!(!non_ascii.is_ascii());
3565     /// ```
3566     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3567     #[inline]
3568     pub fn is_ascii(&self) -> bool {
3569         *self & 128 == 0
3570     }
3571
3572     /// Makes a copy of the value in its ASCII upper case equivalent.
3573     ///
3574     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3575     /// but non-ASCII letters are unchanged.
3576     ///
3577     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
3578     ///
3579     /// # Examples
3580     ///
3581     /// ```
3582     /// let lowercase_a = 97u8;
3583     ///
3584     /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
3585     /// ```
3586     ///
3587     /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
3588     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3589     #[inline]
3590     pub fn to_ascii_uppercase(&self) -> u8 {
3591         ASCII_UPPERCASE_MAP[*self as usize]
3592     }
3593
3594     /// Makes a copy of the value in its ASCII lower case equivalent.
3595     ///
3596     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3597     /// but non-ASCII letters are unchanged.
3598     ///
3599     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
3600     ///
3601     /// # Examples
3602     ///
3603     /// ```
3604     /// let uppercase_a = 65u8;
3605     ///
3606     /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
3607     /// ```
3608     ///
3609     /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
3610     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3611     #[inline]
3612     pub fn to_ascii_lowercase(&self) -> u8 {
3613         ASCII_LOWERCASE_MAP[*self as usize]
3614     }
3615
3616     /// Checks that two values are an ASCII case-insensitive match.
3617     ///
3618     /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3619     ///
3620     /// # Examples
3621     ///
3622     /// ```
3623     /// let lowercase_a = 97u8;
3624     /// let uppercase_a = 65u8;
3625     ///
3626     /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3627     /// ```
3628     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3629     #[inline]
3630     pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3631         self.to_ascii_lowercase() == other.to_ascii_lowercase()
3632     }
3633
3634     /// Converts this value to its ASCII upper case equivalent in-place.
3635     ///
3636     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3637     /// but non-ASCII letters are unchanged.
3638     ///
3639     /// To return a new uppercased value without modifying the existing one, use
3640     /// [`to_ascii_uppercase`].
3641     ///
3642     /// # Examples
3643     ///
3644     /// ```
3645     /// let mut byte = b'a';
3646     ///
3647     /// byte.make_ascii_uppercase();
3648     ///
3649     /// assert_eq!(b'A', byte);
3650     /// ```
3651     ///
3652     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3653     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3654     #[inline]
3655     pub fn make_ascii_uppercase(&mut self) {
3656         *self = self.to_ascii_uppercase();
3657     }
3658
3659     /// Converts this value to its ASCII lower case equivalent in-place.
3660     ///
3661     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3662     /// but non-ASCII letters are unchanged.
3663     ///
3664     /// To return a new lowercased value without modifying the existing one, use
3665     /// [`to_ascii_lowercase`].
3666     ///
3667     /// # Examples
3668     ///
3669     /// ```
3670     /// let mut byte = b'A';
3671     ///
3672     /// byte.make_ascii_lowercase();
3673     ///
3674     /// assert_eq!(b'a', byte);
3675     /// ```
3676     ///
3677     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3678     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3679     #[inline]
3680     pub fn make_ascii_lowercase(&mut self) {
3681         *self = self.to_ascii_lowercase();
3682     }
3683
3684     /// Checks if the value is an ASCII alphabetic character:
3685     ///
3686     /// - U+0041 'A' ... U+005A 'Z', or
3687     /// - U+0061 'a' ... U+007A 'z'.
3688     ///
3689     /// # Examples
3690     ///
3691     /// ```
3692     /// #![feature(ascii_ctype)]
3693     ///
3694     /// let uppercase_a = b'A';
3695     /// let uppercase_g = b'G';
3696     /// let a = b'a';
3697     /// let g = b'g';
3698     /// let zero = b'0';
3699     /// let percent = b'%';
3700     /// let space = b' ';
3701     /// let lf = b'\n';
3702     /// let esc = 0x1b_u8;
3703     ///
3704     /// assert!(uppercase_a.is_ascii_alphabetic());
3705     /// assert!(uppercase_g.is_ascii_alphabetic());
3706     /// assert!(a.is_ascii_alphabetic());
3707     /// assert!(g.is_ascii_alphabetic());
3708     /// assert!(!zero.is_ascii_alphabetic());
3709     /// assert!(!percent.is_ascii_alphabetic());
3710     /// assert!(!space.is_ascii_alphabetic());
3711     /// assert!(!lf.is_ascii_alphabetic());
3712     /// assert!(!esc.is_ascii_alphabetic());
3713     /// ```
3714     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3715     #[inline]
3716     pub fn is_ascii_alphabetic(&self) -> bool {
3717         if *self >= 0x80 { return false; }
3718         match ASCII_CHARACTER_CLASS[*self as usize] {
3719             L | Lx | U | Ux => true,
3720             _ => false
3721         }
3722     }
3723
3724     /// Checks if the value is an ASCII uppercase character:
3725     /// U+0041 'A' ... U+005A 'Z'.
3726     ///
3727     /// # Examples
3728     ///
3729     /// ```
3730     /// #![feature(ascii_ctype)]
3731     ///
3732     /// let uppercase_a = b'A';
3733     /// let uppercase_g = b'G';
3734     /// let a = b'a';
3735     /// let g = b'g';
3736     /// let zero = b'0';
3737     /// let percent = b'%';
3738     /// let space = b' ';
3739     /// let lf = b'\n';
3740     /// let esc = 0x1b_u8;
3741     ///
3742     /// assert!(uppercase_a.is_ascii_uppercase());
3743     /// assert!(uppercase_g.is_ascii_uppercase());
3744     /// assert!(!a.is_ascii_uppercase());
3745     /// assert!(!g.is_ascii_uppercase());
3746     /// assert!(!zero.is_ascii_uppercase());
3747     /// assert!(!percent.is_ascii_uppercase());
3748     /// assert!(!space.is_ascii_uppercase());
3749     /// assert!(!lf.is_ascii_uppercase());
3750     /// assert!(!esc.is_ascii_uppercase());
3751     /// ```
3752     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3753     #[inline]
3754     pub fn is_ascii_uppercase(&self) -> bool {
3755         if *self >= 0x80 { return false }
3756         match ASCII_CHARACTER_CLASS[*self as usize] {
3757             U | Ux => true,
3758             _ => false
3759         }
3760     }
3761
3762     /// Checks if the value is an ASCII lowercase character:
3763     /// U+0061 'a' ... U+007A 'z'.
3764     ///
3765     /// # Examples
3766     ///
3767     /// ```
3768     /// #![feature(ascii_ctype)]
3769     ///
3770     /// let uppercase_a = b'A';
3771     /// let uppercase_g = b'G';
3772     /// let a = b'a';
3773     /// let g = b'g';
3774     /// let zero = b'0';
3775     /// let percent = b'%';
3776     /// let space = b' ';
3777     /// let lf = b'\n';
3778     /// let esc = 0x1b_u8;
3779     ///
3780     /// assert!(!uppercase_a.is_ascii_lowercase());
3781     /// assert!(!uppercase_g.is_ascii_lowercase());
3782     /// assert!(a.is_ascii_lowercase());
3783     /// assert!(g.is_ascii_lowercase());
3784     /// assert!(!zero.is_ascii_lowercase());
3785     /// assert!(!percent.is_ascii_lowercase());
3786     /// assert!(!space.is_ascii_lowercase());
3787     /// assert!(!lf.is_ascii_lowercase());
3788     /// assert!(!esc.is_ascii_lowercase());
3789     /// ```
3790     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3791     #[inline]
3792     pub fn is_ascii_lowercase(&self) -> bool {
3793         if *self >= 0x80 { return false }
3794         match ASCII_CHARACTER_CLASS[*self as usize] {
3795             L | Lx => true,
3796             _ => false
3797         }
3798     }
3799
3800     /// Checks if the value is an ASCII alphanumeric character:
3801     ///
3802     /// - U+0041 'A' ... U+005A 'Z', or
3803     /// - U+0061 'a' ... U+007A 'z', or
3804     /// - U+0030 '0' ... U+0039 '9'.
3805     ///
3806     /// # Examples
3807     ///
3808     /// ```
3809     /// #![feature(ascii_ctype)]
3810     ///
3811     /// let uppercase_a = b'A';
3812     /// let uppercase_g = b'G';
3813     /// let a = b'a';
3814     /// let g = b'g';
3815     /// let zero = b'0';
3816     /// let percent = b'%';
3817     /// let space = b' ';
3818     /// let lf = b'\n';
3819     /// let esc = 0x1b_u8;
3820     ///
3821     /// assert!(uppercase_a.is_ascii_alphanumeric());
3822     /// assert!(uppercase_g.is_ascii_alphanumeric());
3823     /// assert!(a.is_ascii_alphanumeric());
3824     /// assert!(g.is_ascii_alphanumeric());
3825     /// assert!(zero.is_ascii_alphanumeric());
3826     /// assert!(!percent.is_ascii_alphanumeric());
3827     /// assert!(!space.is_ascii_alphanumeric());
3828     /// assert!(!lf.is_ascii_alphanumeric());
3829     /// assert!(!esc.is_ascii_alphanumeric());
3830     /// ```
3831     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3832     #[inline]
3833     pub fn is_ascii_alphanumeric(&self) -> bool {
3834         if *self >= 0x80 { return false }
3835         match ASCII_CHARACTER_CLASS[*self as usize] {
3836             D | L | Lx | U | Ux => true,
3837             _ => false
3838         }
3839     }
3840
3841     /// Checks if the value is an ASCII decimal digit:
3842     /// U+0030 '0' ... U+0039 '9'.
3843     ///
3844     /// # Examples
3845     ///
3846     /// ```
3847     /// #![feature(ascii_ctype)]
3848     ///
3849     /// let uppercase_a = b'A';
3850     /// let uppercase_g = b'G';
3851     /// let a = b'a';
3852     /// let g = b'g';
3853     /// let zero = b'0';
3854     /// let percent = b'%';
3855     /// let space = b' ';
3856     /// let lf = b'\n';
3857     /// let esc = 0x1b_u8;
3858     ///
3859     /// assert!(!uppercase_a.is_ascii_digit());
3860     /// assert!(!uppercase_g.is_ascii_digit());
3861     /// assert!(!a.is_ascii_digit());
3862     /// assert!(!g.is_ascii_digit());
3863     /// assert!(zero.is_ascii_digit());
3864     /// assert!(!percent.is_ascii_digit());
3865     /// assert!(!space.is_ascii_digit());
3866     /// assert!(!lf.is_ascii_digit());
3867     /// assert!(!esc.is_ascii_digit());
3868     /// ```
3869     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3870     #[inline]
3871     pub fn is_ascii_digit(&self) -> bool {
3872         if *self >= 0x80 { return false }
3873         match ASCII_CHARACTER_CLASS[*self as usize] {
3874             D => true,
3875             _ => false
3876         }
3877     }
3878
3879     /// Checks if the value is an ASCII hexadecimal digit:
3880     ///
3881     /// - U+0030 '0' ... U+0039 '9', or
3882     /// - U+0041 'A' ... U+0046 'F', or
3883     /// - U+0061 'a' ... U+0066 'f'.
3884     ///
3885     /// # Examples
3886     ///
3887     /// ```
3888     /// #![feature(ascii_ctype)]
3889     ///
3890     /// let uppercase_a = b'A';
3891     /// let uppercase_g = b'G';
3892     /// let a = b'a';
3893     /// let g = b'g';
3894     /// let zero = b'0';
3895     /// let percent = b'%';
3896     /// let space = b' ';
3897     /// let lf = b'\n';
3898     /// let esc = 0x1b_u8;
3899     ///
3900     /// assert!(uppercase_a.is_ascii_hexdigit());
3901     /// assert!(!uppercase_g.is_ascii_hexdigit());
3902     /// assert!(a.is_ascii_hexdigit());
3903     /// assert!(!g.is_ascii_hexdigit());
3904     /// assert!(zero.is_ascii_hexdigit());
3905     /// assert!(!percent.is_ascii_hexdigit());
3906     /// assert!(!space.is_ascii_hexdigit());
3907     /// assert!(!lf.is_ascii_hexdigit());
3908     /// assert!(!esc.is_ascii_hexdigit());
3909     /// ```
3910     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3911     #[inline]
3912     pub fn is_ascii_hexdigit(&self) -> bool {
3913         if *self >= 0x80 { return false }
3914         match ASCII_CHARACTER_CLASS[*self as usize] {
3915             D | Lx | Ux => true,
3916             _ => false
3917         }
3918     }
3919
3920     /// Checks if the value is an ASCII punctuation character:
3921     ///
3922     /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
3923     /// - U+003A ... U+0040 `: ; < = > ? @`, or
3924     /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
3925     /// - U+007B ... U+007E `{ | } ~`
3926     ///
3927     /// # Examples
3928     ///
3929     /// ```
3930     /// #![feature(ascii_ctype)]
3931     ///
3932     /// let uppercase_a = b'A';
3933     /// let uppercase_g = b'G';
3934     /// let a = b'a';
3935     /// let g = b'g';
3936     /// let zero = b'0';
3937     /// let percent = b'%';
3938     /// let space = b' ';
3939     /// let lf = b'\n';
3940     /// let esc = 0x1b_u8;
3941     ///
3942     /// assert!(!uppercase_a.is_ascii_punctuation());
3943     /// assert!(!uppercase_g.is_ascii_punctuation());
3944     /// assert!(!a.is_ascii_punctuation());
3945     /// assert!(!g.is_ascii_punctuation());
3946     /// assert!(!zero.is_ascii_punctuation());
3947     /// assert!(percent.is_ascii_punctuation());
3948     /// assert!(!space.is_ascii_punctuation());
3949     /// assert!(!lf.is_ascii_punctuation());
3950     /// assert!(!esc.is_ascii_punctuation());
3951     /// ```
3952     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3953     #[inline]
3954     pub fn is_ascii_punctuation(&self) -> bool {
3955         if *self >= 0x80 { return false }
3956         match ASCII_CHARACTER_CLASS[*self as usize] {
3957             P => true,
3958             _ => false
3959         }
3960     }
3961
3962     /// Checks if the value is an ASCII graphic character:
3963     /// U+0021 '!' ... U+007E '~'.
3964     ///
3965     /// # Examples
3966     ///
3967     /// ```
3968     /// #![feature(ascii_ctype)]
3969     ///
3970     /// let uppercase_a = b'A';
3971     /// let uppercase_g = b'G';
3972     /// let a = b'a';
3973     /// let g = b'g';
3974     /// let zero = b'0';
3975     /// let percent = b'%';
3976     /// let space = b' ';
3977     /// let lf = b'\n';
3978     /// let esc = 0x1b_u8;
3979     ///
3980     /// assert!(uppercase_a.is_ascii_graphic());
3981     /// assert!(uppercase_g.is_ascii_graphic());
3982     /// assert!(a.is_ascii_graphic());
3983     /// assert!(g.is_ascii_graphic());
3984     /// assert!(zero.is_ascii_graphic());
3985     /// assert!(percent.is_ascii_graphic());
3986     /// assert!(!space.is_ascii_graphic());
3987     /// assert!(!lf.is_ascii_graphic());
3988     /// assert!(!esc.is_ascii_graphic());
3989     /// ```
3990     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3991     #[inline]
3992     pub fn is_ascii_graphic(&self) -> bool {
3993         if *self >= 0x80 { return false; }
3994         match ASCII_CHARACTER_CLASS[*self as usize] {
3995             Ux | U | Lx | L | D | P => true,
3996             _ => false
3997         }
3998     }
3999
4000     /// Checks if the value is an ASCII whitespace character:
4001     /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4002     /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4003     ///
4004     /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4005     /// whitespace][infra-aw]. There are several other definitions in
4006     /// wide use. For instance, [the POSIX locale][pct] includes
4007     /// U+000B VERTICAL TAB as well as all the above characters,
4008     /// but—from the very same specification—[the default rule for
4009     /// "field splitting" in the Bourne shell][bfs] considers *only*
4010     /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4011     ///
4012     /// If you are writing a program that will process an existing
4013     /// file format, check what that format's definition of whitespace is
4014     /// before using this function.
4015     ///
4016     /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4017     /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4018     /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4019     ///
4020     /// # Examples
4021     ///
4022     /// ```
4023     /// #![feature(ascii_ctype)]
4024     ///
4025     /// let uppercase_a = b'A';
4026     /// let uppercase_g = b'G';
4027     /// let a = b'a';
4028     /// let g = b'g';
4029     /// let zero = b'0';
4030     /// let percent = b'%';
4031     /// let space = b' ';
4032     /// let lf = b'\n';
4033     /// let esc = 0x1b_u8;
4034     ///
4035     /// assert!(!uppercase_a.is_ascii_whitespace());
4036     /// assert!(!uppercase_g.is_ascii_whitespace());
4037     /// assert!(!a.is_ascii_whitespace());
4038     /// assert!(!g.is_ascii_whitespace());
4039     /// assert!(!zero.is_ascii_whitespace());
4040     /// assert!(!percent.is_ascii_whitespace());
4041     /// assert!(space.is_ascii_whitespace());
4042     /// assert!(lf.is_ascii_whitespace());
4043     /// assert!(!esc.is_ascii_whitespace());
4044     /// ```
4045     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4046     #[inline]
4047     pub fn is_ascii_whitespace(&self) -> bool {
4048         if *self >= 0x80 { return false; }
4049         match ASCII_CHARACTER_CLASS[*self as usize] {
4050             Cw | W => true,
4051             _ => false
4052         }
4053     }
4054
4055     /// Checks if the value is an ASCII control character:
4056     /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4057     /// Note that most ASCII whitespace characters are control
4058     /// characters, but SPACE is not.
4059     ///
4060     /// # Examples
4061     ///
4062     /// ```
4063     /// #![feature(ascii_ctype)]
4064     ///
4065     /// let uppercase_a = b'A';
4066     /// let uppercase_g = b'G';
4067     /// let a = b'a';
4068     /// let g = b'g';
4069     /// let zero = b'0';
4070     /// let percent = b'%';
4071     /// let space = b' ';
4072     /// let lf = b'\n';
4073     /// let esc = 0x1b_u8;
4074     ///
4075     /// assert!(!uppercase_a.is_ascii_control());
4076     /// assert!(!uppercase_g.is_ascii_control());
4077     /// assert!(!a.is_ascii_control());
4078     /// assert!(!g.is_ascii_control());
4079     /// assert!(!zero.is_ascii_control());
4080     /// assert!(!percent.is_ascii_control());
4081     /// assert!(!space.is_ascii_control());
4082     /// assert!(lf.is_ascii_control());
4083     /// assert!(esc.is_ascii_control());
4084     /// ```
4085     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4086     #[inline]
4087     pub fn is_ascii_control(&self) -> bool {
4088         if *self >= 0x80 { return false; }
4089         match ASCII_CHARACTER_CLASS[*self as usize] {
4090             C | Cw => true,
4091             _ => false
4092         }
4093     }
4094 }
4095
4096 #[lang = "u16"]
4097 impl u16 {
4098     uint_impl! { u16, u16, 16, 65535, "", "" }
4099 }
4100
4101 #[lang = "u32"]
4102 impl u32 {
4103     uint_impl! { u32, u32, 32, 4294967295, "", "" }
4104 }
4105
4106 #[lang = "u64"]
4107 impl u64 {
4108     uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
4109 }
4110
4111 #[lang = "u128"]
4112 impl u128 {
4113     uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "" }
4114 }
4115
4116 #[cfg(target_pointer_width = "16")]
4117 #[lang = "usize"]
4118 impl usize {
4119     uint_impl! { usize, u16, 16, 65536, "", "" }
4120 }
4121 #[cfg(target_pointer_width = "32")]
4122 #[lang = "usize"]
4123 impl usize {
4124     uint_impl! { usize, u32, 32, 4294967295, "", "" }
4125 }
4126
4127 #[cfg(target_pointer_width = "64")]
4128 #[lang = "usize"]
4129 impl usize {
4130     uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
4131 }
4132
4133 /// A classification of floating point numbers.
4134 ///
4135 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4136 /// their documentation for more.
4137 ///
4138 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4139 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4140 ///
4141 /// # Examples
4142 ///
4143 /// ```
4144 /// use std::num::FpCategory;
4145 /// use std::f32;
4146 ///
4147 /// let num = 12.4_f32;
4148 /// let inf = f32::INFINITY;
4149 /// let zero = 0f32;
4150 /// let sub: f32 = 1.1754942e-38;
4151 /// let nan = f32::NAN;
4152 ///
4153 /// assert_eq!(num.classify(), FpCategory::Normal);
4154 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4155 /// assert_eq!(zero.classify(), FpCategory::Zero);
4156 /// assert_eq!(nan.classify(), FpCategory::Nan);
4157 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4158 /// ```
4159 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4160 #[stable(feature = "rust1", since = "1.0.0")]
4161 pub enum FpCategory {
4162     /// "Not a Number", often obtained by dividing by zero.
4163     #[stable(feature = "rust1", since = "1.0.0")]
4164     Nan,
4165
4166     /// Positive or negative infinity.
4167     #[stable(feature = "rust1", since = "1.0.0")]
4168     Infinite,
4169
4170     /// Positive or negative zero.
4171     #[stable(feature = "rust1", since = "1.0.0")]
4172     Zero,
4173
4174     /// De-normalized floating point representation (less precise than `Normal`).
4175     #[stable(feature = "rust1", since = "1.0.0")]
4176     Subnormal,
4177
4178     /// A regular floating point number.
4179     #[stable(feature = "rust1", since = "1.0.0")]
4180     Normal,
4181 }
4182
4183 macro_rules! from_str_radix_int_impl {
4184     ($($t:ty)*) => {$(
4185         #[stable(feature = "rust1", since = "1.0.0")]
4186         impl FromStr for $t {
4187             type Err = ParseIntError;
4188             fn from_str(src: &str) -> Result<Self, ParseIntError> {
4189                 from_str_radix(src, 10)
4190             }
4191         }
4192     )*}
4193 }
4194 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4195
4196 /// The error type returned when a checked integral type conversion fails.
4197 #[unstable(feature = "try_from", issue = "33417")]
4198 #[derive(Debug, Copy, Clone)]
4199 pub struct TryFromIntError(());
4200
4201 impl TryFromIntError {
4202     #[unstable(feature = "int_error_internals",
4203                reason = "available through Error trait and this method should \
4204                          not be exposed publicly",
4205                issue = "0")]
4206     #[doc(hidden)]
4207     pub fn __description(&self) -> &str {
4208         "out of range integral type conversion attempted"
4209     }
4210 }
4211
4212 #[unstable(feature = "try_from", issue = "33417")]
4213 impl fmt::Display for TryFromIntError {
4214     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4215         self.__description().fmt(fmt)
4216     }
4217 }
4218
4219 #[unstable(feature = "try_from", issue = "33417")]
4220 impl From<!> for TryFromIntError {
4221     fn from(never: !) -> TryFromIntError {
4222         never
4223     }
4224 }
4225
4226 // no possible bounds violation
4227 macro_rules! try_from_unbounded {
4228     ($source:ty, $($target:ty),*) => {$(
4229         #[unstable(feature = "try_from", issue = "33417")]
4230         impl TryFrom<$source> for $target {
4231             type Error = TryFromIntError;
4232
4233             #[inline]
4234             fn try_from(value: $source) -> Result<Self, Self::Error> {
4235                 Ok(value as $target)
4236             }
4237         }
4238     )*}
4239 }
4240
4241 // only negative bounds
4242 macro_rules! try_from_lower_bounded {
4243     ($source:ty, $($target:ty),*) => {$(
4244         #[unstable(feature = "try_from", issue = "33417")]
4245         impl TryFrom<$source> for $target {
4246             type Error = TryFromIntError;
4247
4248             #[inline]
4249             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4250                 if u >= 0 {
4251                     Ok(u as $target)
4252                 } else {
4253                     Err(TryFromIntError(()))
4254                 }
4255             }
4256         }
4257     )*}
4258 }
4259
4260 // unsigned to signed (only positive bound)
4261 macro_rules! try_from_upper_bounded {
4262     ($source:ty, $($target:ty),*) => {$(
4263         #[unstable(feature = "try_from", issue = "33417")]
4264         impl TryFrom<$source> for $target {
4265             type Error = TryFromIntError;
4266
4267             #[inline]
4268             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4269                 if u > (<$target>::max_value() as $source) {
4270                     Err(TryFromIntError(()))
4271                 } else {
4272                     Ok(u as $target)
4273                 }
4274             }
4275         }
4276     )*}
4277 }
4278
4279 // all other cases
4280 macro_rules! try_from_both_bounded {
4281     ($source:ty, $($target:ty),*) => {$(
4282         #[unstable(feature = "try_from", issue = "33417")]
4283         impl TryFrom<$source> for $target {
4284             type Error = TryFromIntError;
4285
4286             #[inline]
4287             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4288                 let min = <$target>::min_value() as $source;
4289                 let max = <$target>::max_value() as $source;
4290                 if u < min || u > max {
4291                     Err(TryFromIntError(()))
4292                 } else {
4293                     Ok(u as $target)
4294                 }
4295             }
4296         }
4297     )*}
4298 }
4299
4300 macro_rules! rev {
4301     ($mac:ident, $source:ty, $($target:ty),*) => {$(
4302         $mac!($target, $source);
4303     )*}
4304 }
4305
4306 /// intra-sign conversions
4307 try_from_upper_bounded!(u16, u8);
4308 try_from_upper_bounded!(u32, u16, u8);
4309 try_from_upper_bounded!(u64, u32, u16, u8);
4310 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4311
4312 try_from_both_bounded!(i16, i8);
4313 try_from_both_bounded!(i32, i16, i8);
4314 try_from_both_bounded!(i64, i32, i16, i8);
4315 try_from_both_bounded!(i128, i64, i32, i16, i8);
4316
4317 // unsigned-to-signed
4318 try_from_upper_bounded!(u8, i8);
4319 try_from_upper_bounded!(u16, i8, i16);
4320 try_from_upper_bounded!(u32, i8, i16, i32);
4321 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4322 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4323
4324 // signed-to-unsigned
4325 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4326 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4327 try_from_lower_bounded!(i32, u32, u64, u128);
4328 try_from_lower_bounded!(i64, u64, u128);
4329 try_from_lower_bounded!(i128, u128);
4330 try_from_both_bounded!(i16, u8);
4331 try_from_both_bounded!(i32, u16, u8);
4332 try_from_both_bounded!(i64, u32, u16, u8);
4333 try_from_both_bounded!(i128, u64, u32, u16, u8);
4334
4335 // usize/isize
4336 try_from_upper_bounded!(usize, isize);
4337 try_from_lower_bounded!(isize, usize);
4338
4339 #[cfg(target_pointer_width = "16")]
4340 mod ptr_try_from_impls {
4341     use super::TryFromIntError;
4342     use convert::TryFrom;
4343
4344     try_from_upper_bounded!(usize, u8);
4345     try_from_unbounded!(usize, u16, u32, u64, u128);
4346     try_from_upper_bounded!(usize, i8, i16);
4347     try_from_unbounded!(usize, i32, i64, i128);
4348
4349     try_from_both_bounded!(isize, u8);
4350     try_from_lower_bounded!(isize, u16, u32, u64, u128);
4351     try_from_both_bounded!(isize, i8);
4352     try_from_unbounded!(isize, i16, i32, i64, i128);
4353
4354     rev!(try_from_upper_bounded, usize, u32, u64, u128);
4355     rev!(try_from_lower_bounded, usize, i8, i16);
4356     rev!(try_from_both_bounded, usize, i32, i64, i128);
4357
4358     rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4359     rev!(try_from_both_bounded, isize, i32, i64, i128);
4360 }
4361
4362 #[cfg(target_pointer_width = "32")]
4363 mod ptr_try_from_impls {
4364     use super::TryFromIntError;
4365     use convert::TryFrom;
4366
4367     try_from_upper_bounded!(usize, u8, u16);
4368     try_from_unbounded!(usize, u32, u64, u128);
4369     try_from_upper_bounded!(usize, i8, i16, i32);
4370     try_from_unbounded!(usize, i64, i128);
4371
4372     try_from_both_bounded!(isize, u8, u16);
4373     try_from_lower_bounded!(isize, u32, u64, u128);
4374     try_from_both_bounded!(isize, i8, i16);
4375     try_from_unbounded!(isize, i32, i64, i128);
4376
4377     rev!(try_from_unbounded, usize, u32);
4378     rev!(try_from_upper_bounded, usize, u64, u128);
4379     rev!(try_from_lower_bounded, usize, i8, i16, i32);
4380     rev!(try_from_both_bounded, usize, i64, i128);
4381
4382     rev!(try_from_unbounded, isize, u16);
4383     rev!(try_from_upper_bounded, isize, u32, u64, u128);
4384     rev!(try_from_unbounded, isize, i32);
4385     rev!(try_from_both_bounded, isize, i64, i128);
4386 }
4387
4388 #[cfg(target_pointer_width = "64")]
4389 mod ptr_try_from_impls {
4390     use super::TryFromIntError;
4391     use convert::TryFrom;
4392
4393     try_from_upper_bounded!(usize, u8, u16, u32);
4394     try_from_unbounded!(usize, u64, u128);
4395     try_from_upper_bounded!(usize, i8, i16, i32, i64);
4396     try_from_unbounded!(usize, i128);
4397
4398     try_from_both_bounded!(isize, u8, u16, u32);
4399     try_from_lower_bounded!(isize, u64, u128);
4400     try_from_both_bounded!(isize, i8, i16, i32);
4401     try_from_unbounded!(isize, i64, i128);
4402
4403     rev!(try_from_unbounded, usize, u32, u64);
4404     rev!(try_from_upper_bounded, usize, u128);
4405     rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4406     rev!(try_from_both_bounded, usize, i128);
4407
4408     rev!(try_from_unbounded, isize, u16, u32);
4409     rev!(try_from_upper_bounded, isize, u64, u128);
4410     rev!(try_from_unbounded, isize, i32, i64);
4411     rev!(try_from_both_bounded, isize, i128);
4412 }
4413
4414 #[doc(hidden)]
4415 trait FromStrRadixHelper: PartialOrd + Copy {
4416     fn min_value() -> Self;
4417     fn max_value() -> Self;
4418     fn from_u32(u: u32) -> Self;
4419     fn checked_mul(&self, other: u32) -> Option<Self>;
4420     fn checked_sub(&self, other: u32) -> Option<Self>;
4421     fn checked_add(&self, other: u32) -> Option<Self>;
4422 }
4423
4424 macro_rules! doit {
4425     ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4426         #[inline]
4427         fn min_value() -> Self { Self::min_value() }
4428         #[inline]
4429         fn max_value() -> Self { Self::max_value() }
4430         #[inline]
4431         fn from_u32(u: u32) -> Self { u as Self }
4432         #[inline]
4433         fn checked_mul(&self, other: u32) -> Option<Self> {
4434             Self::checked_mul(*self, other as Self)
4435         }
4436         #[inline]
4437         fn checked_sub(&self, other: u32) -> Option<Self> {
4438             Self::checked_sub(*self, other as Self)
4439         }
4440         #[inline]
4441         fn checked_add(&self, other: u32) -> Option<Self> {
4442             Self::checked_add(*self, other as Self)
4443         }
4444     })*)
4445 }
4446 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4447
4448 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4449     use self::IntErrorKind::*;
4450     use self::ParseIntError as PIE;
4451
4452     assert!(radix >= 2 && radix <= 36,
4453            "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4454            radix);
4455
4456     if src.is_empty() {
4457         return Err(PIE { kind: Empty });
4458     }
4459
4460     let is_signed_ty = T::from_u32(0) > T::min_value();
4461
4462     // all valid digits are ascii, so we will just iterate over the utf8 bytes
4463     // and cast them to chars. .to_digit() will safely return None for anything
4464     // other than a valid ascii digit for the given radix, including the first-byte
4465     // of multi-byte sequences
4466     let src = src.as_bytes();
4467
4468     let (is_positive, digits) = match src[0] {
4469         b'+' => (true, &src[1..]),
4470         b'-' if is_signed_ty => (false, &src[1..]),
4471         _ => (true, src),
4472     };
4473
4474     if digits.is_empty() {
4475         return Err(PIE { kind: Empty });
4476     }
4477
4478     let mut result = T::from_u32(0);
4479     if is_positive {
4480         // The number is positive
4481         for &c in digits {
4482             let x = match (c as char).to_digit(radix) {
4483                 Some(x) => x,
4484                 None => return Err(PIE { kind: InvalidDigit }),
4485             };
4486             result = match result.checked_mul(radix) {
4487                 Some(result) => result,
4488                 None => return Err(PIE { kind: Overflow }),
4489             };
4490             result = match result.checked_add(x) {
4491                 Some(result) => result,
4492                 None => return Err(PIE { kind: Overflow }),
4493             };
4494         }
4495     } else {
4496         // The number is negative
4497         for &c in digits {
4498             let x = match (c as char).to_digit(radix) {
4499                 Some(x) => x,
4500                 None => return Err(PIE { kind: InvalidDigit }),
4501             };
4502             result = match result.checked_mul(radix) {
4503                 Some(result) => result,
4504                 None => return Err(PIE { kind: Underflow }),
4505             };
4506             result = match result.checked_sub(x) {
4507                 Some(result) => result,
4508                 None => return Err(PIE { kind: Underflow }),
4509             };
4510         }
4511     }
4512     Ok(result)
4513 }
4514
4515 /// An error which can be returned when parsing an integer.
4516 ///
4517 /// This error is used as the error type for the `from_str_radix()` functions
4518 /// on the primitive integer types, such as [`i8::from_str_radix`].
4519 ///
4520 /// # Potential causes
4521 ///
4522 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
4523 /// in the string e.g. when it is obtained from the standard input.
4524 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
4525 ///
4526 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
4527 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
4528 #[derive(Debug, Clone, PartialEq, Eq)]
4529 #[stable(feature = "rust1", since = "1.0.0")]
4530 pub struct ParseIntError {
4531     kind: IntErrorKind,
4532 }
4533
4534 #[derive(Debug, Clone, PartialEq, Eq)]
4535 enum IntErrorKind {
4536     Empty,
4537     InvalidDigit,
4538     Overflow,
4539     Underflow,
4540 }
4541
4542 impl ParseIntError {
4543     #[unstable(feature = "int_error_internals",
4544                reason = "available through Error trait and this method should \
4545                          not be exposed publicly",
4546                issue = "0")]
4547     #[doc(hidden)]
4548     pub fn __description(&self) -> &str {
4549         match self.kind {
4550             IntErrorKind::Empty => "cannot parse integer from empty string",
4551             IntErrorKind::InvalidDigit => "invalid digit found in string",
4552             IntErrorKind::Overflow => "number too large to fit in target type",
4553             IntErrorKind::Underflow => "number too small to fit in target type",
4554         }
4555     }
4556 }
4557
4558 #[stable(feature = "rust1", since = "1.0.0")]
4559 impl fmt::Display for ParseIntError {
4560     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4561         self.__description().fmt(f)
4562     }
4563 }
4564
4565 #[stable(feature = "rust1", since = "1.0.0")]
4566 pub use num::dec2flt::ParseFloatError;
4567
4568 // Conversion traits for primitive integer and float types
4569 // Conversions T -> T are covered by a blanket impl and therefore excluded
4570 // Some conversions from and to usize/isize are not implemented due to portability concerns
4571 macro_rules! impl_from {
4572     ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
4573         #[$attr]
4574         #[doc = $doc]
4575         impl From<$Small> for $Large {
4576             #[inline]
4577             fn from(small: $Small) -> $Large {
4578                 small as $Large
4579             }
4580         }
4581     };
4582     ($Small: ty, $Large: ty, #[$attr:meta]) => {
4583         impl_from!($Small,
4584                    $Large,
4585                    #[$attr],
4586                    concat!("Converts `",
4587                            stringify!($Small),
4588                            "` to `",
4589                            stringify!($Large),
4590                            "` losslessly."));
4591     }
4592 }
4593
4594 macro_rules! impl_from_bool {
4595     ($target: ty, #[$attr:meta]) => {
4596         impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
4597             stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
4598 values.
4599
4600 # Examples
4601
4602 ```
4603 assert_eq!(", stringify!($target), "::from(true), 1);
4604 assert_eq!(", stringify!($target), "::from(false), 0);
4605 ```"));
4606     };
4607 }
4608
4609 // Bool -> Any
4610 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
4611 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
4612 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
4613 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
4614 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
4615 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
4616 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
4617 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
4618 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
4619 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
4620 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
4621 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
4622
4623 // Unsigned -> Unsigned
4624 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4625 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4626 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4627 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
4628 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4629 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4630 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4631 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
4632 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4633 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
4634 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
4635
4636 // Signed -> Signed
4637 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4638 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4639 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4640 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4641 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4642 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4643 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4644 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4645 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4646 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4647 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4648
4649 // Unsigned -> Signed
4650 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4651 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4652 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4653 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4654 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4655 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4656 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4657 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4658 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4659 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4660
4661 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
4662 // which imply that pointer-sized integers must be at least 16 bits:
4663 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
4664 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4665 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4666 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4667
4668 // RISC-V defines the possibility of a 128-bit address space (RV128).
4669
4670 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
4671 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
4672 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
4673
4674
4675 // Note: integers can only be represented with full precision in a float if
4676 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4677 // Lossy float conversions are not implemented at this time.
4678
4679 // Signed -> Float
4680 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4681 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4682 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4683 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4684 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4685
4686 // Unsigned -> Float
4687 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4688 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4689 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4690 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4691 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4692
4693 // Float -> Float
4694 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4695
4696 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4697     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4698     0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4699     0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4700     0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4701     b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4702     b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4703     b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4704     b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4705     b'@',
4706
4707           b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4708     b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4709     b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4710     b'x', b'y', b'z',
4711
4712                       b'[', b'\\', b']', b'^', b'_',
4713     b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4714     b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4715     b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4716     b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4717     0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4718     0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4719     0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4720     0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4721     0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4722     0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4723     0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4724     0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4725     0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4726     0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4727     0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4728     0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4729     0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4730     0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4731     0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4732     0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4733 ];
4734
4735 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4736     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4737     0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4738     0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4739     0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4740     b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4741     b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4742     b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4743     b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4744     b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4745     b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4746     b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4747     b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4748     b'`',
4749
4750           b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4751     b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4752     b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4753     b'X', b'Y', b'Z',
4754
4755                       b'{', b'|', b'}', b'~', 0x7f,
4756     0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4757     0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4758     0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4759     0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4760     0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4761     0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4762     0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4763     0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4764     0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4765     0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4766     0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4767     0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4768     0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4769     0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4770     0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4771     0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4772 ];
4773
4774 enum AsciiCharacterClass {
4775     C,  // control
4776     Cw, // control whitespace
4777     W,  // whitespace
4778     D,  // digit
4779     L,  // lowercase
4780     Lx, // lowercase hex digit
4781     U,  // uppercase
4782     Ux, // uppercase hex digit
4783     P,  // punctuation
4784 }
4785 use self::AsciiCharacterClass::*;
4786
4787 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4788 //  _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4789     C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4790     C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4791     W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4792     D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4793     P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4794     U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4795     P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4796     L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_
4797 ];