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