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!(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_stable(feature = "const_int_conversion", since = "1.44.0")]
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_stable(feature = "const_int_conversion", since = "1.44.0")]
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_stable(feature = "const_int_conversion", since = "1.44.0")]
2213 // SAFETY: const sound because integers are plain old datatypes so we can always
2214 // transmute them to arrays of bytes
2215 #[allow_internal_unstable(const_fn_union)]
2217 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2221 bytes: [u8; mem::size_of::<$SelfT>()],
2223 // SAFETY: integers are plain old datatypes so we can always transmute them to
2225 unsafe { Bytes { val: self }.bytes }
2230 concat!("Create an integer value from its representation as a byte array in
2238 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2239 assert_eq!(value, ", $swap_op, ");
2242 When starting from a slice rather than an array, fallible conversion APIs can be used:
2245 use std::convert::TryInto;
2247 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2248 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2250 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2253 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2254 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2256 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2257 Self::from_be(Self::from_ne_bytes(bytes))
2263 Create an integer value from its representation as a byte array in
2271 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2272 assert_eq!(value, ", $swap_op, ");
2275 When starting from a slice rather than an array, fallible conversion APIs can be used:
2278 use std::convert::TryInto;
2280 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2281 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2283 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2286 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2287 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2289 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2290 Self::from_le(Self::from_ne_bytes(bytes))
2295 concat!("Create an integer value from its memory representation as a byte
2296 array in native endianness.
2298 As the target platform's native endianness is used, portable code
2299 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2300 appropriate instead.
2302 [`from_be_bytes`]: #method.from_be_bytes
2303 [`from_le_bytes`]: #method.from_le_bytes
2310 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2315 assert_eq!(value, ", $swap_op, ");
2318 When starting from a slice rather than an array, fallible conversion APIs can be used:
2321 use std::convert::TryInto;
2323 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2324 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2326 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2329 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2330 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2331 // SAFETY: const sound because integers are plain old datatypes so we can always
2332 // transmute to them
2333 #[allow_internal_unstable(const_fn_union)]
2335 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2339 bytes: [u8; mem::size_of::<$SelfT>()],
2341 // SAFETY: integers are plain old datatypes so we can always transmute to them
2342 unsafe { Bytes { bytes }.val }
2347 concat!("**This method is soft-deprecated.**
2349 Although using it won’t cause compilation warning,
2350 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
2352 Returns the smallest value that can be represented by this integer type."),
2353 #[stable(feature = "rust1", since = "1.0.0")]
2356 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2357 pub const fn min_value() -> Self {
2363 concat!("**This method is soft-deprecated.**
2365 Although using it won’t cause compilation warning,
2366 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
2368 Returns the largest value that can be represented by this integer type."),
2369 #[stable(feature = "rust1", since = "1.0.0")]
2372 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2373 pub const fn max_value() -> Self {
2382 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2383 "[0x12]", "[0x12]", "", "" }
2388 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2389 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2394 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2395 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2396 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2401 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2402 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2403 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2404 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2409 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2410 170141183460469231731687303715884105727, "", "", 16,
2411 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2412 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2413 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2414 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2415 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2416 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2419 #[cfg(target_pointer_width = "16")]
2422 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2423 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2424 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2427 #[cfg(target_pointer_width = "32")]
2430 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2431 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2432 "[0x12, 0x34, 0x56, 0x78]",
2433 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2436 #[cfg(target_pointer_width = "64")]
2439 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2440 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2441 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2442 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2443 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2446 macro_rules! uint_impl {
2447 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2448 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2449 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2450 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2452 concat!("The smallest value that can be represented by this integer type.
2459 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, 0);", $EndFeature, "
2461 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2462 pub const MIN: Self = 0;
2466 concat!("The largest value that can be represented by this integer type.
2473 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");",
2476 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2477 pub const MAX: Self = !0;
2481 concat!("Converts a string slice in a given base to an integer.
2483 The string is expected to be an optional `+` sign
2485 Leading and trailing whitespace represent an error.
2486 Digits are a subset of these characters, depending on `radix`:
2494 This function panics if `radix` is not in the range from 2 to 36.
2501 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2504 #[stable(feature = "rust1", since = "1.0.0")]
2505 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2506 from_str_radix(src, radix)
2511 concat!("Returns the number of ones in the binary representation of `self`.
2518 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2520 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2522 #[stable(feature = "rust1", since = "1.0.0")]
2523 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2525 pub const fn count_ones(self) -> u32 {
2526 intrinsics::ctpop(self as $ActualT) as u32
2531 concat!("Returns the number of zeros in the binary representation of `self`.
2538 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);", $EndFeature, "
2540 #[stable(feature = "rust1", since = "1.0.0")]
2541 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2543 pub const fn count_zeros(self) -> u32 {
2544 (!self).count_ones()
2549 concat!("Returns the number of leading zeros in the binary representation of `self`.
2556 ", $Feature, "let n = ", stringify!($SelfT), "::MAX >> 2;
2558 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2560 #[stable(feature = "rust1", since = "1.0.0")]
2561 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2563 pub const fn leading_zeros(self) -> u32 {
2564 intrinsics::ctlz(self as $ActualT) as u32
2569 concat!("Returns the number of trailing zeros in the binary representation
2577 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2579 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2581 #[stable(feature = "rust1", since = "1.0.0")]
2582 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2584 pub const fn trailing_zeros(self) -> u32 {
2585 intrinsics::cttz(self) as u32
2590 concat!("Returns the number of leading ones in the binary representation of `self`.
2597 ", $Feature, "#![feature(leading_trailing_ones)]
2598 let n = !(", stringify!($SelfT), "::MAX >> 2);
2600 assert_eq!(n.leading_ones(), 2);", $EndFeature, "
2602 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2604 pub const fn leading_ones(self) -> u32 {
2605 (!self).leading_zeros()
2610 concat!("Returns the number of trailing ones in the binary representation
2618 ", $Feature, "#![feature(leading_trailing_ones)]
2619 let n = 0b1010111", stringify!($SelfT), ";
2621 assert_eq!(n.trailing_ones(), 3);", $EndFeature, "
2623 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2625 pub const fn trailing_ones(self) -> u32 {
2626 (!self).trailing_zeros()
2631 concat!("Shifts the bits to the left by a specified amount, `n`,
2632 wrapping the truncated bits to the end of the resulting integer.
2634 Please note this isn't the same operation as the `<<` shifting operator!
2641 let n = ", $rot_op, stringify!($SelfT), ";
2642 let m = ", $rot_result, ";
2644 assert_eq!(n.rotate_left(", $rot, "), m);
2646 #[stable(feature = "rust1", since = "1.0.0")]
2647 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2648 #[must_use = "this returns the result of the operation, \
2649 without modifying the original"]
2651 pub const fn rotate_left(self, n: u32) -> Self {
2652 intrinsics::rotate_left(self, n as $SelfT)
2657 concat!("Shifts the bits to the right by a specified amount, `n`,
2658 wrapping the truncated bits to the beginning of the resulting
2661 Please note this isn't the same operation as the `>>` shifting operator!
2668 let n = ", $rot_result, stringify!($SelfT), ";
2669 let m = ", $rot_op, ";
2671 assert_eq!(n.rotate_right(", $rot, "), m);
2673 #[stable(feature = "rust1", since = "1.0.0")]
2674 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2675 #[must_use = "this returns the result of the operation, \
2676 without modifying the original"]
2678 pub const fn rotate_right(self, n: u32) -> Self {
2679 intrinsics::rotate_right(self, n as $SelfT)
2685 Reverses the byte order of the integer.
2692 let n = ", $swap_op, stringify!($SelfT), ";
2693 let m = n.swap_bytes();
2695 assert_eq!(m, ", $swapped, ");
2697 #[stable(feature = "rust1", since = "1.0.0")]
2698 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2700 pub const fn swap_bytes(self) -> Self {
2701 intrinsics::bswap(self as $ActualT) as Self
2706 concat!("Reverses the bit pattern of the integer.
2713 let n = ", $swap_op, stringify!($SelfT), ";
2714 let m = n.reverse_bits();
2716 assert_eq!(m, ", $reversed, ");
2718 #[stable(feature = "reverse_bits", since = "1.37.0")]
2719 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2722 pub const fn reverse_bits(self) -> Self {
2723 intrinsics::bitreverse(self as $ActualT) as Self
2728 concat!("Converts an integer from big endian to the target's endianness.
2730 On big endian this is a no-op. On little endian the bytes are
2738 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2740 if cfg!(target_endian = \"big\") {
2741 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2743 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2746 #[stable(feature = "rust1", since = "1.0.0")]
2747 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2749 pub const fn from_be(x: Self) -> Self {
2750 #[cfg(target_endian = "big")]
2754 #[cfg(not(target_endian = "big"))]
2762 concat!("Converts an integer from little endian to the target's endianness.
2764 On little endian this is a no-op. On big endian the bytes are
2772 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2774 if cfg!(target_endian = \"little\") {
2775 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2777 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2780 #[stable(feature = "rust1", since = "1.0.0")]
2781 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2783 pub const fn from_le(x: Self) -> Self {
2784 #[cfg(target_endian = "little")]
2788 #[cfg(not(target_endian = "little"))]
2796 concat!("Converts `self` to big endian from the target's endianness.
2798 On big endian this is a no-op. On little endian the bytes are
2806 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2808 if cfg!(target_endian = \"big\") {
2809 assert_eq!(n.to_be(), n)
2811 assert_eq!(n.to_be(), n.swap_bytes())
2814 #[stable(feature = "rust1", since = "1.0.0")]
2815 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2817 pub const fn to_be(self) -> Self { // or not to be?
2818 #[cfg(target_endian = "big")]
2822 #[cfg(not(target_endian = "big"))]
2830 concat!("Converts `self` to little endian from the target's endianness.
2832 On little endian this is a no-op. On big endian the bytes are
2840 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2842 if cfg!(target_endian = \"little\") {
2843 assert_eq!(n.to_le(), n)
2845 assert_eq!(n.to_le(), n.swap_bytes())
2848 #[stable(feature = "rust1", since = "1.0.0")]
2849 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2851 pub const fn to_le(self) -> Self {
2852 #[cfg(target_endian = "little")]
2856 #[cfg(not(target_endian = "little"))]
2864 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2865 if overflow occurred.
2872 ", $Feature, "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
2873 "Some(", stringify!($SelfT), "::MAX - 1));
2874 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);", $EndFeature, "
2876 #[stable(feature = "rust1", since = "1.0.0")]
2877 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2878 #[must_use = "this returns the result of the operation, \
2879 without modifying the original"]
2881 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
2882 let (a, b) = self.overflowing_add(rhs);
2883 if b {None} else {Some(a)}
2888 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2889 `None` if overflow occurred.
2896 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2897 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2899 #[stable(feature = "rust1", since = "1.0.0")]
2900 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2901 #[must_use = "this returns the result of the operation, \
2902 without modifying the original"]
2904 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
2905 let (a, b) = self.overflowing_sub(rhs);
2906 if b {None} else {Some(a)}
2911 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2912 `None` if overflow occurred.
2919 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2920 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);", $EndFeature, "
2922 #[stable(feature = "rust1", since = "1.0.0")]
2923 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2924 #[must_use = "this returns the result of the operation, \
2925 without modifying the original"]
2927 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
2928 let (a, b) = self.overflowing_mul(rhs);
2929 if b {None} else {Some(a)}
2934 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2942 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2943 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2945 #[stable(feature = "rust1", since = "1.0.0")]
2946 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2947 #[must_use = "this returns the result of the operation, \
2948 without modifying the original"]
2950 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
2953 // SAFETY: div by zero has been checked above and unsigned types have no other
2954 // failure modes for division
2955 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2961 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2969 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
2970 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
2972 #[stable(feature = "euclidean_division", since = "1.38.0")]
2973 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2974 #[must_use = "this returns the result of the operation, \
2975 without modifying the original"]
2977 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
2981 Some(self.div_euclid(rhs))
2988 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2996 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2997 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2999 #[stable(feature = "wrapping", since = "1.7.0")]
3000 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3001 #[must_use = "this returns the result of the operation, \
3002 without modifying the original"]
3004 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
3008 // SAFETY: div by zero has been checked above and unsigned types have no other
3009 // failure modes for division
3010 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3016 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3024 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3025 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3027 #[stable(feature = "euclidean_division", since = "1.38.0")]
3028 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3029 #[must_use = "this returns the result of the operation, \
3030 without modifying the original"]
3032 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3036 Some(self.rem_euclid(rhs))
3042 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3045 Note that negating any positive integer will overflow.
3052 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3053 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3055 #[stable(feature = "wrapping", since = "1.7.0")]
3056 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3058 pub const fn checked_neg(self) -> Option<Self> {
3059 let (a, b) = self.overflowing_neg();
3060 if b {None} else {Some(a)}
3065 concat!("Checked shift left. Computes `self << rhs`, returning `None`
3066 if `rhs` is larger than or equal to the number of bits in `self`.
3073 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3074 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3076 #[stable(feature = "wrapping", since = "1.7.0")]
3077 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3078 #[must_use = "this returns the result of the operation, \
3079 without modifying the original"]
3081 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
3082 let (a, b) = self.overflowing_shl(rhs);
3083 if b {None} else {Some(a)}
3088 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3089 if `rhs` is larger than or equal to the number of bits in `self`.
3096 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3097 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3099 #[stable(feature = "wrapping", since = "1.7.0")]
3100 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3101 #[must_use = "this returns the result of the operation, \
3102 without modifying the original"]
3104 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
3105 let (a, b) = self.overflowing_shr(rhs);
3106 if b {None} else {Some(a)}
3111 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3119 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3120 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);", $EndFeature, "
3122 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3123 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3124 #[must_use = "this returns the result of the operation, \
3125 without modifying the original"]
3127 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
3128 let mut base = self;
3129 let mut acc: Self = 1;
3133 acc = try_opt!(acc.checked_mul(base));
3136 base = try_opt!(base.checked_mul(base));
3139 // Deal with the final bit of the exponent separately, since
3140 // squaring the base afterwards is not necessary and may cause a
3141 // needless overflow.
3143 acc = try_opt!(acc.checked_mul(base));
3151 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3152 the numeric bounds instead of overflowing.
3159 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3160 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
3163 #[stable(feature = "rust1", since = "1.0.0")]
3164 #[must_use = "this returns the result of the operation, \
3165 without modifying the original"]
3166 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3168 pub const fn saturating_add(self, rhs: Self) -> Self {
3169 intrinsics::saturating_add(self, rhs)
3174 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3175 at the numeric bounds instead of overflowing.
3182 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3183 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3185 #[stable(feature = "rust1", since = "1.0.0")]
3186 #[must_use = "this returns the result of the operation, \
3187 without modifying the original"]
3188 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3190 pub const fn saturating_sub(self, rhs: Self) -> Self {
3191 intrinsics::saturating_sub(self, rhs)
3196 concat!("Saturating integer multiplication. Computes `self * rhs`,
3197 saturating at the numeric bounds instead of overflowing.
3205 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3206 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3207 "::MAX);", $EndFeature, "
3209 #[stable(feature = "wrapping", since = "1.7.0")]
3210 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3211 #[must_use = "this returns the result of the operation, \
3212 without modifying the original"]
3214 pub const fn saturating_mul(self, rhs: Self) -> Self {
3215 match self.checked_mul(rhs) {
3217 None => Self::max_value(),
3223 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3224 saturating at the numeric bounds instead of overflowing.
3232 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3233 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3236 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3237 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3238 #[must_use = "this returns the result of the operation, \
3239 without modifying the original"]
3241 pub const fn saturating_pow(self, exp: u32) -> Self {
3242 match self.checked_pow(exp) {
3244 None => Self::max_value(),
3250 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3251 wrapping around at the boundary of the type.
3258 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3259 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);",
3262 #[stable(feature = "rust1", since = "1.0.0")]
3263 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3264 #[must_use = "this returns the result of the operation, \
3265 without modifying the original"]
3267 pub const fn wrapping_add(self, rhs: Self) -> Self {
3268 intrinsics::wrapping_add(self, rhs)
3273 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3274 wrapping around at the boundary of the type.
3281 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3282 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);",
3285 #[stable(feature = "rust1", since = "1.0.0")]
3286 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3287 #[must_use = "this returns the result of the operation, \
3288 without modifying the original"]
3290 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3291 intrinsics::wrapping_sub(self, rhs)
3295 /// Wrapping (modular) multiplication. Computes `self *
3296 /// rhs`, wrapping around at the boundary of the type.
3302 /// Please note that this example is shared between integer types.
3303 /// Which explains why `u8` is used here.
3306 /// assert_eq!(10u8.wrapping_mul(12), 120);
3307 /// assert_eq!(25u8.wrapping_mul(12), 44);
3309 #[stable(feature = "rust1", since = "1.0.0")]
3310 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3311 #[must_use = "this returns the result of the operation, \
3312 without modifying the original"]
3314 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3315 intrinsics::wrapping_mul(self, rhs)
3319 concat!("Wrapping (modular) division. Computes `self / rhs`.
3320 Wrapped division on unsigned types is just normal division.
3321 There's no way wrapping could ever happen.
3322 This function exists, so that all operations
3323 are accounted for in the wrapping operations.
3330 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3332 #[stable(feature = "num_wrapping", since = "1.2.0")]
3333 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3334 #[must_use = "this returns the result of the operation, \
3335 without modifying the original"]
3337 pub const fn wrapping_div(self, rhs: Self) -> Self {
3343 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3344 Wrapped division on unsigned types is just normal division.
3345 There's no way wrapping could ever happen.
3346 This function exists, so that all operations
3347 are accounted for in the wrapping operations.
3348 Since, for the positive integers, all common
3349 definitions of division are equal, this
3350 is exactly equal to `self.wrapping_div(rhs)`.
3357 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3359 #[stable(feature = "euclidean_division", since = "1.38.0")]
3360 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3361 #[must_use = "this returns the result of the operation, \
3362 without modifying the original"]
3364 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
3370 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3371 Wrapped remainder calculation on unsigned types is
3372 just the regular remainder calculation.
3373 There's no way wrapping could ever happen.
3374 This function exists, so that all operations
3375 are accounted for in the wrapping operations.
3382 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3384 #[stable(feature = "num_wrapping", since = "1.2.0")]
3385 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3386 #[must_use = "this returns the result of the operation, \
3387 without modifying the original"]
3389 pub const fn wrapping_rem(self, rhs: Self) -> Self {
3395 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3396 Wrapped modulo calculation on unsigned types is
3397 just the regular remainder calculation.
3398 There's no way wrapping could ever happen.
3399 This function exists, so that all operations
3400 are accounted for in the wrapping operations.
3401 Since, for the positive integers, all common
3402 definitions of division are equal, this
3403 is exactly equal to `self.wrapping_rem(rhs)`.
3410 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3412 #[stable(feature = "euclidean_division", since = "1.38.0")]
3413 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3414 #[must_use = "this returns the result of the operation, \
3415 without modifying the original"]
3417 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3422 /// Wrapping (modular) negation. Computes `-self`,
3423 /// wrapping around at the boundary of the type.
3425 /// Since unsigned types do not have negative equivalents
3426 /// all applications of this function will wrap (except for `-0`).
3427 /// For values smaller than the corresponding signed type's maximum
3428 /// the result is the same as casting the corresponding signed value.
3429 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3430 /// `MAX` is the corresponding signed type's maximum.
3436 /// Please note that this example is shared between integer types.
3437 /// Which explains why `i8` is used here.
3440 /// assert_eq!(100i8.wrapping_neg(), -100);
3441 /// assert_eq!((-128i8).wrapping_neg(), -128);
3443 #[stable(feature = "num_wrapping", since = "1.2.0")]
3444 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3446 pub const fn wrapping_neg(self) -> Self {
3447 self.overflowing_neg().0
3451 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3452 where `mask` removes any high-order bits of `rhs` that
3453 would cause the shift to exceed the bitwidth of the type.
3455 Note that this is *not* the same as a rotate-left; the
3456 RHS of a wrapping shift-left is restricted to the range
3457 of the type, rather than the bits shifted out of the LHS
3458 being returned to the other end. The primitive integer
3459 types all implement a `rotate_left` function, which may
3460 be what you want instead.
3467 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3468 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3470 #[stable(feature = "num_wrapping", since = "1.2.0")]
3471 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3472 #[must_use = "this returns the result of the operation, \
3473 without modifying the original"]
3475 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3476 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3479 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3485 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3486 where `mask` removes any high-order bits of `rhs` that
3487 would cause the shift to exceed the bitwidth of the type.
3489 Note that this is *not* the same as a rotate-right; the
3490 RHS of a wrapping shift-right is restricted to the range
3491 of the type, rather than the bits shifted out of the LHS
3492 being returned to the other end. The primitive integer
3493 types all implement a `rotate_right` function, which may
3494 be what you want instead.
3501 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3502 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3504 #[stable(feature = "num_wrapping", since = "1.2.0")]
3505 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3506 #[must_use = "this returns the result of the operation, \
3507 without modifying the original"]
3509 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3510 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3513 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3519 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3520 wrapping around at the boundary of the type.
3527 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3528 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3530 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3531 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3532 #[must_use = "this returns the result of the operation, \
3533 without modifying the original"]
3535 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
3536 let mut base = self;
3537 let mut acc: Self = 1;
3541 acc = acc.wrapping_mul(base);
3544 base = base.wrapping_mul(base);
3547 // Deal with the final bit of the exponent separately, since
3548 // squaring the base afterwards is not necessary and may cause a
3549 // needless overflow.
3551 acc = acc.wrapping_mul(base);
3559 concat!("Calculates `self` + `rhs`
3561 Returns a tuple of the addition along with a boolean indicating
3562 whether an arithmetic overflow would occur. If an overflow would
3563 have occurred then the wrapped value is returned.
3571 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3572 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3574 #[stable(feature = "wrapping", since = "1.7.0")]
3575 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3576 #[must_use = "this returns the result of the operation, \
3577 without modifying the original"]
3579 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3580 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3586 concat!("Calculates `self` - `rhs`
3588 Returns a tuple of the subtraction along with a boolean indicating
3589 whether an arithmetic overflow would occur. If an overflow would
3590 have occurred then the wrapped value is returned.
3598 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3599 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3602 #[stable(feature = "wrapping", since = "1.7.0")]
3603 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3604 #[must_use = "this returns the result of the operation, \
3605 without modifying the original"]
3607 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3608 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3613 /// Calculates the multiplication of `self` and `rhs`.
3615 /// Returns a tuple of the multiplication along with a boolean
3616 /// indicating whether an arithmetic overflow would occur. If an
3617 /// overflow would have occurred then the wrapped value is returned.
3623 /// Please note that this example is shared between integer types.
3624 /// Which explains why `u32` is used here.
3627 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3628 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3630 #[stable(feature = "wrapping", since = "1.7.0")]
3631 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3632 #[must_use = "this returns the result of the operation, \
3633 without modifying the original"]
3635 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3636 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3641 concat!("Calculates the divisor when `self` is divided by `rhs`.
3643 Returns a tuple of the divisor along with a boolean indicating
3644 whether an arithmetic overflow would occur. Note that for unsigned
3645 integers overflow never occurs, so the second value is always
3650 This function will panic if `rhs` is 0.
3657 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3660 #[stable(feature = "wrapping", since = "1.7.0")]
3661 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3662 #[must_use = "this returns the result of the operation, \
3663 without modifying the original"]
3664 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3670 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3672 Returns a tuple of the divisor along with a boolean indicating
3673 whether an arithmetic overflow would occur. Note that for unsigned
3674 integers overflow never occurs, so the second value is always
3676 Since, for the positive integers, all common
3677 definitions of division are equal, this
3678 is exactly equal to `self.overflowing_div(rhs)`.
3682 This function will panic if `rhs` is 0.
3689 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3692 #[stable(feature = "euclidean_division", since = "1.38.0")]
3693 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3694 #[must_use = "this returns the result of the operation, \
3695 without modifying the original"]
3696 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3702 concat!("Calculates the remainder when `self` is divided by `rhs`.
3704 Returns a tuple of the remainder after dividing along with a boolean
3705 indicating whether an arithmetic overflow would occur. Note that for
3706 unsigned integers overflow never occurs, so the second value is
3711 This function will panic if `rhs` is 0.
3718 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3721 #[stable(feature = "wrapping", since = "1.7.0")]
3722 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3723 #[must_use = "this returns the result of the operation, \
3724 without modifying the original"]
3725 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3731 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3733 Returns a tuple of the modulo after dividing along with a boolean
3734 indicating whether an arithmetic overflow would occur. Note that for
3735 unsigned integers overflow never occurs, so the second value is
3737 Since, for the positive integers, all common
3738 definitions of division are equal, this operation
3739 is exactly equal to `self.overflowing_rem(rhs)`.
3743 This function will panic if `rhs` is 0.
3750 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3753 #[stable(feature = "euclidean_division", since = "1.38.0")]
3754 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3755 #[must_use = "this returns the result of the operation, \
3756 without modifying the original"]
3757 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3763 concat!("Negates self in an overflowing fashion.
3765 Returns `!self + 1` using wrapping operations to return the value
3766 that represents the negation of this unsigned value. Note that for
3767 positive unsigned values overflow always occurs, but negating 0 does
3775 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3776 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3777 ", true));", $EndFeature, "
3780 #[stable(feature = "wrapping", since = "1.7.0")]
3781 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3782 pub const fn overflowing_neg(self) -> (Self, bool) {
3783 ((!self).wrapping_add(1), self != 0)
3788 concat!("Shifts self left by `rhs` bits.
3790 Returns a tuple of the shifted version of self along with a boolean
3791 indicating whether the shift value was larger than or equal to the
3792 number of bits. If the shift value is too large, then value is
3793 masked (N-1) where N is the number of bits, and this value is then
3794 used to perform the shift.
3801 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3802 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3804 #[stable(feature = "wrapping", since = "1.7.0")]
3805 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3806 #[must_use = "this returns the result of the operation, \
3807 without modifying the original"]
3809 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3810 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3815 concat!("Shifts self right by `rhs` bits.
3817 Returns a tuple of the shifted version of self along with a boolean
3818 indicating whether the shift value was larger than or equal to the
3819 number of bits. If the shift value is too large, then value is
3820 masked (N-1) where N is the number of bits, and this value is then
3821 used to perform the shift.
3828 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3829 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3831 #[stable(feature = "wrapping", since = "1.7.0")]
3832 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3833 #[must_use = "this returns the result of the operation, \
3834 without modifying the original"]
3836 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3837 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3842 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3844 Returns a tuple of the exponentiation along with a bool indicating
3845 whether an overflow happened.
3852 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3853 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3855 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3856 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3857 #[must_use = "this returns the result of the operation, \
3858 without modifying the original"]
3860 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3861 let mut base = self;
3862 let mut acc: Self = 1;
3863 let mut overflown = false;
3864 // Scratch space for storing results of overflowing_mul.
3869 r = acc.overflowing_mul(base);
3874 r = base.overflowing_mul(base);
3879 // Deal with the final bit of the exponent separately, since
3880 // squaring the base afterwards is not necessary and may cause a
3881 // needless overflow.
3883 r = acc.overflowing_mul(base);
3893 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3900 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3902 #[stable(feature = "rust1", since = "1.0.0")]
3903 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3904 #[must_use = "this returns the result of the operation, \
3905 without modifying the original"]
3907 #[rustc_inherit_overflow_checks]
3908 pub const fn pow(self, mut exp: u32) -> Self {
3909 let mut base = self;
3920 // Deal with the final bit of the exponent separately, since
3921 // squaring the base afterwards is not necessary and may cause a
3922 // needless overflow.
3932 concat!("Performs Euclidean division.
3934 Since, for the positive integers, all common
3935 definitions of division are equal, this
3936 is exactly equal to `self / rhs`.
3940 This function will panic if `rhs` is 0.
3947 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
3949 #[stable(feature = "euclidean_division", since = "1.38.0")]
3950 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3951 #[must_use = "this returns the result of the operation, \
3952 without modifying the original"]
3954 #[rustc_inherit_overflow_checks]
3955 pub const fn div_euclid(self, rhs: Self) -> Self {
3962 concat!("Calculates the least remainder of `self (mod rhs)`.
3964 Since, for the positive integers, all common
3965 definitions of division are equal, this
3966 is exactly equal to `self % rhs`.
3970 This function will panic if `rhs` is 0.
3977 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
3979 #[stable(feature = "euclidean_division", since = "1.38.0")]
3980 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3981 #[must_use = "this returns the result of the operation, \
3982 without modifying the original"]
3984 #[rustc_inherit_overflow_checks]
3985 pub const fn rem_euclid(self, rhs: Self) -> Self {
3991 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3998 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3999 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
4001 #[stable(feature = "rust1", since = "1.0.0")]
4002 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
4004 pub const fn is_power_of_two(self) -> bool {
4005 self.count_ones() == 1
4009 // Returns one less than next power of two.
4010 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
4012 // 8u8.one_less_than_next_power_of_two() == 7
4013 // 6u8.one_less_than_next_power_of_two() == 7
4015 // This method cannot overflow, as in the `next_power_of_two`
4016 // overflow cases it instead ends up returning the maximum value
4017 // of the type, and can return 0 for 0.
4019 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4020 const fn one_less_than_next_power_of_two(self) -> Self {
4021 if self <= 1 { return 0; }
4024 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4025 // That means the shift is always in-bounds, and some processors
4026 // (such as intel pre-haswell) have more efficient ctlz
4027 // intrinsics when the argument is non-zero.
4028 let z = unsafe { intrinsics::ctlz_nonzero(p) };
4029 <$SelfT>::max_value() >> z
4033 concat!("Returns the smallest power of two greater than or equal to `self`.
4035 When return value overflows (i.e., `self > (1 << (N-1))` for type
4036 `uN`), it panics in debug mode and return value is wrapped to 0 in
4037 release mode (the only situation in which method can return 0).
4044 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4045 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4047 #[stable(feature = "rust1", since = "1.0.0")]
4048 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4050 #[rustc_inherit_overflow_checks]
4051 pub const fn next_power_of_two(self) -> Self {
4052 self.one_less_than_next_power_of_two() + 1
4057 concat!("Returns the smallest power of two greater than or equal to `n`. If
4058 the next power of two is greater than the type's maximum value,
4059 `None` is returned, otherwise the power of two is wrapped in `Some`.
4066 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4067 ".checked_next_power_of_two(), Some(2));
4068 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4069 assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);",
4073 #[stable(feature = "rust1", since = "1.0.0")]
4074 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4075 pub const fn checked_next_power_of_two(self) -> Option<Self> {
4076 self.one_less_than_next_power_of_two().checked_add(1)
4081 concat!("Returns the smallest power of two greater than or equal to `n`. If
4082 the next power of two is greater than the type's maximum value,
4083 the return value is wrapped to `0`.
4090 #![feature(wrapping_next_power_of_two)]
4092 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4093 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4094 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);",
4097 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4098 reason = "needs decision on wrapping behaviour")]
4099 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4100 pub const fn wrapping_next_power_of_two(self) -> Self {
4101 self.one_less_than_next_power_of_two().wrapping_add(1)
4106 concat!("Return the memory representation of this integer as a byte array in
4107 big-endian (network) byte order.
4114 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4115 assert_eq!(bytes, ", $be_bytes, ");
4117 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4118 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4120 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4121 self.to_be().to_ne_bytes()
4126 concat!("Return the memory representation of this integer as a byte array in
4127 little-endian byte order.
4134 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4135 assert_eq!(bytes, ", $le_bytes, ");
4137 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4138 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4140 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4141 self.to_le().to_ne_bytes()
4147 Return the memory representation of this integer as a byte array in
4150 As the target platform's native endianness is used, portable code
4151 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4156 [`to_be_bytes`]: #method.to_be_bytes
4157 [`to_le_bytes`]: #method.to_le_bytes
4162 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4165 if cfg!(target_endian = \"big\") {
4172 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4173 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4174 // SAFETY: const sound because integers are plain old datatypes so we can always
4175 // transmute them to arrays of bytes
4176 #[allow_internal_unstable(const_fn_union)]
4178 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4182 bytes: [u8; mem::size_of::<$SelfT>()],
4184 // SAFETY: integers are plain old datatypes so we can always transmute them to
4186 unsafe { Bytes { val: self }.bytes }
4191 concat!("Create an integer value from its representation as a byte array in
4199 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4200 assert_eq!(value, ", $swap_op, ");
4203 When starting from a slice rather than an array, fallible conversion APIs can be used:
4206 use std::convert::TryInto;
4208 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4209 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4211 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4214 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4215 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4217 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4218 Self::from_be(Self::from_ne_bytes(bytes))
4224 Create an integer value from its representation as a byte array in
4232 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4233 assert_eq!(value, ", $swap_op, ");
4236 When starting from a slice rather than an array, fallible conversion APIs can be used:
4239 use std::convert::TryInto;
4241 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4242 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4244 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4247 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4248 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4250 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4251 Self::from_le(Self::from_ne_bytes(bytes))
4256 concat!("Create an integer value from its memory representation as a byte
4257 array in native endianness.
4259 As the target platform's native endianness is used, portable code
4260 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4261 appropriate instead.
4263 [`from_be_bytes`]: #method.from_be_bytes
4264 [`from_le_bytes`]: #method.from_le_bytes
4271 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4276 assert_eq!(value, ", $swap_op, ");
4279 When starting from a slice rather than an array, fallible conversion APIs can be used:
4282 use std::convert::TryInto;
4284 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4285 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4287 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4290 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4291 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4292 // SAFETY: const sound because integers are plain old datatypes so we can always
4293 // transmute to them
4294 #[allow_internal_unstable(const_fn_union)]
4296 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4300 bytes: [u8; mem::size_of::<$SelfT>()],
4302 // SAFETY: integers are plain old datatypes so we can always transmute to them
4303 unsafe { Bytes { bytes }.val }
4308 concat!("**This method is soft-deprecated.**
4310 Although using it won’t cause compilation warning,
4311 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
4313 Returns the smallest value that can be represented by this integer type."),
4314 #[stable(feature = "rust1", since = "1.0.0")]
4317 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4318 pub const fn min_value() -> Self { Self::MIN }
4322 concat!("**This method is soft-deprecated.**
4324 Although using it won’t cause compilation warning,
4325 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
4327 Returns the largest value that can be represented by this integer type."),
4328 #[stable(feature = "rust1", since = "1.0.0")]
4331 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4332 pub const fn max_value() -> Self { Self::MAX }
4339 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4342 /// Checks if the value is within the ASCII range.
4347 /// let ascii = 97u8;
4348 /// let non_ascii = 150u8;
4350 /// assert!(ascii.is_ascii());
4351 /// assert!(!non_ascii.is_ascii());
4353 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4354 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.43.0")]
4356 pub const fn is_ascii(&self) -> bool {
4360 /// Makes a copy of the value in its ASCII upper case equivalent.
4362 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4363 /// but non-ASCII letters are unchanged.
4365 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4370 /// let lowercase_a = 97u8;
4372 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4375 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4376 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4378 pub fn to_ascii_uppercase(&self) -> u8 {
4379 // Unset the fifth bit if this is a lowercase letter
4380 *self & !((self.is_ascii_lowercase() as u8) << 5)
4383 /// Makes a copy of the value in its ASCII lower case equivalent.
4385 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4386 /// but non-ASCII letters are unchanged.
4388 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4393 /// let uppercase_a = 65u8;
4395 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4398 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4399 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4401 pub fn to_ascii_lowercase(&self) -> u8 {
4402 // Set the fifth bit if this is an uppercase letter
4403 *self | ((self.is_ascii_uppercase() as u8) << 5)
4406 /// Checks that two values are an ASCII case-insensitive match.
4408 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4413 /// let lowercase_a = 97u8;
4414 /// let uppercase_a = 65u8;
4416 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4418 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4420 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4421 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4424 /// Converts this value to its ASCII upper case equivalent in-place.
4426 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4427 /// but non-ASCII letters are unchanged.
4429 /// To return a new uppercased value without modifying the existing one, use
4430 /// [`to_ascii_uppercase`].
4435 /// let mut byte = b'a';
4437 /// byte.make_ascii_uppercase();
4439 /// assert_eq!(b'A', byte);
4442 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4443 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4445 pub fn make_ascii_uppercase(&mut self) {
4446 *self = self.to_ascii_uppercase();
4449 /// Converts this value to its ASCII lower case equivalent in-place.
4451 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4452 /// but non-ASCII letters are unchanged.
4454 /// To return a new lowercased value without modifying the existing one, use
4455 /// [`to_ascii_lowercase`].
4460 /// let mut byte = b'A';
4462 /// byte.make_ascii_lowercase();
4464 /// assert_eq!(b'a', byte);
4467 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4468 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4470 pub fn make_ascii_lowercase(&mut self) {
4471 *self = self.to_ascii_lowercase();
4474 /// Checks if the value is an ASCII alphabetic character:
4476 /// - U+0041 'A' ..= U+005A 'Z', or
4477 /// - U+0061 'a' ..= U+007A 'z'.
4482 /// let uppercase_a = b'A';
4483 /// let uppercase_g = b'G';
4486 /// let zero = b'0';
4487 /// let percent = b'%';
4488 /// let space = b' ';
4490 /// let esc = 0x1b_u8;
4492 /// assert!(uppercase_a.is_ascii_alphabetic());
4493 /// assert!(uppercase_g.is_ascii_alphabetic());
4494 /// assert!(a.is_ascii_alphabetic());
4495 /// assert!(g.is_ascii_alphabetic());
4496 /// assert!(!zero.is_ascii_alphabetic());
4497 /// assert!(!percent.is_ascii_alphabetic());
4498 /// assert!(!space.is_ascii_alphabetic());
4499 /// assert!(!lf.is_ascii_alphabetic());
4500 /// assert!(!esc.is_ascii_alphabetic());
4502 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4503 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4505 pub const fn is_ascii_alphabetic(&self) -> bool {
4506 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
4509 /// Checks if the value is an ASCII uppercase character:
4510 /// U+0041 'A' ..= U+005A 'Z'.
4515 /// let uppercase_a = b'A';
4516 /// let uppercase_g = b'G';
4519 /// let zero = b'0';
4520 /// let percent = b'%';
4521 /// let space = b' ';
4523 /// let esc = 0x1b_u8;
4525 /// assert!(uppercase_a.is_ascii_uppercase());
4526 /// assert!(uppercase_g.is_ascii_uppercase());
4527 /// assert!(!a.is_ascii_uppercase());
4528 /// assert!(!g.is_ascii_uppercase());
4529 /// assert!(!zero.is_ascii_uppercase());
4530 /// assert!(!percent.is_ascii_uppercase());
4531 /// assert!(!space.is_ascii_uppercase());
4532 /// assert!(!lf.is_ascii_uppercase());
4533 /// assert!(!esc.is_ascii_uppercase());
4535 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4536 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4538 pub const fn is_ascii_uppercase(&self) -> bool {
4539 matches!(*self, b'A'..=b'Z')
4542 /// Checks if the value is an ASCII lowercase character:
4543 /// U+0061 'a' ..= U+007A 'z'.
4548 /// let uppercase_a = b'A';
4549 /// let uppercase_g = b'G';
4552 /// let zero = b'0';
4553 /// let percent = b'%';
4554 /// let space = b' ';
4556 /// let esc = 0x1b_u8;
4558 /// assert!(!uppercase_a.is_ascii_lowercase());
4559 /// assert!(!uppercase_g.is_ascii_lowercase());
4560 /// assert!(a.is_ascii_lowercase());
4561 /// assert!(g.is_ascii_lowercase());
4562 /// assert!(!zero.is_ascii_lowercase());
4563 /// assert!(!percent.is_ascii_lowercase());
4564 /// assert!(!space.is_ascii_lowercase());
4565 /// assert!(!lf.is_ascii_lowercase());
4566 /// assert!(!esc.is_ascii_lowercase());
4568 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4569 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4571 pub const fn is_ascii_lowercase(&self) -> bool {
4572 matches!(*self, b'a'..=b'z')
4575 /// Checks if the value is an ASCII alphanumeric character:
4577 /// - U+0041 'A' ..= U+005A 'Z', or
4578 /// - U+0061 'a' ..= U+007A 'z', or
4579 /// - U+0030 '0' ..= U+0039 '9'.
4584 /// let uppercase_a = b'A';
4585 /// let uppercase_g = b'G';
4588 /// let zero = b'0';
4589 /// let percent = b'%';
4590 /// let space = b' ';
4592 /// let esc = 0x1b_u8;
4594 /// assert!(uppercase_a.is_ascii_alphanumeric());
4595 /// assert!(uppercase_g.is_ascii_alphanumeric());
4596 /// assert!(a.is_ascii_alphanumeric());
4597 /// assert!(g.is_ascii_alphanumeric());
4598 /// assert!(zero.is_ascii_alphanumeric());
4599 /// assert!(!percent.is_ascii_alphanumeric());
4600 /// assert!(!space.is_ascii_alphanumeric());
4601 /// assert!(!lf.is_ascii_alphanumeric());
4602 /// assert!(!esc.is_ascii_alphanumeric());
4604 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4605 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4607 pub const fn is_ascii_alphanumeric(&self) -> bool {
4608 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
4611 /// Checks if the value is an ASCII decimal digit:
4612 /// U+0030 '0' ..= U+0039 '9'.
4617 /// let uppercase_a = b'A';
4618 /// let uppercase_g = b'G';
4621 /// let zero = b'0';
4622 /// let percent = b'%';
4623 /// let space = b' ';
4625 /// let esc = 0x1b_u8;
4627 /// assert!(!uppercase_a.is_ascii_digit());
4628 /// assert!(!uppercase_g.is_ascii_digit());
4629 /// assert!(!a.is_ascii_digit());
4630 /// assert!(!g.is_ascii_digit());
4631 /// assert!(zero.is_ascii_digit());
4632 /// assert!(!percent.is_ascii_digit());
4633 /// assert!(!space.is_ascii_digit());
4634 /// assert!(!lf.is_ascii_digit());
4635 /// assert!(!esc.is_ascii_digit());
4637 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4638 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4640 pub const fn is_ascii_digit(&self) -> bool {
4641 matches!(*self, b'0'..=b'9')
4644 /// Checks if the value is an ASCII hexadecimal digit:
4646 /// - U+0030 '0' ..= U+0039 '9', or
4647 /// - U+0041 'A' ..= U+0046 'F', or
4648 /// - U+0061 'a' ..= U+0066 'f'.
4653 /// let uppercase_a = b'A';
4654 /// let uppercase_g = b'G';
4657 /// let zero = b'0';
4658 /// let percent = b'%';
4659 /// let space = b' ';
4661 /// let esc = 0x1b_u8;
4663 /// assert!(uppercase_a.is_ascii_hexdigit());
4664 /// assert!(!uppercase_g.is_ascii_hexdigit());
4665 /// assert!(a.is_ascii_hexdigit());
4666 /// assert!(!g.is_ascii_hexdigit());
4667 /// assert!(zero.is_ascii_hexdigit());
4668 /// assert!(!percent.is_ascii_hexdigit());
4669 /// assert!(!space.is_ascii_hexdigit());
4670 /// assert!(!lf.is_ascii_hexdigit());
4671 /// assert!(!esc.is_ascii_hexdigit());
4673 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4674 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4676 pub const fn is_ascii_hexdigit(&self) -> bool {
4677 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
4680 /// Checks if the value is an ASCII punctuation character:
4682 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4683 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4684 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4685 /// - U+007B ..= U+007E `{ | } ~`
4690 /// let uppercase_a = b'A';
4691 /// let uppercase_g = b'G';
4694 /// let zero = b'0';
4695 /// let percent = b'%';
4696 /// let space = b' ';
4698 /// let esc = 0x1b_u8;
4700 /// assert!(!uppercase_a.is_ascii_punctuation());
4701 /// assert!(!uppercase_g.is_ascii_punctuation());
4702 /// assert!(!a.is_ascii_punctuation());
4703 /// assert!(!g.is_ascii_punctuation());
4704 /// assert!(!zero.is_ascii_punctuation());
4705 /// assert!(percent.is_ascii_punctuation());
4706 /// assert!(!space.is_ascii_punctuation());
4707 /// assert!(!lf.is_ascii_punctuation());
4708 /// assert!(!esc.is_ascii_punctuation());
4710 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4711 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4713 pub const fn is_ascii_punctuation(&self) -> bool {
4714 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
4717 /// Checks if the value is an ASCII graphic character:
4718 /// U+0021 '!' ..= U+007E '~'.
4723 /// let uppercase_a = b'A';
4724 /// let uppercase_g = b'G';
4727 /// let zero = b'0';
4728 /// let percent = b'%';
4729 /// let space = b' ';
4731 /// let esc = 0x1b_u8;
4733 /// assert!(uppercase_a.is_ascii_graphic());
4734 /// assert!(uppercase_g.is_ascii_graphic());
4735 /// assert!(a.is_ascii_graphic());
4736 /// assert!(g.is_ascii_graphic());
4737 /// assert!(zero.is_ascii_graphic());
4738 /// assert!(percent.is_ascii_graphic());
4739 /// assert!(!space.is_ascii_graphic());
4740 /// assert!(!lf.is_ascii_graphic());
4741 /// assert!(!esc.is_ascii_graphic());
4743 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4744 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4746 pub const fn is_ascii_graphic(&self) -> bool {
4747 matches!(*self, b'!'..=b'~')
4750 /// Checks if the value is an ASCII whitespace character:
4751 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4752 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4754 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4755 /// whitespace][infra-aw]. There are several other definitions in
4756 /// wide use. For instance, [the POSIX locale][pct] includes
4757 /// U+000B VERTICAL TAB as well as all the above characters,
4758 /// but—from the very same specification—[the default rule for
4759 /// "field splitting" in the Bourne shell][bfs] considers *only*
4760 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4762 /// If you are writing a program that will process an existing
4763 /// file format, check what that format's definition of whitespace is
4764 /// before using this function.
4766 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4767 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4768 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4773 /// let uppercase_a = b'A';
4774 /// let uppercase_g = b'G';
4777 /// let zero = b'0';
4778 /// let percent = b'%';
4779 /// let space = b' ';
4781 /// let esc = 0x1b_u8;
4783 /// assert!(!uppercase_a.is_ascii_whitespace());
4784 /// assert!(!uppercase_g.is_ascii_whitespace());
4785 /// assert!(!a.is_ascii_whitespace());
4786 /// assert!(!g.is_ascii_whitespace());
4787 /// assert!(!zero.is_ascii_whitespace());
4788 /// assert!(!percent.is_ascii_whitespace());
4789 /// assert!(space.is_ascii_whitespace());
4790 /// assert!(lf.is_ascii_whitespace());
4791 /// assert!(!esc.is_ascii_whitespace());
4793 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4794 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4796 pub const fn is_ascii_whitespace(&self) -> bool {
4797 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
4800 /// Checks if the value is an ASCII control character:
4801 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4802 /// Note that most ASCII whitespace characters are control
4803 /// characters, but SPACE is not.
4808 /// let uppercase_a = b'A';
4809 /// let uppercase_g = b'G';
4812 /// let zero = b'0';
4813 /// let percent = b'%';
4814 /// let space = b' ';
4816 /// let esc = 0x1b_u8;
4818 /// assert!(!uppercase_a.is_ascii_control());
4819 /// assert!(!uppercase_g.is_ascii_control());
4820 /// assert!(!a.is_ascii_control());
4821 /// assert!(!g.is_ascii_control());
4822 /// assert!(!zero.is_ascii_control());
4823 /// assert!(!percent.is_ascii_control());
4824 /// assert!(!space.is_ascii_control());
4825 /// assert!(lf.is_ascii_control());
4826 /// assert!(esc.is_ascii_control());
4828 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4829 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4831 pub const fn is_ascii_control(&self) -> bool {
4832 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
4838 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4839 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4844 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4845 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4850 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4851 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4852 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4853 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4859 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4860 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4861 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4862 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4863 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4864 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4865 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4869 #[cfg(target_pointer_width = "16")]
4872 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4873 "[0x34, 0x12]", "[0x12, 0x34]",
4874 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4876 #[cfg(target_pointer_width = "32")]
4879 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4880 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4881 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4884 #[cfg(target_pointer_width = "64")]
4887 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4888 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4889 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4890 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4891 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4894 /// A classification of floating point numbers.
4896 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4897 /// their documentation for more.
4899 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4900 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4905 /// use std::num::FpCategory;
4907 /// let num = 12.4_f32;
4908 /// let inf = f32::INFINITY;
4909 /// let zero = 0f32;
4910 /// let sub: f32 = 1.1754942e-38;
4911 /// let nan = f32::NAN;
4913 /// assert_eq!(num.classify(), FpCategory::Normal);
4914 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4915 /// assert_eq!(zero.classify(), FpCategory::Zero);
4916 /// assert_eq!(nan.classify(), FpCategory::Nan);
4917 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4919 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4920 #[stable(feature = "rust1", since = "1.0.0")]
4921 pub enum FpCategory {
4922 /// "Not a Number", often obtained by dividing by zero.
4923 #[stable(feature = "rust1", since = "1.0.0")]
4926 /// Positive or negative infinity.
4927 #[stable(feature = "rust1", since = "1.0.0")]
4930 /// Positive or negative zero.
4931 #[stable(feature = "rust1", since = "1.0.0")]
4934 /// De-normalized floating point representation (less precise than `Normal`).
4935 #[stable(feature = "rust1", since = "1.0.0")]
4938 /// A regular floating point number.
4939 #[stable(feature = "rust1", since = "1.0.0")]
4943 macro_rules! from_str_radix_int_impl {
4945 #[stable(feature = "rust1", since = "1.0.0")]
4946 impl FromStr for $t {
4947 type Err = ParseIntError;
4948 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4949 from_str_radix(src, 10)
4954 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4956 /// The error type returned when a checked integral type conversion fails.
4957 #[stable(feature = "try_from", since = "1.34.0")]
4958 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4959 pub struct TryFromIntError(pub(crate) ());
4961 impl TryFromIntError {
4963 feature = "int_error_internals",
4964 reason = "available through Error trait and this method should \
4965 not be exposed publicly",
4969 pub fn __description(&self) -> &str {
4970 "out of range integral type conversion attempted"
4974 #[stable(feature = "try_from", since = "1.34.0")]
4975 impl fmt::Display for TryFromIntError {
4976 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4977 self.__description().fmt(fmt)
4981 #[stable(feature = "try_from", since = "1.34.0")]
4982 impl From<Infallible> for TryFromIntError {
4983 fn from(x: Infallible) -> TryFromIntError {
4988 #[unstable(feature = "never_type", issue = "35121")]
4989 impl From<!> for TryFromIntError {
4990 fn from(never: !) -> TryFromIntError {
4991 // Match rather than coerce to make sure that code like
4992 // `From<Infallible> for TryFromIntError` above will keep working
4993 // when `Infallible` becomes an alias to `!`.
4999 trait FromStrRadixHelper: PartialOrd + Copy {
5000 fn min_value() -> Self;
5001 fn max_value() -> Self;
5002 fn from_u32(u: u32) -> Self;
5003 fn checked_mul(&self, other: u32) -> Option<Self>;
5004 fn checked_sub(&self, other: u32) -> Option<Self>;
5005 fn checked_add(&self, other: u32) -> Option<Self>;
5009 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
5011 fn min_value() -> Self { Self::min_value() }
5013 fn max_value() -> Self { Self::max_value() }
5015 fn from_u32(u: u32) -> Self { u as Self }
5017 fn checked_mul(&self, other: u32) -> Option<Self> {
5018 Self::checked_mul(*self, other as Self)
5021 fn checked_sub(&self, other: u32) -> Option<Self> {
5022 Self::checked_sub(*self, other as Self)
5025 fn checked_add(&self, other: u32) -> Option<Self> {
5026 Self::checked_add(*self, other as Self)
5030 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5032 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5033 use self::IntErrorKind::*;
5034 use self::ParseIntError as PIE;
5037 radix >= 2 && radix <= 36,
5038 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5043 return Err(PIE { kind: Empty });
5046 let is_signed_ty = T::from_u32(0) > T::min_value();
5048 // all valid digits are ascii, so we will just iterate over the utf8 bytes
5049 // and cast them to chars. .to_digit() will safely return None for anything
5050 // other than a valid ascii digit for the given radix, including the first-byte
5051 // of multi-byte sequences
5052 let src = src.as_bytes();
5054 let (is_positive, digits) = match src[0] {
5055 b'+' => (true, &src[1..]),
5056 b'-' if is_signed_ty => (false, &src[1..]),
5060 if digits.is_empty() {
5061 return Err(PIE { kind: Empty });
5064 let mut result = T::from_u32(0);
5066 // The number is positive
5068 let x = match (c as char).to_digit(radix) {
5070 None => return Err(PIE { kind: InvalidDigit }),
5072 result = match result.checked_mul(radix) {
5073 Some(result) => result,
5074 None => return Err(PIE { kind: Overflow }),
5076 result = match result.checked_add(x) {
5077 Some(result) => result,
5078 None => return Err(PIE { kind: Overflow }),
5082 // The number is negative
5084 let x = match (c as char).to_digit(radix) {
5086 None => return Err(PIE { kind: InvalidDigit }),
5088 result = match result.checked_mul(radix) {
5089 Some(result) => result,
5090 None => return Err(PIE { kind: Underflow }),
5092 result = match result.checked_sub(x) {
5093 Some(result) => result,
5094 None => return Err(PIE { kind: Underflow }),
5101 /// An error which can be returned when parsing an integer.
5103 /// This error is used as the error type for the `from_str_radix()` functions
5104 /// on the primitive integer types, such as [`i8::from_str_radix`].
5106 /// # Potential causes
5108 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5109 /// in the string e.g., when it is obtained from the standard input.
5110 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5112 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5113 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5114 #[derive(Debug, Clone, PartialEq, Eq)]
5115 #[stable(feature = "rust1", since = "1.0.0")]
5116 pub struct ParseIntError {
5120 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5122 feature = "int_error_matching",
5123 reason = "it can be useful to match errors when making error messages \
5124 for integer parsing",
5127 #[derive(Debug, Clone, PartialEq, Eq)]
5129 pub enum IntErrorKind {
5130 /// Value being parsed is empty.
5132 /// Among other causes, this variant will be constructed when parsing an empty string.
5134 /// Contains an invalid digit.
5136 /// Among other causes, this variant will be constructed when parsing a string that
5137 /// contains a letter.
5139 /// Integer is too large to store in target integer type.
5141 /// Integer is too small to store in target integer type.
5145 /// This variant will be emitted when the parsing string has a value of zero, which
5146 /// would be illegal for non-zero types.
5150 impl ParseIntError {
5151 /// Outputs the detailed cause of parsing an integer failing.
5153 feature = "int_error_matching",
5154 reason = "it can be useful to match errors when making error messages \
5155 for integer parsing",
5158 pub fn kind(&self) -> &IntErrorKind {
5162 feature = "int_error_internals",
5163 reason = "available through Error trait and this method should \
5164 not be exposed publicly",
5168 pub fn __description(&self) -> &str {
5170 IntErrorKind::Empty => "cannot parse integer from empty string",
5171 IntErrorKind::InvalidDigit => "invalid digit found in string",
5172 IntErrorKind::Overflow => "number too large to fit in target type",
5173 IntErrorKind::Underflow => "number too small to fit in target type",
5174 IntErrorKind::Zero => "number would be zero for non-zero type",
5179 #[stable(feature = "rust1", since = "1.0.0")]
5180 impl fmt::Display for ParseIntError {
5181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5182 self.__description().fmt(f)
5186 #[stable(feature = "rust1", since = "1.0.0")]
5187 pub use crate::num::dec2flt::ParseFloatError;