1 // ignore-tidy-filelength
3 //! Numeric traits and functions for the built-in numeric types.
5 #![stable(feature = "rust1", since = "1.0.0")]
7 use crate::convert::Infallible;
11 use crate::str::FromStr;
13 // Used because the `?` operator is not allowed in a const context.
14 macro_rules! try_opt {
23 macro_rules! impl_nonzero_fmt {
24 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
27 impl fmt::$Trait for $Ty {
29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 macro_rules! doc_comment {
38 ($x:expr, $($tt:tt)*) => {
44 macro_rules! nonzero_integers {
45 ( $( #[$stability: meta] $Ty: ident($Int: ty); )+ ) => {
48 concat!("An integer that is known not to equal zero.
50 This enables some memory layout optimization.
51 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
54 use std::mem::size_of;
55 assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
59 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
61 #[rustc_layout_scalar_valid_range_start(1)]
62 #[rustc_nonnull_optimization_guaranteed]
67 /// Creates a non-zero without checking the value.
71 /// The value must not be zero.
73 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
75 pub const unsafe fn new_unchecked(n: $Int) -> Self {
79 /// Creates a non-zero if the given value is not zero.
81 #[rustc_const_unstable(feature = "const_nonzero_int_methods", issue = "53718")]
83 pub const fn new(n: $Int) -> Option<Self> {
85 // SAFETY: we just checked that there's no `0`
86 Some(unsafe { Self(n) })
92 /// Returns the value as a primitive type.
95 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
96 pub const fn get(self) -> $Int {
102 #[stable(feature = "from_nonzero", since = "1.31.0")]
103 impl From<$Ty> for $Int {
106 "Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`"),
107 fn from(nonzero: $Ty) -> Self {
114 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
121 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
122 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
123 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
124 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
125 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
126 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
127 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
128 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
129 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
130 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
131 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
132 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
135 macro_rules! from_str_radix_nzint_impl {
137 #[stable(feature = "nonzero_parse", since = "1.35.0")]
138 impl FromStr for $t {
139 type Err = ParseIntError;
140 fn from_str(src: &str) -> Result<Self, Self::Err> {
141 Self::new(from_str_radix(src, 10)?)
142 .ok_or(ParseIntError {
143 kind: IntErrorKind::Zero
150 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
151 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
153 /// Provides intentionally-wrapped arithmetic on `T`.
155 /// Operations like `+` on `u32` values are intended to never overflow,
156 /// and in some debug configurations overflow is detected and results
157 /// in a panic. While most arithmetic falls into this category, some
158 /// code explicitly expects and relies upon modular arithmetic (e.g.,
161 /// Wrapping arithmetic can be achieved either through methods like
162 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
163 /// all standard arithmetic operations on the underlying value are
164 /// intended to have wrapping semantics.
166 /// The underlying value can be retrieved through the `.0` index of the
167 /// `Wrapping` tuple.
172 /// use std::num::Wrapping;
174 /// let zero = Wrapping(0u32);
175 /// let one = Wrapping(1u32);
177 /// assert_eq!(std::u32::MAX, (zero - one).0);
179 #[stable(feature = "rust1", since = "1.0.0")]
180 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
182 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
184 #[stable(feature = "rust1", since = "1.0.0")]
185 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 #[stable(feature = "wrapping_display", since = "1.10.0")]
192 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
199 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
206 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
213 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
220 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226 // All these modules are technically private and only exposed for coretests:
234 macro_rules! usize_isize_to_xe_bytes_doc {
238 **Note**: This function returns an array of length 2, 4 or 8 bytes
239 depending on the target pointer size.
245 macro_rules! usize_isize_from_xe_bytes_doc {
249 **Note**: This function takes an array of length 2, 4 or 8 bytes
250 depending on the target pointer size.
256 macro_rules! int_impl {
257 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
258 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
259 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
260 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
262 concat!("The smallest value that can be represented by this integer type.
269 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, ", stringify!($Min), ");",
272 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
273 pub const MIN: Self = !0 ^ ((!0 as $UnsignedT) >> 1) as Self;
277 concat!("The largest value that can be represented by this integer type.
284 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");",
287 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
288 pub const MAX: Self = !Self::MIN;
292 concat!("Converts a string slice in a given base to an integer.
294 The string is expected to be an optional `+` or `-` sign followed by digits.
295 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
296 depending on `radix`:
304 This function panics if `radix` is not in the range from 2 to 36.
311 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
316 from_str_radix(src, radix)
321 concat!("Returns the number of ones in the binary representation of `self`.
328 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
330 assert_eq!(n.count_ones(), 1);",
334 #[stable(feature = "rust1", since = "1.0.0")]
335 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
337 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
341 concat!("Returns the number of zeros in the binary representation of `self`.
348 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 1);", $EndFeature, "
350 #[stable(feature = "rust1", since = "1.0.0")]
351 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
353 pub const fn count_zeros(self) -> u32 {
359 concat!("Returns the number of leading zeros in the binary representation of `self`.
366 ", $Feature, "let n = -1", stringify!($SelfT), ";
368 assert_eq!(n.leading_zeros(), 0);",
371 #[stable(feature = "rust1", since = "1.0.0")]
372 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
374 pub const fn leading_zeros(self) -> u32 {
375 (self as $UnsignedT).leading_zeros()
380 concat!("Returns the number of trailing zeros in the binary representation of `self`.
387 ", $Feature, "let n = -4", stringify!($SelfT), ";
389 assert_eq!(n.trailing_zeros(), 2);",
392 #[stable(feature = "rust1", since = "1.0.0")]
393 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
395 pub const fn trailing_zeros(self) -> u32 {
396 (self as $UnsignedT).trailing_zeros()
401 concat!("Returns the number of leading ones in the binary representation of `self`.
408 ", $Feature, "#![feature(leading_trailing_ones)]
409 let n = -1", stringify!($SelfT), ";
411 assert_eq!(n.leading_ones(), ", stringify!($BITS), ");",
414 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
416 pub const fn leading_ones(self) -> u32 {
417 (self as $UnsignedT).leading_ones()
422 concat!("Returns the number of trailing ones in the binary representation of `self`.
429 ", $Feature, "#![feature(leading_trailing_ones)]
430 let n = 3", stringify!($SelfT), ";
432 assert_eq!(n.trailing_ones(), 2);",
435 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
437 pub const fn trailing_ones(self) -> u32 {
438 (self as $UnsignedT).trailing_ones()
443 concat!("Shifts the bits to the left by a specified amount, `n`,
444 wrapping the truncated bits to the end of the resulting integer.
446 Please note this isn't the same operation as the `<<` shifting operator!
453 let n = ", $rot_op, stringify!($SelfT), ";
454 let m = ", $rot_result, ";
456 assert_eq!(n.rotate_left(", $rot, "), m);
458 #[stable(feature = "rust1", since = "1.0.0")]
459 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
460 #[must_use = "this returns the result of the operation, \
461 without modifying the original"]
463 pub const fn rotate_left(self, n: u32) -> Self {
464 (self as $UnsignedT).rotate_left(n) as Self
469 concat!("Shifts the bits to the right by a specified amount, `n`,
470 wrapping the truncated bits to the beginning of the resulting
473 Please note this isn't the same operation as the `>>` shifting operator!
480 let n = ", $rot_result, stringify!($SelfT), ";
481 let m = ", $rot_op, ";
483 assert_eq!(n.rotate_right(", $rot, "), m);
485 #[stable(feature = "rust1", since = "1.0.0")]
486 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
487 #[must_use = "this returns the result of the operation, \
488 without modifying the original"]
490 pub const fn rotate_right(self, n: u32) -> Self {
491 (self as $UnsignedT).rotate_right(n) as Self
496 concat!("Reverses the byte order of the integer.
503 let n = ", $swap_op, stringify!($SelfT), ";
505 let m = n.swap_bytes();
507 assert_eq!(m, ", $swapped, ");
509 #[stable(feature = "rust1", since = "1.0.0")]
510 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
512 pub const fn swap_bytes(self) -> Self {
513 (self as $UnsignedT).swap_bytes() as Self
518 concat!("Reverses the bit pattern of the integer.
525 let n = ", $swap_op, stringify!($SelfT), ";
526 let m = n.reverse_bits();
528 assert_eq!(m, ", $reversed, ");
530 #[stable(feature = "reverse_bits", since = "1.37.0")]
531 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
534 pub const fn reverse_bits(self) -> Self {
535 (self as $UnsignedT).reverse_bits() as Self
540 concat!("Converts an integer from big endian to the target's endianness.
542 On big endian this is a no-op. On little endian the bytes are swapped.
549 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
551 if cfg!(target_endian = \"big\") {
552 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
554 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
558 #[stable(feature = "rust1", since = "1.0.0")]
559 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
561 pub const fn from_be(x: Self) -> Self {
562 #[cfg(target_endian = "big")]
566 #[cfg(not(target_endian = "big"))]
574 concat!("Converts an integer from little endian to the target's endianness.
576 On little endian this is a no-op. On big endian the bytes are swapped.
583 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
585 if cfg!(target_endian = \"little\") {
586 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
588 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
592 #[stable(feature = "rust1", since = "1.0.0")]
593 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
595 pub const fn from_le(x: Self) -> Self {
596 #[cfg(target_endian = "little")]
600 #[cfg(not(target_endian = "little"))]
608 concat!("Converts `self` to big endian from the target's endianness.
610 On big endian this is a no-op. On little endian the bytes are swapped.
617 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
619 if cfg!(target_endian = \"big\") {
620 assert_eq!(n.to_be(), n)
622 assert_eq!(n.to_be(), n.swap_bytes())
626 #[stable(feature = "rust1", since = "1.0.0")]
627 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
629 pub const fn to_be(self) -> Self { // or not to be?
630 #[cfg(target_endian = "big")]
634 #[cfg(not(target_endian = "big"))]
642 concat!("Converts `self` to little endian from the target's endianness.
644 On little endian this is a no-op. On big endian the bytes are swapped.
651 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
653 if cfg!(target_endian = \"little\") {
654 assert_eq!(n.to_le(), n)
656 assert_eq!(n.to_le(), n.swap_bytes())
660 #[stable(feature = "rust1", since = "1.0.0")]
661 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
663 pub const fn to_le(self) -> Self {
664 #[cfg(target_endian = "little")]
668 #[cfg(not(target_endian = "little"))]
676 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
677 if overflow occurred.
684 ", $Feature, "assert_eq!((", stringify!($SelfT),
685 "::MAX - 2).checked_add(1), Some(", stringify!($SelfT), "::MAX - 1));
686 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);",
689 #[stable(feature = "rust1", since = "1.0.0")]
690 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
691 #[must_use = "this returns the result of the operation, \
692 without modifying the original"]
694 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
695 let (a, b) = self.overflowing_add(rhs);
696 if b {None} else {Some(a)}
701 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
709 ", $Feature, "assert_eq!((", stringify!($SelfT),
710 "::MIN + 2).checked_sub(1), Some(", stringify!($SelfT), "::MIN + 1));
711 assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(3), None);",
714 #[stable(feature = "rust1", since = "1.0.0")]
715 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
716 #[must_use = "this returns the result of the operation, \
717 without modifying the original"]
719 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
720 let (a, b) = self.overflowing_sub(rhs);
721 if b {None} else {Some(a)}
726 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
734 ", $Feature, "assert_eq!(", stringify!($SelfT),
735 "::MAX.checked_mul(1), Some(", stringify!($SelfT), "::MAX));
736 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);",
739 #[stable(feature = "rust1", since = "1.0.0")]
740 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
741 #[must_use = "this returns the result of the operation, \
742 without modifying the original"]
744 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
745 let (a, b) = self.overflowing_mul(rhs);
746 if b {None} else {Some(a)}
751 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
752 or the division results in overflow.
759 ", $Feature, "assert_eq!((", stringify!($SelfT),
760 "::MIN + 1).checked_div(-1), Some(", stringify!($Max), "));
761 assert_eq!(", stringify!($SelfT), "::MIN.checked_div(-1), None);
762 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
765 #[stable(feature = "rust1", since = "1.0.0")]
766 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
767 #[must_use = "this returns the result of the operation, \
768 without modifying the original"]
770 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
771 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
774 // SAFETY: div by zero and by INT_MIN have been checked above
775 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
781 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
782 returning `None` if `rhs == 0` or the division results in overflow.
789 assert_eq!((", stringify!($SelfT),
790 "::MIN + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
791 assert_eq!(", stringify!($SelfT), "::MIN.checked_div_euclid(-1), None);
792 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
794 #[stable(feature = "euclidean_division", since = "1.38.0")]
795 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
796 #[must_use = "this returns the result of the operation, \
797 without modifying the original"]
799 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
800 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
803 Some(self.div_euclid(rhs))
809 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
810 `rhs == 0` or the division results in overflow.
818 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
819 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
820 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
823 #[stable(feature = "wrapping", since = "1.7.0")]
824 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
825 #[must_use = "this returns the result of the operation, \
826 without modifying the original"]
828 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
829 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
832 // SAFETY: div by zero and by INT_MIN have been checked above
833 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
839 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
840 if `rhs == 0` or the division results in overflow.
847 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
848 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
849 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
851 #[stable(feature = "euclidean_division", since = "1.38.0")]
852 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
853 #[must_use = "this returns the result of the operation, \
854 without modifying the original"]
856 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
857 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
860 Some(self.rem_euclid(rhs))
866 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
874 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
875 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
878 #[stable(feature = "wrapping", since = "1.7.0")]
879 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
881 pub const fn checked_neg(self) -> Option<Self> {
882 let (a, b) = self.overflowing_neg();
883 if b {None} else {Some(a)}
888 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
889 than or equal to the number of bits in `self`.
896 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
897 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
900 #[stable(feature = "wrapping", since = "1.7.0")]
901 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
902 #[must_use = "this returns the result of the operation, \
903 without modifying the original"]
905 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
906 let (a, b) = self.overflowing_shl(rhs);
907 if b {None} else {Some(a)}
912 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
913 larger than or equal to the number of bits in `self`.
920 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
921 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
924 #[stable(feature = "wrapping", since = "1.7.0")]
925 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
926 #[must_use = "this returns the result of the operation, \
927 without modifying the original"]
929 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
930 let (a, b) = self.overflowing_shr(rhs);
931 if b {None} else {Some(a)}
936 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
945 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
946 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
949 #[stable(feature = "no_panic_abs", since = "1.13.0")]
950 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
952 pub const fn checked_abs(self) -> Option<Self> {
953 if self.is_negative() {
962 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
970 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
971 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);",
975 #[stable(feature = "no_panic_pow", since = "1.34.0")]
976 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
977 #[must_use = "this returns the result of the operation, \
978 without modifying the original"]
980 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
982 let mut acc: Self = 1;
986 acc = try_opt!(acc.checked_mul(base));
989 base = try_opt!(base.checked_mul(base));
992 // Deal with the final bit of the exponent separately, since
993 // squaring the base afterwards is not necessary and may cause a
994 // needless overflow.
996 acc = try_opt!(acc.checked_mul(base));
1004 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
1005 bounds instead of overflowing.
1012 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
1013 assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT),
1015 assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT),
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1022 #[must_use = "this returns the result of the operation, \
1023 without modifying the original"]
1025 pub const fn saturating_add(self, rhs: Self) -> Self {
1026 intrinsics::saturating_add(self, rhs)
1031 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
1032 numeric bounds instead of overflowing.
1039 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
1040 assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT),
1042 assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT),
1046 #[stable(feature = "rust1", since = "1.0.0")]
1047 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1048 #[must_use = "this returns the result of the operation, \
1049 without modifying the original"]
1051 pub const fn saturating_sub(self, rhs: Self) -> Self {
1052 intrinsics::saturating_sub(self, rhs)
1057 concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
1058 instead of overflowing.
1065 ", $Feature, "#![feature(saturating_neg)]
1066 assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
1067 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
1068 assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT),
1070 assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT),
1075 #[unstable(feature = "saturating_neg", issue = "59983")]
1076 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1078 pub const fn saturating_neg(self) -> Self {
1079 intrinsics::saturating_sub(0, self)
1084 concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1085 MIN` instead of overflowing.
1092 ", $Feature, "#![feature(saturating_neg)]
1093 assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
1094 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
1095 assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT),
1097 assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT),
1102 #[unstable(feature = "saturating_neg", issue = "59983")]
1103 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1105 pub const fn saturating_abs(self) -> Self {
1106 if self.is_negative() {
1107 self.saturating_neg()
1115 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1116 numeric bounds instead of overflowing.
1124 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1125 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1126 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1129 #[stable(feature = "wrapping", since = "1.7.0")]
1130 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1131 #[must_use = "this returns the result of the operation, \
1132 without modifying the original"]
1134 pub const fn saturating_mul(self, rhs: Self) -> Self {
1135 match self.checked_mul(rhs) {
1137 None => if (self < 0) == (rhs < 0) {
1147 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1148 saturating at the numeric bounds instead of overflowing.
1156 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1157 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1158 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1161 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1162 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1163 #[must_use = "this returns the result of the operation, \
1164 without modifying the original"]
1166 pub const fn saturating_pow(self, exp: u32) -> Self {
1167 match self.checked_pow(exp) {
1169 None if self < 0 && exp % 2 == 1 => Self::min_value(),
1170 None => Self::max_value(),
1176 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1177 boundary of the type.
1184 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1185 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT),
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1191 #[must_use = "this returns the result of the operation, \
1192 without modifying the original"]
1194 pub const fn wrapping_add(self, rhs: Self) -> Self {
1195 intrinsics::wrapping_add(self, rhs)
1200 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1201 boundary of the type.
1208 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1209 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ",
1210 stringify!($SelfT), "::MAX);",
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1215 #[must_use = "this returns the result of the operation, \
1216 without modifying the original"]
1218 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1219 intrinsics::wrapping_sub(self, rhs)
1224 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1225 the boundary of the type.
1232 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1233 assert_eq!(11i8.wrapping_mul(12), -124);",
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1238 #[must_use = "this returns the result of the operation, \
1239 without modifying the original"]
1241 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1242 intrinsics::wrapping_mul(self, rhs)
1247 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1248 boundary of the type.
1250 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1251 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1252 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1256 This function will panic if `rhs` is 0.
1263 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1264 assert_eq!((-128i8).wrapping_div(-1), -128);",
1267 #[stable(feature = "num_wrapping", since = "1.2.0")]
1268 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1269 #[must_use = "this returns the result of the operation, \
1270 without modifying the original"]
1272 pub const fn wrapping_div(self, rhs: Self) -> Self {
1273 self.overflowing_div(rhs).0
1278 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1279 wrapping around at the boundary of the type.
1281 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1282 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1283 type. In this case, this method returns `MIN` itself.
1287 This function will panic if `rhs` is 0.
1294 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1295 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1297 #[stable(feature = "euclidean_division", since = "1.38.0")]
1298 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1299 #[must_use = "this returns the result of the operation, \
1300 without modifying the original"]
1302 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1303 self.overflowing_div_euclid(rhs).0
1308 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1309 boundary of the type.
1311 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1312 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1313 this function returns `0`.
1317 This function will panic if `rhs` is 0.
1324 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1325 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1328 #[stable(feature = "num_wrapping", since = "1.2.0")]
1329 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1330 #[must_use = "this returns the result of the operation, \
1331 without modifying the original"]
1333 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1334 self.overflowing_rem(rhs).0
1339 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1340 at the boundary of the type.
1342 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1343 for the type). In this case, this method returns 0.
1347 This function will panic if `rhs` is 0.
1354 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1355 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1357 #[stable(feature = "euclidean_division", since = "1.38.0")]
1358 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1359 #[must_use = "this returns the result of the operation, \
1360 without modifying the original"]
1362 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1363 self.overflowing_rem_euclid(rhs).0
1368 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1371 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1372 is the negative minimal value for the type); this is a positive value that is too large to represent
1373 in the type. In such a case, this function returns `MIN` itself.
1380 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1381 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT),
1385 #[stable(feature = "num_wrapping", since = "1.2.0")]
1386 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1388 pub const fn wrapping_neg(self) -> Self {
1389 self.overflowing_neg().0
1394 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1395 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1397 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1398 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1399 The primitive integer types all implement a `rotate_left` function, which may be what you want
1407 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1408 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1411 #[stable(feature = "num_wrapping", since = "1.2.0")]
1412 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1413 #[must_use = "this returns the result of the operation, \
1414 without modifying the original"]
1416 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1417 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1420 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1426 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1427 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1429 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1430 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1431 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1439 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1440 assert_eq!((-128i16).wrapping_shr(64), -128);",
1443 #[stable(feature = "num_wrapping", since = "1.2.0")]
1444 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1445 #[must_use = "this returns the result of the operation, \
1446 without modifying the original"]
1448 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1449 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1452 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1458 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1459 the boundary of the type.
1461 The only case where such wrapping can occur is when one takes the absolute value of the negative
1462 minimal value for the type this is a positive value that is too large to represent in the type. In
1463 such a case, this function returns `MIN` itself.
1470 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1471 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1472 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT),
1474 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1477 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1478 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1479 #[allow(unused_attributes)]
1480 #[allow_internal_unstable(const_if_match)]
1482 pub const fn wrapping_abs(self) -> Self {
1483 if self.is_negative() {
1492 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1493 wrapping around at the boundary of the type.
1500 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1501 assert_eq!(3i8.wrapping_pow(5), -13);
1502 assert_eq!(3i8.wrapping_pow(6), -39);",
1505 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1506 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1507 #[must_use = "this returns the result of the operation, \
1508 without modifying the original"]
1510 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1511 let mut base = self;
1512 let mut acc: Self = 1;
1516 acc = acc.wrapping_mul(base);
1519 base = base.wrapping_mul(base);
1522 // Deal with the final bit of the exponent separately, since
1523 // squaring the base afterwards is not necessary and may cause a
1524 // needless overflow.
1526 acc = acc.wrapping_mul(base);
1534 concat!("Calculates `self` + `rhs`
1536 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1537 occur. If an overflow would have occurred then the wrapped value is returned.
1545 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1546 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1547 "::MIN, true));", $EndFeature, "
1549 #[stable(feature = "wrapping", since = "1.7.0")]
1550 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1551 #[must_use = "this returns the result of the operation, \
1552 without modifying the original"]
1554 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1555 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1561 concat!("Calculates `self` - `rhs`
1563 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1564 would occur. If an overflow would have occurred then the wrapped value is returned.
1572 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1573 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1574 "::MAX, true));", $EndFeature, "
1576 #[stable(feature = "wrapping", since = "1.7.0")]
1577 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1578 #[must_use = "this returns the result of the operation, \
1579 without modifying the original"]
1581 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1582 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1588 concat!("Calculates the multiplication of `self` and `rhs`.
1590 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1591 would occur. If an overflow would have occurred then the wrapped value is returned.
1598 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1599 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1602 #[stable(feature = "wrapping", since = "1.7.0")]
1603 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1604 #[must_use = "this returns the result of the operation, \
1605 without modifying the original"]
1607 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1608 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1614 concat!("Calculates the divisor when `self` is divided by `rhs`.
1616 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1617 occur. If an overflow would occur then self is returned.
1621 This function will panic if `rhs` is 0.
1629 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1630 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1635 #[stable(feature = "wrapping", since = "1.7.0")]
1636 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1637 #[must_use = "this returns the result of the operation, \
1638 without modifying the original"]
1639 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1640 if self == Self::min_value() && rhs == -1 {
1649 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1651 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1652 occur. If an overflow would occur then `self` is returned.
1656 This function will panic if `rhs` is 0.
1663 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1664 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1668 #[stable(feature = "euclidean_division", since = "1.38.0")]
1669 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1670 #[must_use = "this returns the result of the operation, \
1671 without modifying the original"]
1672 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1673 if self == Self::min_value() && rhs == -1 {
1676 (self.div_euclid(rhs), false)
1682 concat!("Calculates the remainder when `self` is divided by `rhs`.
1684 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1685 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1689 This function will panic if `rhs` is 0.
1697 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1698 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1702 #[stable(feature = "wrapping", since = "1.7.0")]
1703 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1704 #[must_use = "this returns the result of the operation, \
1705 without modifying the original"]
1706 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1707 if self == Self::min_value() && rhs == -1 {
1717 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1719 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1720 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1724 This function will panic if `rhs` is 0.
1731 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1732 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1734 #[stable(feature = "euclidean_division", since = "1.38.0")]
1735 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1736 #[must_use = "this returns the result of the operation, \
1737 without modifying the original"]
1739 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1740 if self == Self::min_value() && rhs == -1 {
1743 (self.rem_euclid(rhs), false)
1750 concat!("Negates self, overflowing if this is equal to the minimum value.
1752 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1753 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1754 minimum value will be returned again and `true` will be returned for an overflow happening.
1761 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1762 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1763 "::MIN, true));", $EndFeature, "
1766 #[stable(feature = "wrapping", since = "1.7.0")]
1767 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1768 #[allow(unused_attributes)]
1769 #[allow_internal_unstable(const_if_match)]
1770 pub const fn overflowing_neg(self) -> (Self, bool) {
1771 if self == Self::min_value() {
1772 (Self::min_value(), true)
1780 concat!("Shifts self left by `rhs` bits.
1782 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1783 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1784 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1791 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1792 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1795 #[stable(feature = "wrapping", since = "1.7.0")]
1796 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1797 #[must_use = "this returns the result of the operation, \
1798 without modifying the original"]
1800 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1801 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1806 concat!("Shifts self right by `rhs` bits.
1808 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1809 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1810 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1817 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1818 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1821 #[stable(feature = "wrapping", since = "1.7.0")]
1822 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1823 #[must_use = "this returns the result of the operation, \
1824 without modifying the original"]
1826 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1827 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1832 concat!("Computes the absolute value of `self`.
1834 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1835 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1836 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1837 for an overflow happening.
1844 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1845 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1846 assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT),
1850 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1851 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1853 pub const fn overflowing_abs(self) -> (Self, bool) {
1854 (self.wrapping_abs(), self == Self::min_value())
1859 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1861 Returns a tuple of the exponentiation along with a bool indicating
1862 whether an overflow happened.
1869 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1870 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1873 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1874 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1875 #[must_use = "this returns the result of the operation, \
1876 without modifying the original"]
1878 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1879 let mut base = self;
1880 let mut acc: Self = 1;
1881 let mut overflown = false;
1882 // Scratch space for storing results of overflowing_mul.
1887 r = acc.overflowing_mul(base);
1892 r = base.overflowing_mul(base);
1897 // Deal with the final bit of the exponent separately, since
1898 // squaring the base afterwards is not necessary and may cause a
1899 // needless overflow.
1901 r = acc.overflowing_mul(base);
1911 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1918 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1920 assert_eq!(x.pow(5), 32);",
1923 #[stable(feature = "rust1", since = "1.0.0")]
1924 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1925 #[must_use = "this returns the result of the operation, \
1926 without modifying the original"]
1928 #[rustc_inherit_overflow_checks]
1929 pub const fn pow(self, mut exp: u32) -> Self {
1930 let mut base = self;
1941 // Deal with the final bit of the exponent separately, since
1942 // squaring the base afterwards is not necessary and may cause a
1943 // needless overflow.
1953 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1955 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
1956 with `0 <= self.rem_euclid(rhs) < rhs`.
1958 In other words, the result is `self / rhs` rounded to the integer `n`
1959 such that `self >= n * rhs`.
1960 If `self > 0`, this is equal to round towards zero (the default in Rust);
1961 if `self < 0`, this is equal to round towards +/- infinity.
1965 This function will panic if `rhs` is 0 or the division results in overflow.
1972 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1975 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
1976 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
1977 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
1978 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
1980 #[stable(feature = "euclidean_division", since = "1.38.0")]
1981 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1982 #[must_use = "this returns the result of the operation, \
1983 without modifying the original"]
1985 #[rustc_inherit_overflow_checks]
1986 pub const fn div_euclid(self, rhs: Self) -> Self {
1989 return if rhs > 0 { q - 1 } else { q + 1 }
1997 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
1999 This is done as if by the Euclidean division algorithm -- given
2000 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
2001 `0 <= r < abs(rhs)`.
2005 This function will panic if `rhs` is 0 or the division results in overflow.
2012 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2015 assert_eq!(a.rem_euclid(b), 3);
2016 assert_eq!((-a).rem_euclid(b), 1);
2017 assert_eq!(a.rem_euclid(-b), 3);
2018 assert_eq!((-a).rem_euclid(-b), 1);
2020 #[stable(feature = "euclidean_division", since = "1.38.0")]
2021 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2022 #[must_use = "this returns the result of the operation, \
2023 without modifying the original"]
2025 #[rustc_inherit_overflow_checks]
2026 pub const fn rem_euclid(self, rhs: Self) -> Self {
2041 concat!("Computes the absolute value of `self`.
2045 The absolute value of `", stringify!($SelfT), "::MIN` cannot be represented as an
2046 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
2047 code in debug mode will trigger a panic on this case and optimized code will return `",
2048 stringify!($SelfT), "::MIN` without a panic.
2055 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
2056 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
2059 #[stable(feature = "rust1", since = "1.0.0")]
2060 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2061 #[allow(unused_attributes)]
2062 #[allow_internal_unstable(const_if_match)]
2064 #[rustc_inherit_overflow_checks]
2065 pub const fn abs(self) -> Self {
2066 // Note that the #[inline] above means that the overflow
2067 // semantics of the subtraction depend on the crate we're being
2069 if self.is_negative() {
2078 concat!("Returns a number representing sign of `self`.
2080 - `0` if the number is zero
2081 - `1` if the number is positive
2082 - `-1` if the number is negative
2089 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
2090 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
2091 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
2094 #[stable(feature = "rust1", since = "1.0.0")]
2095 #[rustc_const_unstable(feature = "const_int_sign", issue = "53718")]
2097 pub const fn signum(self) -> Self {
2107 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2115 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2116 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2119 #[stable(feature = "rust1", since = "1.0.0")]
2120 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2122 pub const fn is_positive(self) -> bool { self > 0 }
2126 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2134 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2135 assert!(!10", stringify!($SelfT), ".is_negative());",
2138 #[stable(feature = "rust1", since = "1.0.0")]
2139 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2141 pub const fn is_negative(self) -> bool { self < 0 }
2145 concat!("Return the memory representation of this integer as a byte array in
2146 big-endian (network) byte order.
2153 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2154 assert_eq!(bytes, ", $be_bytes, ");
2156 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2157 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2159 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2160 self.to_be().to_ne_bytes()
2165 concat!("Return the memory representation of this integer as a byte array in
2166 little-endian byte order.
2173 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2174 assert_eq!(bytes, ", $le_bytes, ");
2176 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2177 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2179 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2180 self.to_le().to_ne_bytes()
2186 Return the memory representation of this integer as a byte array in
2189 As the target platform's native endianness is used, portable code
2190 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2195 [`to_be_bytes`]: #method.to_be_bytes
2196 [`to_le_bytes`]: #method.to_le_bytes
2201 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2204 if cfg!(target_endian = \"big\") {
2211 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2212 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2214 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2215 // SAFETY: integers are plain old datatypes so we can always transmute them to
2217 unsafe { mem::transmute(self) }
2222 concat!("Create an integer value from its representation as a byte array in
2230 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2231 assert_eq!(value, ", $swap_op, ");
2234 When starting from a slice rather than an array, fallible conversion APIs can be used:
2237 use std::convert::TryInto;
2239 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2240 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2242 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2245 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2246 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2248 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2249 Self::from_be(Self::from_ne_bytes(bytes))
2255 Create an integer value from its representation as a byte array in
2263 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2264 assert_eq!(value, ", $swap_op, ");
2267 When starting from a slice rather than an array, fallible conversion APIs can be used:
2270 use std::convert::TryInto;
2272 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2273 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2275 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2278 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2279 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2281 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2282 Self::from_le(Self::from_ne_bytes(bytes))
2287 concat!("Create an integer value from its memory representation as a byte
2288 array in native endianness.
2290 As the target platform's native endianness is used, portable code
2291 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2292 appropriate instead.
2294 [`from_be_bytes`]: #method.from_be_bytes
2295 [`from_le_bytes`]: #method.from_le_bytes
2302 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2307 assert_eq!(value, ", $swap_op, ");
2310 When starting from a slice rather than an array, fallible conversion APIs can be used:
2313 use std::convert::TryInto;
2315 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2316 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2318 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2321 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2322 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2324 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2325 // SAFETY: integers are plain old datatypes so we can always transmute to them
2326 unsafe { mem::transmute(bytes) }
2331 concat!("**This method is soft-deprecated.**
2333 Although using it won’t cause compilation warning,
2334 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
2336 Returns the smallest value that can be represented by this integer type."),
2337 #[stable(feature = "rust1", since = "1.0.0")]
2340 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2341 pub const fn min_value() -> Self {
2347 concat!("**This method is soft-deprecated.**
2349 Although using it won’t cause compilation warning,
2350 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
2352 Returns the largest value that can be represented by this integer type."),
2353 #[stable(feature = "rust1", since = "1.0.0")]
2356 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2357 pub const fn max_value() -> Self {
2366 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2367 "[0x12]", "[0x12]", "", "" }
2372 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2373 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2378 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2379 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2380 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2385 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2386 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2387 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2388 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2393 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2394 170141183460469231731687303715884105727, "", "", 16,
2395 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2396 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2397 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2398 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2399 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2400 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2403 #[cfg(target_pointer_width = "16")]
2406 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2407 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2408 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2411 #[cfg(target_pointer_width = "32")]
2414 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2415 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2416 "[0x12, 0x34, 0x56, 0x78]",
2417 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2420 #[cfg(target_pointer_width = "64")]
2423 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2424 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2425 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2426 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2427 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2430 macro_rules! uint_impl {
2431 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2432 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2433 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2434 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2436 concat!("The smallest value that can be represented by this integer type.
2443 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, 0);", $EndFeature, "
2445 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2446 pub const MIN: Self = 0;
2450 concat!("The largest value that can be represented by this integer type.
2457 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");",
2460 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2461 pub const MAX: Self = !0;
2465 concat!("Converts a string slice in a given base to an integer.
2467 The string is expected to be an optional `+` sign
2469 Leading and trailing whitespace represent an error.
2470 Digits are a subset of these characters, depending on `radix`:
2478 This function panics if `radix` is not in the range from 2 to 36.
2485 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2488 #[stable(feature = "rust1", since = "1.0.0")]
2489 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2490 from_str_radix(src, radix)
2495 concat!("Returns the number of ones in the binary representation of `self`.
2502 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2504 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2506 #[stable(feature = "rust1", since = "1.0.0")]
2507 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2509 pub const fn count_ones(self) -> u32 {
2510 intrinsics::ctpop(self as $ActualT) as u32
2515 concat!("Returns the number of zeros in the binary representation of `self`.
2522 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);", $EndFeature, "
2524 #[stable(feature = "rust1", since = "1.0.0")]
2525 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2527 pub const fn count_zeros(self) -> u32 {
2528 (!self).count_ones()
2533 concat!("Returns the number of leading zeros in the binary representation of `self`.
2540 ", $Feature, "let n = ", stringify!($SelfT), "::MAX >> 2;
2542 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2544 #[stable(feature = "rust1", since = "1.0.0")]
2545 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2547 pub const fn leading_zeros(self) -> u32 {
2548 intrinsics::ctlz(self as $ActualT) as u32
2553 concat!("Returns the number of trailing zeros in the binary representation
2561 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2563 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2565 #[stable(feature = "rust1", since = "1.0.0")]
2566 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2568 pub const fn trailing_zeros(self) -> u32 {
2569 intrinsics::cttz(self) as u32
2574 concat!("Returns the number of leading ones in the binary representation of `self`.
2581 ", $Feature, "#![feature(leading_trailing_ones)]
2582 let n = !(", stringify!($SelfT), "::MAX >> 2);
2584 assert_eq!(n.leading_ones(), 2);", $EndFeature, "
2586 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2588 pub const fn leading_ones(self) -> u32 {
2589 (!self).leading_zeros()
2594 concat!("Returns the number of trailing ones in the binary representation
2602 ", $Feature, "#![feature(leading_trailing_ones)]
2603 let n = 0b1010111", stringify!($SelfT), ";
2605 assert_eq!(n.trailing_ones(), 3);", $EndFeature, "
2607 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2609 pub const fn trailing_ones(self) -> u32 {
2610 (!self).trailing_zeros()
2615 concat!("Shifts the bits to the left by a specified amount, `n`,
2616 wrapping the truncated bits to the end of the resulting integer.
2618 Please note this isn't the same operation as the `<<` shifting operator!
2625 let n = ", $rot_op, stringify!($SelfT), ";
2626 let m = ", $rot_result, ";
2628 assert_eq!(n.rotate_left(", $rot, "), m);
2630 #[stable(feature = "rust1", since = "1.0.0")]
2631 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2632 #[must_use = "this returns the result of the operation, \
2633 without modifying the original"]
2635 pub const fn rotate_left(self, n: u32) -> Self {
2636 intrinsics::rotate_left(self, n as $SelfT)
2641 concat!("Shifts the bits to the right by a specified amount, `n`,
2642 wrapping the truncated bits to the beginning of the resulting
2645 Please note this isn't the same operation as the `>>` shifting operator!
2652 let n = ", $rot_result, stringify!($SelfT), ";
2653 let m = ", $rot_op, ";
2655 assert_eq!(n.rotate_right(", $rot, "), m);
2657 #[stable(feature = "rust1", since = "1.0.0")]
2658 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2659 #[must_use = "this returns the result of the operation, \
2660 without modifying the original"]
2662 pub const fn rotate_right(self, n: u32) -> Self {
2663 intrinsics::rotate_right(self, n as $SelfT)
2669 Reverses the byte order of the integer.
2676 let n = ", $swap_op, stringify!($SelfT), ";
2677 let m = n.swap_bytes();
2679 assert_eq!(m, ", $swapped, ");
2681 #[stable(feature = "rust1", since = "1.0.0")]
2682 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2684 pub const fn swap_bytes(self) -> Self {
2685 intrinsics::bswap(self as $ActualT) as Self
2690 concat!("Reverses the bit pattern of the integer.
2697 let n = ", $swap_op, stringify!($SelfT), ";
2698 let m = n.reverse_bits();
2700 assert_eq!(m, ", $reversed, ");
2702 #[stable(feature = "reverse_bits", since = "1.37.0")]
2703 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2706 pub const fn reverse_bits(self) -> Self {
2707 intrinsics::bitreverse(self as $ActualT) as Self
2712 concat!("Converts an integer from big endian to the target's endianness.
2714 On big endian this is a no-op. On little endian the bytes are
2722 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2724 if cfg!(target_endian = \"big\") {
2725 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2727 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2730 #[stable(feature = "rust1", since = "1.0.0")]
2731 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2733 pub const fn from_be(x: Self) -> Self {
2734 #[cfg(target_endian = "big")]
2738 #[cfg(not(target_endian = "big"))]
2746 concat!("Converts an integer from little endian to the target's endianness.
2748 On little endian this is a no-op. On big endian the bytes are
2756 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2758 if cfg!(target_endian = \"little\") {
2759 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2761 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2764 #[stable(feature = "rust1", since = "1.0.0")]
2765 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2767 pub const fn from_le(x: Self) -> Self {
2768 #[cfg(target_endian = "little")]
2772 #[cfg(not(target_endian = "little"))]
2780 concat!("Converts `self` to big endian from the target's endianness.
2782 On big endian this is a no-op. On little endian the bytes are
2790 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2792 if cfg!(target_endian = \"big\") {
2793 assert_eq!(n.to_be(), n)
2795 assert_eq!(n.to_be(), n.swap_bytes())
2798 #[stable(feature = "rust1", since = "1.0.0")]
2799 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2801 pub const fn to_be(self) -> Self { // or not to be?
2802 #[cfg(target_endian = "big")]
2806 #[cfg(not(target_endian = "big"))]
2814 concat!("Converts `self` to little endian from the target's endianness.
2816 On little endian this is a no-op. On big endian the bytes are
2824 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2826 if cfg!(target_endian = \"little\") {
2827 assert_eq!(n.to_le(), n)
2829 assert_eq!(n.to_le(), n.swap_bytes())
2832 #[stable(feature = "rust1", since = "1.0.0")]
2833 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2835 pub const fn to_le(self) -> Self {
2836 #[cfg(target_endian = "little")]
2840 #[cfg(not(target_endian = "little"))]
2848 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2849 if overflow occurred.
2856 ", $Feature, "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
2857 "Some(", stringify!($SelfT), "::MAX - 1));
2858 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);", $EndFeature, "
2860 #[stable(feature = "rust1", since = "1.0.0")]
2861 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2862 #[must_use = "this returns the result of the operation, \
2863 without modifying the original"]
2865 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
2866 let (a, b) = self.overflowing_add(rhs);
2867 if b {None} else {Some(a)}
2872 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2873 `None` if overflow occurred.
2880 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2881 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2883 #[stable(feature = "rust1", since = "1.0.0")]
2884 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2885 #[must_use = "this returns the result of the operation, \
2886 without modifying the original"]
2888 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
2889 let (a, b) = self.overflowing_sub(rhs);
2890 if b {None} else {Some(a)}
2895 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2896 `None` if overflow occurred.
2903 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2904 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);", $EndFeature, "
2906 #[stable(feature = "rust1", since = "1.0.0")]
2907 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2908 #[must_use = "this returns the result of the operation, \
2909 without modifying the original"]
2911 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
2912 let (a, b) = self.overflowing_mul(rhs);
2913 if b {None} else {Some(a)}
2918 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2926 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2927 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2929 #[stable(feature = "rust1", since = "1.0.0")]
2930 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2931 #[must_use = "this returns the result of the operation, \
2932 without modifying the original"]
2934 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
2937 // SAFETY: div by zero has been checked above and unsigned types have no other
2938 // failure modes for division
2939 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2945 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2953 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
2954 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
2956 #[stable(feature = "euclidean_division", since = "1.38.0")]
2957 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2958 #[must_use = "this returns the result of the operation, \
2959 without modifying the original"]
2961 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
2965 Some(self.div_euclid(rhs))
2972 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2980 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2981 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2983 #[stable(feature = "wrapping", since = "1.7.0")]
2984 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2985 #[must_use = "this returns the result of the operation, \
2986 without modifying the original"]
2988 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
2992 // SAFETY: div by zero has been checked above and unsigned types have no other
2993 // failure modes for division
2994 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3000 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3008 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3009 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3011 #[stable(feature = "euclidean_division", since = "1.38.0")]
3012 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3013 #[must_use = "this returns the result of the operation, \
3014 without modifying the original"]
3016 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3020 Some(self.rem_euclid(rhs))
3026 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3029 Note that negating any positive integer will overflow.
3036 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3037 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3039 #[stable(feature = "wrapping", since = "1.7.0")]
3040 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3042 pub const fn checked_neg(self) -> Option<Self> {
3043 let (a, b) = self.overflowing_neg();
3044 if b {None} else {Some(a)}
3049 concat!("Checked shift left. Computes `self << rhs`, returning `None`
3050 if `rhs` is larger than or equal to the number of bits in `self`.
3057 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3058 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3060 #[stable(feature = "wrapping", since = "1.7.0")]
3061 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3062 #[must_use = "this returns the result of the operation, \
3063 without modifying the original"]
3065 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
3066 let (a, b) = self.overflowing_shl(rhs);
3067 if b {None} else {Some(a)}
3072 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3073 if `rhs` is larger than or equal to the number of bits in `self`.
3080 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3081 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3083 #[stable(feature = "wrapping", since = "1.7.0")]
3084 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3085 #[must_use = "this returns the result of the operation, \
3086 without modifying the original"]
3088 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
3089 let (a, b) = self.overflowing_shr(rhs);
3090 if b {None} else {Some(a)}
3095 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3103 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3104 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);", $EndFeature, "
3106 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3107 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3108 #[must_use = "this returns the result of the operation, \
3109 without modifying the original"]
3111 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
3112 let mut base = self;
3113 let mut acc: Self = 1;
3117 acc = try_opt!(acc.checked_mul(base));
3120 base = try_opt!(base.checked_mul(base));
3123 // Deal with the final bit of the exponent separately, since
3124 // squaring the base afterwards is not necessary and may cause a
3125 // needless overflow.
3127 acc = try_opt!(acc.checked_mul(base));
3135 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3136 the numeric bounds instead of overflowing.
3143 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3144 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
3147 #[stable(feature = "rust1", since = "1.0.0")]
3148 #[must_use = "this returns the result of the operation, \
3149 without modifying the original"]
3150 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3152 pub const fn saturating_add(self, rhs: Self) -> Self {
3153 intrinsics::saturating_add(self, rhs)
3158 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3159 at the numeric bounds instead of overflowing.
3166 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3167 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3169 #[stable(feature = "rust1", since = "1.0.0")]
3170 #[must_use = "this returns the result of the operation, \
3171 without modifying the original"]
3172 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3174 pub const fn saturating_sub(self, rhs: Self) -> Self {
3175 intrinsics::saturating_sub(self, rhs)
3180 concat!("Saturating integer multiplication. Computes `self * rhs`,
3181 saturating at the numeric bounds instead of overflowing.
3189 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3190 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3191 "::MAX);", $EndFeature, "
3193 #[stable(feature = "wrapping", since = "1.7.0")]
3194 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3195 #[must_use = "this returns the result of the operation, \
3196 without modifying the original"]
3198 pub const fn saturating_mul(self, rhs: Self) -> Self {
3199 match self.checked_mul(rhs) {
3201 None => Self::max_value(),
3207 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3208 saturating at the numeric bounds instead of overflowing.
3216 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3217 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3220 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3221 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3222 #[must_use = "this returns the result of the operation, \
3223 without modifying the original"]
3225 pub const fn saturating_pow(self, exp: u32) -> Self {
3226 match self.checked_pow(exp) {
3228 None => Self::max_value(),
3234 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3235 wrapping around at the boundary of the type.
3242 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3243 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);",
3246 #[stable(feature = "rust1", since = "1.0.0")]
3247 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3248 #[must_use = "this returns the result of the operation, \
3249 without modifying the original"]
3251 pub const fn wrapping_add(self, rhs: Self) -> Self {
3252 intrinsics::wrapping_add(self, rhs)
3257 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3258 wrapping around at the boundary of the type.
3265 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3266 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);",
3269 #[stable(feature = "rust1", since = "1.0.0")]
3270 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3271 #[must_use = "this returns the result of the operation, \
3272 without modifying the original"]
3274 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3275 intrinsics::wrapping_sub(self, rhs)
3279 /// Wrapping (modular) multiplication. Computes `self *
3280 /// rhs`, wrapping around at the boundary of the type.
3286 /// Please note that this example is shared between integer types.
3287 /// Which explains why `u8` is used here.
3290 /// assert_eq!(10u8.wrapping_mul(12), 120);
3291 /// assert_eq!(25u8.wrapping_mul(12), 44);
3293 #[stable(feature = "rust1", since = "1.0.0")]
3294 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3295 #[must_use = "this returns the result of the operation, \
3296 without modifying the original"]
3298 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3299 intrinsics::wrapping_mul(self, rhs)
3303 concat!("Wrapping (modular) division. Computes `self / rhs`.
3304 Wrapped division on unsigned types is just normal division.
3305 There's no way wrapping could ever happen.
3306 This function exists, so that all operations
3307 are accounted for in the wrapping operations.
3314 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3316 #[stable(feature = "num_wrapping", since = "1.2.0")]
3317 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3318 #[must_use = "this returns the result of the operation, \
3319 without modifying the original"]
3321 pub const fn wrapping_div(self, rhs: Self) -> Self {
3327 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3328 Wrapped division on unsigned types is just normal division.
3329 There's no way wrapping could ever happen.
3330 This function exists, so that all operations
3331 are accounted for in the wrapping operations.
3332 Since, for the positive integers, all common
3333 definitions of division are equal, this
3334 is exactly equal to `self.wrapping_div(rhs)`.
3341 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3343 #[stable(feature = "euclidean_division", since = "1.38.0")]
3344 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3345 #[must_use = "this returns the result of the operation, \
3346 without modifying the original"]
3348 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
3354 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3355 Wrapped remainder calculation on unsigned types is
3356 just the regular remainder calculation.
3357 There's no way wrapping could ever happen.
3358 This function exists, so that all operations
3359 are accounted for in the wrapping operations.
3366 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3368 #[stable(feature = "num_wrapping", since = "1.2.0")]
3369 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3370 #[must_use = "this returns the result of the operation, \
3371 without modifying the original"]
3373 pub const fn wrapping_rem(self, rhs: Self) -> Self {
3379 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3380 Wrapped modulo calculation on unsigned types is
3381 just the regular remainder calculation.
3382 There's no way wrapping could ever happen.
3383 This function exists, so that all operations
3384 are accounted for in the wrapping operations.
3385 Since, for the positive integers, all common
3386 definitions of division are equal, this
3387 is exactly equal to `self.wrapping_rem(rhs)`.
3394 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3396 #[stable(feature = "euclidean_division", since = "1.38.0")]
3397 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3398 #[must_use = "this returns the result of the operation, \
3399 without modifying the original"]
3401 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3406 /// Wrapping (modular) negation. Computes `-self`,
3407 /// wrapping around at the boundary of the type.
3409 /// Since unsigned types do not have negative equivalents
3410 /// all applications of this function will wrap (except for `-0`).
3411 /// For values smaller than the corresponding signed type's maximum
3412 /// the result is the same as casting the corresponding signed value.
3413 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3414 /// `MAX` is the corresponding signed type's maximum.
3420 /// Please note that this example is shared between integer types.
3421 /// Which explains why `i8` is used here.
3424 /// assert_eq!(100i8.wrapping_neg(), -100);
3425 /// assert_eq!((-128i8).wrapping_neg(), -128);
3427 #[stable(feature = "num_wrapping", since = "1.2.0")]
3428 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3430 pub const fn wrapping_neg(self) -> Self {
3431 self.overflowing_neg().0
3435 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3436 where `mask` removes any high-order bits of `rhs` that
3437 would cause the shift to exceed the bitwidth of the type.
3439 Note that this is *not* the same as a rotate-left; the
3440 RHS of a wrapping shift-left is restricted to the range
3441 of the type, rather than the bits shifted out of the LHS
3442 being returned to the other end. The primitive integer
3443 types all implement a `rotate_left` function, which may
3444 be what you want instead.
3451 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3452 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3454 #[stable(feature = "num_wrapping", since = "1.2.0")]
3455 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3456 #[must_use = "this returns the result of the operation, \
3457 without modifying the original"]
3459 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3460 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3463 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3469 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3470 where `mask` removes any high-order bits of `rhs` that
3471 would cause the shift to exceed the bitwidth of the type.
3473 Note that this is *not* the same as a rotate-right; the
3474 RHS of a wrapping shift-right is restricted to the range
3475 of the type, rather than the bits shifted out of the LHS
3476 being returned to the other end. The primitive integer
3477 types all implement a `rotate_right` function, which may
3478 be what you want instead.
3485 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3486 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3488 #[stable(feature = "num_wrapping", since = "1.2.0")]
3489 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3490 #[must_use = "this returns the result of the operation, \
3491 without modifying the original"]
3493 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3494 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3497 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3503 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3504 wrapping around at the boundary of the type.
3511 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3512 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3514 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3515 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3516 #[must_use = "this returns the result of the operation, \
3517 without modifying the original"]
3519 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
3520 let mut base = self;
3521 let mut acc: Self = 1;
3525 acc = acc.wrapping_mul(base);
3528 base = base.wrapping_mul(base);
3531 // Deal with the final bit of the exponent separately, since
3532 // squaring the base afterwards is not necessary and may cause a
3533 // needless overflow.
3535 acc = acc.wrapping_mul(base);
3543 concat!("Calculates `self` + `rhs`
3545 Returns a tuple of the addition along with a boolean indicating
3546 whether an arithmetic overflow would occur. If an overflow would
3547 have occurred then the wrapped value is returned.
3555 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3556 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3558 #[stable(feature = "wrapping", since = "1.7.0")]
3559 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3560 #[must_use = "this returns the result of the operation, \
3561 without modifying the original"]
3563 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3564 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3570 concat!("Calculates `self` - `rhs`
3572 Returns a tuple of the subtraction along with a boolean indicating
3573 whether an arithmetic overflow would occur. If an overflow would
3574 have occurred then the wrapped value is returned.
3582 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3583 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3586 #[stable(feature = "wrapping", since = "1.7.0")]
3587 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3588 #[must_use = "this returns the result of the operation, \
3589 without modifying the original"]
3591 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3592 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3597 /// Calculates the multiplication of `self` and `rhs`.
3599 /// Returns a tuple of the multiplication along with a boolean
3600 /// indicating whether an arithmetic overflow would occur. If an
3601 /// overflow would have occurred then the wrapped value is returned.
3607 /// Please note that this example is shared between integer types.
3608 /// Which explains why `u32` is used here.
3611 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3612 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3614 #[stable(feature = "wrapping", since = "1.7.0")]
3615 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3616 #[must_use = "this returns the result of the operation, \
3617 without modifying the original"]
3619 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3620 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3625 concat!("Calculates the divisor when `self` is divided by `rhs`.
3627 Returns a tuple of the divisor along with a boolean indicating
3628 whether an arithmetic overflow would occur. Note that for unsigned
3629 integers overflow never occurs, so the second value is always
3634 This function will panic if `rhs` is 0.
3641 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3644 #[stable(feature = "wrapping", since = "1.7.0")]
3645 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3646 #[must_use = "this returns the result of the operation, \
3647 without modifying the original"]
3648 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3654 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3656 Returns a tuple of the divisor along with a boolean indicating
3657 whether an arithmetic overflow would occur. Note that for unsigned
3658 integers overflow never occurs, so the second value is always
3660 Since, for the positive integers, all common
3661 definitions of division are equal, this
3662 is exactly equal to `self.overflowing_div(rhs)`.
3666 This function will panic if `rhs` is 0.
3673 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3676 #[stable(feature = "euclidean_division", since = "1.38.0")]
3677 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3678 #[must_use = "this returns the result of the operation, \
3679 without modifying the original"]
3680 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3686 concat!("Calculates the remainder when `self` is divided by `rhs`.
3688 Returns a tuple of the remainder after dividing along with a boolean
3689 indicating whether an arithmetic overflow would occur. Note that for
3690 unsigned integers overflow never occurs, so the second value is
3695 This function will panic if `rhs` is 0.
3702 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3705 #[stable(feature = "wrapping", since = "1.7.0")]
3706 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3707 #[must_use = "this returns the result of the operation, \
3708 without modifying the original"]
3709 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3715 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3717 Returns a tuple of the modulo after dividing along with a boolean
3718 indicating whether an arithmetic overflow would occur. Note that for
3719 unsigned integers overflow never occurs, so the second value is
3721 Since, for the positive integers, all common
3722 definitions of division are equal, this operation
3723 is exactly equal to `self.overflowing_rem(rhs)`.
3727 This function will panic if `rhs` is 0.
3734 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3737 #[stable(feature = "euclidean_division", since = "1.38.0")]
3738 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3739 #[must_use = "this returns the result of the operation, \
3740 without modifying the original"]
3741 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3747 concat!("Negates self in an overflowing fashion.
3749 Returns `!self + 1` using wrapping operations to return the value
3750 that represents the negation of this unsigned value. Note that for
3751 positive unsigned values overflow always occurs, but negating 0 does
3759 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3760 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3761 ", true));", $EndFeature, "
3764 #[stable(feature = "wrapping", since = "1.7.0")]
3765 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3766 pub const fn overflowing_neg(self) -> (Self, bool) {
3767 ((!self).wrapping_add(1), self != 0)
3772 concat!("Shifts self left by `rhs` bits.
3774 Returns a tuple of the shifted version of self along with a boolean
3775 indicating whether the shift value was larger than or equal to the
3776 number of bits. If the shift value is too large, then value is
3777 masked (N-1) where N is the number of bits, and this value is then
3778 used to perform the shift.
3785 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3786 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3788 #[stable(feature = "wrapping", since = "1.7.0")]
3789 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3790 #[must_use = "this returns the result of the operation, \
3791 without modifying the original"]
3793 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3794 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3799 concat!("Shifts self right by `rhs` bits.
3801 Returns a tuple of the shifted version of self along with a boolean
3802 indicating whether the shift value was larger than or equal to the
3803 number of bits. If the shift value is too large, then value is
3804 masked (N-1) where N is the number of bits, and this value is then
3805 used to perform the shift.
3812 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3813 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3815 #[stable(feature = "wrapping", since = "1.7.0")]
3816 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3817 #[must_use = "this returns the result of the operation, \
3818 without modifying the original"]
3820 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3821 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3826 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3828 Returns a tuple of the exponentiation along with a bool indicating
3829 whether an overflow happened.
3836 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3837 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3839 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3840 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3841 #[must_use = "this returns the result of the operation, \
3842 without modifying the original"]
3844 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3845 let mut base = self;
3846 let mut acc: Self = 1;
3847 let mut overflown = false;
3848 // Scratch space for storing results of overflowing_mul.
3853 r = acc.overflowing_mul(base);
3858 r = base.overflowing_mul(base);
3863 // Deal with the final bit of the exponent separately, since
3864 // squaring the base afterwards is not necessary and may cause a
3865 // needless overflow.
3867 r = acc.overflowing_mul(base);
3877 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3884 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3886 #[stable(feature = "rust1", since = "1.0.0")]
3887 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3888 #[must_use = "this returns the result of the operation, \
3889 without modifying the original"]
3891 #[rustc_inherit_overflow_checks]
3892 pub const fn pow(self, mut exp: u32) -> Self {
3893 let mut base = self;
3904 // Deal with the final bit of the exponent separately, since
3905 // squaring the base afterwards is not necessary and may cause a
3906 // needless overflow.
3916 concat!("Performs Euclidean division.
3918 Since, for the positive integers, all common
3919 definitions of division are equal, this
3920 is exactly equal to `self / rhs`.
3924 This function will panic if `rhs` is 0.
3931 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
3933 #[stable(feature = "euclidean_division", since = "1.38.0")]
3934 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3935 #[must_use = "this returns the result of the operation, \
3936 without modifying the original"]
3938 #[rustc_inherit_overflow_checks]
3939 pub const fn div_euclid(self, rhs: Self) -> Self {
3946 concat!("Calculates the least remainder of `self (mod rhs)`.
3948 Since, for the positive integers, all common
3949 definitions of division are equal, this
3950 is exactly equal to `self % rhs`.
3954 This function will panic if `rhs` is 0.
3961 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
3963 #[stable(feature = "euclidean_division", since = "1.38.0")]
3964 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3965 #[must_use = "this returns the result of the operation, \
3966 without modifying the original"]
3968 #[rustc_inherit_overflow_checks]
3969 pub const fn rem_euclid(self, rhs: Self) -> Self {
3975 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3982 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3983 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3985 #[stable(feature = "rust1", since = "1.0.0")]
3986 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
3988 pub const fn is_power_of_two(self) -> bool {
3989 self.count_ones() == 1
3993 // Returns one less than next power of two.
3994 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3996 // 8u8.one_less_than_next_power_of_two() == 7
3997 // 6u8.one_less_than_next_power_of_two() == 7
3999 // This method cannot overflow, as in the `next_power_of_two`
4000 // overflow cases it instead ends up returning the maximum value
4001 // of the type, and can return 0 for 0.
4003 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4004 const fn one_less_than_next_power_of_two(self) -> Self {
4005 if self <= 1 { return 0; }
4008 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4009 // That means the shift is always in-bounds, and some processors
4010 // (such as intel pre-haswell) have more efficient ctlz
4011 // intrinsics when the argument is non-zero.
4012 let z = unsafe { intrinsics::ctlz_nonzero(p) };
4013 <$SelfT>::max_value() >> z
4017 concat!("Returns the smallest power of two greater than or equal to `self`.
4019 When return value overflows (i.e., `self > (1 << (N-1))` for type
4020 `uN`), it panics in debug mode and return value is wrapped to 0 in
4021 release mode (the only situation in which method can return 0).
4028 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4029 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4031 #[stable(feature = "rust1", since = "1.0.0")]
4032 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4034 #[rustc_inherit_overflow_checks]
4035 pub const fn next_power_of_two(self) -> Self {
4036 self.one_less_than_next_power_of_two() + 1
4041 concat!("Returns the smallest power of two greater than or equal to `n`. If
4042 the next power of two is greater than the type's maximum value,
4043 `None` is returned, otherwise the power of two is wrapped in `Some`.
4050 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4051 ".checked_next_power_of_two(), Some(2));
4052 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4053 assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);",
4057 #[stable(feature = "rust1", since = "1.0.0")]
4058 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4059 pub const fn checked_next_power_of_two(self) -> Option<Self> {
4060 self.one_less_than_next_power_of_two().checked_add(1)
4065 concat!("Returns the smallest power of two greater than or equal to `n`. If
4066 the next power of two is greater than the type's maximum value,
4067 the return value is wrapped to `0`.
4074 #![feature(wrapping_next_power_of_two)]
4076 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4077 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4078 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);",
4081 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4082 reason = "needs decision on wrapping behaviour")]
4083 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4084 pub const fn wrapping_next_power_of_two(self) -> Self {
4085 self.one_less_than_next_power_of_two().wrapping_add(1)
4090 concat!("Return the memory representation of this integer as a byte array in
4091 big-endian (network) byte order.
4098 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4099 assert_eq!(bytes, ", $be_bytes, ");
4101 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4102 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4104 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4105 self.to_be().to_ne_bytes()
4110 concat!("Return the memory representation of this integer as a byte array in
4111 little-endian byte order.
4118 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4119 assert_eq!(bytes, ", $le_bytes, ");
4121 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4122 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4124 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4125 self.to_le().to_ne_bytes()
4131 Return the memory representation of this integer as a byte array in
4134 As the target platform's native endianness is used, portable code
4135 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4140 [`to_be_bytes`]: #method.to_be_bytes
4141 [`to_le_bytes`]: #method.to_le_bytes
4146 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4149 if cfg!(target_endian = \"big\") {
4156 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4157 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4159 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4160 // SAFETY: integers are plain old datatypes so we can always transmute them to
4162 unsafe { mem::transmute(self) }
4167 concat!("Create an integer value from its representation as a byte array in
4175 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4176 assert_eq!(value, ", $swap_op, ");
4179 When starting from a slice rather than an array, fallible conversion APIs can be used:
4182 use std::convert::TryInto;
4184 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4185 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4187 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4190 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4191 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4193 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4194 Self::from_be(Self::from_ne_bytes(bytes))
4200 Create an integer value from its representation as a byte array in
4208 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4209 assert_eq!(value, ", $swap_op, ");
4212 When starting from a slice rather than an array, fallible conversion APIs can be used:
4215 use std::convert::TryInto;
4217 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4218 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4220 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4223 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4224 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4226 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4227 Self::from_le(Self::from_ne_bytes(bytes))
4232 concat!("Create an integer value from its memory representation as a byte
4233 array in native endianness.
4235 As the target platform's native endianness is used, portable code
4236 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4237 appropriate instead.
4239 [`from_be_bytes`]: #method.from_be_bytes
4240 [`from_le_bytes`]: #method.from_le_bytes
4247 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4252 assert_eq!(value, ", $swap_op, ");
4255 When starting from a slice rather than an array, fallible conversion APIs can be used:
4258 use std::convert::TryInto;
4260 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4261 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4263 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4266 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4267 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4269 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4270 // SAFETY: integers are plain old datatypes so we can always transmute to them
4271 unsafe { mem::transmute(bytes) }
4276 concat!("**This method is soft-deprecated.**
4278 Although using it won’t cause compilation warning,
4279 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
4281 Returns the smallest value that can be represented by this integer type."),
4282 #[stable(feature = "rust1", since = "1.0.0")]
4285 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4286 pub const fn min_value() -> Self { Self::MIN }
4290 concat!("**This method is soft-deprecated.**
4292 Although using it won’t cause compilation warning,
4293 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
4295 Returns the largest value that can be represented by this integer type."),
4296 #[stable(feature = "rust1", since = "1.0.0")]
4299 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4300 pub const fn max_value() -> Self { Self::MAX }
4307 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4310 /// Checks if the value is within the ASCII range.
4315 /// let ascii = 97u8;
4316 /// let non_ascii = 150u8;
4318 /// assert!(ascii.is_ascii());
4319 /// assert!(!non_ascii.is_ascii());
4321 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4322 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.43.0")]
4324 pub const fn is_ascii(&self) -> bool {
4328 /// Makes a copy of the value in its ASCII upper case equivalent.
4330 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4331 /// but non-ASCII letters are unchanged.
4333 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4338 /// let lowercase_a = 97u8;
4340 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4343 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4344 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4346 pub fn to_ascii_uppercase(&self) -> u8 {
4347 // Unset the fith bit if this is a lowercase letter
4348 *self & !((self.is_ascii_lowercase() as u8) << 5)
4351 /// Makes a copy of the value in its ASCII lower case equivalent.
4353 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4354 /// but non-ASCII letters are unchanged.
4356 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4361 /// let uppercase_a = 65u8;
4363 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4366 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4367 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4369 pub fn to_ascii_lowercase(&self) -> u8 {
4370 // Set the fith bit if this is an uppercase letter
4371 *self | ((self.is_ascii_uppercase() as u8) << 5)
4374 /// Checks that two values are an ASCII case-insensitive match.
4376 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4381 /// let lowercase_a = 97u8;
4382 /// let uppercase_a = 65u8;
4384 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4386 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4388 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4389 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4392 /// Converts this value to its ASCII upper case equivalent in-place.
4394 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4395 /// but non-ASCII letters are unchanged.
4397 /// To return a new uppercased value without modifying the existing one, use
4398 /// [`to_ascii_uppercase`].
4403 /// let mut byte = b'a';
4405 /// byte.make_ascii_uppercase();
4407 /// assert_eq!(b'A', byte);
4410 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4411 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4413 pub fn make_ascii_uppercase(&mut self) {
4414 *self = self.to_ascii_uppercase();
4417 /// Converts this value to its ASCII lower case equivalent in-place.
4419 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4420 /// but non-ASCII letters are unchanged.
4422 /// To return a new lowercased value without modifying the existing one, use
4423 /// [`to_ascii_lowercase`].
4428 /// let mut byte = b'A';
4430 /// byte.make_ascii_lowercase();
4432 /// assert_eq!(b'a', byte);
4435 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4436 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4438 pub fn make_ascii_lowercase(&mut self) {
4439 *self = self.to_ascii_lowercase();
4442 /// Checks if the value is an ASCII alphabetic character:
4444 /// - U+0041 'A' ..= U+005A 'Z', or
4445 /// - U+0061 'a' ..= U+007A 'z'.
4450 /// let uppercase_a = b'A';
4451 /// let uppercase_g = b'G';
4454 /// let zero = b'0';
4455 /// let percent = b'%';
4456 /// let space = b' ';
4458 /// let esc = 0x1b_u8;
4460 /// assert!(uppercase_a.is_ascii_alphabetic());
4461 /// assert!(uppercase_g.is_ascii_alphabetic());
4462 /// assert!(a.is_ascii_alphabetic());
4463 /// assert!(g.is_ascii_alphabetic());
4464 /// assert!(!zero.is_ascii_alphabetic());
4465 /// assert!(!percent.is_ascii_alphabetic());
4466 /// assert!(!space.is_ascii_alphabetic());
4467 /// assert!(!lf.is_ascii_alphabetic());
4468 /// assert!(!esc.is_ascii_alphabetic());
4470 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4471 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4473 pub const fn is_ascii_alphabetic(&self) -> bool {
4474 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
4477 /// Checks if the value is an ASCII uppercase character:
4478 /// U+0041 'A' ..= U+005A 'Z'.
4483 /// let uppercase_a = b'A';
4484 /// let uppercase_g = b'G';
4487 /// let zero = b'0';
4488 /// let percent = b'%';
4489 /// let space = b' ';
4491 /// let esc = 0x1b_u8;
4493 /// assert!(uppercase_a.is_ascii_uppercase());
4494 /// assert!(uppercase_g.is_ascii_uppercase());
4495 /// assert!(!a.is_ascii_uppercase());
4496 /// assert!(!g.is_ascii_uppercase());
4497 /// assert!(!zero.is_ascii_uppercase());
4498 /// assert!(!percent.is_ascii_uppercase());
4499 /// assert!(!space.is_ascii_uppercase());
4500 /// assert!(!lf.is_ascii_uppercase());
4501 /// assert!(!esc.is_ascii_uppercase());
4503 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4504 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4506 pub const fn is_ascii_uppercase(&self) -> bool {
4507 matches!(*self, b'A'..=b'Z')
4510 /// Checks if the value is an ASCII lowercase character:
4511 /// U+0061 'a' ..= U+007A 'z'.
4516 /// let uppercase_a = b'A';
4517 /// let uppercase_g = b'G';
4520 /// let zero = b'0';
4521 /// let percent = b'%';
4522 /// let space = b' ';
4524 /// let esc = 0x1b_u8;
4526 /// assert!(!uppercase_a.is_ascii_lowercase());
4527 /// assert!(!uppercase_g.is_ascii_lowercase());
4528 /// assert!(a.is_ascii_lowercase());
4529 /// assert!(g.is_ascii_lowercase());
4530 /// assert!(!zero.is_ascii_lowercase());
4531 /// assert!(!percent.is_ascii_lowercase());
4532 /// assert!(!space.is_ascii_lowercase());
4533 /// assert!(!lf.is_ascii_lowercase());
4534 /// assert!(!esc.is_ascii_lowercase());
4536 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4537 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4539 pub const fn is_ascii_lowercase(&self) -> bool {
4540 matches!(*self, b'a'..=b'z')
4543 /// Checks if the value is an ASCII alphanumeric character:
4545 /// - U+0041 'A' ..= U+005A 'Z', or
4546 /// - U+0061 'a' ..= U+007A 'z', or
4547 /// - U+0030 '0' ..= U+0039 '9'.
4552 /// let uppercase_a = b'A';
4553 /// let uppercase_g = b'G';
4556 /// let zero = b'0';
4557 /// let percent = b'%';
4558 /// let space = b' ';
4560 /// let esc = 0x1b_u8;
4562 /// assert!(uppercase_a.is_ascii_alphanumeric());
4563 /// assert!(uppercase_g.is_ascii_alphanumeric());
4564 /// assert!(a.is_ascii_alphanumeric());
4565 /// assert!(g.is_ascii_alphanumeric());
4566 /// assert!(zero.is_ascii_alphanumeric());
4567 /// assert!(!percent.is_ascii_alphanumeric());
4568 /// assert!(!space.is_ascii_alphanumeric());
4569 /// assert!(!lf.is_ascii_alphanumeric());
4570 /// assert!(!esc.is_ascii_alphanumeric());
4572 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4573 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4575 pub const fn is_ascii_alphanumeric(&self) -> bool {
4576 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
4579 /// Checks if the value is an ASCII decimal digit:
4580 /// U+0030 '0' ..= U+0039 '9'.
4585 /// let uppercase_a = b'A';
4586 /// let uppercase_g = b'G';
4589 /// let zero = b'0';
4590 /// let percent = b'%';
4591 /// let space = b' ';
4593 /// let esc = 0x1b_u8;
4595 /// assert!(!uppercase_a.is_ascii_digit());
4596 /// assert!(!uppercase_g.is_ascii_digit());
4597 /// assert!(!a.is_ascii_digit());
4598 /// assert!(!g.is_ascii_digit());
4599 /// assert!(zero.is_ascii_digit());
4600 /// assert!(!percent.is_ascii_digit());
4601 /// assert!(!space.is_ascii_digit());
4602 /// assert!(!lf.is_ascii_digit());
4603 /// assert!(!esc.is_ascii_digit());
4605 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4606 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4608 pub const fn is_ascii_digit(&self) -> bool {
4609 matches!(*self, b'0'..=b'9')
4612 /// Checks if the value is an ASCII hexadecimal digit:
4614 /// - U+0030 '0' ..= U+0039 '9', or
4615 /// - U+0041 'A' ..= U+0046 'F', or
4616 /// - U+0061 'a' ..= U+0066 'f'.
4621 /// let uppercase_a = b'A';
4622 /// let uppercase_g = b'G';
4625 /// let zero = b'0';
4626 /// let percent = b'%';
4627 /// let space = b' ';
4629 /// let esc = 0x1b_u8;
4631 /// assert!(uppercase_a.is_ascii_hexdigit());
4632 /// assert!(!uppercase_g.is_ascii_hexdigit());
4633 /// assert!(a.is_ascii_hexdigit());
4634 /// assert!(!g.is_ascii_hexdigit());
4635 /// assert!(zero.is_ascii_hexdigit());
4636 /// assert!(!percent.is_ascii_hexdigit());
4637 /// assert!(!space.is_ascii_hexdigit());
4638 /// assert!(!lf.is_ascii_hexdigit());
4639 /// assert!(!esc.is_ascii_hexdigit());
4641 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4642 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4644 pub const fn is_ascii_hexdigit(&self) -> bool {
4645 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
4648 /// Checks if the value is an ASCII punctuation character:
4650 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4651 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4652 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4653 /// - U+007B ..= U+007E `{ | } ~`
4658 /// let uppercase_a = b'A';
4659 /// let uppercase_g = b'G';
4662 /// let zero = b'0';
4663 /// let percent = b'%';
4664 /// let space = b' ';
4666 /// let esc = 0x1b_u8;
4668 /// assert!(!uppercase_a.is_ascii_punctuation());
4669 /// assert!(!uppercase_g.is_ascii_punctuation());
4670 /// assert!(!a.is_ascii_punctuation());
4671 /// assert!(!g.is_ascii_punctuation());
4672 /// assert!(!zero.is_ascii_punctuation());
4673 /// assert!(percent.is_ascii_punctuation());
4674 /// assert!(!space.is_ascii_punctuation());
4675 /// assert!(!lf.is_ascii_punctuation());
4676 /// assert!(!esc.is_ascii_punctuation());
4678 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4679 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4681 pub const fn is_ascii_punctuation(&self) -> bool {
4682 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
4685 /// Checks if the value is an ASCII graphic character:
4686 /// U+0021 '!' ..= U+007E '~'.
4691 /// let uppercase_a = b'A';
4692 /// let uppercase_g = b'G';
4695 /// let zero = b'0';
4696 /// let percent = b'%';
4697 /// let space = b' ';
4699 /// let esc = 0x1b_u8;
4701 /// assert!(uppercase_a.is_ascii_graphic());
4702 /// assert!(uppercase_g.is_ascii_graphic());
4703 /// assert!(a.is_ascii_graphic());
4704 /// assert!(g.is_ascii_graphic());
4705 /// assert!(zero.is_ascii_graphic());
4706 /// assert!(percent.is_ascii_graphic());
4707 /// assert!(!space.is_ascii_graphic());
4708 /// assert!(!lf.is_ascii_graphic());
4709 /// assert!(!esc.is_ascii_graphic());
4711 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4712 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4714 pub const fn is_ascii_graphic(&self) -> bool {
4715 matches!(*self, b'!'..=b'~')
4718 /// Checks if the value is an ASCII whitespace character:
4719 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4720 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4722 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4723 /// whitespace][infra-aw]. There are several other definitions in
4724 /// wide use. For instance, [the POSIX locale][pct] includes
4725 /// U+000B VERTICAL TAB as well as all the above characters,
4726 /// but—from the very same specification—[the default rule for
4727 /// "field splitting" in the Bourne shell][bfs] considers *only*
4728 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4730 /// If you are writing a program that will process an existing
4731 /// file format, check what that format's definition of whitespace is
4732 /// before using this function.
4734 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4735 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4736 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4741 /// let uppercase_a = b'A';
4742 /// let uppercase_g = b'G';
4745 /// let zero = b'0';
4746 /// let percent = b'%';
4747 /// let space = b' ';
4749 /// let esc = 0x1b_u8;
4751 /// assert!(!uppercase_a.is_ascii_whitespace());
4752 /// assert!(!uppercase_g.is_ascii_whitespace());
4753 /// assert!(!a.is_ascii_whitespace());
4754 /// assert!(!g.is_ascii_whitespace());
4755 /// assert!(!zero.is_ascii_whitespace());
4756 /// assert!(!percent.is_ascii_whitespace());
4757 /// assert!(space.is_ascii_whitespace());
4758 /// assert!(lf.is_ascii_whitespace());
4759 /// assert!(!esc.is_ascii_whitespace());
4761 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4762 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4764 pub const fn is_ascii_whitespace(&self) -> bool {
4765 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
4768 /// Checks if the value is an ASCII control character:
4769 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4770 /// Note that most ASCII whitespace characters are control
4771 /// characters, but SPACE is not.
4776 /// let uppercase_a = b'A';
4777 /// let uppercase_g = b'G';
4780 /// let zero = b'0';
4781 /// let percent = b'%';
4782 /// let space = b' ';
4784 /// let esc = 0x1b_u8;
4786 /// assert!(!uppercase_a.is_ascii_control());
4787 /// assert!(!uppercase_g.is_ascii_control());
4788 /// assert!(!a.is_ascii_control());
4789 /// assert!(!g.is_ascii_control());
4790 /// assert!(!zero.is_ascii_control());
4791 /// assert!(!percent.is_ascii_control());
4792 /// assert!(!space.is_ascii_control());
4793 /// assert!(lf.is_ascii_control());
4794 /// assert!(esc.is_ascii_control());
4796 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4797 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4799 pub const fn is_ascii_control(&self) -> bool {
4800 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
4806 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4807 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4812 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4813 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4818 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4819 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4820 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4821 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4827 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4828 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4829 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4830 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4831 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4832 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4833 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4837 #[cfg(target_pointer_width = "16")]
4840 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4841 "[0x34, 0x12]", "[0x12, 0x34]",
4842 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4844 #[cfg(target_pointer_width = "32")]
4847 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4848 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4849 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4852 #[cfg(target_pointer_width = "64")]
4855 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4856 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4857 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4858 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4859 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4862 /// A classification of floating point numbers.
4864 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4865 /// their documentation for more.
4867 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4868 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4873 /// use std::num::FpCategory;
4875 /// let num = 12.4_f32;
4876 /// let inf = f32::INFINITY;
4877 /// let zero = 0f32;
4878 /// let sub: f32 = 1.1754942e-38;
4879 /// let nan = f32::NAN;
4881 /// assert_eq!(num.classify(), FpCategory::Normal);
4882 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4883 /// assert_eq!(zero.classify(), FpCategory::Zero);
4884 /// assert_eq!(nan.classify(), FpCategory::Nan);
4885 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4887 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4888 #[stable(feature = "rust1", since = "1.0.0")]
4889 pub enum FpCategory {
4890 /// "Not a Number", often obtained by dividing by zero.
4891 #[stable(feature = "rust1", since = "1.0.0")]
4894 /// Positive or negative infinity.
4895 #[stable(feature = "rust1", since = "1.0.0")]
4898 /// Positive or negative zero.
4899 #[stable(feature = "rust1", since = "1.0.0")]
4902 /// De-normalized floating point representation (less precise than `Normal`).
4903 #[stable(feature = "rust1", since = "1.0.0")]
4906 /// A regular floating point number.
4907 #[stable(feature = "rust1", since = "1.0.0")]
4911 macro_rules! from_str_radix_int_impl {
4913 #[stable(feature = "rust1", since = "1.0.0")]
4914 impl FromStr for $t {
4915 type Err = ParseIntError;
4916 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4917 from_str_radix(src, 10)
4922 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4924 /// The error type returned when a checked integral type conversion fails.
4925 #[stable(feature = "try_from", since = "1.34.0")]
4926 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4927 pub struct TryFromIntError(pub(crate) ());
4929 impl TryFromIntError {
4931 feature = "int_error_internals",
4932 reason = "available through Error trait and this method should \
4933 not be exposed publicly",
4937 pub fn __description(&self) -> &str {
4938 "out of range integral type conversion attempted"
4942 #[stable(feature = "try_from", since = "1.34.0")]
4943 impl fmt::Display for TryFromIntError {
4944 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4945 self.__description().fmt(fmt)
4949 #[stable(feature = "try_from", since = "1.34.0")]
4950 impl From<Infallible> for TryFromIntError {
4951 fn from(x: Infallible) -> TryFromIntError {
4956 #[unstable(feature = "never_type", issue = "35121")]
4957 impl From<!> for TryFromIntError {
4958 fn from(never: !) -> TryFromIntError {
4959 // Match rather than coerce to make sure that code like
4960 // `From<Infallible> for TryFromIntError` above will keep working
4961 // when `Infallible` becomes an alias to `!`.
4967 trait FromStrRadixHelper: PartialOrd + Copy {
4968 fn min_value() -> Self;
4969 fn max_value() -> Self;
4970 fn from_u32(u: u32) -> Self;
4971 fn checked_mul(&self, other: u32) -> Option<Self>;
4972 fn checked_sub(&self, other: u32) -> Option<Self>;
4973 fn checked_add(&self, other: u32) -> Option<Self>;
4977 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4979 fn min_value() -> Self { Self::min_value() }
4981 fn max_value() -> Self { Self::max_value() }
4983 fn from_u32(u: u32) -> Self { u as Self }
4985 fn checked_mul(&self, other: u32) -> Option<Self> {
4986 Self::checked_mul(*self, other as Self)
4989 fn checked_sub(&self, other: u32) -> Option<Self> {
4990 Self::checked_sub(*self, other as Self)
4993 fn checked_add(&self, other: u32) -> Option<Self> {
4994 Self::checked_add(*self, other as Self)
4998 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5000 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5001 use self::IntErrorKind::*;
5002 use self::ParseIntError as PIE;
5005 radix >= 2 && radix <= 36,
5006 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5011 return Err(PIE { kind: Empty });
5014 let is_signed_ty = T::from_u32(0) > T::min_value();
5016 // all valid digits are ascii, so we will just iterate over the utf8 bytes
5017 // and cast them to chars. .to_digit() will safely return None for anything
5018 // other than a valid ascii digit for the given radix, including the first-byte
5019 // of multi-byte sequences
5020 let src = src.as_bytes();
5022 let (is_positive, digits) = match src[0] {
5023 b'+' => (true, &src[1..]),
5024 b'-' if is_signed_ty => (false, &src[1..]),
5028 if digits.is_empty() {
5029 return Err(PIE { kind: Empty });
5032 let mut result = T::from_u32(0);
5034 // The number is positive
5036 let x = match (c as char).to_digit(radix) {
5038 None => return Err(PIE { kind: InvalidDigit }),
5040 result = match result.checked_mul(radix) {
5041 Some(result) => result,
5042 None => return Err(PIE { kind: Overflow }),
5044 result = match result.checked_add(x) {
5045 Some(result) => result,
5046 None => return Err(PIE { kind: Overflow }),
5050 // The number is negative
5052 let x = match (c as char).to_digit(radix) {
5054 None => return Err(PIE { kind: InvalidDigit }),
5056 result = match result.checked_mul(radix) {
5057 Some(result) => result,
5058 None => return Err(PIE { kind: Underflow }),
5060 result = match result.checked_sub(x) {
5061 Some(result) => result,
5062 None => return Err(PIE { kind: Underflow }),
5069 /// An error which can be returned when parsing an integer.
5071 /// This error is used as the error type for the `from_str_radix()` functions
5072 /// on the primitive integer types, such as [`i8::from_str_radix`].
5074 /// # Potential causes
5076 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5077 /// in the string e.g., when it is obtained from the standard input.
5078 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5080 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5081 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5082 #[derive(Debug, Clone, PartialEq, Eq)]
5083 #[stable(feature = "rust1", since = "1.0.0")]
5084 pub struct ParseIntError {
5088 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5090 feature = "int_error_matching",
5091 reason = "it can be useful to match errors when making error messages \
5092 for integer parsing",
5095 #[derive(Debug, Clone, PartialEq, Eq)]
5097 pub enum IntErrorKind {
5098 /// Value being parsed is empty.
5100 /// Among other causes, this variant will be constructed when parsing an empty string.
5102 /// Contains an invalid digit.
5104 /// Among other causes, this variant will be constructed when parsing a string that
5105 /// contains a letter.
5107 /// Integer is too large to store in target integer type.
5109 /// Integer is too small to store in target integer type.
5113 /// This variant will be emitted when the parsing string has a value of zero, which
5114 /// would be illegal for non-zero types.
5118 impl ParseIntError {
5119 /// Outputs the detailed cause of parsing an integer failing.
5121 feature = "int_error_matching",
5122 reason = "it can be useful to match errors when making error messages \
5123 for integer parsing",
5126 pub fn kind(&self) -> &IntErrorKind {
5130 feature = "int_error_internals",
5131 reason = "available through Error trait and this method should \
5132 not be exposed publicly",
5136 pub fn __description(&self) -> &str {
5138 IntErrorKind::Empty => "cannot parse integer from empty string",
5139 IntErrorKind::InvalidDigit => "invalid digit found in string",
5140 IntErrorKind::Overflow => "number too large to fit in target type",
5141 IntErrorKind::Underflow => "number too small to fit in target type",
5142 IntErrorKind::Zero => "number would be zero for non-zero type",
5147 #[stable(feature = "rust1", since = "1.0.0")]
5148 impl fmt::Display for ParseIntError {
5149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5150 self.__description().fmt(f)
5154 #[stable(feature = "rust1", since = "1.0.0")]
5155 pub use crate::num::dec2flt::ParseFloatError;