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_unstable(feature = "const_int_conversion", issue = "53718")]
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_unstable(feature = "const_int_conversion", issue = "53718")]
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_unstable(feature = "const_int_conversion", issue = "53718")]
2255 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2256 // SAFETY: integers are plain old datatypes so we can always transmute them to
2258 unsafe { mem::transmute(self) }
2263 concat!("Create an integer value from its representation as a byte array in
2271 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2272 assert_eq!(value, ", $swap_op, ");
2275 When starting from a slice rather than an array, fallible conversion APIs can be used:
2278 use std::convert::TryInto;
2280 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2281 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2283 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2286 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2287 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2289 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2290 Self::from_be(Self::from_ne_bytes(bytes))
2296 Create an integer value from its representation as a byte array in
2304 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2305 assert_eq!(value, ", $swap_op, ");
2308 When starting from a slice rather than an array, fallible conversion APIs can be used:
2311 use std::convert::TryInto;
2313 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2314 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2316 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2319 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2320 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2322 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2323 Self::from_le(Self::from_ne_bytes(bytes))
2328 concat!("Create an integer value from its memory representation as a byte
2329 array in native endianness.
2331 As the target platform's native endianness is used, portable code
2332 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2333 appropriate instead.
2335 [`from_be_bytes`]: #method.from_be_bytes
2336 [`from_le_bytes`]: #method.from_le_bytes
2343 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2348 assert_eq!(value, ", $swap_op, ");
2351 When starting from a slice rather than an array, fallible conversion APIs can be used:
2354 use std::convert::TryInto;
2356 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2357 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2359 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2362 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2363 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2365 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2366 // SAFETY: integers are plain old datatypes so we can always transmute to them
2367 unsafe { mem::transmute(bytes) }
2375 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2376 "[0x12]", "[0x12]", "", "" }
2381 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2382 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2387 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2388 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2389 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2394 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2395 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2396 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2397 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2402 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2403 170141183460469231731687303715884105727, "", "", 16,
2404 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2405 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2406 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2407 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2408 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2409 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2412 #[cfg(target_pointer_width = "16")]
2415 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2416 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2417 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2420 #[cfg(target_pointer_width = "32")]
2423 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2424 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2425 "[0x12, 0x34, 0x56, 0x78]",
2426 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2429 #[cfg(target_pointer_width = "64")]
2432 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2433 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2434 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2435 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2436 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2439 macro_rules! uint_impl {
2440 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2441 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2442 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2443 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2445 concat!("The smallest value that can be represented by this integer type.
2452 #![feature(assoc_int_consts)]
2453 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, 0);", $EndFeature, "
2455 #[unstable(feature = "assoc_int_consts", reason = "recently added", issue = "68490")]
2456 pub const MIN: Self = 0;
2460 concat!("The largest value that can be represented by this integer type.
2467 #![feature(assoc_int_consts)]
2468 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");",
2471 #[unstable(feature = "assoc_int_consts", reason = "recently added", issue = "68490")]
2472 pub const MAX: Self = !0;
2476 "Returns the smallest value that can be represented by this integer type.",
2477 #[stable(feature = "rust1", since = "1.0.0")]
2480 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2481 pub const fn min_value() -> Self { Self::MIN }
2485 "Returns the largest value that can be represented by this integer type.",
2486 #[stable(feature = "rust1", since = "1.0.0")]
2489 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2490 pub const fn max_value() -> Self { Self::MAX }
2494 concat!("Converts a string slice in a given base to an integer.
2496 The string is expected to be an optional `+` sign
2498 Leading and trailing whitespace represent an error.
2499 Digits are a subset of these characters, depending on `radix`:
2507 This function panics if `radix` is not in the range from 2 to 36.
2514 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2517 #[stable(feature = "rust1", since = "1.0.0")]
2518 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2519 from_str_radix(src, radix)
2524 concat!("Returns the number of ones in the binary representation of `self`.
2531 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2533 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2535 #[stable(feature = "rust1", since = "1.0.0")]
2536 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2538 pub const fn count_ones(self) -> u32 {
2539 intrinsics::ctpop(self as $ActualT) as u32
2544 concat!("Returns the number of zeros in the binary representation of `self`.
2551 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2553 #[stable(feature = "rust1", since = "1.0.0")]
2554 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2556 pub const fn count_zeros(self) -> u32 {
2557 (!self).count_ones()
2562 concat!("Returns the number of leading zeros in the binary representation of `self`.
2569 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2571 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2573 #[stable(feature = "rust1", since = "1.0.0")]
2574 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2576 pub const fn leading_zeros(self) -> u32 {
2577 intrinsics::ctlz(self as $ActualT) as u32
2582 concat!("Returns the number of trailing zeros in the binary representation
2590 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2592 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2594 #[stable(feature = "rust1", since = "1.0.0")]
2595 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2597 pub const fn trailing_zeros(self) -> u32 {
2598 intrinsics::cttz(self) as u32
2603 concat!("Returns the number of leading ones in the binary representation of `self`.
2610 ", $Feature, "#![feature(leading_trailing_ones)]
2611 let n = !(", stringify!($SelfT), "::max_value() >> 2);
2613 assert_eq!(n.leading_ones(), 2);", $EndFeature, "
2615 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2617 pub const fn leading_ones(self) -> u32 {
2618 (!self).leading_zeros()
2623 concat!("Returns the number of trailing ones in the binary representation
2631 ", $Feature, "#![feature(leading_trailing_ones)]
2632 let n = 0b1010111", stringify!($SelfT), ";
2634 assert_eq!(n.trailing_ones(), 3);", $EndFeature, "
2636 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2638 pub const fn trailing_ones(self) -> u32 {
2639 (!self).trailing_zeros()
2644 concat!("Shifts the bits to the left by a specified amount, `n`,
2645 wrapping the truncated bits to the end of the resulting integer.
2647 Please note this isn't the same operation as the `<<` shifting operator!
2654 let n = ", $rot_op, stringify!($SelfT), ";
2655 let m = ", $rot_result, ";
2657 assert_eq!(n.rotate_left(", $rot, "), m);
2659 #[stable(feature = "rust1", since = "1.0.0")]
2660 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2661 #[must_use = "this returns the result of the operation, \
2662 without modifying the original"]
2664 pub const fn rotate_left(self, n: u32) -> Self {
2665 intrinsics::rotate_left(self, n as $SelfT)
2670 concat!("Shifts the bits to the right by a specified amount, `n`,
2671 wrapping the truncated bits to the beginning of the resulting
2674 Please note this isn't the same operation as the `>>` shifting operator!
2681 let n = ", $rot_result, stringify!($SelfT), ";
2682 let m = ", $rot_op, ";
2684 assert_eq!(n.rotate_right(", $rot, "), m);
2686 #[stable(feature = "rust1", since = "1.0.0")]
2687 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2688 #[must_use = "this returns the result of the operation, \
2689 without modifying the original"]
2691 pub const fn rotate_right(self, n: u32) -> Self {
2692 intrinsics::rotate_right(self, n as $SelfT)
2698 Reverses the byte order of the integer.
2705 let n = ", $swap_op, stringify!($SelfT), ";
2706 let m = n.swap_bytes();
2708 assert_eq!(m, ", $swapped, ");
2710 #[stable(feature = "rust1", since = "1.0.0")]
2711 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2713 pub const fn swap_bytes(self) -> Self {
2714 intrinsics::bswap(self as $ActualT) as Self
2719 concat!("Reverses the bit pattern of the integer.
2726 let n = ", $swap_op, stringify!($SelfT), ";
2727 let m = n.reverse_bits();
2729 assert_eq!(m, ", $reversed, ");
2731 #[stable(feature = "reverse_bits", since = "1.37.0")]
2732 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2735 pub const fn reverse_bits(self) -> Self {
2736 intrinsics::bitreverse(self as $ActualT) as Self
2741 concat!("Converts an integer from big endian to the target's endianness.
2743 On big endian this is a no-op. On little endian the bytes are
2751 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2753 if cfg!(target_endian = \"big\") {
2754 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2756 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2759 #[stable(feature = "rust1", since = "1.0.0")]
2760 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2762 pub const fn from_be(x: Self) -> Self {
2763 #[cfg(target_endian = "big")]
2767 #[cfg(not(target_endian = "big"))]
2775 concat!("Converts an integer from little endian to the target's endianness.
2777 On little endian this is a no-op. On big endian the bytes are
2785 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2787 if cfg!(target_endian = \"little\") {
2788 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2790 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2793 #[stable(feature = "rust1", since = "1.0.0")]
2794 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2796 pub const fn from_le(x: Self) -> Self {
2797 #[cfg(target_endian = "little")]
2801 #[cfg(not(target_endian = "little"))]
2809 concat!("Converts `self` to big endian from the target's endianness.
2811 On big endian this is a no-op. On little endian the bytes are
2819 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2821 if cfg!(target_endian = \"big\") {
2822 assert_eq!(n.to_be(), n)
2824 assert_eq!(n.to_be(), n.swap_bytes())
2827 #[stable(feature = "rust1", since = "1.0.0")]
2828 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2830 pub const fn to_be(self) -> Self { // or not to be?
2831 #[cfg(target_endian = "big")]
2835 #[cfg(not(target_endian = "big"))]
2843 concat!("Converts `self` to little endian from the target's endianness.
2845 On little endian this is a no-op. On big endian the bytes are
2853 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2855 if cfg!(target_endian = \"little\") {
2856 assert_eq!(n.to_le(), n)
2858 assert_eq!(n.to_le(), n.swap_bytes())
2861 #[stable(feature = "rust1", since = "1.0.0")]
2862 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2864 pub const fn to_le(self) -> Self {
2865 #[cfg(target_endian = "little")]
2869 #[cfg(not(target_endian = "little"))]
2877 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2878 if overflow occurred.
2885 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2886 "Some(", stringify!($SelfT), "::max_value() - 1));
2887 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2889 #[stable(feature = "rust1", since = "1.0.0")]
2890 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2891 #[must_use = "this returns the result of the operation, \
2892 without modifying the original"]
2894 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
2895 let (a, b) = self.overflowing_add(rhs);
2896 if b {None} else {Some(a)}
2901 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2902 `None` if overflow occurred.
2909 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2910 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2912 #[stable(feature = "rust1", since = "1.0.0")]
2913 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2914 #[must_use = "this returns the result of the operation, \
2915 without modifying the original"]
2917 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
2918 let (a, b) = self.overflowing_sub(rhs);
2919 if b {None} else {Some(a)}
2924 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2925 `None` if overflow occurred.
2932 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2933 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2935 #[stable(feature = "rust1", since = "1.0.0")]
2936 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2937 #[must_use = "this returns the result of the operation, \
2938 without modifying the original"]
2940 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
2941 let (a, b) = self.overflowing_mul(rhs);
2942 if b {None} else {Some(a)}
2947 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2955 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2956 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2958 #[stable(feature = "rust1", since = "1.0.0")]
2959 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2960 #[must_use = "this returns the result of the operation, \
2961 without modifying the original"]
2963 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
2966 // SAFETY: div by zero has been checked above and unsigned types have no other
2967 // failure modes for division
2968 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2974 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2982 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
2983 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
2985 #[stable(feature = "euclidean_division", since = "1.38.0")]
2986 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2987 #[must_use = "this returns the result of the operation, \
2988 without modifying the original"]
2990 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
2994 Some(self.div_euclid(rhs))
3001 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
3009 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
3010 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
3012 #[stable(feature = "wrapping", since = "1.7.0")]
3013 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3014 #[must_use = "this returns the result of the operation, \
3015 without modifying the original"]
3017 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
3021 // SAFETY: div by zero has been checked above and unsigned types have no other
3022 // failure modes for division
3023 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3029 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3037 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3038 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3040 #[stable(feature = "euclidean_division", since = "1.38.0")]
3041 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3042 #[must_use = "this returns the result of the operation, \
3043 without modifying the original"]
3045 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3049 Some(self.rem_euclid(rhs))
3055 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3058 Note that negating any positive integer will overflow.
3065 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3066 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3068 #[stable(feature = "wrapping", since = "1.7.0")]
3069 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3071 pub const fn checked_neg(self) -> Option<Self> {
3072 let (a, b) = self.overflowing_neg();
3073 if b {None} else {Some(a)}
3078 concat!("Checked shift left. Computes `self << rhs`, returning `None`
3079 if `rhs` is larger than or equal to the number of bits in `self`.
3086 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3087 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3089 #[stable(feature = "wrapping", since = "1.7.0")]
3090 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3091 #[must_use = "this returns the result of the operation, \
3092 without modifying the original"]
3094 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
3095 let (a, b) = self.overflowing_shl(rhs);
3096 if b {None} else {Some(a)}
3101 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3102 if `rhs` is larger than or equal to the number of bits in `self`.
3109 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3110 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3112 #[stable(feature = "wrapping", since = "1.7.0")]
3113 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3114 #[must_use = "this returns the result of the operation, \
3115 without modifying the original"]
3117 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
3118 let (a, b) = self.overflowing_shr(rhs);
3119 if b {None} else {Some(a)}
3124 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3132 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3133 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
3135 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3136 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3137 #[must_use = "this returns the result of the operation, \
3138 without modifying the original"]
3140 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
3141 let mut base = self;
3142 let mut acc: Self = 1;
3146 acc = try_opt!(acc.checked_mul(base));
3149 base = try_opt!(base.checked_mul(base));
3152 // Deal with the final bit of the exponent separately, since
3153 // squaring the base afterwards is not necessary and may cause a
3154 // needless overflow.
3156 acc = try_opt!(acc.checked_mul(base));
3164 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3165 the numeric bounds instead of overflowing.
3172 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3173 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
3176 #[stable(feature = "rust1", since = "1.0.0")]
3177 #[must_use = "this returns the result of the operation, \
3178 without modifying the original"]
3179 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3181 pub const fn saturating_add(self, rhs: Self) -> Self {
3182 intrinsics::saturating_add(self, rhs)
3187 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3188 at the numeric bounds instead of overflowing.
3195 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3196 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3198 #[stable(feature = "rust1", since = "1.0.0")]
3199 #[must_use = "this returns the result of the operation, \
3200 without modifying the original"]
3201 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3203 pub const fn saturating_sub(self, rhs: Self) -> Self {
3204 intrinsics::saturating_sub(self, rhs)
3209 concat!("Saturating integer multiplication. Computes `self * rhs`,
3210 saturating at the numeric bounds instead of overflowing.
3217 ", $Feature, "use std::", stringify!($SelfT), ";
3219 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3220 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3221 "::MAX);", $EndFeature, "
3223 #[stable(feature = "wrapping", since = "1.7.0")]
3224 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3225 #[must_use = "this returns the result of the operation, \
3226 without modifying the original"]
3228 pub const fn saturating_mul(self, rhs: Self) -> Self {
3229 match self.checked_mul(rhs) {
3231 None => Self::max_value(),
3237 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3238 saturating at the numeric bounds instead of overflowing.
3245 ", $Feature, "use std::", stringify!($SelfT), ";
3247 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3248 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3251 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3252 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3253 #[must_use = "this returns the result of the operation, \
3254 without modifying the original"]
3256 pub const fn saturating_pow(self, exp: u32) -> Self {
3257 match self.checked_pow(exp) {
3259 None => Self::max_value(),
3265 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3266 wrapping around at the boundary of the type.
3273 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3274 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
3277 #[stable(feature = "rust1", since = "1.0.0")]
3278 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3279 #[must_use = "this returns the result of the operation, \
3280 without modifying the original"]
3282 pub const fn wrapping_add(self, rhs: Self) -> Self {
3283 intrinsics::wrapping_add(self, rhs)
3288 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3289 wrapping around at the boundary of the type.
3296 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3297 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
3300 #[stable(feature = "rust1", since = "1.0.0")]
3301 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3302 #[must_use = "this returns the result of the operation, \
3303 without modifying the original"]
3305 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3306 intrinsics::wrapping_sub(self, rhs)
3310 /// Wrapping (modular) multiplication. Computes `self *
3311 /// rhs`, wrapping around at the boundary of the type.
3317 /// Please note that this example is shared between integer types.
3318 /// Which explains why `u8` is used here.
3321 /// assert_eq!(10u8.wrapping_mul(12), 120);
3322 /// assert_eq!(25u8.wrapping_mul(12), 44);
3324 #[stable(feature = "rust1", since = "1.0.0")]
3325 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3326 #[must_use = "this returns the result of the operation, \
3327 without modifying the original"]
3329 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3330 intrinsics::wrapping_mul(self, rhs)
3334 concat!("Wrapping (modular) division. Computes `self / rhs`.
3335 Wrapped division on unsigned types is just normal division.
3336 There's no way wrapping could ever happen.
3337 This function exists, so that all operations
3338 are accounted for in the wrapping operations.
3345 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3347 #[stable(feature = "num_wrapping", since = "1.2.0")]
3348 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3349 #[must_use = "this returns the result of the operation, \
3350 without modifying the original"]
3352 pub const fn wrapping_div(self, rhs: Self) -> Self {
3358 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3359 Wrapped division on unsigned types is just normal division.
3360 There's no way wrapping could ever happen.
3361 This function exists, so that all operations
3362 are accounted for in the wrapping operations.
3363 Since, for the positive integers, all common
3364 definitions of division are equal, this
3365 is exactly equal to `self.wrapping_div(rhs)`.
3372 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3374 #[stable(feature = "euclidean_division", since = "1.38.0")]
3375 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3376 #[must_use = "this returns the result of the operation, \
3377 without modifying the original"]
3379 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
3385 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3386 Wrapped remainder calculation on unsigned types is
3387 just the regular remainder calculation.
3388 There's no way wrapping could ever happen.
3389 This function exists, so that all operations
3390 are accounted for in the wrapping operations.
3397 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3399 #[stable(feature = "num_wrapping", since = "1.2.0")]
3400 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3401 #[must_use = "this returns the result of the operation, \
3402 without modifying the original"]
3404 pub const fn wrapping_rem(self, rhs: Self) -> Self {
3410 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3411 Wrapped modulo calculation on unsigned types is
3412 just the regular remainder calculation.
3413 There's no way wrapping could ever happen.
3414 This function exists, so that all operations
3415 are accounted for in the wrapping operations.
3416 Since, for the positive integers, all common
3417 definitions of division are equal, this
3418 is exactly equal to `self.wrapping_rem(rhs)`.
3425 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3427 #[stable(feature = "euclidean_division", since = "1.38.0")]
3428 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3429 #[must_use = "this returns the result of the operation, \
3430 without modifying the original"]
3432 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3437 /// Wrapping (modular) negation. Computes `-self`,
3438 /// wrapping around at the boundary of the type.
3440 /// Since unsigned types do not have negative equivalents
3441 /// all applications of this function will wrap (except for `-0`).
3442 /// For values smaller than the corresponding signed type's maximum
3443 /// the result is the same as casting the corresponding signed value.
3444 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3445 /// `MAX` is the corresponding signed type's maximum.
3451 /// Please note that this example is shared between integer types.
3452 /// Which explains why `i8` is used here.
3455 /// assert_eq!(100i8.wrapping_neg(), -100);
3456 /// assert_eq!((-128i8).wrapping_neg(), -128);
3458 #[stable(feature = "num_wrapping", since = "1.2.0")]
3459 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3461 pub const fn wrapping_neg(self) -> Self {
3462 self.overflowing_neg().0
3466 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3467 where `mask` removes any high-order bits of `rhs` that
3468 would cause the shift to exceed the bitwidth of the type.
3470 Note that this is *not* the same as a rotate-left; the
3471 RHS of a wrapping shift-left is restricted to the range
3472 of the type, rather than the bits shifted out of the LHS
3473 being returned to the other end. The primitive integer
3474 types all implement a `rotate_left` function, which may
3475 be what you want instead.
3482 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3483 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3485 #[stable(feature = "num_wrapping", since = "1.2.0")]
3486 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3487 #[must_use = "this returns the result of the operation, \
3488 without modifying the original"]
3490 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3491 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3494 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3500 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3501 where `mask` removes any high-order bits of `rhs` that
3502 would cause the shift to exceed the bitwidth of the type.
3504 Note that this is *not* the same as a rotate-right; the
3505 RHS of a wrapping shift-right is restricted to the range
3506 of the type, rather than the bits shifted out of the LHS
3507 being returned to the other end. The primitive integer
3508 types all implement a `rotate_right` function, which may
3509 be what you want instead.
3516 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3517 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3519 #[stable(feature = "num_wrapping", since = "1.2.0")]
3520 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3521 #[must_use = "this returns the result of the operation, \
3522 without modifying the original"]
3524 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3525 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3528 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3534 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3535 wrapping around at the boundary of the type.
3542 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3543 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3545 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3546 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3547 #[must_use = "this returns the result of the operation, \
3548 without modifying the original"]
3550 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
3551 let mut base = self;
3552 let mut acc: Self = 1;
3556 acc = acc.wrapping_mul(base);
3559 base = base.wrapping_mul(base);
3562 // Deal with the final bit of the exponent separately, since
3563 // squaring the base afterwards is not necessary and may cause a
3564 // needless overflow.
3566 acc = acc.wrapping_mul(base);
3574 concat!("Calculates `self` + `rhs`
3576 Returns a tuple of the addition along with a boolean indicating
3577 whether an arithmetic overflow would occur. If an overflow would
3578 have occurred then the wrapped value is returned.
3585 ", $Feature, "use std::", stringify!($SelfT), ";
3587 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3588 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3590 #[stable(feature = "wrapping", since = "1.7.0")]
3591 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3592 #[must_use = "this returns the result of the operation, \
3593 without modifying the original"]
3595 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3596 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3602 concat!("Calculates `self` - `rhs`
3604 Returns a tuple of the subtraction along with a boolean indicating
3605 whether an arithmetic overflow would occur. If an overflow would
3606 have occurred then the wrapped value is returned.
3613 ", $Feature, "use std::", stringify!($SelfT), ";
3615 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3616 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3619 #[stable(feature = "wrapping", since = "1.7.0")]
3620 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3621 #[must_use = "this returns the result of the operation, \
3622 without modifying the original"]
3624 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3625 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3630 /// Calculates the multiplication of `self` and `rhs`.
3632 /// Returns a tuple of the multiplication along with a boolean
3633 /// indicating whether an arithmetic overflow would occur. If an
3634 /// overflow would have occurred then the wrapped value is returned.
3640 /// Please note that this example is shared between integer types.
3641 /// Which explains why `u32` is used here.
3644 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3645 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3647 #[stable(feature = "wrapping", since = "1.7.0")]
3648 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3649 #[must_use = "this returns the result of the operation, \
3650 without modifying the original"]
3652 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3653 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3658 concat!("Calculates the divisor when `self` is divided by `rhs`.
3660 Returns a tuple of the divisor along with a boolean indicating
3661 whether an arithmetic overflow would occur. Note that for unsigned
3662 integers overflow never occurs, so the second value is always
3667 This function will panic if `rhs` is 0.
3674 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3677 #[stable(feature = "wrapping", since = "1.7.0")]
3678 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3679 #[must_use = "this returns the result of the operation, \
3680 without modifying the original"]
3681 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3687 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3689 Returns a tuple of the divisor along with a boolean indicating
3690 whether an arithmetic overflow would occur. Note that for unsigned
3691 integers overflow never occurs, so the second value is always
3693 Since, for the positive integers, all common
3694 definitions of division are equal, this
3695 is exactly equal to `self.overflowing_div(rhs)`.
3699 This function will panic if `rhs` is 0.
3706 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3709 #[stable(feature = "euclidean_division", since = "1.38.0")]
3710 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3711 #[must_use = "this returns the result of the operation, \
3712 without modifying the original"]
3713 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3719 concat!("Calculates the remainder when `self` is divided by `rhs`.
3721 Returns a tuple of the remainder after dividing along with a boolean
3722 indicating whether an arithmetic overflow would occur. Note that for
3723 unsigned integers overflow never occurs, so the second value is
3728 This function will panic if `rhs` is 0.
3735 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3738 #[stable(feature = "wrapping", since = "1.7.0")]
3739 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3740 #[must_use = "this returns the result of the operation, \
3741 without modifying the original"]
3742 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3748 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3750 Returns a tuple of the modulo after dividing along with a boolean
3751 indicating whether an arithmetic overflow would occur. Note that for
3752 unsigned integers overflow never occurs, so the second value is
3754 Since, for the positive integers, all common
3755 definitions of division are equal, this operation
3756 is exactly equal to `self.overflowing_rem(rhs)`.
3760 This function will panic if `rhs` is 0.
3767 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3770 #[stable(feature = "euclidean_division", since = "1.38.0")]
3771 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3772 #[must_use = "this returns the result of the operation, \
3773 without modifying the original"]
3774 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3780 concat!("Negates self in an overflowing fashion.
3782 Returns `!self + 1` using wrapping operations to return the value
3783 that represents the negation of this unsigned value. Note that for
3784 positive unsigned values overflow always occurs, but negating 0 does
3792 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3793 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3794 ", true));", $EndFeature, "
3797 #[stable(feature = "wrapping", since = "1.7.0")]
3798 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3799 pub const fn overflowing_neg(self) -> (Self, bool) {
3800 ((!self).wrapping_add(1), self != 0)
3805 concat!("Shifts self left by `rhs` bits.
3807 Returns a tuple of the shifted version of self along with a boolean
3808 indicating whether the shift value was larger than or equal to the
3809 number of bits. If the shift value is too large, then value is
3810 masked (N-1) where N is the number of bits, and this value is then
3811 used to perform the shift.
3818 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3819 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3821 #[stable(feature = "wrapping", since = "1.7.0")]
3822 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3823 #[must_use = "this returns the result of the operation, \
3824 without modifying the original"]
3826 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3827 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3832 concat!("Shifts self right by `rhs` bits.
3834 Returns a tuple of the shifted version of self along with a boolean
3835 indicating whether the shift value was larger than or equal to the
3836 number of bits. If the shift value is too large, then value is
3837 masked (N-1) where N is the number of bits, and this value is then
3838 used to perform the shift.
3845 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3846 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3848 #[stable(feature = "wrapping", since = "1.7.0")]
3849 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3850 #[must_use = "this returns the result of the operation, \
3851 without modifying the original"]
3853 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3854 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3859 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3861 Returns a tuple of the exponentiation along with a bool indicating
3862 whether an overflow happened.
3869 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3870 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3872 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3873 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3874 #[must_use = "this returns the result of the operation, \
3875 without modifying the original"]
3877 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3878 let mut base = self;
3879 let mut acc: Self = 1;
3880 let mut overflown = false;
3881 // Scratch space for storing results of overflowing_mul.
3886 r = acc.overflowing_mul(base);
3891 r = base.overflowing_mul(base);
3896 // Deal with the final bit of the exponent separately, since
3897 // squaring the base afterwards is not necessary and may cause a
3898 // needless overflow.
3900 r = acc.overflowing_mul(base);
3910 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3917 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3919 #[stable(feature = "rust1", since = "1.0.0")]
3920 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3921 #[must_use = "this returns the result of the operation, \
3922 without modifying the original"]
3924 #[rustc_inherit_overflow_checks]
3925 pub const fn pow(self, mut exp: u32) -> Self {
3926 let mut base = self;
3937 // Deal with the final bit of the exponent separately, since
3938 // squaring the base afterwards is not necessary and may cause a
3939 // needless overflow.
3949 concat!("Performs Euclidean division.
3951 Since, for the positive integers, all common
3952 definitions of division are equal, this
3953 is exactly equal to `self / rhs`.
3957 This function will panic if `rhs` is 0.
3964 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
3966 #[stable(feature = "euclidean_division", since = "1.38.0")]
3967 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3968 #[must_use = "this returns the result of the operation, \
3969 without modifying the original"]
3971 #[rustc_inherit_overflow_checks]
3972 pub const fn div_euclid(self, rhs: Self) -> Self {
3979 concat!("Calculates the least remainder of `self (mod rhs)`.
3981 Since, for the positive integers, all common
3982 definitions of division are equal, this
3983 is exactly equal to `self % rhs`.
3987 This function will panic if `rhs` is 0.
3994 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
3996 #[stable(feature = "euclidean_division", since = "1.38.0")]
3997 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3998 #[must_use = "this returns the result of the operation, \
3999 without modifying the original"]
4001 #[rustc_inherit_overflow_checks]
4002 pub const fn rem_euclid(self, rhs: Self) -> Self {
4008 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
4015 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
4016 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
4018 #[stable(feature = "rust1", since = "1.0.0")]
4019 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
4021 pub const fn is_power_of_two(self) -> bool {
4022 self.count_ones() == 1
4026 // Returns one less than next power of two.
4027 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
4029 // 8u8.one_less_than_next_power_of_two() == 7
4030 // 6u8.one_less_than_next_power_of_two() == 7
4032 // This method cannot overflow, as in the `next_power_of_two`
4033 // overflow cases it instead ends up returning the maximum value
4034 // of the type, and can return 0 for 0.
4036 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4037 const fn one_less_than_next_power_of_two(self) -> Self {
4038 if self <= 1 { return 0; }
4041 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4042 // That means the shift is always in-bounds, and some processors
4043 // (such as intel pre-haswell) have more efficient ctlz
4044 // intrinsics when the argument is non-zero.
4045 let z = unsafe { intrinsics::ctlz_nonzero(p) };
4046 <$SelfT>::max_value() >> z
4050 concat!("Returns the smallest power of two greater than or equal to `self`.
4052 When return value overflows (i.e., `self > (1 << (N-1))` for type
4053 `uN`), it panics in debug mode and return value is wrapped to 0 in
4054 release mode (the only situation in which method can return 0).
4061 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4062 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4064 #[stable(feature = "rust1", since = "1.0.0")]
4065 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4067 #[rustc_inherit_overflow_checks]
4068 pub const fn next_power_of_two(self) -> Self {
4069 self.one_less_than_next_power_of_two() + 1
4074 concat!("Returns the smallest power of two greater than or equal to `n`. If
4075 the next power of two is greater than the type's maximum value,
4076 `None` is returned, otherwise the power of two is wrapped in `Some`.
4083 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4084 ".checked_next_power_of_two(), Some(2));
4085 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4086 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
4090 #[stable(feature = "rust1", since = "1.0.0")]
4091 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4092 pub const fn checked_next_power_of_two(self) -> Option<Self> {
4093 self.one_less_than_next_power_of_two().checked_add(1)
4098 concat!("Returns the smallest power of two greater than or equal to `n`. If
4099 the next power of two is greater than the type's maximum value,
4100 the return value is wrapped to `0`.
4107 #![feature(wrapping_next_power_of_two)]
4109 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4110 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4111 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
4114 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4115 reason = "needs decision on wrapping behaviour")]
4116 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4117 pub const fn wrapping_next_power_of_two(self) -> Self {
4118 self.one_less_than_next_power_of_two().wrapping_add(1)
4123 concat!("Return the memory representation of this integer as a byte array in
4124 big-endian (network) byte order.
4131 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4132 assert_eq!(bytes, ", $be_bytes, ");
4134 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4135 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4137 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4138 self.to_be().to_ne_bytes()
4143 concat!("Return the memory representation of this integer as a byte array in
4144 little-endian byte order.
4151 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4152 assert_eq!(bytes, ", $le_bytes, ");
4154 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4155 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4157 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4158 self.to_le().to_ne_bytes()
4164 Return the memory representation of this integer as a byte array in
4167 As the target platform's native endianness is used, portable code
4168 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4173 [`to_be_bytes`]: #method.to_be_bytes
4174 [`to_le_bytes`]: #method.to_le_bytes
4179 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4182 if cfg!(target_endian = \"big\") {
4189 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4190 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4192 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4193 // SAFETY: integers are plain old datatypes so we can always transmute them to
4195 unsafe { mem::transmute(self) }
4200 concat!("Create an integer value from its representation as a byte array in
4208 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4209 assert_eq!(value, ", $swap_op, ");
4212 When starting from a slice rather than an array, fallible conversion APIs can be used:
4215 use std::convert::TryInto;
4217 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4218 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4220 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4223 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4224 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4226 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4227 Self::from_be(Self::from_ne_bytes(bytes))
4233 Create an integer value from its representation as a byte array in
4241 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4242 assert_eq!(value, ", $swap_op, ");
4245 When starting from a slice rather than an array, fallible conversion APIs can be used:
4248 use std::convert::TryInto;
4250 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4251 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4253 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4256 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4257 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4259 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4260 Self::from_le(Self::from_ne_bytes(bytes))
4265 concat!("Create an integer value from its memory representation as a byte
4266 array in native endianness.
4268 As the target platform's native endianness is used, portable code
4269 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4270 appropriate instead.
4272 [`from_be_bytes`]: #method.from_be_bytes
4273 [`from_le_bytes`]: #method.from_le_bytes
4280 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4285 assert_eq!(value, ", $swap_op, ");
4288 When starting from a slice rather than an array, fallible conversion APIs can be used:
4291 use std::convert::TryInto;
4293 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4294 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4296 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4299 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4300 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4302 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4303 // SAFETY: integers are plain old datatypes so we can always transmute to them
4304 unsafe { mem::transmute(bytes) }
4312 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4315 /// Checks if the value is within the ASCII range.
4320 /// let ascii = 97u8;
4321 /// let non_ascii = 150u8;
4323 /// assert!(ascii.is_ascii());
4324 /// assert!(!non_ascii.is_ascii());
4326 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4328 pub fn is_ascii(&self) -> bool {
4332 /// Makes a copy of the value in its ASCII upper case equivalent.
4334 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4335 /// but non-ASCII letters are unchanged.
4337 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4342 /// let lowercase_a = 97u8;
4344 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4347 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4348 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4350 pub fn to_ascii_uppercase(&self) -> u8 {
4351 // Unset the fith bit if this is a lowercase letter
4352 *self & !((self.is_ascii_lowercase() as u8) << 5)
4355 /// Makes a copy of the value in its ASCII lower case equivalent.
4357 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4358 /// but non-ASCII letters are unchanged.
4360 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4365 /// let uppercase_a = 65u8;
4367 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4370 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4371 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4373 pub fn to_ascii_lowercase(&self) -> u8 {
4374 // Set the fith bit if this is an uppercase letter
4375 *self | ((self.is_ascii_uppercase() as u8) << 5)
4378 /// Checks that two values are an ASCII case-insensitive match.
4380 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4385 /// let lowercase_a = 97u8;
4386 /// let uppercase_a = 65u8;
4388 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4390 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4392 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4393 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4396 /// Converts this value to its ASCII upper case equivalent in-place.
4398 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4399 /// but non-ASCII letters are unchanged.
4401 /// To return a new uppercased value without modifying the existing one, use
4402 /// [`to_ascii_uppercase`].
4407 /// let mut byte = b'a';
4409 /// byte.make_ascii_uppercase();
4411 /// assert_eq!(b'A', byte);
4414 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4415 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4417 pub fn make_ascii_uppercase(&mut self) {
4418 *self = self.to_ascii_uppercase();
4421 /// Converts this value to its ASCII lower case equivalent in-place.
4423 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4424 /// but non-ASCII letters are unchanged.
4426 /// To return a new lowercased value without modifying the existing one, use
4427 /// [`to_ascii_lowercase`].
4432 /// let mut byte = b'A';
4434 /// byte.make_ascii_lowercase();
4436 /// assert_eq!(b'a', byte);
4439 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4440 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4442 pub fn make_ascii_lowercase(&mut self) {
4443 *self = self.to_ascii_lowercase();
4446 /// Checks if the value is an ASCII alphabetic character:
4448 /// - U+0041 'A' ..= U+005A 'Z', or
4449 /// - U+0061 'a' ..= U+007A 'z'.
4454 /// let uppercase_a = b'A';
4455 /// let uppercase_g = b'G';
4458 /// let zero = b'0';
4459 /// let percent = b'%';
4460 /// let space = b' ';
4462 /// let esc = 0x1b_u8;
4464 /// assert!(uppercase_a.is_ascii_alphabetic());
4465 /// assert!(uppercase_g.is_ascii_alphabetic());
4466 /// assert!(a.is_ascii_alphabetic());
4467 /// assert!(g.is_ascii_alphabetic());
4468 /// assert!(!zero.is_ascii_alphabetic());
4469 /// assert!(!percent.is_ascii_alphabetic());
4470 /// assert!(!space.is_ascii_alphabetic());
4471 /// assert!(!lf.is_ascii_alphabetic());
4472 /// assert!(!esc.is_ascii_alphabetic());
4474 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4475 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4477 pub const fn is_ascii_alphabetic(&self) -> bool {
4478 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
4481 /// Checks if the value is an ASCII uppercase character:
4482 /// U+0041 'A' ..= U+005A 'Z'.
4487 /// let uppercase_a = b'A';
4488 /// let uppercase_g = b'G';
4491 /// let zero = b'0';
4492 /// let percent = b'%';
4493 /// let space = b' ';
4495 /// let esc = 0x1b_u8;
4497 /// assert!(uppercase_a.is_ascii_uppercase());
4498 /// assert!(uppercase_g.is_ascii_uppercase());
4499 /// assert!(!a.is_ascii_uppercase());
4500 /// assert!(!g.is_ascii_uppercase());
4501 /// assert!(!zero.is_ascii_uppercase());
4502 /// assert!(!percent.is_ascii_uppercase());
4503 /// assert!(!space.is_ascii_uppercase());
4504 /// assert!(!lf.is_ascii_uppercase());
4505 /// assert!(!esc.is_ascii_uppercase());
4507 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4508 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4510 pub const fn is_ascii_uppercase(&self) -> bool {
4511 matches!(*self, b'A'..=b'Z')
4514 /// Checks if the value is an ASCII lowercase character:
4515 /// U+0061 'a' ..= U+007A 'z'.
4520 /// let uppercase_a = b'A';
4521 /// let uppercase_g = b'G';
4524 /// let zero = b'0';
4525 /// let percent = b'%';
4526 /// let space = b' ';
4528 /// let esc = 0x1b_u8;
4530 /// assert!(!uppercase_a.is_ascii_lowercase());
4531 /// assert!(!uppercase_g.is_ascii_lowercase());
4532 /// assert!(a.is_ascii_lowercase());
4533 /// assert!(g.is_ascii_lowercase());
4534 /// assert!(!zero.is_ascii_lowercase());
4535 /// assert!(!percent.is_ascii_lowercase());
4536 /// assert!(!space.is_ascii_lowercase());
4537 /// assert!(!lf.is_ascii_lowercase());
4538 /// assert!(!esc.is_ascii_lowercase());
4540 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4541 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4543 pub const fn is_ascii_lowercase(&self) -> bool {
4544 matches!(*self, b'a'..=b'z')
4547 /// Checks if the value is an ASCII alphanumeric character:
4549 /// - U+0041 'A' ..= U+005A 'Z', or
4550 /// - U+0061 'a' ..= U+007A 'z', or
4551 /// - U+0030 '0' ..= U+0039 '9'.
4556 /// let uppercase_a = b'A';
4557 /// let uppercase_g = b'G';
4560 /// let zero = b'0';
4561 /// let percent = b'%';
4562 /// let space = b' ';
4564 /// let esc = 0x1b_u8;
4566 /// assert!(uppercase_a.is_ascii_alphanumeric());
4567 /// assert!(uppercase_g.is_ascii_alphanumeric());
4568 /// assert!(a.is_ascii_alphanumeric());
4569 /// assert!(g.is_ascii_alphanumeric());
4570 /// assert!(zero.is_ascii_alphanumeric());
4571 /// assert!(!percent.is_ascii_alphanumeric());
4572 /// assert!(!space.is_ascii_alphanumeric());
4573 /// assert!(!lf.is_ascii_alphanumeric());
4574 /// assert!(!esc.is_ascii_alphanumeric());
4576 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4577 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4579 pub const fn is_ascii_alphanumeric(&self) -> bool {
4580 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
4583 /// Checks if the value is an ASCII decimal digit:
4584 /// U+0030 '0' ..= U+0039 '9'.
4589 /// let uppercase_a = b'A';
4590 /// let uppercase_g = b'G';
4593 /// let zero = b'0';
4594 /// let percent = b'%';
4595 /// let space = b' ';
4597 /// let esc = 0x1b_u8;
4599 /// assert!(!uppercase_a.is_ascii_digit());
4600 /// assert!(!uppercase_g.is_ascii_digit());
4601 /// assert!(!a.is_ascii_digit());
4602 /// assert!(!g.is_ascii_digit());
4603 /// assert!(zero.is_ascii_digit());
4604 /// assert!(!percent.is_ascii_digit());
4605 /// assert!(!space.is_ascii_digit());
4606 /// assert!(!lf.is_ascii_digit());
4607 /// assert!(!esc.is_ascii_digit());
4609 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4610 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4612 pub const fn is_ascii_digit(&self) -> bool {
4613 matches!(*self, b'0'..=b'9')
4616 /// Checks if the value is an ASCII hexadecimal digit:
4618 /// - U+0030 '0' ..= U+0039 '9', or
4619 /// - U+0041 'A' ..= U+0046 'F', or
4620 /// - U+0061 'a' ..= U+0066 'f'.
4625 /// let uppercase_a = b'A';
4626 /// let uppercase_g = b'G';
4629 /// let zero = b'0';
4630 /// let percent = b'%';
4631 /// let space = b' ';
4633 /// let esc = 0x1b_u8;
4635 /// assert!(uppercase_a.is_ascii_hexdigit());
4636 /// assert!(!uppercase_g.is_ascii_hexdigit());
4637 /// assert!(a.is_ascii_hexdigit());
4638 /// assert!(!g.is_ascii_hexdigit());
4639 /// assert!(zero.is_ascii_hexdigit());
4640 /// assert!(!percent.is_ascii_hexdigit());
4641 /// assert!(!space.is_ascii_hexdigit());
4642 /// assert!(!lf.is_ascii_hexdigit());
4643 /// assert!(!esc.is_ascii_hexdigit());
4645 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4646 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4648 pub const fn is_ascii_hexdigit(&self) -> bool {
4649 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
4652 /// Checks if the value is an ASCII punctuation character:
4654 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4655 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4656 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4657 /// - U+007B ..= U+007E `{ | } ~`
4662 /// let uppercase_a = b'A';
4663 /// let uppercase_g = b'G';
4666 /// let zero = b'0';
4667 /// let percent = b'%';
4668 /// let space = b' ';
4670 /// let esc = 0x1b_u8;
4672 /// assert!(!uppercase_a.is_ascii_punctuation());
4673 /// assert!(!uppercase_g.is_ascii_punctuation());
4674 /// assert!(!a.is_ascii_punctuation());
4675 /// assert!(!g.is_ascii_punctuation());
4676 /// assert!(!zero.is_ascii_punctuation());
4677 /// assert!(percent.is_ascii_punctuation());
4678 /// assert!(!space.is_ascii_punctuation());
4679 /// assert!(!lf.is_ascii_punctuation());
4680 /// assert!(!esc.is_ascii_punctuation());
4682 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4683 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4685 pub const fn is_ascii_punctuation(&self) -> bool {
4686 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
4689 /// Checks if the value is an ASCII graphic character:
4690 /// U+0021 '!' ..= U+007E '~'.
4695 /// let uppercase_a = b'A';
4696 /// let uppercase_g = b'G';
4699 /// let zero = b'0';
4700 /// let percent = b'%';
4701 /// let space = b' ';
4703 /// let esc = 0x1b_u8;
4705 /// assert!(uppercase_a.is_ascii_graphic());
4706 /// assert!(uppercase_g.is_ascii_graphic());
4707 /// assert!(a.is_ascii_graphic());
4708 /// assert!(g.is_ascii_graphic());
4709 /// assert!(zero.is_ascii_graphic());
4710 /// assert!(percent.is_ascii_graphic());
4711 /// assert!(!space.is_ascii_graphic());
4712 /// assert!(!lf.is_ascii_graphic());
4713 /// assert!(!esc.is_ascii_graphic());
4715 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4716 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4718 pub const fn is_ascii_graphic(&self) -> bool {
4719 matches!(*self, b'!'..=b'~')
4722 /// Checks if the value is an ASCII whitespace character:
4723 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4724 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4726 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4727 /// whitespace][infra-aw]. There are several other definitions in
4728 /// wide use. For instance, [the POSIX locale][pct] includes
4729 /// U+000B VERTICAL TAB as well as all the above characters,
4730 /// but—from the very same specification—[the default rule for
4731 /// "field splitting" in the Bourne shell][bfs] considers *only*
4732 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4734 /// If you are writing a program that will process an existing
4735 /// file format, check what that format's definition of whitespace is
4736 /// before using this function.
4738 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4739 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4740 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4745 /// let uppercase_a = b'A';
4746 /// let uppercase_g = b'G';
4749 /// let zero = b'0';
4750 /// let percent = b'%';
4751 /// let space = b' ';
4753 /// let esc = 0x1b_u8;
4755 /// assert!(!uppercase_a.is_ascii_whitespace());
4756 /// assert!(!uppercase_g.is_ascii_whitespace());
4757 /// assert!(!a.is_ascii_whitespace());
4758 /// assert!(!g.is_ascii_whitespace());
4759 /// assert!(!zero.is_ascii_whitespace());
4760 /// assert!(!percent.is_ascii_whitespace());
4761 /// assert!(space.is_ascii_whitespace());
4762 /// assert!(lf.is_ascii_whitespace());
4763 /// assert!(!esc.is_ascii_whitespace());
4765 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4766 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4768 pub const fn is_ascii_whitespace(&self) -> bool {
4769 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
4772 /// Checks if the value is an ASCII control character:
4773 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4774 /// Note that most ASCII whitespace characters are control
4775 /// characters, but SPACE is not.
4780 /// let uppercase_a = b'A';
4781 /// let uppercase_g = b'G';
4784 /// let zero = b'0';
4785 /// let percent = b'%';
4786 /// let space = b' ';
4788 /// let esc = 0x1b_u8;
4790 /// assert!(!uppercase_a.is_ascii_control());
4791 /// assert!(!uppercase_g.is_ascii_control());
4792 /// assert!(!a.is_ascii_control());
4793 /// assert!(!g.is_ascii_control());
4794 /// assert!(!zero.is_ascii_control());
4795 /// assert!(!percent.is_ascii_control());
4796 /// assert!(!space.is_ascii_control());
4797 /// assert!(lf.is_ascii_control());
4798 /// assert!(esc.is_ascii_control());
4800 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4801 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4803 pub const fn is_ascii_control(&self) -> bool {
4804 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
4810 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4811 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4816 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4817 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4822 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4823 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4824 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4825 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4831 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4832 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4833 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4834 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4835 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4836 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4837 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4841 #[cfg(target_pointer_width = "16")]
4844 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4845 "[0x34, 0x12]", "[0x12, 0x34]",
4846 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4848 #[cfg(target_pointer_width = "32")]
4851 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4852 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4853 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4856 #[cfg(target_pointer_width = "64")]
4859 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4860 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4861 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4862 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4863 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4866 /// A classification of floating point numbers.
4868 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4869 /// their documentation for more.
4871 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4872 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4877 /// use std::num::FpCategory;
4880 /// let num = 12.4_f32;
4881 /// let inf = f32::INFINITY;
4882 /// let zero = 0f32;
4883 /// let sub: f32 = 1.1754942e-38;
4884 /// let nan = f32::NAN;
4886 /// assert_eq!(num.classify(), FpCategory::Normal);
4887 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4888 /// assert_eq!(zero.classify(), FpCategory::Zero);
4889 /// assert_eq!(nan.classify(), FpCategory::Nan);
4890 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4892 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4893 #[stable(feature = "rust1", since = "1.0.0")]
4894 pub enum FpCategory {
4895 /// "Not a Number", often obtained by dividing by zero.
4896 #[stable(feature = "rust1", since = "1.0.0")]
4899 /// Positive or negative infinity.
4900 #[stable(feature = "rust1", since = "1.0.0")]
4903 /// Positive or negative zero.
4904 #[stable(feature = "rust1", since = "1.0.0")]
4907 /// De-normalized floating point representation (less precise than `Normal`).
4908 #[stable(feature = "rust1", since = "1.0.0")]
4911 /// A regular floating point number.
4912 #[stable(feature = "rust1", since = "1.0.0")]
4916 macro_rules! from_str_radix_int_impl {
4918 #[stable(feature = "rust1", since = "1.0.0")]
4919 impl FromStr for $t {
4920 type Err = ParseIntError;
4921 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4922 from_str_radix(src, 10)
4927 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4929 /// The error type returned when a checked integral type conversion fails.
4930 #[stable(feature = "try_from", since = "1.34.0")]
4931 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4932 pub struct TryFromIntError(pub(crate) ());
4934 impl TryFromIntError {
4936 feature = "int_error_internals",
4937 reason = "available through Error trait and this method should \
4938 not be exposed publicly",
4942 pub fn __description(&self) -> &str {
4943 "out of range integral type conversion attempted"
4947 #[stable(feature = "try_from", since = "1.34.0")]
4948 impl fmt::Display for TryFromIntError {
4949 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4950 self.__description().fmt(fmt)
4954 #[stable(feature = "try_from", since = "1.34.0")]
4955 impl From<Infallible> for TryFromIntError {
4956 fn from(x: Infallible) -> TryFromIntError {
4961 #[unstable(feature = "never_type", issue = "35121")]
4962 impl From<!> for TryFromIntError {
4963 fn from(never: !) -> TryFromIntError {
4964 // Match rather than coerce to make sure that code like
4965 // `From<Infallible> for TryFromIntError` above will keep working
4966 // when `Infallible` becomes an alias to `!`.
4972 trait FromStrRadixHelper: PartialOrd + Copy {
4973 fn min_value() -> Self;
4974 fn max_value() -> Self;
4975 fn from_u32(u: u32) -> Self;
4976 fn checked_mul(&self, other: u32) -> Option<Self>;
4977 fn checked_sub(&self, other: u32) -> Option<Self>;
4978 fn checked_add(&self, other: u32) -> Option<Self>;
4982 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4984 fn min_value() -> Self { Self::min_value() }
4986 fn max_value() -> Self { Self::max_value() }
4988 fn from_u32(u: u32) -> Self { u as Self }
4990 fn checked_mul(&self, other: u32) -> Option<Self> {
4991 Self::checked_mul(*self, other as Self)
4994 fn checked_sub(&self, other: u32) -> Option<Self> {
4995 Self::checked_sub(*self, other as Self)
4998 fn checked_add(&self, other: u32) -> Option<Self> {
4999 Self::checked_add(*self, other as Self)
5003 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5005 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5006 use self::IntErrorKind::*;
5007 use self::ParseIntError as PIE;
5010 radix >= 2 && radix <= 36,
5011 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5016 return Err(PIE { kind: Empty });
5019 let is_signed_ty = T::from_u32(0) > T::min_value();
5021 // all valid digits are ascii, so we will just iterate over the utf8 bytes
5022 // and cast them to chars. .to_digit() will safely return None for anything
5023 // other than a valid ascii digit for the given radix, including the first-byte
5024 // of multi-byte sequences
5025 let src = src.as_bytes();
5027 let (is_positive, digits) = match src[0] {
5028 b'+' => (true, &src[1..]),
5029 b'-' if is_signed_ty => (false, &src[1..]),
5033 if digits.is_empty() {
5034 return Err(PIE { kind: Empty });
5037 let mut result = T::from_u32(0);
5039 // The number is positive
5041 let x = match (c as char).to_digit(radix) {
5043 None => return Err(PIE { kind: InvalidDigit }),
5045 result = match result.checked_mul(radix) {
5046 Some(result) => result,
5047 None => return Err(PIE { kind: Overflow }),
5049 result = match result.checked_add(x) {
5050 Some(result) => result,
5051 None => return Err(PIE { kind: Overflow }),
5055 // The number is negative
5057 let x = match (c as char).to_digit(radix) {
5059 None => return Err(PIE { kind: InvalidDigit }),
5061 result = match result.checked_mul(radix) {
5062 Some(result) => result,
5063 None => return Err(PIE { kind: Underflow }),
5065 result = match result.checked_sub(x) {
5066 Some(result) => result,
5067 None => return Err(PIE { kind: Underflow }),
5074 /// An error which can be returned when parsing an integer.
5076 /// This error is used as the error type for the `from_str_radix()` functions
5077 /// on the primitive integer types, such as [`i8::from_str_radix`].
5079 /// # Potential causes
5081 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5082 /// in the string e.g., when it is obtained from the standard input.
5083 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5085 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5086 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5087 #[derive(Debug, Clone, PartialEq, Eq)]
5088 #[stable(feature = "rust1", since = "1.0.0")]
5089 pub struct ParseIntError {
5093 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5095 feature = "int_error_matching",
5096 reason = "it can be useful to match errors when making error messages \
5097 for integer parsing",
5100 #[derive(Debug, Clone, PartialEq, Eq)]
5102 pub enum IntErrorKind {
5103 /// Value being parsed is empty.
5105 /// Among other causes, this variant will be constructed when parsing an empty string.
5107 /// Contains an invalid digit.
5109 /// Among other causes, this variant will be constructed when parsing a string that
5110 /// contains a letter.
5112 /// Integer is too large to store in target integer type.
5114 /// Integer is too small to store in target integer type.
5118 /// This variant will be emitted when the parsing string has a value of zero, which
5119 /// would be illegal for non-zero types.
5123 impl ParseIntError {
5124 /// Outputs the detailed cause of parsing an integer failing.
5126 feature = "int_error_matching",
5127 reason = "it can be useful to match errors when making error messages \
5128 for integer parsing",
5131 pub fn kind(&self) -> &IntErrorKind {
5135 feature = "int_error_internals",
5136 reason = "available through Error trait and this method should \
5137 not be exposed publicly",
5141 pub fn __description(&self) -> &str {
5143 IntErrorKind::Empty => "cannot parse integer from empty string",
5144 IntErrorKind::InvalidDigit => "invalid digit found in string",
5145 IntErrorKind::Overflow => "number too large to fit in target type",
5146 IntErrorKind::Underflow => "number too small to fit in target type",
5147 IntErrorKind::Zero => "number would be zero for non-zero type",
5152 #[stable(feature = "rust1", since = "1.0.0")]
5153 impl fmt::Display for ParseIntError {
5154 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5155 self.__description().fmt(f)
5159 #[stable(feature = "rust1", since = "1.0.0")]
5160 pub use crate::num::dec2flt::ParseFloatError;