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