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