1 // ignore-tidy-filelength
3 //! Numeric traits and functions for the built-in numeric types.
5 #![stable(feature = "rust1", since = "1.0.0")]
7 use crate::convert::Infallible;
11 use crate::str::FromStr;
13 // Used because the `?` operator is not allowed in a const context.
14 macro_rules! try_opt {
23 macro_rules! impl_nonzero_fmt {
24 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
27 impl fmt::$Trait for $Ty {
29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 macro_rules! doc_comment {
38 ($x:expr, $($tt:tt)*) => {
44 macro_rules! nonzero_integers {
45 ( $( #[$stability: meta] $Ty: ident($Int: ty); )+ ) => {
48 concat!("An integer that is known not to equal zero.
50 This enables some memory layout optimization.
51 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
54 use std::mem::size_of;
55 assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
59 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
61 #[rustc_layout_scalar_valid_range_start(1)]
62 #[rustc_nonnull_optimization_guaranteed]
67 /// Creates a non-zero without checking the value.
71 /// The value must not be zero.
73 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
75 pub const unsafe fn new_unchecked(n: $Int) -> Self {
79 /// Creates a non-zero if the given value is not zero.
81 #[rustc_const_unstable(feature = "const_nonzero_int_methods", issue = "53718")]
83 pub const fn new(n: $Int) -> Option<Self> {
85 // SAFETY: we just checked that there's no `0`
86 Some(unsafe { Self(n) })
92 /// Returns the value as a primitive type.
95 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
96 pub const fn get(self) -> $Int {
102 #[stable(feature = "from_nonzero", since = "1.31.0")]
103 impl From<$Ty> for $Int {
106 "Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`"),
107 fn from(nonzero: $Ty) -> Self {
114 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
121 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
122 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
123 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
124 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
125 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
126 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
127 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
128 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
129 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
130 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
131 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
132 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
135 macro_rules! from_str_radix_nzint_impl {
137 #[stable(feature = "nonzero_parse", since = "1.35.0")]
138 impl FromStr for $t {
139 type Err = ParseIntError;
140 fn from_str(src: &str) -> Result<Self, Self::Err> {
141 Self::new(from_str_radix(src, 10)?)
142 .ok_or(ParseIntError {
143 kind: IntErrorKind::Zero
150 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
151 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
153 /// Provides intentionally-wrapped arithmetic on `T`.
155 /// Operations like `+` on `u32` values are intended to never overflow,
156 /// and in some debug configurations overflow is detected and results
157 /// in a panic. While most arithmetic falls into this category, some
158 /// code explicitly expects and relies upon modular arithmetic (e.g.,
161 /// Wrapping arithmetic can be achieved either through methods like
162 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
163 /// all standard arithmetic operations on the underlying value are
164 /// intended to have wrapping semantics.
166 /// The underlying value can be retrieved through the `.0` index of the
167 /// `Wrapping` tuple.
172 /// use std::num::Wrapping;
174 /// let zero = Wrapping(0u32);
175 /// let one = Wrapping(1u32);
177 /// assert_eq!(std::u32::MAX, (zero - one).0);
179 #[stable(feature = "rust1", since = "1.0.0")]
180 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
182 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
184 #[stable(feature = "rust1", since = "1.0.0")]
185 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 #[stable(feature = "wrapping_display", since = "1.10.0")]
192 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
199 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
206 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
213 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
220 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226 // All these modules are technically private and only exposed for coretests:
234 macro_rules! usize_isize_to_xe_bytes_doc {
238 **Note**: This function returns an array of length 2, 4 or 8 bytes
239 depending on the target pointer size.
245 macro_rules! usize_isize_from_xe_bytes_doc {
249 **Note**: This function takes an array of length 2, 4 or 8 bytes
250 depending on the target pointer size.
256 macro_rules! int_impl {
257 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
258 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
259 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
260 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
262 concat!("The smallest value that can be represented by this integer type.
269 #![feature(assoc_int_consts)]
270 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, ", stringify!($Min), ");",
273 #[unstable(feature = "assoc_int_consts", reason = "recently added", issue = "68490")]
274 pub const MIN: Self = !0 ^ ((!0 as $UnsignedT) >> 1) as Self;
278 concat!("The largest value that can be represented by this integer type.
285 #![feature(assoc_int_consts)]
286 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");",
289 #[unstable(feature = "assoc_int_consts", reason = "recently added", issue = "68490")]
290 pub const MAX: Self = !Self::MIN;
294 "Returns the smallest value that can be represented by this integer type.",
295 #[stable(feature = "rust1", since = "1.0.0")]
298 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
299 pub const fn min_value() -> Self {
305 "Returns the largest value that can be represented by this integer type.",
306 #[stable(feature = "rust1", since = "1.0.0")]
309 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
310 pub const fn max_value() -> Self {
316 concat!("Converts a string slice in a given base to an integer.
318 The string is expected to be an optional `+` or `-` sign followed by digits.
319 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
320 depending on `radix`:
328 This function panics if `radix` is not in the range from 2 to 36.
335 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
338 #[stable(feature = "rust1", since = "1.0.0")]
339 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
340 from_str_radix(src, radix)
345 concat!("Returns the number of ones in the binary representation of `self`.
352 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
354 assert_eq!(n.count_ones(), 1);",
358 #[stable(feature = "rust1", since = "1.0.0")]
359 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
361 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
365 concat!("Returns the number of zeros in the binary representation of `self`.
372 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
374 #[stable(feature = "rust1", since = "1.0.0")]
375 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
377 pub const fn count_zeros(self) -> u32 {
383 concat!("Returns the number of leading zeros in the binary representation of `self`.
390 ", $Feature, "let n = -1", stringify!($SelfT), ";
392 assert_eq!(n.leading_zeros(), 0);",
395 #[stable(feature = "rust1", since = "1.0.0")]
396 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
398 pub const fn leading_zeros(self) -> u32 {
399 (self as $UnsignedT).leading_zeros()
404 concat!("Returns the number of trailing zeros in the binary representation of `self`.
411 ", $Feature, "let n = -4", stringify!($SelfT), ";
413 assert_eq!(n.trailing_zeros(), 2);",
416 #[stable(feature = "rust1", since = "1.0.0")]
417 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
419 pub const fn trailing_zeros(self) -> u32 {
420 (self as $UnsignedT).trailing_zeros()
425 concat!("Returns the number of leading ones in the binary representation of `self`.
432 ", $Feature, "#![feature(leading_trailing_ones)]
433 let n = -1", stringify!($SelfT), ";
435 assert_eq!(n.leading_ones(), ", stringify!($BITS), ");",
438 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
440 pub const fn leading_ones(self) -> u32 {
441 (self as $UnsignedT).leading_ones()
446 concat!("Returns the number of trailing ones in the binary representation of `self`.
453 ", $Feature, "#![feature(leading_trailing_ones)]
454 let n = 3", stringify!($SelfT), ";
456 assert_eq!(n.trailing_ones(), 2);",
459 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
461 pub const fn trailing_ones(self) -> u32 {
462 (self as $UnsignedT).trailing_ones()
467 concat!("Shifts the bits to the left by a specified amount, `n`,
468 wrapping the truncated bits to the end of the resulting integer.
470 Please note this isn't the same operation as the `<<` shifting operator!
477 let n = ", $rot_op, stringify!($SelfT), ";
478 let m = ", $rot_result, ";
480 assert_eq!(n.rotate_left(", $rot, "), m);
482 #[stable(feature = "rust1", since = "1.0.0")]
483 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
484 #[must_use = "this returns the result of the operation, \
485 without modifying the original"]
487 pub const fn rotate_left(self, n: u32) -> Self {
488 (self as $UnsignedT).rotate_left(n) as Self
493 concat!("Shifts the bits to the right by a specified amount, `n`,
494 wrapping the truncated bits to the beginning of the resulting
497 Please note this isn't the same operation as the `>>` shifting operator!
504 let n = ", $rot_result, stringify!($SelfT), ";
505 let m = ", $rot_op, ";
507 assert_eq!(n.rotate_right(", $rot, "), m);
509 #[stable(feature = "rust1", since = "1.0.0")]
510 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
511 #[must_use = "this returns the result of the operation, \
512 without modifying the original"]
514 pub const fn rotate_right(self, n: u32) -> Self {
515 (self as $UnsignedT).rotate_right(n) as Self
520 concat!("Reverses the byte order of the integer.
527 let n = ", $swap_op, stringify!($SelfT), ";
529 let m = n.swap_bytes();
531 assert_eq!(m, ", $swapped, ");
533 #[stable(feature = "rust1", since = "1.0.0")]
534 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
536 pub const fn swap_bytes(self) -> Self {
537 (self as $UnsignedT).swap_bytes() as Self
542 concat!("Reverses the bit pattern of the integer.
549 let n = ", $swap_op, stringify!($SelfT), ";
550 let m = n.reverse_bits();
552 assert_eq!(m, ", $reversed, ");
554 #[stable(feature = "reverse_bits", since = "1.37.0")]
555 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
558 pub const fn reverse_bits(self) -> Self {
559 (self as $UnsignedT).reverse_bits() as Self
564 concat!("Converts an integer from big endian to the target's endianness.
566 On big endian this is a no-op. On little endian the bytes are swapped.
573 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
575 if cfg!(target_endian = \"big\") {
576 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
578 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
582 #[stable(feature = "rust1", since = "1.0.0")]
583 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
585 pub const fn from_be(x: Self) -> Self {
586 #[cfg(target_endian = "big")]
590 #[cfg(not(target_endian = "big"))]
598 concat!("Converts an integer from little endian to the target's endianness.
600 On little endian this is a no-op. On big endian the bytes are swapped.
607 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
609 if cfg!(target_endian = \"little\") {
610 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
612 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
616 #[stable(feature = "rust1", since = "1.0.0")]
617 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
619 pub const fn from_le(x: Self) -> Self {
620 #[cfg(target_endian = "little")]
624 #[cfg(not(target_endian = "little"))]
632 concat!("Converts `self` to big endian from the target's endianness.
634 On big endian this is a no-op. On little endian the bytes are swapped.
641 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
643 if cfg!(target_endian = \"big\") {
644 assert_eq!(n.to_be(), n)
646 assert_eq!(n.to_be(), n.swap_bytes())
650 #[stable(feature = "rust1", since = "1.0.0")]
651 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
653 pub const fn to_be(self) -> Self { // or not to be?
654 #[cfg(target_endian = "big")]
658 #[cfg(not(target_endian = "big"))]
666 concat!("Converts `self` to little endian from the target's endianness.
668 On little endian this is a no-op. On big endian the bytes are swapped.
675 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
677 if cfg!(target_endian = \"little\") {
678 assert_eq!(n.to_le(), n)
680 assert_eq!(n.to_le(), n.swap_bytes())
684 #[stable(feature = "rust1", since = "1.0.0")]
685 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
687 pub const fn to_le(self) -> Self {
688 #[cfg(target_endian = "little")]
692 #[cfg(not(target_endian = "little"))]
700 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
701 if overflow occurred.
708 ", $Feature, "assert_eq!((", stringify!($SelfT),
709 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
710 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
713 #[stable(feature = "rust1", since = "1.0.0")]
714 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
715 #[must_use = "this returns the result of the operation, \
716 without modifying the original"]
718 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
719 let (a, b) = self.overflowing_add(rhs);
720 if b {None} else {Some(a)}
725 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
733 ", $Feature, "assert_eq!((", stringify!($SelfT),
734 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
735 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
738 #[stable(feature = "rust1", since = "1.0.0")]
739 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
740 #[must_use = "this returns the result of the operation, \
741 without modifying the original"]
743 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
744 let (a, b) = self.overflowing_sub(rhs);
745 if b {None} else {Some(a)}
750 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
758 ", $Feature, "assert_eq!(", stringify!($SelfT),
759 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
760 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
763 #[stable(feature = "rust1", since = "1.0.0")]
764 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
765 #[must_use = "this returns the result of the operation, \
766 without modifying the original"]
768 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
769 let (a, b) = self.overflowing_mul(rhs);
770 if b {None} else {Some(a)}
775 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
776 or the division results in overflow.
783 ", $Feature, "assert_eq!((", stringify!($SelfT),
784 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
785 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
786 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
789 #[stable(feature = "rust1", since = "1.0.0")]
790 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
791 #[must_use = "this returns the result of the operation, \
792 without modifying the original"]
794 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
795 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
798 // SAFETY: div by zero and by INT_MIN have been checked above
799 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
805 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
806 returning `None` if `rhs == 0` or the division results in overflow.
813 assert_eq!((", stringify!($SelfT),
814 "::min_value() + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
815 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euclid(-1), None);
816 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
818 #[stable(feature = "euclidean_division", since = "1.38.0")]
819 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
820 #[must_use = "this returns the result of the operation, \
821 without modifying the original"]
823 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
824 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
827 Some(self.div_euclid(rhs))
833 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
834 `rhs == 0` or the division results in overflow.
841 ", $Feature, "use std::", stringify!($SelfT), ";
843 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
844 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
845 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
848 #[stable(feature = "wrapping", since = "1.7.0")]
849 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
850 #[must_use = "this returns the result of the operation, \
851 without modifying the original"]
853 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
854 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
857 // SAFETY: div by zero and by INT_MIN have been checked above
858 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
864 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
865 if `rhs == 0` or the division results in overflow.
872 use std::", stringify!($SelfT), ";
874 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
875 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
876 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
878 #[stable(feature = "euclidean_division", since = "1.38.0")]
879 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
880 #[must_use = "this returns the result of the operation, \
881 without modifying the original"]
883 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
884 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
887 Some(self.rem_euclid(rhs))
893 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
900 ", $Feature, "use std::", stringify!($SelfT), ";
902 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
903 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
906 #[stable(feature = "wrapping", since = "1.7.0")]
907 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
909 pub const fn checked_neg(self) -> Option<Self> {
910 let (a, b) = self.overflowing_neg();
911 if b {None} else {Some(a)}
916 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
917 than or equal to the number of bits in `self`.
924 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
925 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
928 #[stable(feature = "wrapping", since = "1.7.0")]
929 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
930 #[must_use = "this returns the result of the operation, \
931 without modifying the original"]
933 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
934 let (a, b) = self.overflowing_shl(rhs);
935 if b {None} else {Some(a)}
940 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
941 larger than or equal to the number of bits in `self`.
948 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
949 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
952 #[stable(feature = "wrapping", since = "1.7.0")]
953 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
954 #[must_use = "this returns the result of the operation, \
955 without modifying the original"]
957 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
958 let (a, b) = self.overflowing_shr(rhs);
959 if b {None} else {Some(a)}
964 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
972 ", $Feature, "use std::", stringify!($SelfT), ";
974 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
975 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
978 #[stable(feature = "no_panic_abs", since = "1.13.0")]
979 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
981 pub const fn checked_abs(self) -> Option<Self> {
982 if self.is_negative() {
991 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
999 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
1000 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
1004 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1005 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1006 #[must_use = "this returns the result of the operation, \
1007 without modifying the original"]
1009 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
1010 let mut base = self;
1011 let mut acc: Self = 1;
1015 acc = try_opt!(acc.checked_mul(base));
1018 base = try_opt!(base.checked_mul(base));
1021 // Deal with the final bit of the exponent separately, since
1022 // squaring the base afterwards is not necessary and may cause a
1023 // needless overflow.
1025 acc = try_opt!(acc.checked_mul(base));
1033 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
1034 bounds instead of overflowing.
1041 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
1042 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
1044 assert_eq!(", stringify!($SelfT), "::min_value().saturating_add(-1), ", stringify!($SelfT),
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1051 #[must_use = "this returns the result of the operation, \
1052 without modifying the original"]
1054 pub const fn saturating_add(self, rhs: Self) -> Self {
1055 intrinsics::saturating_add(self, rhs)
1060 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
1061 numeric bounds instead of overflowing.
1068 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
1069 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
1071 assert_eq!(", stringify!($SelfT), "::max_value().saturating_sub(-1), ", stringify!($SelfT),
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1077 #[must_use = "this returns the result of the operation, \
1078 without modifying the original"]
1080 pub const fn saturating_sub(self, rhs: Self) -> Self {
1081 intrinsics::saturating_sub(self, rhs)
1086 concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
1087 instead of overflowing.
1094 ", $Feature, "#![feature(saturating_neg)]
1095 assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
1096 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
1097 assert_eq!(", stringify!($SelfT), "::min_value().saturating_neg(), ", stringify!($SelfT),
1099 assert_eq!(", stringify!($SelfT), "::max_value().saturating_neg(), ", stringify!($SelfT),
1100 "::min_value() + 1);",
1104 #[unstable(feature = "saturating_neg", issue = "59983")]
1105 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1107 pub const fn saturating_neg(self) -> Self {
1108 intrinsics::saturating_sub(0, self)
1113 concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1114 MIN` instead of overflowing.
1121 ", $Feature, "#![feature(saturating_neg)]
1122 assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
1123 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
1124 assert_eq!(", stringify!($SelfT), "::min_value().saturating_abs(), ", stringify!($SelfT),
1126 assert_eq!((", stringify!($SelfT), "::min_value() + 1).saturating_abs(), ", stringify!($SelfT),
1131 #[unstable(feature = "saturating_neg", issue = "59983")]
1132 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1134 pub const fn saturating_abs(self) -> Self {
1135 if self.is_negative() {
1136 self.saturating_neg()
1144 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1145 numeric bounds instead of overflowing.
1152 ", $Feature, "use std::", stringify!($SelfT), ";
1154 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1155 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1156 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1159 #[stable(feature = "wrapping", since = "1.7.0")]
1160 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1161 #[must_use = "this returns the result of the operation, \
1162 without modifying the original"]
1164 pub const fn saturating_mul(self, rhs: Self) -> Self {
1165 match self.checked_mul(rhs) {
1167 None => if (self < 0) == (rhs < 0) {
1177 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1178 saturating at the numeric bounds instead of overflowing.
1185 ", $Feature, "use std::", stringify!($SelfT), ";
1187 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1188 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1189 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1192 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1193 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1194 #[must_use = "this returns the result of the operation, \
1195 without modifying the original"]
1197 pub const fn saturating_pow(self, exp: u32) -> Self {
1198 match self.checked_pow(exp) {
1200 None if self < 0 && exp % 2 == 1 => Self::min_value(),
1201 None => Self::max_value(),
1207 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1208 boundary of the type.
1215 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1216 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
1217 "::min_value() + 1);",
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1222 #[must_use = "this returns the result of the operation, \
1223 without modifying the original"]
1225 pub const fn wrapping_add(self, rhs: Self) -> Self {
1226 intrinsics::wrapping_add(self, rhs)
1231 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1232 boundary of the type.
1239 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1240 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1241 stringify!($SelfT), "::max_value());",
1244 #[stable(feature = "rust1", since = "1.0.0")]
1245 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1246 #[must_use = "this returns the result of the operation, \
1247 without modifying the original"]
1249 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1250 intrinsics::wrapping_sub(self, rhs)
1255 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1256 the boundary of the type.
1263 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1264 assert_eq!(11i8.wrapping_mul(12), -124);",
1267 #[stable(feature = "rust1", since = "1.0.0")]
1268 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1269 #[must_use = "this returns the result of the operation, \
1270 without modifying the original"]
1272 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1273 intrinsics::wrapping_mul(self, rhs)
1278 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1279 boundary of the type.
1281 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1282 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1283 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1287 This function will panic if `rhs` is 0.
1294 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1295 assert_eq!((-128i8).wrapping_div(-1), -128);",
1298 #[stable(feature = "num_wrapping", since = "1.2.0")]
1299 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1300 #[must_use = "this returns the result of the operation, \
1301 without modifying the original"]
1303 pub const fn wrapping_div(self, rhs: Self) -> Self {
1304 self.overflowing_div(rhs).0
1309 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1310 wrapping around at the boundary of the type.
1312 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1313 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1314 type. In this case, this method returns `MIN` itself.
1318 This function will panic if `rhs` is 0.
1325 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1326 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1328 #[stable(feature = "euclidean_division", since = "1.38.0")]
1329 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1330 #[must_use = "this returns the result of the operation, \
1331 without modifying the original"]
1333 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1334 self.overflowing_div_euclid(rhs).0
1339 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1340 boundary of the type.
1342 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1343 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1344 this function returns `0`.
1348 This function will panic if `rhs` is 0.
1355 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1356 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1359 #[stable(feature = "num_wrapping", since = "1.2.0")]
1360 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1361 #[must_use = "this returns the result of the operation, \
1362 without modifying the original"]
1364 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1365 self.overflowing_rem(rhs).0
1370 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1371 at the boundary of the type.
1373 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1374 for the type). In this case, this method returns 0.
1378 This function will panic if `rhs` is 0.
1385 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1386 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1388 #[stable(feature = "euclidean_division", since = "1.38.0")]
1389 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1390 #[must_use = "this returns the result of the operation, \
1391 without modifying the original"]
1393 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1394 self.overflowing_rem_euclid(rhs).0
1399 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1402 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1403 is the negative minimal value for the type); this is a positive value that is too large to represent
1404 in the type. In such a case, this function returns `MIN` itself.
1411 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1412 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1416 #[stable(feature = "num_wrapping", since = "1.2.0")]
1417 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1419 pub const fn wrapping_neg(self) -> Self {
1420 self.overflowing_neg().0
1425 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1426 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1428 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1429 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1430 The primitive integer types all implement a `rotate_left` function, which may be what you want
1438 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1439 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1442 #[stable(feature = "num_wrapping", since = "1.2.0")]
1443 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1444 #[must_use = "this returns the result of the operation, \
1445 without modifying the original"]
1447 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1448 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1451 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1457 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1458 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1460 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1461 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1462 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1470 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1471 assert_eq!((-128i16).wrapping_shr(64), -128);",
1474 #[stable(feature = "num_wrapping", since = "1.2.0")]
1475 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1476 #[must_use = "this returns the result of the operation, \
1477 without modifying the original"]
1479 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1480 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1483 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1489 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1490 the boundary of the type.
1492 The only case where such wrapping can occur is when one takes the absolute value of the negative
1493 minimal value for the type this is a positive value that is too large to represent in the type. In
1494 such a case, this function returns `MIN` itself.
1501 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1502 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1503 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1505 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1508 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1509 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1510 #[allow(unused_attributes)]
1511 #[allow_internal_unstable(const_if_match)]
1513 pub const fn wrapping_abs(self) -> Self {
1514 if self.is_negative() {
1523 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1524 wrapping around at the boundary of the type.
1531 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1532 assert_eq!(3i8.wrapping_pow(5), -13);
1533 assert_eq!(3i8.wrapping_pow(6), -39);",
1536 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1537 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1538 #[must_use = "this returns the result of the operation, \
1539 without modifying the original"]
1541 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1542 let mut base = self;
1543 let mut acc: Self = 1;
1547 acc = acc.wrapping_mul(base);
1550 base = base.wrapping_mul(base);
1553 // Deal with the final bit of the exponent separately, since
1554 // squaring the base afterwards is not necessary and may cause a
1555 // needless overflow.
1557 acc = acc.wrapping_mul(base);
1565 concat!("Calculates `self` + `rhs`
1567 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1568 occur. If an overflow would have occurred then the wrapped value is returned.
1575 ", $Feature, "use std::", stringify!($SelfT), ";
1577 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1578 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1579 "::MIN, true));", $EndFeature, "
1581 #[stable(feature = "wrapping", since = "1.7.0")]
1582 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1583 #[must_use = "this returns the result of the operation, \
1584 without modifying the original"]
1586 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1587 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1593 concat!("Calculates `self` - `rhs`
1595 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1596 would occur. If an overflow would have occurred then the wrapped value is returned.
1603 ", $Feature, "use std::", stringify!($SelfT), ";
1605 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1606 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1607 "::MAX, true));", $EndFeature, "
1609 #[stable(feature = "wrapping", since = "1.7.0")]
1610 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1611 #[must_use = "this returns the result of the operation, \
1612 without modifying the original"]
1614 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1615 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1621 concat!("Calculates the multiplication of `self` and `rhs`.
1623 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1624 would occur. If an overflow would have occurred then the wrapped value is returned.
1631 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1632 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1635 #[stable(feature = "wrapping", since = "1.7.0")]
1636 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1637 #[must_use = "this returns the result of the operation, \
1638 without modifying the original"]
1640 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1641 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1647 concat!("Calculates the divisor when `self` is divided by `rhs`.
1649 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1650 occur. If an overflow would occur then self is returned.
1654 This function will panic if `rhs` is 0.
1661 ", $Feature, "use std::", stringify!($SelfT), ";
1663 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1664 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1669 #[stable(feature = "wrapping", since = "1.7.0")]
1670 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1671 #[must_use = "this returns the result of the operation, \
1672 without modifying the original"]
1673 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1674 if self == Self::min_value() && rhs == -1 {
1683 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1685 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1686 occur. If an overflow would occur then `self` is returned.
1690 This function will panic if `rhs` is 0.
1697 use std::", stringify!($SelfT), ";
1699 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1700 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1704 #[stable(feature = "euclidean_division", since = "1.38.0")]
1705 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1706 #[must_use = "this returns the result of the operation, \
1707 without modifying the original"]
1708 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1709 if self == Self::min_value() && rhs == -1 {
1712 (self.div_euclid(rhs), false)
1718 concat!("Calculates the remainder when `self` is divided by `rhs`.
1720 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1721 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1725 This function will panic if `rhs` is 0.
1732 ", $Feature, "use std::", stringify!($SelfT), ";
1734 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1735 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1739 #[stable(feature = "wrapping", since = "1.7.0")]
1740 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1741 #[must_use = "this returns the result of the operation, \
1742 without modifying the original"]
1743 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1744 if self == Self::min_value() && rhs == -1 {
1754 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1756 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1757 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1761 This function will panic if `rhs` is 0.
1768 use std::", stringify!($SelfT), ";
1770 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1771 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1773 #[stable(feature = "euclidean_division", since = "1.38.0")]
1774 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1775 #[must_use = "this returns the result of the operation, \
1776 without modifying the original"]
1778 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1779 if self == Self::min_value() && rhs == -1 {
1782 (self.rem_euclid(rhs), false)
1789 concat!("Negates self, overflowing if this is equal to the minimum value.
1791 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1792 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1793 minimum value will be returned again and `true` will be returned for an overflow happening.
1800 ", $Feature, "use std::", stringify!($SelfT), ";
1802 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1803 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1804 "::MIN, true));", $EndFeature, "
1807 #[stable(feature = "wrapping", since = "1.7.0")]
1808 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1809 #[allow(unused_attributes)]
1810 #[allow_internal_unstable(const_if_match)]
1811 pub const fn overflowing_neg(self) -> (Self, bool) {
1812 if self == Self::min_value() {
1813 (Self::min_value(), true)
1821 concat!("Shifts self left by `rhs` bits.
1823 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1824 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1825 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1832 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1833 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1836 #[stable(feature = "wrapping", since = "1.7.0")]
1837 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1838 #[must_use = "this returns the result of the operation, \
1839 without modifying the original"]
1841 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1842 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1847 concat!("Shifts self right by `rhs` bits.
1849 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1850 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1851 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1858 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1859 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1862 #[stable(feature = "wrapping", since = "1.7.0")]
1863 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1864 #[must_use = "this returns the result of the operation, \
1865 without modifying the original"]
1867 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1868 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1873 concat!("Computes the absolute value of `self`.
1875 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1876 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1877 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1878 for an overflow happening.
1885 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1886 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1887 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1888 "::min_value(), true));",
1891 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1892 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1894 pub const fn overflowing_abs(self) -> (Self, bool) {
1895 (self.wrapping_abs(), self == Self::min_value())
1900 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1902 Returns a tuple of the exponentiation along with a bool indicating
1903 whether an overflow happened.
1910 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1911 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1914 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1915 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1916 #[must_use = "this returns the result of the operation, \
1917 without modifying the original"]
1919 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1920 let mut base = self;
1921 let mut acc: Self = 1;
1922 let mut overflown = false;
1923 // Scratch space for storing results of overflowing_mul.
1928 r = acc.overflowing_mul(base);
1933 r = base.overflowing_mul(base);
1938 // Deal with the final bit of the exponent separately, since
1939 // squaring the base afterwards is not necessary and may cause a
1940 // needless overflow.
1942 r = acc.overflowing_mul(base);
1952 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1959 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1961 assert_eq!(x.pow(5), 32);",
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1966 #[must_use = "this returns the result of the operation, \
1967 without modifying the original"]
1969 #[rustc_inherit_overflow_checks]
1970 pub const fn pow(self, mut exp: u32) -> Self {
1971 let mut base = self;
1982 // Deal with the final bit of the exponent separately, since
1983 // squaring the base afterwards is not necessary and may cause a
1984 // needless overflow.
1994 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1996 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
1997 with `0 <= self.rem_euclid(rhs) < rhs`.
1999 In other words, the result is `self / rhs` rounded to the integer `n`
2000 such that `self >= n * rhs`.
2001 If `self > 0`, this is equal to round towards zero (the default in Rust);
2002 if `self < 0`, this is equal to round towards +/- infinity.
2006 This function will panic if `rhs` is 0 or the division results in overflow.
2013 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2016 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
2017 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
2018 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
2019 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
2021 #[stable(feature = "euclidean_division", since = "1.38.0")]
2022 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2023 #[must_use = "this returns the result of the operation, \
2024 without modifying the original"]
2026 #[rustc_inherit_overflow_checks]
2027 pub const fn div_euclid(self, rhs: Self) -> Self {
2030 return if rhs > 0 { q - 1 } else { q + 1 }
2038 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
2040 This is done as if by the Euclidean division algorithm -- given
2041 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
2042 `0 <= r < abs(rhs)`.
2046 This function will panic if `rhs` is 0 or the division results in overflow.
2053 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2056 assert_eq!(a.rem_euclid(b), 3);
2057 assert_eq!((-a).rem_euclid(b), 1);
2058 assert_eq!(a.rem_euclid(-b), 3);
2059 assert_eq!((-a).rem_euclid(-b), 1);
2061 #[stable(feature = "euclidean_division", since = "1.38.0")]
2062 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2063 #[must_use = "this returns the result of the operation, \
2064 without modifying the original"]
2066 #[rustc_inherit_overflow_checks]
2067 pub const fn rem_euclid(self, rhs: Self) -> Self {
2082 concat!("Computes the absolute value of `self`.
2086 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
2087 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
2088 code in debug mode will trigger a panic on this case and optimized code will return `",
2089 stringify!($SelfT), "::min_value()` without a panic.
2096 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
2097 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
2100 #[stable(feature = "rust1", since = "1.0.0")]
2101 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2102 #[allow(unused_attributes)]
2103 #[allow_internal_unstable(const_if_match)]
2105 #[rustc_inherit_overflow_checks]
2106 pub const fn abs(self) -> Self {
2107 // Note that the #[inline] above means that the overflow
2108 // semantics of the subtraction depend on the crate we're being
2110 if self.is_negative() {
2119 concat!("Returns a number representing sign of `self`.
2121 - `0` if the number is zero
2122 - `1` if the number is positive
2123 - `-1` if the number is negative
2130 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
2131 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
2132 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
2135 #[stable(feature = "rust1", since = "1.0.0")]
2136 #[rustc_const_unstable(feature = "const_int_sign", issue = "53718")]
2138 pub const fn signum(self) -> Self {
2148 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2156 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2157 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2160 #[stable(feature = "rust1", since = "1.0.0")]
2161 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2163 pub const fn is_positive(self) -> bool { self > 0 }
2167 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2175 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2176 assert!(!10", stringify!($SelfT), ".is_negative());",
2179 #[stable(feature = "rust1", since = "1.0.0")]
2180 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2182 pub const fn is_negative(self) -> bool { self < 0 }
2186 concat!("Return the memory representation of this integer as a byte array in
2187 big-endian (network) byte order.
2194 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2195 assert_eq!(bytes, ", $be_bytes, ");
2197 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2198 #[rustc_const_stable(feature = "const_int_conversion", since = "1.43.0")]
2200 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2201 self.to_be().to_ne_bytes()
2206 concat!("Return the memory representation of this integer as a byte array in
2207 little-endian byte order.
2214 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2215 assert_eq!(bytes, ", $le_bytes, ");
2217 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2218 #[rustc_const_stable(feature = "const_int_conversion", since = "1.43.0")]
2220 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2221 self.to_le().to_ne_bytes()
2227 Return the memory representation of this integer as a byte array in
2230 As the target platform's native endianness is used, portable code
2231 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2236 [`to_be_bytes`]: #method.to_be_bytes
2237 [`to_le_bytes`]: #method.to_le_bytes
2242 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2245 if cfg!(target_endian = \"big\") {
2252 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2253 #[rustc_const_stable(feature = "const_int_conversion", since = "1.43.0")]
2254 #[allow_internal_unstable(const_transmute)]
2256 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2257 // SAFETY: integers are plain old datatypes so we can always transmute them to
2259 unsafe { mem::transmute(self) }
2264 concat!("Create an integer value from its representation as a byte array in
2272 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2273 assert_eq!(value, ", $swap_op, ");
2276 When starting from a slice rather than an array, fallible conversion APIs can be used:
2279 use std::convert::TryInto;
2281 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2282 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2284 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2287 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2288 #[rustc_const_stable(feature = "const_int_conversion", since = "1.43.0")]
2290 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2291 Self::from_be(Self::from_ne_bytes(bytes))
2297 Create an integer value from its representation as a byte array in
2305 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2306 assert_eq!(value, ", $swap_op, ");
2309 When starting from a slice rather than an array, fallible conversion APIs can be used:
2312 use std::convert::TryInto;
2314 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2315 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2317 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2320 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2321 #[rustc_const_stable(feature = "const_int_conversion", since = "1.43.0")]
2323 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2324 Self::from_le(Self::from_ne_bytes(bytes))
2329 concat!("Create an integer value from its memory representation as a byte
2330 array in native endianness.
2332 As the target platform's native endianness is used, portable code
2333 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2334 appropriate instead.
2336 [`from_be_bytes`]: #method.from_be_bytes
2337 [`from_le_bytes`]: #method.from_le_bytes
2344 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2349 assert_eq!(value, ", $swap_op, ");
2352 When starting from a slice rather than an array, fallible conversion APIs can be used:
2355 use std::convert::TryInto;
2357 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2358 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2360 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2363 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2364 #[rustc_const_stable(feature = "const_int_conversion", since = "1.43.0")]
2365 #[allow_internal_unstable(const_transmute)]
2367 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2368 // SAFETY: integers are plain old datatypes so we can always transmute to them
2369 unsafe { mem::transmute(bytes) }
2377 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2378 "[0x12]", "[0x12]", "", "" }
2383 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2384 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2389 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2390 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2391 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2396 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2397 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2398 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2399 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2404 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2405 170141183460469231731687303715884105727, "", "", 16,
2406 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2407 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2408 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2409 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2410 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2411 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2414 #[cfg(target_pointer_width = "16")]
2417 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2418 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2419 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2422 #[cfg(target_pointer_width = "32")]
2425 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2426 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2427 "[0x12, 0x34, 0x56, 0x78]",
2428 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2431 #[cfg(target_pointer_width = "64")]
2434 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2435 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2436 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2437 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2438 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2441 macro_rules! uint_impl {
2442 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2443 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2444 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2445 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2447 concat!("The smallest value that can be represented by this integer type.
2454 #![feature(assoc_int_consts)]
2455 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, 0);", $EndFeature, "
2457 #[unstable(feature = "assoc_int_consts", reason = "recently added", issue = "68490")]
2458 pub const MIN: Self = 0;
2462 concat!("The largest value that can be represented by this integer type.
2469 #![feature(assoc_int_consts)]
2470 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");",
2473 #[unstable(feature = "assoc_int_consts", reason = "recently added", issue = "68490")]
2474 pub const MAX: Self = !0;
2478 "Returns the smallest value that can be represented by this integer type.",
2479 #[stable(feature = "rust1", since = "1.0.0")]
2482 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2483 pub const fn min_value() -> Self { Self::MIN }
2487 "Returns the largest value that can be represented by this integer type.",
2488 #[stable(feature = "rust1", since = "1.0.0")]
2491 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2492 pub const fn max_value() -> Self { Self::MAX }
2496 concat!("Converts a string slice in a given base to an integer.
2498 The string is expected to be an optional `+` sign
2500 Leading and trailing whitespace represent an error.
2501 Digits are a subset of these characters, depending on `radix`:
2509 This function panics if `radix` is not in the range from 2 to 36.
2516 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2519 #[stable(feature = "rust1", since = "1.0.0")]
2520 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2521 from_str_radix(src, radix)
2526 concat!("Returns the number of ones in the binary representation of `self`.
2533 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2535 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2537 #[stable(feature = "rust1", since = "1.0.0")]
2538 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2540 pub const fn count_ones(self) -> u32 {
2541 intrinsics::ctpop(self as $ActualT) as u32
2546 concat!("Returns the number of zeros in the binary representation of `self`.
2553 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2555 #[stable(feature = "rust1", since = "1.0.0")]
2556 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2558 pub const fn count_zeros(self) -> u32 {
2559 (!self).count_ones()
2564 concat!("Returns the number of leading zeros in the binary representation of `self`.
2571 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2573 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2575 #[stable(feature = "rust1", since = "1.0.0")]
2576 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2578 pub const fn leading_zeros(self) -> u32 {
2579 intrinsics::ctlz(self as $ActualT) as u32
2584 concat!("Returns the number of trailing zeros in the binary representation
2592 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2594 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2596 #[stable(feature = "rust1", since = "1.0.0")]
2597 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2599 pub const fn trailing_zeros(self) -> u32 {
2600 intrinsics::cttz(self) as u32
2605 concat!("Returns the number of leading ones in the binary representation of `self`.
2612 ", $Feature, "#![feature(leading_trailing_ones)]
2613 let n = !(", stringify!($SelfT), "::max_value() >> 2);
2615 assert_eq!(n.leading_ones(), 2);", $EndFeature, "
2617 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2619 pub const fn leading_ones(self) -> u32 {
2620 (!self).leading_zeros()
2625 concat!("Returns the number of trailing ones in the binary representation
2633 ", $Feature, "#![feature(leading_trailing_ones)]
2634 let n = 0b1010111", stringify!($SelfT), ";
2636 assert_eq!(n.trailing_ones(), 3);", $EndFeature, "
2638 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2640 pub const fn trailing_ones(self) -> u32 {
2641 (!self).trailing_zeros()
2646 concat!("Shifts the bits to the left by a specified amount, `n`,
2647 wrapping the truncated bits to the end of the resulting integer.
2649 Please note this isn't the same operation as the `<<` shifting operator!
2656 let n = ", $rot_op, stringify!($SelfT), ";
2657 let m = ", $rot_result, ";
2659 assert_eq!(n.rotate_left(", $rot, "), m);
2661 #[stable(feature = "rust1", since = "1.0.0")]
2662 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2663 #[must_use = "this returns the result of the operation, \
2664 without modifying the original"]
2666 pub const fn rotate_left(self, n: u32) -> Self {
2667 intrinsics::rotate_left(self, n as $SelfT)
2672 concat!("Shifts the bits to the right by a specified amount, `n`,
2673 wrapping the truncated bits to the beginning of the resulting
2676 Please note this isn't the same operation as the `>>` shifting operator!
2683 let n = ", $rot_result, stringify!($SelfT), ";
2684 let m = ", $rot_op, ";
2686 assert_eq!(n.rotate_right(", $rot, "), m);
2688 #[stable(feature = "rust1", since = "1.0.0")]
2689 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2690 #[must_use = "this returns the result of the operation, \
2691 without modifying the original"]
2693 pub const fn rotate_right(self, n: u32) -> Self {
2694 intrinsics::rotate_right(self, n as $SelfT)
2700 Reverses the byte order of the integer.
2707 let n = ", $swap_op, stringify!($SelfT), ";
2708 let m = n.swap_bytes();
2710 assert_eq!(m, ", $swapped, ");
2712 #[stable(feature = "rust1", since = "1.0.0")]
2713 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2715 pub const fn swap_bytes(self) -> Self {
2716 intrinsics::bswap(self as $ActualT) as Self
2721 concat!("Reverses the bit pattern of the integer.
2728 let n = ", $swap_op, stringify!($SelfT), ";
2729 let m = n.reverse_bits();
2731 assert_eq!(m, ", $reversed, ");
2733 #[stable(feature = "reverse_bits", since = "1.37.0")]
2734 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2737 pub const fn reverse_bits(self) -> Self {
2738 intrinsics::bitreverse(self as $ActualT) as Self
2743 concat!("Converts an integer from big endian to the target's endianness.
2745 On big endian this is a no-op. On little endian the bytes are
2753 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2755 if cfg!(target_endian = \"big\") {
2756 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2758 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2761 #[stable(feature = "rust1", since = "1.0.0")]
2762 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2764 pub const fn from_be(x: Self) -> Self {
2765 #[cfg(target_endian = "big")]
2769 #[cfg(not(target_endian = "big"))]
2777 concat!("Converts an integer from little endian to the target's endianness.
2779 On little endian this is a no-op. On big endian the bytes are
2787 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2789 if cfg!(target_endian = \"little\") {
2790 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2792 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2795 #[stable(feature = "rust1", since = "1.0.0")]
2796 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2798 pub const fn from_le(x: Self) -> Self {
2799 #[cfg(target_endian = "little")]
2803 #[cfg(not(target_endian = "little"))]
2811 concat!("Converts `self` to big endian from the target's endianness.
2813 On big endian this is a no-op. On little endian the bytes are
2821 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2823 if cfg!(target_endian = \"big\") {
2824 assert_eq!(n.to_be(), n)
2826 assert_eq!(n.to_be(), n.swap_bytes())
2829 #[stable(feature = "rust1", since = "1.0.0")]
2830 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2832 pub const fn to_be(self) -> Self { // or not to be?
2833 #[cfg(target_endian = "big")]
2837 #[cfg(not(target_endian = "big"))]
2845 concat!("Converts `self` to little endian from the target's endianness.
2847 On little endian this is a no-op. On big endian the bytes are
2855 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2857 if cfg!(target_endian = \"little\") {
2858 assert_eq!(n.to_le(), n)
2860 assert_eq!(n.to_le(), n.swap_bytes())
2863 #[stable(feature = "rust1", since = "1.0.0")]
2864 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2866 pub const fn to_le(self) -> Self {
2867 #[cfg(target_endian = "little")]
2871 #[cfg(not(target_endian = "little"))]
2879 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2880 if overflow occurred.
2887 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2888 "Some(", stringify!($SelfT), "::max_value() - 1));
2889 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2891 #[stable(feature = "rust1", since = "1.0.0")]
2892 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2893 #[must_use = "this returns the result of the operation, \
2894 without modifying the original"]
2896 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
2897 let (a, b) = self.overflowing_add(rhs);
2898 if b {None} else {Some(a)}
2903 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2904 `None` if overflow occurred.
2911 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2912 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2914 #[stable(feature = "rust1", since = "1.0.0")]
2915 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2916 #[must_use = "this returns the result of the operation, \
2917 without modifying the original"]
2919 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
2920 let (a, b) = self.overflowing_sub(rhs);
2921 if b {None} else {Some(a)}
2926 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2927 `None` if overflow occurred.
2934 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2935 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2937 #[stable(feature = "rust1", since = "1.0.0")]
2938 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2939 #[must_use = "this returns the result of the operation, \
2940 without modifying the original"]
2942 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
2943 let (a, b) = self.overflowing_mul(rhs);
2944 if b {None} else {Some(a)}
2949 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2957 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2958 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2960 #[stable(feature = "rust1", since = "1.0.0")]
2961 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2962 #[must_use = "this returns the result of the operation, \
2963 without modifying the original"]
2965 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
2968 // SAFETY: div by zero has been checked above and unsigned types have no other
2969 // failure modes for division
2970 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2976 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2984 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
2985 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
2987 #[stable(feature = "euclidean_division", since = "1.38.0")]
2988 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2989 #[must_use = "this returns the result of the operation, \
2990 without modifying the original"]
2992 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
2996 Some(self.div_euclid(rhs))
3003 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
3011 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
3012 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
3014 #[stable(feature = "wrapping", since = "1.7.0")]
3015 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3016 #[must_use = "this returns the result of the operation, \
3017 without modifying the original"]
3019 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
3023 // SAFETY: div by zero has been checked above and unsigned types have no other
3024 // failure modes for division
3025 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3031 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3039 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3040 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3042 #[stable(feature = "euclidean_division", since = "1.38.0")]
3043 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3044 #[must_use = "this returns the result of the operation, \
3045 without modifying the original"]
3047 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3051 Some(self.rem_euclid(rhs))
3057 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3060 Note that negating any positive integer will overflow.
3067 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3068 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3070 #[stable(feature = "wrapping", since = "1.7.0")]
3071 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3073 pub const fn checked_neg(self) -> Option<Self> {
3074 let (a, b) = self.overflowing_neg();
3075 if b {None} else {Some(a)}
3080 concat!("Checked shift left. Computes `self << rhs`, returning `None`
3081 if `rhs` is larger than or equal to the number of bits in `self`.
3088 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3089 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3091 #[stable(feature = "wrapping", since = "1.7.0")]
3092 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3093 #[must_use = "this returns the result of the operation, \
3094 without modifying the original"]
3096 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
3097 let (a, b) = self.overflowing_shl(rhs);
3098 if b {None} else {Some(a)}
3103 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3104 if `rhs` is larger than or equal to the number of bits in `self`.
3111 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3112 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3114 #[stable(feature = "wrapping", since = "1.7.0")]
3115 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3116 #[must_use = "this returns the result of the operation, \
3117 without modifying the original"]
3119 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
3120 let (a, b) = self.overflowing_shr(rhs);
3121 if b {None} else {Some(a)}
3126 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3134 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3135 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
3137 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3138 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3139 #[must_use = "this returns the result of the operation, \
3140 without modifying the original"]
3142 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
3143 let mut base = self;
3144 let mut acc: Self = 1;
3148 acc = try_opt!(acc.checked_mul(base));
3151 base = try_opt!(base.checked_mul(base));
3154 // Deal with the final bit of the exponent separately, since
3155 // squaring the base afterwards is not necessary and may cause a
3156 // needless overflow.
3158 acc = try_opt!(acc.checked_mul(base));
3166 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3167 the numeric bounds instead of overflowing.
3174 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3175 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
3178 #[stable(feature = "rust1", since = "1.0.0")]
3179 #[must_use = "this returns the result of the operation, \
3180 without modifying the original"]
3181 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3183 pub const fn saturating_add(self, rhs: Self) -> Self {
3184 intrinsics::saturating_add(self, rhs)
3189 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3190 at the numeric bounds instead of overflowing.
3197 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3198 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3200 #[stable(feature = "rust1", since = "1.0.0")]
3201 #[must_use = "this returns the result of the operation, \
3202 without modifying the original"]
3203 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3205 pub const fn saturating_sub(self, rhs: Self) -> Self {
3206 intrinsics::saturating_sub(self, rhs)
3211 concat!("Saturating integer multiplication. Computes `self * rhs`,
3212 saturating at the numeric bounds instead of overflowing.
3219 ", $Feature, "use std::", stringify!($SelfT), ";
3221 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3222 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3223 "::MAX);", $EndFeature, "
3225 #[stable(feature = "wrapping", since = "1.7.0")]
3226 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3227 #[must_use = "this returns the result of the operation, \
3228 without modifying the original"]
3230 pub const fn saturating_mul(self, rhs: Self) -> Self {
3231 match self.checked_mul(rhs) {
3233 None => Self::max_value(),
3239 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3240 saturating at the numeric bounds instead of overflowing.
3247 ", $Feature, "use std::", stringify!($SelfT), ";
3249 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3250 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3253 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3254 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3255 #[must_use = "this returns the result of the operation, \
3256 without modifying the original"]
3258 pub const fn saturating_pow(self, exp: u32) -> Self {
3259 match self.checked_pow(exp) {
3261 None => Self::max_value(),
3267 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3268 wrapping around at the boundary of the type.
3275 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3276 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
3279 #[stable(feature = "rust1", since = "1.0.0")]
3280 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3281 #[must_use = "this returns the result of the operation, \
3282 without modifying the original"]
3284 pub const fn wrapping_add(self, rhs: Self) -> Self {
3285 intrinsics::wrapping_add(self, rhs)
3290 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3291 wrapping around at the boundary of the type.
3298 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3299 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
3302 #[stable(feature = "rust1", since = "1.0.0")]
3303 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3304 #[must_use = "this returns the result of the operation, \
3305 without modifying the original"]
3307 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3308 intrinsics::wrapping_sub(self, rhs)
3312 /// Wrapping (modular) multiplication. Computes `self *
3313 /// rhs`, wrapping around at the boundary of the type.
3319 /// Please note that this example is shared between integer types.
3320 /// Which explains why `u8` is used here.
3323 /// assert_eq!(10u8.wrapping_mul(12), 120);
3324 /// assert_eq!(25u8.wrapping_mul(12), 44);
3326 #[stable(feature = "rust1", since = "1.0.0")]
3327 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3328 #[must_use = "this returns the result of the operation, \
3329 without modifying the original"]
3331 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3332 intrinsics::wrapping_mul(self, rhs)
3336 concat!("Wrapping (modular) division. Computes `self / rhs`.
3337 Wrapped division on unsigned types is just normal division.
3338 There's no way wrapping could ever happen.
3339 This function exists, so that all operations
3340 are accounted for in the wrapping operations.
3347 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3349 #[stable(feature = "num_wrapping", since = "1.2.0")]
3350 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3351 #[must_use = "this returns the result of the operation, \
3352 without modifying the original"]
3354 pub const fn wrapping_div(self, rhs: Self) -> Self {
3360 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3361 Wrapped division on unsigned types is just normal division.
3362 There's no way wrapping could ever happen.
3363 This function exists, so that all operations
3364 are accounted for in the wrapping operations.
3365 Since, for the positive integers, all common
3366 definitions of division are equal, this
3367 is exactly equal to `self.wrapping_div(rhs)`.
3374 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3376 #[stable(feature = "euclidean_division", since = "1.38.0")]
3377 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3378 #[must_use = "this returns the result of the operation, \
3379 without modifying the original"]
3381 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
3387 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3388 Wrapped remainder calculation on unsigned types is
3389 just the regular remainder calculation.
3390 There's no way wrapping could ever happen.
3391 This function exists, so that all operations
3392 are accounted for in the wrapping operations.
3399 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3401 #[stable(feature = "num_wrapping", since = "1.2.0")]
3402 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3403 #[must_use = "this returns the result of the operation, \
3404 without modifying the original"]
3406 pub const fn wrapping_rem(self, rhs: Self) -> Self {
3412 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3413 Wrapped modulo calculation on unsigned types is
3414 just the regular remainder calculation.
3415 There's no way wrapping could ever happen.
3416 This function exists, so that all operations
3417 are accounted for in the wrapping operations.
3418 Since, for the positive integers, all common
3419 definitions of division are equal, this
3420 is exactly equal to `self.wrapping_rem(rhs)`.
3427 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3429 #[stable(feature = "euclidean_division", since = "1.38.0")]
3430 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3431 #[must_use = "this returns the result of the operation, \
3432 without modifying the original"]
3434 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3439 /// Wrapping (modular) negation. Computes `-self`,
3440 /// wrapping around at the boundary of the type.
3442 /// Since unsigned types do not have negative equivalents
3443 /// all applications of this function will wrap (except for `-0`).
3444 /// For values smaller than the corresponding signed type's maximum
3445 /// the result is the same as casting the corresponding signed value.
3446 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3447 /// `MAX` is the corresponding signed type's maximum.
3453 /// Please note that this example is shared between integer types.
3454 /// Which explains why `i8` is used here.
3457 /// assert_eq!(100i8.wrapping_neg(), -100);
3458 /// assert_eq!((-128i8).wrapping_neg(), -128);
3460 #[stable(feature = "num_wrapping", since = "1.2.0")]
3461 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3463 pub const fn wrapping_neg(self) -> Self {
3464 self.overflowing_neg().0
3468 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3469 where `mask` removes any high-order bits of `rhs` that
3470 would cause the shift to exceed the bitwidth of the type.
3472 Note that this is *not* the same as a rotate-left; the
3473 RHS of a wrapping shift-left is restricted to the range
3474 of the type, rather than the bits shifted out of the LHS
3475 being returned to the other end. The primitive integer
3476 types all implement a `rotate_left` function, which may
3477 be what you want instead.
3484 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3485 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3487 #[stable(feature = "num_wrapping", since = "1.2.0")]
3488 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3489 #[must_use = "this returns the result of the operation, \
3490 without modifying the original"]
3492 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3493 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3496 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3502 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3503 where `mask` removes any high-order bits of `rhs` that
3504 would cause the shift to exceed the bitwidth of the type.
3506 Note that this is *not* the same as a rotate-right; the
3507 RHS of a wrapping shift-right is restricted to the range
3508 of the type, rather than the bits shifted out of the LHS
3509 being returned to the other end. The primitive integer
3510 types all implement a `rotate_right` function, which may
3511 be what you want instead.
3518 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3519 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3521 #[stable(feature = "num_wrapping", since = "1.2.0")]
3522 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3523 #[must_use = "this returns the result of the operation, \
3524 without modifying the original"]
3526 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3527 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3530 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3536 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3537 wrapping around at the boundary of the type.
3544 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3545 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3547 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3548 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3549 #[must_use = "this returns the result of the operation, \
3550 without modifying the original"]
3552 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
3553 let mut base = self;
3554 let mut acc: Self = 1;
3558 acc = acc.wrapping_mul(base);
3561 base = base.wrapping_mul(base);
3564 // Deal with the final bit of the exponent separately, since
3565 // squaring the base afterwards is not necessary and may cause a
3566 // needless overflow.
3568 acc = acc.wrapping_mul(base);
3576 concat!("Calculates `self` + `rhs`
3578 Returns a tuple of the addition along with a boolean indicating
3579 whether an arithmetic overflow would occur. If an overflow would
3580 have occurred then the wrapped value is returned.
3587 ", $Feature, "use std::", stringify!($SelfT), ";
3589 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3590 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3592 #[stable(feature = "wrapping", since = "1.7.0")]
3593 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3594 #[must_use = "this returns the result of the operation, \
3595 without modifying the original"]
3597 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3598 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3604 concat!("Calculates `self` - `rhs`
3606 Returns a tuple of the subtraction along with a boolean indicating
3607 whether an arithmetic overflow would occur. If an overflow would
3608 have occurred then the wrapped value is returned.
3615 ", $Feature, "use std::", stringify!($SelfT), ";
3617 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3618 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3621 #[stable(feature = "wrapping", since = "1.7.0")]
3622 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3623 #[must_use = "this returns the result of the operation, \
3624 without modifying the original"]
3626 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3627 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3632 /// Calculates the multiplication of `self` and `rhs`.
3634 /// Returns a tuple of the multiplication along with a boolean
3635 /// indicating whether an arithmetic overflow would occur. If an
3636 /// overflow would have occurred then the wrapped value is returned.
3642 /// Please note that this example is shared between integer types.
3643 /// Which explains why `u32` is used here.
3646 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3647 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3649 #[stable(feature = "wrapping", since = "1.7.0")]
3650 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3651 #[must_use = "this returns the result of the operation, \
3652 without modifying the original"]
3654 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3655 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3660 concat!("Calculates the divisor when `self` is divided by `rhs`.
3662 Returns a tuple of the divisor along with a boolean indicating
3663 whether an arithmetic overflow would occur. Note that for unsigned
3664 integers overflow never occurs, so the second value is always
3669 This function will panic if `rhs` is 0.
3676 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3679 #[stable(feature = "wrapping", since = "1.7.0")]
3680 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3681 #[must_use = "this returns the result of the operation, \
3682 without modifying the original"]
3683 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3689 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3691 Returns a tuple of the divisor along with a boolean indicating
3692 whether an arithmetic overflow would occur. Note that for unsigned
3693 integers overflow never occurs, so the second value is always
3695 Since, for the positive integers, all common
3696 definitions of division are equal, this
3697 is exactly equal to `self.overflowing_div(rhs)`.
3701 This function will panic if `rhs` is 0.
3708 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3711 #[stable(feature = "euclidean_division", since = "1.38.0")]
3712 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3713 #[must_use = "this returns the result of the operation, \
3714 without modifying the original"]
3715 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3721 concat!("Calculates the remainder when `self` is divided by `rhs`.
3723 Returns a tuple of the remainder after dividing along with a boolean
3724 indicating whether an arithmetic overflow would occur. Note that for
3725 unsigned integers overflow never occurs, so the second value is
3730 This function will panic if `rhs` is 0.
3737 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3740 #[stable(feature = "wrapping", since = "1.7.0")]
3741 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3742 #[must_use = "this returns the result of the operation, \
3743 without modifying the original"]
3744 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3750 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3752 Returns a tuple of the modulo after dividing along with a boolean
3753 indicating whether an arithmetic overflow would occur. Note that for
3754 unsigned integers overflow never occurs, so the second value is
3756 Since, for the positive integers, all common
3757 definitions of division are equal, this operation
3758 is exactly equal to `self.overflowing_rem(rhs)`.
3762 This function will panic if `rhs` is 0.
3769 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3772 #[stable(feature = "euclidean_division", since = "1.38.0")]
3773 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3774 #[must_use = "this returns the result of the operation, \
3775 without modifying the original"]
3776 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3782 concat!("Negates self in an overflowing fashion.
3784 Returns `!self + 1` using wrapping operations to return the value
3785 that represents the negation of this unsigned value. Note that for
3786 positive unsigned values overflow always occurs, but negating 0 does
3794 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3795 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3796 ", true));", $EndFeature, "
3799 #[stable(feature = "wrapping", since = "1.7.0")]
3800 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3801 pub const fn overflowing_neg(self) -> (Self, bool) {
3802 ((!self).wrapping_add(1), self != 0)
3807 concat!("Shifts self left by `rhs` bits.
3809 Returns a tuple of the shifted version of self along with a boolean
3810 indicating whether the shift value was larger than or equal to the
3811 number of bits. If the shift value is too large, then value is
3812 masked (N-1) where N is the number of bits, and this value is then
3813 used to perform the shift.
3820 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3821 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3823 #[stable(feature = "wrapping", since = "1.7.0")]
3824 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3825 #[must_use = "this returns the result of the operation, \
3826 without modifying the original"]
3828 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3829 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3834 concat!("Shifts self right by `rhs` bits.
3836 Returns a tuple of the shifted version of self along with a boolean
3837 indicating whether the shift value was larger than or equal to the
3838 number of bits. If the shift value is too large, then value is
3839 masked (N-1) where N is the number of bits, and this value is then
3840 used to perform the shift.
3847 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3848 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3850 #[stable(feature = "wrapping", since = "1.7.0")]
3851 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3852 #[must_use = "this returns the result of the operation, \
3853 without modifying the original"]
3855 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3856 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3861 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3863 Returns a tuple of the exponentiation along with a bool indicating
3864 whether an overflow happened.
3871 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3872 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3874 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3875 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3876 #[must_use = "this returns the result of the operation, \
3877 without modifying the original"]
3879 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3880 let mut base = self;
3881 let mut acc: Self = 1;
3882 let mut overflown = false;
3883 // Scratch space for storing results of overflowing_mul.
3888 r = acc.overflowing_mul(base);
3893 r = base.overflowing_mul(base);
3898 // Deal with the final bit of the exponent separately, since
3899 // squaring the base afterwards is not necessary and may cause a
3900 // needless overflow.
3902 r = acc.overflowing_mul(base);
3912 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3919 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3921 #[stable(feature = "rust1", since = "1.0.0")]
3922 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3923 #[must_use = "this returns the result of the operation, \
3924 without modifying the original"]
3926 #[rustc_inherit_overflow_checks]
3927 pub const fn pow(self, mut exp: u32) -> Self {
3928 let mut base = self;
3939 // Deal with the final bit of the exponent separately, since
3940 // squaring the base afterwards is not necessary and may cause a
3941 // needless overflow.
3951 concat!("Performs Euclidean division.
3953 Since, for the positive integers, all common
3954 definitions of division are equal, this
3955 is exactly equal to `self / rhs`.
3959 This function will panic if `rhs` is 0.
3966 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
3968 #[stable(feature = "euclidean_division", since = "1.38.0")]
3969 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3970 #[must_use = "this returns the result of the operation, \
3971 without modifying the original"]
3973 #[rustc_inherit_overflow_checks]
3974 pub const fn div_euclid(self, rhs: Self) -> Self {
3981 concat!("Calculates the least remainder of `self (mod rhs)`.
3983 Since, for the positive integers, all common
3984 definitions of division are equal, this
3985 is exactly equal to `self % rhs`.
3989 This function will panic if `rhs` is 0.
3996 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
3998 #[stable(feature = "euclidean_division", since = "1.38.0")]
3999 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
4000 #[must_use = "this returns the result of the operation, \
4001 without modifying the original"]
4003 #[rustc_inherit_overflow_checks]
4004 pub const fn rem_euclid(self, rhs: Self) -> Self {
4010 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
4017 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
4018 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
4020 #[stable(feature = "rust1", since = "1.0.0")]
4021 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
4023 pub const fn is_power_of_two(self) -> bool {
4024 self.count_ones() == 1
4028 // Returns one less than next power of two.
4029 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
4031 // 8u8.one_less_than_next_power_of_two() == 7
4032 // 6u8.one_less_than_next_power_of_two() == 7
4034 // This method cannot overflow, as in the `next_power_of_two`
4035 // overflow cases it instead ends up returning the maximum value
4036 // of the type, and can return 0 for 0.
4038 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4039 const fn one_less_than_next_power_of_two(self) -> Self {
4040 if self <= 1 { return 0; }
4043 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4044 // That means the shift is always in-bounds, and some processors
4045 // (such as intel pre-haswell) have more efficient ctlz
4046 // intrinsics when the argument is non-zero.
4047 let z = unsafe { intrinsics::ctlz_nonzero(p) };
4048 <$SelfT>::max_value() >> z
4052 concat!("Returns the smallest power of two greater than or equal to `self`.
4054 When return value overflows (i.e., `self > (1 << (N-1))` for type
4055 `uN`), it panics in debug mode and return value is wrapped to 0 in
4056 release mode (the only situation in which method can return 0).
4063 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4064 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4066 #[stable(feature = "rust1", since = "1.0.0")]
4067 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4069 #[rustc_inherit_overflow_checks]
4070 pub const fn next_power_of_two(self) -> Self {
4071 self.one_less_than_next_power_of_two() + 1
4076 concat!("Returns the smallest power of two greater than or equal to `n`. If
4077 the next power of two is greater than the type's maximum value,
4078 `None` is returned, otherwise the power of two is wrapped in `Some`.
4085 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4086 ".checked_next_power_of_two(), Some(2));
4087 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4088 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
4092 #[stable(feature = "rust1", since = "1.0.0")]
4093 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4094 pub const fn checked_next_power_of_two(self) -> Option<Self> {
4095 self.one_less_than_next_power_of_two().checked_add(1)
4100 concat!("Returns the smallest power of two greater than or equal to `n`. If
4101 the next power of two is greater than the type's maximum value,
4102 the return value is wrapped to `0`.
4109 #![feature(wrapping_next_power_of_two)]
4111 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4112 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4113 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
4116 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4117 reason = "needs decision on wrapping behaviour")]
4118 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4119 pub const fn wrapping_next_power_of_two(self) -> Self {
4120 self.one_less_than_next_power_of_two().wrapping_add(1)
4125 concat!("Return the memory representation of this integer as a byte array in
4126 big-endian (network) byte order.
4133 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4134 assert_eq!(bytes, ", $be_bytes, ");
4136 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4137 #[rustc_const_stable(feature = "const_int_conversion", since = "1.43.0")]
4139 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4140 self.to_be().to_ne_bytes()
4145 concat!("Return the memory representation of this integer as a byte array in
4146 little-endian byte order.
4153 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4154 assert_eq!(bytes, ", $le_bytes, ");
4156 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4157 #[rustc_const_stable(feature = "const_int_conversion", since = "1.43.0")]
4159 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4160 self.to_le().to_ne_bytes()
4166 Return the memory representation of this integer as a byte array in
4169 As the target platform's native endianness is used, portable code
4170 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4175 [`to_be_bytes`]: #method.to_be_bytes
4176 [`to_le_bytes`]: #method.to_le_bytes
4181 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4184 if cfg!(target_endian = \"big\") {
4191 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4192 #[rustc_const_stable(feature = "const_int_conversion", since = "1.43.0")]
4193 #[allow_internal_unstable(const_transmute)]
4195 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4196 // SAFETY: integers are plain old datatypes so we can always transmute them to
4198 unsafe { mem::transmute(self) }
4203 concat!("Create an integer value from its representation as a byte array in
4211 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4212 assert_eq!(value, ", $swap_op, ");
4215 When starting from a slice rather than an array, fallible conversion APIs can be used:
4218 use std::convert::TryInto;
4220 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4221 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4223 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4226 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4227 #[rustc_const_stable(feature = "const_int_conversion", since = "1.43.0")]
4229 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4230 Self::from_be(Self::from_ne_bytes(bytes))
4236 Create an integer value from its representation as a byte array in
4244 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4245 assert_eq!(value, ", $swap_op, ");
4248 When starting from a slice rather than an array, fallible conversion APIs can be used:
4251 use std::convert::TryInto;
4253 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4254 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4256 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4259 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4260 #[rustc_const_stable(feature = "const_int_conversion", since = "1.43.0")]
4262 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4263 Self::from_le(Self::from_ne_bytes(bytes))
4268 concat!("Create an integer value from its memory representation as a byte
4269 array in native endianness.
4271 As the target platform's native endianness is used, portable code
4272 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4273 appropriate instead.
4275 [`from_be_bytes`]: #method.from_be_bytes
4276 [`from_le_bytes`]: #method.from_le_bytes
4283 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4288 assert_eq!(value, ", $swap_op, ");
4291 When starting from a slice rather than an array, fallible conversion APIs can be used:
4294 use std::convert::TryInto;
4296 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4297 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4299 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4302 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4303 #[rustc_const_stable(feature = "const_int_conversion", since = "1.43.0")]
4304 #[allow_internal_unstable(const_transmute)]
4306 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4307 // SAFETY: integers are plain old datatypes so we can always transmute to them
4308 unsafe { mem::transmute(bytes) }
4316 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4319 /// Checks if the value is within the ASCII range.
4324 /// let ascii = 97u8;
4325 /// let non_ascii = 150u8;
4327 /// assert!(ascii.is_ascii());
4328 /// assert!(!non_ascii.is_ascii());
4330 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4332 pub fn is_ascii(&self) -> bool {
4336 /// Makes a copy of the value in its ASCII upper case equivalent.
4338 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4339 /// but non-ASCII letters are unchanged.
4341 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4346 /// let lowercase_a = 97u8;
4348 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4351 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4352 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4354 pub fn to_ascii_uppercase(&self) -> u8 {
4355 // Unset the fith bit if this is a lowercase letter
4356 *self & !((self.is_ascii_lowercase() as u8) << 5)
4359 /// Makes a copy of the value in its ASCII lower case equivalent.
4361 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4362 /// but non-ASCII letters are unchanged.
4364 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4369 /// let uppercase_a = 65u8;
4371 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4374 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4375 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4377 pub fn to_ascii_lowercase(&self) -> u8 {
4378 // Set the fith bit if this is an uppercase letter
4379 *self | ((self.is_ascii_uppercase() as u8) << 5)
4382 /// Checks that two values are an ASCII case-insensitive match.
4384 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4389 /// let lowercase_a = 97u8;
4390 /// let uppercase_a = 65u8;
4392 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4394 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4396 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4397 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4400 /// Converts this value to its ASCII upper case equivalent in-place.
4402 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4403 /// but non-ASCII letters are unchanged.
4405 /// To return a new uppercased value without modifying the existing one, use
4406 /// [`to_ascii_uppercase`].
4411 /// let mut byte = b'a';
4413 /// byte.make_ascii_uppercase();
4415 /// assert_eq!(b'A', byte);
4418 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4419 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4421 pub fn make_ascii_uppercase(&mut self) {
4422 *self = self.to_ascii_uppercase();
4425 /// Converts this value to its ASCII lower case equivalent in-place.
4427 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4428 /// but non-ASCII letters are unchanged.
4430 /// To return a new lowercased value without modifying the existing one, use
4431 /// [`to_ascii_lowercase`].
4436 /// let mut byte = b'A';
4438 /// byte.make_ascii_lowercase();
4440 /// assert_eq!(b'a', byte);
4443 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4444 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4446 pub fn make_ascii_lowercase(&mut self) {
4447 *self = self.to_ascii_lowercase();
4450 /// Checks if the value is an ASCII alphabetic character:
4452 /// - U+0041 'A' ..= U+005A 'Z', or
4453 /// - U+0061 'a' ..= U+007A 'z'.
4458 /// let uppercase_a = b'A';
4459 /// let uppercase_g = b'G';
4462 /// let zero = b'0';
4463 /// let percent = b'%';
4464 /// let space = b' ';
4466 /// let esc = 0x1b_u8;
4468 /// assert!(uppercase_a.is_ascii_alphabetic());
4469 /// assert!(uppercase_g.is_ascii_alphabetic());
4470 /// assert!(a.is_ascii_alphabetic());
4471 /// assert!(g.is_ascii_alphabetic());
4472 /// assert!(!zero.is_ascii_alphabetic());
4473 /// assert!(!percent.is_ascii_alphabetic());
4474 /// assert!(!space.is_ascii_alphabetic());
4475 /// assert!(!lf.is_ascii_alphabetic());
4476 /// assert!(!esc.is_ascii_alphabetic());
4478 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4479 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4481 pub const fn is_ascii_alphabetic(&self) -> bool {
4482 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
4485 /// Checks if the value is an ASCII uppercase character:
4486 /// U+0041 'A' ..= U+005A 'Z'.
4491 /// let uppercase_a = b'A';
4492 /// let uppercase_g = b'G';
4495 /// let zero = b'0';
4496 /// let percent = b'%';
4497 /// let space = b' ';
4499 /// let esc = 0x1b_u8;
4501 /// assert!(uppercase_a.is_ascii_uppercase());
4502 /// assert!(uppercase_g.is_ascii_uppercase());
4503 /// assert!(!a.is_ascii_uppercase());
4504 /// assert!(!g.is_ascii_uppercase());
4505 /// assert!(!zero.is_ascii_uppercase());
4506 /// assert!(!percent.is_ascii_uppercase());
4507 /// assert!(!space.is_ascii_uppercase());
4508 /// assert!(!lf.is_ascii_uppercase());
4509 /// assert!(!esc.is_ascii_uppercase());
4511 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4512 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4514 pub const fn is_ascii_uppercase(&self) -> bool {
4515 matches!(*self, b'A'..=b'Z')
4518 /// Checks if the value is an ASCII lowercase character:
4519 /// U+0061 'a' ..= U+007A 'z'.
4524 /// let uppercase_a = b'A';
4525 /// let uppercase_g = b'G';
4528 /// let zero = b'0';
4529 /// let percent = b'%';
4530 /// let space = b' ';
4532 /// let esc = 0x1b_u8;
4534 /// assert!(!uppercase_a.is_ascii_lowercase());
4535 /// assert!(!uppercase_g.is_ascii_lowercase());
4536 /// assert!(a.is_ascii_lowercase());
4537 /// assert!(g.is_ascii_lowercase());
4538 /// assert!(!zero.is_ascii_lowercase());
4539 /// assert!(!percent.is_ascii_lowercase());
4540 /// assert!(!space.is_ascii_lowercase());
4541 /// assert!(!lf.is_ascii_lowercase());
4542 /// assert!(!esc.is_ascii_lowercase());
4544 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4545 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4547 pub const fn is_ascii_lowercase(&self) -> bool {
4548 matches!(*self, b'a'..=b'z')
4551 /// Checks if the value is an ASCII alphanumeric character:
4553 /// - U+0041 'A' ..= U+005A 'Z', or
4554 /// - U+0061 'a' ..= U+007A 'z', or
4555 /// - U+0030 '0' ..= U+0039 '9'.
4560 /// let uppercase_a = b'A';
4561 /// let uppercase_g = b'G';
4564 /// let zero = b'0';
4565 /// let percent = b'%';
4566 /// let space = b' ';
4568 /// let esc = 0x1b_u8;
4570 /// assert!(uppercase_a.is_ascii_alphanumeric());
4571 /// assert!(uppercase_g.is_ascii_alphanumeric());
4572 /// assert!(a.is_ascii_alphanumeric());
4573 /// assert!(g.is_ascii_alphanumeric());
4574 /// assert!(zero.is_ascii_alphanumeric());
4575 /// assert!(!percent.is_ascii_alphanumeric());
4576 /// assert!(!space.is_ascii_alphanumeric());
4577 /// assert!(!lf.is_ascii_alphanumeric());
4578 /// assert!(!esc.is_ascii_alphanumeric());
4580 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4581 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4583 pub const fn is_ascii_alphanumeric(&self) -> bool {
4584 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
4587 /// Checks if the value is an ASCII decimal digit:
4588 /// U+0030 '0' ..= U+0039 '9'.
4593 /// let uppercase_a = b'A';
4594 /// let uppercase_g = b'G';
4597 /// let zero = b'0';
4598 /// let percent = b'%';
4599 /// let space = b' ';
4601 /// let esc = 0x1b_u8;
4603 /// assert!(!uppercase_a.is_ascii_digit());
4604 /// assert!(!uppercase_g.is_ascii_digit());
4605 /// assert!(!a.is_ascii_digit());
4606 /// assert!(!g.is_ascii_digit());
4607 /// assert!(zero.is_ascii_digit());
4608 /// assert!(!percent.is_ascii_digit());
4609 /// assert!(!space.is_ascii_digit());
4610 /// assert!(!lf.is_ascii_digit());
4611 /// assert!(!esc.is_ascii_digit());
4613 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4614 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4616 pub const fn is_ascii_digit(&self) -> bool {
4617 matches!(*self, b'0'..=b'9')
4620 /// Checks if the value is an ASCII hexadecimal digit:
4622 /// - U+0030 '0' ..= U+0039 '9', or
4623 /// - U+0041 'A' ..= U+0046 'F', or
4624 /// - U+0061 'a' ..= U+0066 'f'.
4629 /// let uppercase_a = b'A';
4630 /// let uppercase_g = b'G';
4633 /// let zero = b'0';
4634 /// let percent = b'%';
4635 /// let space = b' ';
4637 /// let esc = 0x1b_u8;
4639 /// assert!(uppercase_a.is_ascii_hexdigit());
4640 /// assert!(!uppercase_g.is_ascii_hexdigit());
4641 /// assert!(a.is_ascii_hexdigit());
4642 /// assert!(!g.is_ascii_hexdigit());
4643 /// assert!(zero.is_ascii_hexdigit());
4644 /// assert!(!percent.is_ascii_hexdigit());
4645 /// assert!(!space.is_ascii_hexdigit());
4646 /// assert!(!lf.is_ascii_hexdigit());
4647 /// assert!(!esc.is_ascii_hexdigit());
4649 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4650 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4652 pub const fn is_ascii_hexdigit(&self) -> bool {
4653 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
4656 /// Checks if the value is an ASCII punctuation character:
4658 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4659 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4660 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4661 /// - U+007B ..= U+007E `{ | } ~`
4666 /// let uppercase_a = b'A';
4667 /// let uppercase_g = b'G';
4670 /// let zero = b'0';
4671 /// let percent = b'%';
4672 /// let space = b' ';
4674 /// let esc = 0x1b_u8;
4676 /// assert!(!uppercase_a.is_ascii_punctuation());
4677 /// assert!(!uppercase_g.is_ascii_punctuation());
4678 /// assert!(!a.is_ascii_punctuation());
4679 /// assert!(!g.is_ascii_punctuation());
4680 /// assert!(!zero.is_ascii_punctuation());
4681 /// assert!(percent.is_ascii_punctuation());
4682 /// assert!(!space.is_ascii_punctuation());
4683 /// assert!(!lf.is_ascii_punctuation());
4684 /// assert!(!esc.is_ascii_punctuation());
4686 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4687 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4689 pub const fn is_ascii_punctuation(&self) -> bool {
4690 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
4693 /// Checks if the value is an ASCII graphic character:
4694 /// U+0021 '!' ..= U+007E '~'.
4699 /// let uppercase_a = b'A';
4700 /// let uppercase_g = b'G';
4703 /// let zero = b'0';
4704 /// let percent = b'%';
4705 /// let space = b' ';
4707 /// let esc = 0x1b_u8;
4709 /// assert!(uppercase_a.is_ascii_graphic());
4710 /// assert!(uppercase_g.is_ascii_graphic());
4711 /// assert!(a.is_ascii_graphic());
4712 /// assert!(g.is_ascii_graphic());
4713 /// assert!(zero.is_ascii_graphic());
4714 /// assert!(percent.is_ascii_graphic());
4715 /// assert!(!space.is_ascii_graphic());
4716 /// assert!(!lf.is_ascii_graphic());
4717 /// assert!(!esc.is_ascii_graphic());
4719 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4720 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4722 pub const fn is_ascii_graphic(&self) -> bool {
4723 matches!(*self, b'!'..=b'~')
4726 /// Checks if the value is an ASCII whitespace character:
4727 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4728 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4730 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4731 /// whitespace][infra-aw]. There are several other definitions in
4732 /// wide use. For instance, [the POSIX locale][pct] includes
4733 /// U+000B VERTICAL TAB as well as all the above characters,
4734 /// but—from the very same specification—[the default rule for
4735 /// "field splitting" in the Bourne shell][bfs] considers *only*
4736 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4738 /// If you are writing a program that will process an existing
4739 /// file format, check what that format's definition of whitespace is
4740 /// before using this function.
4742 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4743 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4744 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4749 /// let uppercase_a = b'A';
4750 /// let uppercase_g = b'G';
4753 /// let zero = b'0';
4754 /// let percent = b'%';
4755 /// let space = b' ';
4757 /// let esc = 0x1b_u8;
4759 /// assert!(!uppercase_a.is_ascii_whitespace());
4760 /// assert!(!uppercase_g.is_ascii_whitespace());
4761 /// assert!(!a.is_ascii_whitespace());
4762 /// assert!(!g.is_ascii_whitespace());
4763 /// assert!(!zero.is_ascii_whitespace());
4764 /// assert!(!percent.is_ascii_whitespace());
4765 /// assert!(space.is_ascii_whitespace());
4766 /// assert!(lf.is_ascii_whitespace());
4767 /// assert!(!esc.is_ascii_whitespace());
4769 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4770 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4772 pub const fn is_ascii_whitespace(&self) -> bool {
4773 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
4776 /// Checks if the value is an ASCII control character:
4777 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4778 /// Note that most ASCII whitespace characters are control
4779 /// characters, but SPACE is not.
4784 /// let uppercase_a = b'A';
4785 /// let uppercase_g = b'G';
4788 /// let zero = b'0';
4789 /// let percent = b'%';
4790 /// let space = b' ';
4792 /// let esc = 0x1b_u8;
4794 /// assert!(!uppercase_a.is_ascii_control());
4795 /// assert!(!uppercase_g.is_ascii_control());
4796 /// assert!(!a.is_ascii_control());
4797 /// assert!(!g.is_ascii_control());
4798 /// assert!(!zero.is_ascii_control());
4799 /// assert!(!percent.is_ascii_control());
4800 /// assert!(!space.is_ascii_control());
4801 /// assert!(lf.is_ascii_control());
4802 /// assert!(esc.is_ascii_control());
4804 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4805 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4807 pub const fn is_ascii_control(&self) -> bool {
4808 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
4814 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4815 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4820 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4821 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4826 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4827 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4828 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4829 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4835 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4836 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4837 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4838 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4839 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4840 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4841 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4845 #[cfg(target_pointer_width = "16")]
4848 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4849 "[0x34, 0x12]", "[0x12, 0x34]",
4850 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4852 #[cfg(target_pointer_width = "32")]
4855 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4856 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4857 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4860 #[cfg(target_pointer_width = "64")]
4863 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4864 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4865 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4866 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4867 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4870 /// A classification of floating point numbers.
4872 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4873 /// their documentation for more.
4875 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4876 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4881 /// use std::num::FpCategory;
4884 /// let num = 12.4_f32;
4885 /// let inf = f32::INFINITY;
4886 /// let zero = 0f32;
4887 /// let sub: f32 = 1.1754942e-38;
4888 /// let nan = f32::NAN;
4890 /// assert_eq!(num.classify(), FpCategory::Normal);
4891 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4892 /// assert_eq!(zero.classify(), FpCategory::Zero);
4893 /// assert_eq!(nan.classify(), FpCategory::Nan);
4894 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4896 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4897 #[stable(feature = "rust1", since = "1.0.0")]
4898 pub enum FpCategory {
4899 /// "Not a Number", often obtained by dividing by zero.
4900 #[stable(feature = "rust1", since = "1.0.0")]
4903 /// Positive or negative infinity.
4904 #[stable(feature = "rust1", since = "1.0.0")]
4907 /// Positive or negative zero.
4908 #[stable(feature = "rust1", since = "1.0.0")]
4911 /// De-normalized floating point representation (less precise than `Normal`).
4912 #[stable(feature = "rust1", since = "1.0.0")]
4915 /// A regular floating point number.
4916 #[stable(feature = "rust1", since = "1.0.0")]
4920 macro_rules! from_str_radix_int_impl {
4922 #[stable(feature = "rust1", since = "1.0.0")]
4923 impl FromStr for $t {
4924 type Err = ParseIntError;
4925 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4926 from_str_radix(src, 10)
4931 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4933 /// The error type returned when a checked integral type conversion fails.
4934 #[stable(feature = "try_from", since = "1.34.0")]
4935 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4936 pub struct TryFromIntError(pub(crate) ());
4938 impl TryFromIntError {
4940 feature = "int_error_internals",
4941 reason = "available through Error trait and this method should \
4942 not be exposed publicly",
4946 pub fn __description(&self) -> &str {
4947 "out of range integral type conversion attempted"
4951 #[stable(feature = "try_from", since = "1.34.0")]
4952 impl fmt::Display for TryFromIntError {
4953 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4954 self.__description().fmt(fmt)
4958 #[stable(feature = "try_from", since = "1.34.0")]
4959 impl From<Infallible> for TryFromIntError {
4960 fn from(x: Infallible) -> TryFromIntError {
4965 #[unstable(feature = "never_type", issue = "35121")]
4966 impl From<!> for TryFromIntError {
4967 fn from(never: !) -> TryFromIntError {
4968 // Match rather than coerce to make sure that code like
4969 // `From<Infallible> for TryFromIntError` above will keep working
4970 // when `Infallible` becomes an alias to `!`.
4976 trait FromStrRadixHelper: PartialOrd + Copy {
4977 fn min_value() -> Self;
4978 fn max_value() -> Self;
4979 fn from_u32(u: u32) -> Self;
4980 fn checked_mul(&self, other: u32) -> Option<Self>;
4981 fn checked_sub(&self, other: u32) -> Option<Self>;
4982 fn checked_add(&self, other: u32) -> Option<Self>;
4986 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4988 fn min_value() -> Self { Self::min_value() }
4990 fn max_value() -> Self { Self::max_value() }
4992 fn from_u32(u: u32) -> Self { u as Self }
4994 fn checked_mul(&self, other: u32) -> Option<Self> {
4995 Self::checked_mul(*self, other as Self)
4998 fn checked_sub(&self, other: u32) -> Option<Self> {
4999 Self::checked_sub(*self, other as Self)
5002 fn checked_add(&self, other: u32) -> Option<Self> {
5003 Self::checked_add(*self, other as Self)
5007 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5009 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5010 use self::IntErrorKind::*;
5011 use self::ParseIntError as PIE;
5014 radix >= 2 && radix <= 36,
5015 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5020 return Err(PIE { kind: Empty });
5023 let is_signed_ty = T::from_u32(0) > T::min_value();
5025 // all valid digits are ascii, so we will just iterate over the utf8 bytes
5026 // and cast them to chars. .to_digit() will safely return None for anything
5027 // other than a valid ascii digit for the given radix, including the first-byte
5028 // of multi-byte sequences
5029 let src = src.as_bytes();
5031 let (is_positive, digits) = match src[0] {
5032 b'+' => (true, &src[1..]),
5033 b'-' if is_signed_ty => (false, &src[1..]),
5037 if digits.is_empty() {
5038 return Err(PIE { kind: Empty });
5041 let mut result = T::from_u32(0);
5043 // The number is positive
5045 let x = match (c as char).to_digit(radix) {
5047 None => return Err(PIE { kind: InvalidDigit }),
5049 result = match result.checked_mul(radix) {
5050 Some(result) => result,
5051 None => return Err(PIE { kind: Overflow }),
5053 result = match result.checked_add(x) {
5054 Some(result) => result,
5055 None => return Err(PIE { kind: Overflow }),
5059 // The number is negative
5061 let x = match (c as char).to_digit(radix) {
5063 None => return Err(PIE { kind: InvalidDigit }),
5065 result = match result.checked_mul(radix) {
5066 Some(result) => result,
5067 None => return Err(PIE { kind: Underflow }),
5069 result = match result.checked_sub(x) {
5070 Some(result) => result,
5071 None => return Err(PIE { kind: Underflow }),
5078 /// An error which can be returned when parsing an integer.
5080 /// This error is used as the error type for the `from_str_radix()` functions
5081 /// on the primitive integer types, such as [`i8::from_str_radix`].
5083 /// # Potential causes
5085 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5086 /// in the string e.g., when it is obtained from the standard input.
5087 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5089 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5090 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5091 #[derive(Debug, Clone, PartialEq, Eq)]
5092 #[stable(feature = "rust1", since = "1.0.0")]
5093 pub struct ParseIntError {
5097 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5099 feature = "int_error_matching",
5100 reason = "it can be useful to match errors when making error messages \
5101 for integer parsing",
5104 #[derive(Debug, Clone, PartialEq, Eq)]
5106 pub enum IntErrorKind {
5107 /// Value being parsed is empty.
5109 /// Among other causes, this variant will be constructed when parsing an empty string.
5111 /// Contains an invalid digit.
5113 /// Among other causes, this variant will be constructed when parsing a string that
5114 /// contains a letter.
5116 /// Integer is too large to store in target integer type.
5118 /// Integer is too small to store in target integer type.
5122 /// This variant will be emitted when the parsing string has a value of zero, which
5123 /// would be illegal for non-zero types.
5127 impl ParseIntError {
5128 /// Outputs the detailed cause of parsing an integer failing.
5130 feature = "int_error_matching",
5131 reason = "it can be useful to match errors when making error messages \
5132 for integer parsing",
5135 pub fn kind(&self) -> &IntErrorKind {
5139 feature = "int_error_internals",
5140 reason = "available through Error trait and this method should \
5141 not be exposed publicly",
5145 pub fn __description(&self) -> &str {
5147 IntErrorKind::Empty => "cannot parse integer from empty string",
5148 IntErrorKind::InvalidDigit => "invalid digit found in string",
5149 IntErrorKind::Overflow => "number too large to fit in target type",
5150 IntErrorKind::Underflow => "number too small to fit in target type",
5151 IntErrorKind::Zero => "number would be zero for non-zero type",
5156 #[stable(feature = "rust1", since = "1.0.0")]
5157 impl fmt::Display for ParseIntError {
5158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5159 self.__description().fmt(f)
5163 #[stable(feature = "rust1", since = "1.0.0")]
5164 pub use crate::num::dec2flt::ParseFloatError;