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