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