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;
12 use crate::str::FromStr;
14 macro_rules! impl_nonzero_fmt {
15 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
18 impl fmt::$Trait for $Ty {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28 macro_rules! doc_comment {
29 ($x:expr, $($tt:tt)*) => {
35 macro_rules! nonzero_integers {
36 ( $( #[$stability: meta] $Ty: ident($Int: ty); )+ ) => {
39 concat!("An integer that is known not to equal zero.
41 This enables some memory layout optimization.
42 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
45 use std::mem::size_of;
46 assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
50 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
52 #[rustc_layout_scalar_valid_range_start(1)]
53 #[rustc_nonnull_optimization_guaranteed]
58 /// Creates a non-zero without checking the value.
62 /// The value must not be zero.
64 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
66 pub const unsafe fn new_unchecked(n: $Int) -> Self {
70 /// Creates a non-zero if the given value is not zero.
72 #[rustc_const_unstable(feature = "const_nonzero_int_methods", issue = "53718")]
74 pub const fn new(n: $Int) -> Option<Self> {
76 // SAFETY: we just checked that there's no `0`
77 Some(unsafe { Self(n) })
83 /// Returns the value as a primitive type.
86 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
87 pub const fn get(self) -> $Int {
93 #[stable(feature = "from_nonzero", since = "1.31.0")]
94 impl From<$Ty> for $Int {
97 "Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`"),
98 fn from(nonzero: $Ty) -> Self {
105 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
112 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
113 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
114 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
115 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
116 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
117 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
118 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
119 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
120 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
121 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
122 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
123 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
126 macro_rules! from_str_radix_nzint_impl {
128 #[stable(feature = "nonzero_parse", since = "1.35.0")]
129 impl FromStr for $t {
130 type Err = ParseIntError;
131 fn from_str(src: &str) -> Result<Self, Self::Err> {
132 Self::new(from_str_radix(src, 10)?)
133 .ok_or(ParseIntError {
134 kind: IntErrorKind::Zero
141 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
142 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
144 /// Provides intentionally-wrapped arithmetic on `T`.
146 /// Operations like `+` on `u32` values are intended to never overflow,
147 /// and in some debug configurations overflow is detected and results
148 /// in a panic. While most arithmetic falls into this category, some
149 /// code explicitly expects and relies upon modular arithmetic (e.g.,
152 /// Wrapping arithmetic can be achieved either through methods like
153 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
154 /// all standard arithmetic operations on the underlying value are
155 /// intended to have wrapping semantics.
157 /// The underlying value can be retrieved through the `.0` index of the
158 /// `Wrapping` tuple.
163 /// use std::num::Wrapping;
165 /// let zero = Wrapping(0u32);
166 /// let one = Wrapping(1u32);
168 /// assert_eq!(std::u32::MAX, (zero - one).0);
170 #[stable(feature = "rust1", since = "1.0.0")]
171 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
173 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
175 #[stable(feature = "rust1", since = "1.0.0")]
176 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 #[stable(feature = "wrapping_display", since = "1.10.0")]
183 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
190 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
197 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
204 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
205 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
211 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 // All these modules are technically private and only exposed for coretests:
225 macro_rules! usize_isize_to_xe_bytes_doc {
229 **Note**: This function returns an array of length 2, 4 or 8 bytes
230 depending on the target pointer size.
236 macro_rules! usize_isize_from_xe_bytes_doc {
240 **Note**: This function takes an array of length 2, 4 or 8 bytes
241 depending on the target pointer size.
247 macro_rules! int_impl {
248 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
249 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
250 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
251 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
253 concat!("The smallest value that can be represented by this integer type.
260 #![feature(assoc_int_consts)]
261 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, ", stringify!($Min), ");",
264 #[unstable(feature = "assoc_int_consts", reason = "recently added", issue = "68490")]
265 pub const MIN: Self = !0 ^ ((!0 as $UnsignedT) >> 1) as Self;
269 concat!("The largest value that can be represented by this integer type.
276 #![feature(assoc_int_consts)]
277 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");",
280 #[unstable(feature = "assoc_int_consts", reason = "recently added", issue = "68490")]
281 pub const MAX: Self = !Self::MIN;
285 "Returns the smallest value that can be represented by this integer type.",
286 #[stable(feature = "rust1", since = "1.0.0")]
289 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
290 pub const fn min_value() -> Self {
296 "Returns the largest value that can be represented by this integer type.",
297 #[stable(feature = "rust1", since = "1.0.0")]
300 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
301 pub const fn max_value() -> Self {
307 concat!("Converts a string slice in a given base to an integer.
309 The string is expected to be an optional `+` or `-` sign followed by digits.
310 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
311 depending on `radix`:
319 This function panics if `radix` is not in the range from 2 to 36.
326 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
331 from_str_radix(src, radix)
336 concat!("Returns the number of ones in the binary representation of `self`.
343 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
345 assert_eq!(n.count_ones(), 1);",
349 #[stable(feature = "rust1", since = "1.0.0")]
350 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
352 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
356 concat!("Returns the number of zeros in the binary representation of `self`.
363 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
365 #[stable(feature = "rust1", since = "1.0.0")]
366 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
368 pub const fn count_zeros(self) -> u32 {
374 concat!("Returns the number of leading zeros in the binary representation of `self`.
381 ", $Feature, "let n = -1", stringify!($SelfT), ";
383 assert_eq!(n.leading_zeros(), 0);",
386 #[stable(feature = "rust1", since = "1.0.0")]
387 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
389 pub const fn leading_zeros(self) -> u32 {
390 (self as $UnsignedT).leading_zeros()
395 concat!("Returns the number of trailing zeros in the binary representation of `self`.
402 ", $Feature, "let n = -4", stringify!($SelfT), ";
404 assert_eq!(n.trailing_zeros(), 2);",
407 #[stable(feature = "rust1", since = "1.0.0")]
408 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
410 pub const fn trailing_zeros(self) -> u32 {
411 (self as $UnsignedT).trailing_zeros()
416 concat!("Returns the number of leading ones in the binary representation of `self`.
423 ", $Feature, "#![feature(leading_trailing_ones)]
424 let n = -1", stringify!($SelfT), ";
426 assert_eq!(n.leading_ones(), ", stringify!($BITS), ");",
429 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
431 pub const fn leading_ones(self) -> u32 {
432 (self as $UnsignedT).leading_ones()
437 concat!("Returns the number of trailing ones in the binary representation of `self`.
444 ", $Feature, "#![feature(leading_trailing_ones)]
445 let n = 3", stringify!($SelfT), ";
447 assert_eq!(n.trailing_ones(), 2);",
450 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
452 pub const fn trailing_ones(self) -> u32 {
453 (self as $UnsignedT).trailing_ones()
458 concat!("Shifts the bits to the left by a specified amount, `n`,
459 wrapping the truncated bits to the end of the resulting integer.
461 Please note this isn't the same operation as the `<<` shifting operator!
468 let n = ", $rot_op, stringify!($SelfT), ";
469 let m = ", $rot_result, ";
471 assert_eq!(n.rotate_left(", $rot, "), m);
473 #[stable(feature = "rust1", since = "1.0.0")]
474 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
475 #[must_use = "this returns the result of the operation, \
476 without modifying the original"]
478 pub const fn rotate_left(self, n: u32) -> Self {
479 (self as $UnsignedT).rotate_left(n) as Self
484 concat!("Shifts the bits to the right by a specified amount, `n`,
485 wrapping the truncated bits to the beginning of the resulting
488 Please note this isn't the same operation as the `>>` shifting operator!
495 let n = ", $rot_result, stringify!($SelfT), ";
496 let m = ", $rot_op, ";
498 assert_eq!(n.rotate_right(", $rot, "), m);
500 #[stable(feature = "rust1", since = "1.0.0")]
501 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
502 #[must_use = "this returns the result of the operation, \
503 without modifying the original"]
505 pub const fn rotate_right(self, n: u32) -> Self {
506 (self as $UnsignedT).rotate_right(n) as Self
511 concat!("Reverses the byte order of the integer.
518 let n = ", $swap_op, stringify!($SelfT), ";
520 let m = n.swap_bytes();
522 assert_eq!(m, ", $swapped, ");
524 #[stable(feature = "rust1", since = "1.0.0")]
525 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
527 pub const fn swap_bytes(self) -> Self {
528 (self as $UnsignedT).swap_bytes() as Self
533 concat!("Reverses the bit pattern of the integer.
540 let n = ", $swap_op, stringify!($SelfT), ";
541 let m = n.reverse_bits();
543 assert_eq!(m, ", $reversed, ");
545 #[stable(feature = "reverse_bits", since = "1.37.0")]
546 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
549 pub const fn reverse_bits(self) -> Self {
550 (self as $UnsignedT).reverse_bits() as Self
555 concat!("Converts an integer from big endian to the target's endianness.
557 On big endian this is a no-op. On little endian the bytes are swapped.
564 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
566 if cfg!(target_endian = \"big\") {
567 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
569 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
573 #[stable(feature = "rust1", since = "1.0.0")]
574 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
576 pub const fn from_be(x: Self) -> Self {
577 #[cfg(target_endian = "big")]
581 #[cfg(not(target_endian = "big"))]
589 concat!("Converts an integer from little endian to the target's endianness.
591 On little endian this is a no-op. On big endian the bytes are swapped.
598 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
600 if cfg!(target_endian = \"little\") {
601 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
603 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
607 #[stable(feature = "rust1", since = "1.0.0")]
608 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
610 pub const fn from_le(x: Self) -> Self {
611 #[cfg(target_endian = "little")]
615 #[cfg(not(target_endian = "little"))]
623 concat!("Converts `self` to big endian from the target's endianness.
625 On big endian this is a no-op. On little endian the bytes are swapped.
632 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
634 if cfg!(target_endian = \"big\") {
635 assert_eq!(n.to_be(), n)
637 assert_eq!(n.to_be(), n.swap_bytes())
641 #[stable(feature = "rust1", since = "1.0.0")]
642 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
644 pub const fn to_be(self) -> Self { // or not to be?
645 #[cfg(target_endian = "big")]
649 #[cfg(not(target_endian = "big"))]
657 concat!("Converts `self` to little endian from the target's endianness.
659 On little endian this is a no-op. On big endian the bytes are swapped.
666 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
668 if cfg!(target_endian = \"little\") {
669 assert_eq!(n.to_le(), n)
671 assert_eq!(n.to_le(), n.swap_bytes())
675 #[stable(feature = "rust1", since = "1.0.0")]
676 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
678 pub const fn to_le(self) -> Self {
679 #[cfg(target_endian = "little")]
683 #[cfg(not(target_endian = "little"))]
691 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
692 if overflow occurred.
699 ", $Feature, "assert_eq!((", stringify!($SelfT),
700 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
701 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
704 #[stable(feature = "rust1", since = "1.0.0")]
705 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
706 #[must_use = "this returns the result of the operation, \
707 without modifying the original"]
709 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
710 let (a, b) = self.overflowing_add(rhs);
711 if b {None} else {Some(a)}
716 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
724 ", $Feature, "assert_eq!((", stringify!($SelfT),
725 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
726 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
729 #[stable(feature = "rust1", since = "1.0.0")]
730 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
731 #[must_use = "this returns the result of the operation, \
732 without modifying the original"]
734 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
735 let (a, b) = self.overflowing_sub(rhs);
736 if b {None} else {Some(a)}
741 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
749 ", $Feature, "assert_eq!(", stringify!($SelfT),
750 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
751 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
754 #[stable(feature = "rust1", since = "1.0.0")]
755 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
756 #[must_use = "this returns the result of the operation, \
757 without modifying the original"]
759 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
760 let (a, b) = self.overflowing_mul(rhs);
761 if b {None} else {Some(a)}
766 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
767 or the division results in overflow.
774 ", $Feature, "assert_eq!((", stringify!($SelfT),
775 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
776 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
777 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
780 #[stable(feature = "rust1", since = "1.0.0")]
781 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
782 #[must_use = "this returns the result of the operation, \
783 without modifying the original"]
785 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
786 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
789 // SAFETY: div by zero and by INT_MIN have been checked above
790 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
796 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
797 returning `None` if `rhs == 0` or the division results in overflow.
804 assert_eq!((", stringify!($SelfT),
805 "::min_value() + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
806 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euclid(-1), None);
807 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
809 #[stable(feature = "euclidean_division", since = "1.38.0")]
810 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
811 #[must_use = "this returns the result of the operation, \
812 without modifying the original"]
814 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
815 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
818 Some(self.div_euclid(rhs))
824 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
825 `rhs == 0` or the division results in overflow.
832 ", $Feature, "use std::", stringify!($SelfT), ";
834 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
835 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
836 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
839 #[stable(feature = "wrapping", since = "1.7.0")]
840 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
841 #[must_use = "this returns the result of the operation, \
842 without modifying the original"]
844 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
845 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
848 // SAFETY: div by zero and by INT_MIN have been checked above
849 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
855 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
856 if `rhs == 0` or the division results in overflow.
863 use std::", stringify!($SelfT), ";
865 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
866 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
867 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
869 #[stable(feature = "euclidean_division", since = "1.38.0")]
870 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
871 #[must_use = "this returns the result of the operation, \
872 without modifying the original"]
874 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
875 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
878 Some(self.rem_euclid(rhs))
884 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
891 ", $Feature, "use std::", stringify!($SelfT), ";
893 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
894 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
897 #[stable(feature = "wrapping", since = "1.7.0")]
898 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
900 pub const fn checked_neg(self) -> Option<Self> {
901 let (a, b) = self.overflowing_neg();
902 if b {None} else {Some(a)}
907 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
908 than or equal to the number of bits in `self`.
915 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
916 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
919 #[stable(feature = "wrapping", since = "1.7.0")]
920 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
921 #[must_use = "this returns the result of the operation, \
922 without modifying the original"]
924 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
925 let (a, b) = self.overflowing_shl(rhs);
926 if b {None} else {Some(a)}
931 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
932 larger than or equal to the number of bits in `self`.
939 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
940 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
943 #[stable(feature = "wrapping", since = "1.7.0")]
944 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
945 #[must_use = "this returns the result of the operation, \
946 without modifying the original"]
948 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
949 let (a, b) = self.overflowing_shr(rhs);
950 if b {None} else {Some(a)}
955 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
963 ", $Feature, "use std::", stringify!($SelfT), ";
965 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
966 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
969 #[stable(feature = "no_panic_abs", since = "1.13.0")]
970 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
972 pub const fn checked_abs(self) -> Option<Self> {
973 if self.is_negative() {
982 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
990 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
991 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
995 #[stable(feature = "no_panic_pow", since = "1.34.0")]
996 #[must_use = "this returns the result of the operation, \
997 without modifying the original"]
999 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
1000 let mut base = self;
1001 let mut acc: Self = 1;
1005 acc = acc.checked_mul(base)?;
1008 base = base.checked_mul(base)?;
1011 // Deal with the final bit of the exponent separately, since
1012 // squaring the base afterwards is not necessary and may cause a
1013 // needless overflow.
1015 acc = acc.checked_mul(base)?;
1023 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
1024 bounds instead of overflowing.
1031 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
1032 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
1034 assert_eq!(", stringify!($SelfT), "::min_value().saturating_add(-1), ", stringify!($SelfT),
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1041 #[must_use = "this returns the result of the operation, \
1042 without modifying the original"]
1044 pub const fn saturating_add(self, rhs: Self) -> Self {
1045 intrinsics::saturating_add(self, rhs)
1050 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
1051 numeric bounds instead of overflowing.
1058 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
1059 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
1061 assert_eq!(", stringify!($SelfT), "::max_value().saturating_sub(-1), ", stringify!($SelfT),
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1067 #[must_use = "this returns the result of the operation, \
1068 without modifying the original"]
1070 pub const fn saturating_sub(self, rhs: Self) -> Self {
1071 intrinsics::saturating_sub(self, rhs)
1076 concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
1077 instead of overflowing.
1084 ", $Feature, "#![feature(saturating_neg)]
1085 assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
1086 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
1087 assert_eq!(", stringify!($SelfT), "::min_value().saturating_neg(), ", stringify!($SelfT),
1089 assert_eq!(", stringify!($SelfT), "::max_value().saturating_neg(), ", stringify!($SelfT),
1090 "::min_value() + 1);",
1094 #[unstable(feature = "saturating_neg", issue = "59983")]
1095 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1097 pub const fn saturating_neg(self) -> Self {
1098 intrinsics::saturating_sub(0, self)
1103 concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1104 MIN` instead of overflowing.
1111 ", $Feature, "#![feature(saturating_neg)]
1112 assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
1113 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
1114 assert_eq!(", stringify!($SelfT), "::min_value().saturating_abs(), ", stringify!($SelfT),
1116 assert_eq!((", stringify!($SelfT), "::min_value() + 1).saturating_abs(), ", stringify!($SelfT),
1121 #[unstable(feature = "saturating_neg", issue = "59983")]
1122 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1124 pub const fn saturating_abs(self) -> Self {
1125 if self.is_negative() {
1126 self.saturating_neg()
1134 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1135 numeric bounds instead of overflowing.
1142 ", $Feature, "use std::", stringify!($SelfT), ";
1144 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1145 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1146 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1149 #[stable(feature = "wrapping", since = "1.7.0")]
1150 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1151 #[must_use = "this returns the result of the operation, \
1152 without modifying the original"]
1154 pub const fn saturating_mul(self, rhs: Self) -> Self {
1155 match self.checked_mul(rhs) {
1157 None => if (self < 0) == (rhs < 0) {
1167 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1168 saturating at the numeric bounds instead of overflowing.
1175 ", $Feature, "use std::", stringify!($SelfT), ";
1177 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1178 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1179 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1182 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1183 #[must_use = "this returns the result of the operation, \
1184 without modifying the original"]
1186 pub fn saturating_pow(self, exp: u32) -> Self {
1187 match self.checked_pow(exp) {
1189 None if self < 0 && exp % 2 == 1 => Self::min_value(),
1190 None => Self::max_value(),
1196 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1197 boundary of the type.
1204 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1205 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
1206 "::min_value() + 1);",
1209 #[stable(feature = "rust1", since = "1.0.0")]
1210 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1211 #[must_use = "this returns the result of the operation, \
1212 without modifying the original"]
1214 pub const fn wrapping_add(self, rhs: Self) -> Self {
1215 intrinsics::wrapping_add(self, rhs)
1220 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1221 boundary of the type.
1228 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1229 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1230 stringify!($SelfT), "::max_value());",
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1235 #[must_use = "this returns the result of the operation, \
1236 without modifying the original"]
1238 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1239 intrinsics::wrapping_sub(self, rhs)
1244 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1245 the boundary of the type.
1252 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1253 assert_eq!(11i8.wrapping_mul(12), -124);",
1256 #[stable(feature = "rust1", since = "1.0.0")]
1257 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1258 #[must_use = "this returns the result of the operation, \
1259 without modifying the original"]
1261 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1262 intrinsics::wrapping_mul(self, rhs)
1267 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1268 boundary of the type.
1270 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1271 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1272 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1276 This function will panic if `rhs` is 0.
1283 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1284 assert_eq!((-128i8).wrapping_div(-1), -128);",
1287 #[stable(feature = "num_wrapping", since = "1.2.0")]
1288 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1289 #[must_use = "this returns the result of the operation, \
1290 without modifying the original"]
1292 pub const fn wrapping_div(self, rhs: Self) -> Self {
1293 self.overflowing_div(rhs).0
1298 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1299 wrapping around at the boundary of the type.
1301 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1302 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1303 type. In this case, this method returns `MIN` itself.
1307 This function will panic if `rhs` is 0.
1314 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1315 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1317 #[stable(feature = "euclidean_division", since = "1.38.0")]
1318 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1319 #[must_use = "this returns the result of the operation, \
1320 without modifying the original"]
1322 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1323 self.overflowing_div_euclid(rhs).0
1328 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1329 boundary of the type.
1331 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1332 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1333 this function returns `0`.
1337 This function will panic if `rhs` is 0.
1344 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1345 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1348 #[stable(feature = "num_wrapping", since = "1.2.0")]
1349 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1350 #[must_use = "this returns the result of the operation, \
1351 without modifying the original"]
1353 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1354 self.overflowing_rem(rhs).0
1359 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1360 at the boundary of the type.
1362 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1363 for the type). In this case, this method returns 0.
1367 This function will panic if `rhs` is 0.
1374 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1375 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1377 #[stable(feature = "euclidean_division", since = "1.38.0")]
1378 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1379 #[must_use = "this returns the result of the operation, \
1380 without modifying the original"]
1382 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1383 self.overflowing_rem_euclid(rhs).0
1388 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1391 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1392 is the negative minimal value for the type); this is a positive value that is too large to represent
1393 in the type. In such a case, this function returns `MIN` itself.
1400 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1401 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1405 #[stable(feature = "num_wrapping", since = "1.2.0")]
1406 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1408 pub const fn wrapping_neg(self) -> Self {
1409 self.overflowing_neg().0
1414 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1415 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1417 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1418 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1419 The primitive integer types all implement a `rotate_left` function, which may be what you want
1427 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1428 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1431 #[stable(feature = "num_wrapping", since = "1.2.0")]
1432 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1433 #[must_use = "this returns the result of the operation, \
1434 without modifying the original"]
1436 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1437 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1440 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1446 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1447 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1449 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1450 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1451 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1459 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1460 assert_eq!((-128i16).wrapping_shr(64), -128);",
1463 #[stable(feature = "num_wrapping", since = "1.2.0")]
1464 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1465 #[must_use = "this returns the result of the operation, \
1466 without modifying the original"]
1468 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1469 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1472 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1478 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1479 the boundary of the type.
1481 The only case where such wrapping can occur is when one takes the absolute value of the negative
1482 minimal value for the type this is a positive value that is too large to represent in the type. In
1483 such a case, this function returns `MIN` itself.
1490 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1491 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1492 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1494 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1497 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1498 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1499 #[allow(unused_attributes)]
1500 #[allow_internal_unstable(const_if_match)]
1502 pub const fn wrapping_abs(self) -> Self {
1503 if self.is_negative() {
1512 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1513 wrapping around at the boundary of the type.
1520 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1521 assert_eq!(3i8.wrapping_pow(5), -13);
1522 assert_eq!(3i8.wrapping_pow(6), -39);",
1525 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1526 #[must_use = "this returns the result of the operation, \
1527 without modifying the original"]
1529 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1530 let mut base = self;
1531 let mut acc: Self = 1;
1535 acc = acc.wrapping_mul(base);
1538 base = base.wrapping_mul(base);
1541 // Deal with the final bit of the exponent separately, since
1542 // squaring the base afterwards is not necessary and may cause a
1543 // needless overflow.
1545 acc = acc.wrapping_mul(base);
1553 concat!("Calculates `self` + `rhs`
1555 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1556 occur. If an overflow would have occurred then the wrapped value is returned.
1563 ", $Feature, "use std::", stringify!($SelfT), ";
1565 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1566 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1567 "::MIN, true));", $EndFeature, "
1569 #[stable(feature = "wrapping", since = "1.7.0")]
1570 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1571 #[must_use = "this returns the result of the operation, \
1572 without modifying the original"]
1574 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1575 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1581 concat!("Calculates `self` - `rhs`
1583 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1584 would occur. If an overflow would have occurred then the wrapped value is returned.
1591 ", $Feature, "use std::", stringify!($SelfT), ";
1593 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1594 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1595 "::MAX, true));", $EndFeature, "
1597 #[stable(feature = "wrapping", since = "1.7.0")]
1598 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1599 #[must_use = "this returns the result of the operation, \
1600 without modifying the original"]
1602 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1603 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1609 concat!("Calculates the multiplication of `self` and `rhs`.
1611 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1612 would occur. If an overflow would have occurred then the wrapped value is returned.
1619 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1620 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1623 #[stable(feature = "wrapping", since = "1.7.0")]
1624 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1625 #[must_use = "this returns the result of the operation, \
1626 without modifying the original"]
1628 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1629 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1635 concat!("Calculates the divisor when `self` is divided by `rhs`.
1637 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1638 occur. If an overflow would occur then self is returned.
1642 This function will panic if `rhs` is 0.
1649 ", $Feature, "use std::", stringify!($SelfT), ";
1651 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1652 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1657 #[stable(feature = "wrapping", since = "1.7.0")]
1658 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1659 #[must_use = "this returns the result of the operation, \
1660 without modifying the original"]
1661 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1662 if self == Self::min_value() && rhs == -1 {
1671 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1673 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1674 occur. If an overflow would occur then `self` is returned.
1678 This function will panic if `rhs` is 0.
1685 use std::", stringify!($SelfT), ";
1687 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1688 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1692 #[stable(feature = "euclidean_division", since = "1.38.0")]
1693 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1694 #[must_use = "this returns the result of the operation, \
1695 without modifying the original"]
1696 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1697 if self == Self::min_value() && rhs == -1 {
1700 (self.div_euclid(rhs), false)
1706 concat!("Calculates the remainder when `self` is divided by `rhs`.
1708 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1709 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1713 This function will panic if `rhs` is 0.
1720 ", $Feature, "use std::", stringify!($SelfT), ";
1722 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1723 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1727 #[stable(feature = "wrapping", since = "1.7.0")]
1728 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1729 #[must_use = "this returns the result of the operation, \
1730 without modifying the original"]
1731 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1732 if self == Self::min_value() && rhs == -1 {
1742 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1744 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1745 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1749 This function will panic if `rhs` is 0.
1756 use std::", stringify!($SelfT), ";
1758 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1759 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1761 #[stable(feature = "euclidean_division", since = "1.38.0")]
1762 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1763 #[must_use = "this returns the result of the operation, \
1764 without modifying the original"]
1766 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1767 if self == Self::min_value() && rhs == -1 {
1770 (self.rem_euclid(rhs), false)
1777 concat!("Negates self, overflowing if this is equal to the minimum value.
1779 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1780 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1781 minimum value will be returned again and `true` will be returned for an overflow happening.
1788 ", $Feature, "use std::", stringify!($SelfT), ";
1790 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1791 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1792 "::MIN, true));", $EndFeature, "
1795 #[stable(feature = "wrapping", since = "1.7.0")]
1796 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1797 #[allow(unused_attributes)]
1798 #[allow_internal_unstable(const_if_match)]
1799 pub const fn overflowing_neg(self) -> (Self, bool) {
1800 if self == Self::min_value() {
1801 (Self::min_value(), true)
1809 concat!("Shifts self left by `rhs` bits.
1811 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1812 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1813 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1820 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1821 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1824 #[stable(feature = "wrapping", since = "1.7.0")]
1825 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1826 #[must_use = "this returns the result of the operation, \
1827 without modifying the original"]
1829 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1830 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1835 concat!("Shifts self right by `rhs` bits.
1837 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1838 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1839 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1846 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1847 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1850 #[stable(feature = "wrapping", since = "1.7.0")]
1851 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1852 #[must_use = "this returns the result of the operation, \
1853 without modifying the original"]
1855 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1856 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1861 concat!("Computes the absolute value of `self`.
1863 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1864 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1865 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1866 for an overflow happening.
1873 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1874 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1875 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1876 "::min_value(), true));",
1879 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1880 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1882 pub const fn overflowing_abs(self) -> (Self, bool) {
1883 (self.wrapping_abs(), self == Self::min_value())
1888 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1890 Returns a tuple of the exponentiation along with a bool indicating
1891 whether an overflow happened.
1898 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1899 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1902 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1903 #[must_use = "this returns the result of the operation, \
1904 without modifying the original"]
1906 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1907 let mut base = self;
1908 let mut acc: Self = 1;
1909 let mut overflown = false;
1910 // Scratch space for storing results of overflowing_mul.
1915 r = acc.overflowing_mul(base);
1920 r = base.overflowing_mul(base);
1925 // Deal with the final bit of the exponent separately, since
1926 // squaring the base afterwards is not necessary and may cause a
1927 // needless overflow.
1929 r = acc.overflowing_mul(base);
1939 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1946 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1948 assert_eq!(x.pow(5), 32);",
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 #[must_use = "this returns the result of the operation, \
1953 without modifying the original"]
1955 #[rustc_inherit_overflow_checks]
1956 pub fn pow(self, mut exp: u32) -> Self {
1957 let mut base = self;
1968 // Deal with the final bit of the exponent separately, since
1969 // squaring the base afterwards is not necessary and may cause a
1970 // needless overflow.
1980 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1982 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
1983 with `0 <= self.rem_euclid(rhs) < rhs`.
1985 In other words, the result is `self / rhs` rounded to the integer `n`
1986 such that `self >= n * rhs`.
1987 If `self > 0`, this is equal to round towards zero (the default in Rust);
1988 if `self < 0`, this is equal to round towards +/- infinity.
1992 This function will panic if `rhs` is 0 or the division results in overflow.
1999 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2002 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
2003 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
2004 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
2005 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
2007 #[stable(feature = "euclidean_division", since = "1.38.0")]
2008 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2009 #[must_use = "this returns the result of the operation, \
2010 without modifying the original"]
2012 #[rustc_inherit_overflow_checks]
2013 pub const fn div_euclid(self, rhs: Self) -> Self {
2016 return if rhs > 0 { q - 1 } else { q + 1 }
2024 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
2026 This is done as if by the Euclidean division algorithm -- given
2027 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
2028 `0 <= r < abs(rhs)`.
2032 This function will panic if `rhs` is 0 or the division results in overflow.
2039 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2042 assert_eq!(a.rem_euclid(b), 3);
2043 assert_eq!((-a).rem_euclid(b), 1);
2044 assert_eq!(a.rem_euclid(-b), 3);
2045 assert_eq!((-a).rem_euclid(-b), 1);
2047 #[stable(feature = "euclidean_division", since = "1.38.0")]
2048 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2049 #[must_use = "this returns the result of the operation, \
2050 without modifying the original"]
2052 #[rustc_inherit_overflow_checks]
2053 pub const fn rem_euclid(self, rhs: Self) -> Self {
2068 concat!("Computes the absolute value of `self`.
2072 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
2073 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
2074 code in debug mode will trigger a panic on this case and optimized code will return `",
2075 stringify!($SelfT), "::min_value()` without a panic.
2082 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
2083 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
2086 #[stable(feature = "rust1", since = "1.0.0")]
2087 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2088 #[allow(unused_attributes)]
2089 #[allow_internal_unstable(const_if_match)]
2091 #[rustc_inherit_overflow_checks]
2092 pub const fn abs(self) -> Self {
2093 // Note that the #[inline] above means that the overflow
2094 // semantics of the subtraction depend on the crate we're being
2096 if self.is_negative() {
2105 concat!("Returns a number representing sign of `self`.
2107 - `0` if the number is zero
2108 - `1` if the number is positive
2109 - `-1` if the number is negative
2116 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
2117 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
2118 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
2121 #[stable(feature = "rust1", since = "1.0.0")]
2122 #[rustc_const_unstable(feature = "const_int_sign", issue = "53718")]
2124 pub const fn signum(self) -> Self {
2134 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2142 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2143 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2149 pub const fn is_positive(self) -> bool { self > 0 }
2153 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2161 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2162 assert!(!10", stringify!($SelfT), ".is_negative());",
2165 #[stable(feature = "rust1", since = "1.0.0")]
2166 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2168 pub const fn is_negative(self) -> bool { self < 0 }
2172 concat!("Return the memory representation of this integer as a byte array in
2173 big-endian (network) byte order.
2180 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2181 assert_eq!(bytes, ", $be_bytes, ");
2183 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2184 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2186 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2187 self.to_be().to_ne_bytes()
2192 concat!("Return the memory representation of this integer as a byte array in
2193 little-endian byte order.
2200 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2201 assert_eq!(bytes, ", $le_bytes, ");
2203 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2204 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2206 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2207 self.to_le().to_ne_bytes()
2213 Return the memory representation of this integer as a byte array in
2216 As the target platform's native endianness is used, portable code
2217 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2222 [`to_be_bytes`]: #method.to_be_bytes
2223 [`to_le_bytes`]: #method.to_le_bytes
2228 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2231 if cfg!(target_endian = \"big\") {
2238 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2239 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2241 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2242 // SAFETY: integers are plain old datatypes so we can always transmute them to
2244 unsafe { mem::transmute(self) }
2249 concat!("Create an integer value from its representation as a byte array in
2257 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2258 assert_eq!(value, ", $swap_op, ");
2261 When starting from a slice rather than an array, fallible conversion APIs can be used:
2264 use std::convert::TryInto;
2266 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2267 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2269 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2272 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2273 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2275 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2276 Self::from_be(Self::from_ne_bytes(bytes))
2282 Create an integer value from its representation as a byte array in
2290 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2291 assert_eq!(value, ", $swap_op, ");
2294 When starting from a slice rather than an array, fallible conversion APIs can be used:
2297 use std::convert::TryInto;
2299 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2300 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2302 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2305 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2306 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2308 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2309 Self::from_le(Self::from_ne_bytes(bytes))
2314 concat!("Create an integer value from its memory representation as a byte
2315 array in native endianness.
2317 As the target platform's native endianness is used, portable code
2318 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2319 appropriate instead.
2321 [`from_be_bytes`]: #method.from_be_bytes
2322 [`from_le_bytes`]: #method.from_le_bytes
2329 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2334 assert_eq!(value, ", $swap_op, ");
2337 When starting from a slice rather than an array, fallible conversion APIs can be used:
2340 use std::convert::TryInto;
2342 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2343 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2345 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2348 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2349 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2351 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2352 // SAFETY: integers are plain old datatypes so we can always transmute to them
2353 unsafe { mem::transmute(bytes) }
2361 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2362 "[0x12]", "[0x12]", "", "" }
2367 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2368 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2373 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2374 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2375 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2380 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2381 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2382 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2383 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2388 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2389 170141183460469231731687303715884105727, "", "", 16,
2390 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2391 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2392 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2393 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2394 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2395 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2398 #[cfg(target_pointer_width = "16")]
2401 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2402 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2403 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2406 #[cfg(target_pointer_width = "32")]
2409 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2410 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2411 "[0x12, 0x34, 0x56, 0x78]",
2412 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2415 #[cfg(target_pointer_width = "64")]
2418 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2419 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2420 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2421 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2422 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2425 macro_rules! uint_impl {
2426 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2427 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2428 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2429 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2431 concat!("The smallest value that can be represented by this integer type.
2438 #![feature(assoc_int_consts)]
2439 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, 0);", $EndFeature, "
2441 #[unstable(feature = "assoc_int_consts", reason = "recently added", issue = "68490")]
2442 pub const MIN: Self = 0;
2446 concat!("The largest value that can be represented by this integer type.
2453 #![feature(assoc_int_consts)]
2454 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");",
2457 #[unstable(feature = "assoc_int_consts", reason = "recently added", issue = "68490")]
2458 pub const MAX: Self = !0;
2462 "Returns the smallest value that can be represented by this integer type.",
2463 #[stable(feature = "rust1", since = "1.0.0")]
2466 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2467 pub const fn min_value() -> Self { Self::MIN }
2471 "Returns the largest value that can be represented by this integer type.",
2472 #[stable(feature = "rust1", since = "1.0.0")]
2475 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2476 pub const fn max_value() -> Self { Self::MAX }
2480 concat!("Converts a string slice in a given base to an integer.
2482 The string is expected to be an optional `+` sign
2484 Leading and trailing whitespace represent an error.
2485 Digits are a subset of these characters, depending on `radix`:
2493 This function panics if `radix` is not in the range from 2 to 36.
2500 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2503 #[stable(feature = "rust1", since = "1.0.0")]
2504 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2505 from_str_radix(src, radix)
2510 concat!("Returns the number of ones in the binary representation of `self`.
2517 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2519 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2521 #[stable(feature = "rust1", since = "1.0.0")]
2522 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2524 pub const fn count_ones(self) -> u32 {
2525 intrinsics::ctpop(self as $ActualT) as u32
2530 concat!("Returns the number of zeros in the binary representation of `self`.
2537 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2539 #[stable(feature = "rust1", since = "1.0.0")]
2540 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2542 pub const fn count_zeros(self) -> u32 {
2543 (!self).count_ones()
2548 concat!("Returns the number of leading zeros in the binary representation of `self`.
2555 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2557 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2559 #[stable(feature = "rust1", since = "1.0.0")]
2560 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2562 pub const fn leading_zeros(self) -> u32 {
2563 intrinsics::ctlz(self as $ActualT) as u32
2568 concat!("Returns the number of trailing zeros in the binary representation
2576 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2578 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2580 #[stable(feature = "rust1", since = "1.0.0")]
2581 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2583 pub const fn trailing_zeros(self) -> u32 {
2584 intrinsics::cttz(self) as u32
2589 concat!("Returns the number of leading ones in the binary representation of `self`.
2596 ", $Feature, "#![feature(leading_trailing_ones)]
2597 let n = !(", stringify!($SelfT), "::max_value() >> 2);
2599 assert_eq!(n.leading_ones(), 2);", $EndFeature, "
2601 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2603 pub const fn leading_ones(self) -> u32 {
2604 (!self).leading_zeros()
2609 concat!("Returns the number of trailing ones in the binary representation
2617 ", $Feature, "#![feature(leading_trailing_ones)]
2618 let n = 0b1010111", stringify!($SelfT), ";
2620 assert_eq!(n.trailing_ones(), 3);", $EndFeature, "
2622 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2624 pub const fn trailing_ones(self) -> u32 {
2625 (!self).trailing_zeros()
2630 concat!("Shifts the bits to the left by a specified amount, `n`,
2631 wrapping the truncated bits to the end of the resulting integer.
2633 Please note this isn't the same operation as the `<<` shifting operator!
2640 let n = ", $rot_op, stringify!($SelfT), ";
2641 let m = ", $rot_result, ";
2643 assert_eq!(n.rotate_left(", $rot, "), m);
2645 #[stable(feature = "rust1", since = "1.0.0")]
2646 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2647 #[must_use = "this returns the result of the operation, \
2648 without modifying the original"]
2650 pub const fn rotate_left(self, n: u32) -> Self {
2651 intrinsics::rotate_left(self, n as $SelfT)
2656 concat!("Shifts the bits to the right by a specified amount, `n`,
2657 wrapping the truncated bits to the beginning of the resulting
2660 Please note this isn't the same operation as the `>>` shifting operator!
2667 let n = ", $rot_result, stringify!($SelfT), ";
2668 let m = ", $rot_op, ";
2670 assert_eq!(n.rotate_right(", $rot, "), m);
2672 #[stable(feature = "rust1", since = "1.0.0")]
2673 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2674 #[must_use = "this returns the result of the operation, \
2675 without modifying the original"]
2677 pub const fn rotate_right(self, n: u32) -> Self {
2678 intrinsics::rotate_right(self, n as $SelfT)
2684 Reverses the byte order of the integer.
2691 let n = ", $swap_op, stringify!($SelfT), ";
2692 let m = n.swap_bytes();
2694 assert_eq!(m, ", $swapped, ");
2696 #[stable(feature = "rust1", since = "1.0.0")]
2697 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2699 pub const fn swap_bytes(self) -> Self {
2700 intrinsics::bswap(self as $ActualT) as Self
2705 concat!("Reverses the bit pattern of the integer.
2712 let n = ", $swap_op, stringify!($SelfT), ";
2713 let m = n.reverse_bits();
2715 assert_eq!(m, ", $reversed, ");
2717 #[stable(feature = "reverse_bits", since = "1.37.0")]
2718 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2721 pub const fn reverse_bits(self) -> Self {
2722 intrinsics::bitreverse(self as $ActualT) as Self
2727 concat!("Converts an integer from big endian to the target's endianness.
2729 On big endian this is a no-op. On little endian the bytes are
2737 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2739 if cfg!(target_endian = \"big\") {
2740 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2742 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2745 #[stable(feature = "rust1", since = "1.0.0")]
2746 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2748 pub const fn from_be(x: Self) -> Self {
2749 #[cfg(target_endian = "big")]
2753 #[cfg(not(target_endian = "big"))]
2761 concat!("Converts an integer from little endian to the target's endianness.
2763 On little endian this is a no-op. On big endian the bytes are
2771 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2773 if cfg!(target_endian = \"little\") {
2774 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2776 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2779 #[stable(feature = "rust1", since = "1.0.0")]
2780 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2782 pub const fn from_le(x: Self) -> Self {
2783 #[cfg(target_endian = "little")]
2787 #[cfg(not(target_endian = "little"))]
2795 concat!("Converts `self` to big endian from the target's endianness.
2797 On big endian this is a no-op. On little endian the bytes are
2805 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2807 if cfg!(target_endian = \"big\") {
2808 assert_eq!(n.to_be(), n)
2810 assert_eq!(n.to_be(), n.swap_bytes())
2813 #[stable(feature = "rust1", since = "1.0.0")]
2814 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2816 pub const fn to_be(self) -> Self { // or not to be?
2817 #[cfg(target_endian = "big")]
2821 #[cfg(not(target_endian = "big"))]
2829 concat!("Converts `self` to little endian from the target's endianness.
2831 On little endian this is a no-op. On big endian the bytes are
2839 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2841 if cfg!(target_endian = \"little\") {
2842 assert_eq!(n.to_le(), n)
2844 assert_eq!(n.to_le(), n.swap_bytes())
2847 #[stable(feature = "rust1", since = "1.0.0")]
2848 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2850 pub const fn to_le(self) -> Self {
2851 #[cfg(target_endian = "little")]
2855 #[cfg(not(target_endian = "little"))]
2863 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2864 if overflow occurred.
2871 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2872 "Some(", stringify!($SelfT), "::max_value() - 1));
2873 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2875 #[stable(feature = "rust1", since = "1.0.0")]
2876 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2877 #[must_use = "this returns the result of the operation, \
2878 without modifying the original"]
2880 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
2881 let (a, b) = self.overflowing_add(rhs);
2882 if b {None} else {Some(a)}
2887 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2888 `None` if overflow occurred.
2895 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2896 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2898 #[stable(feature = "rust1", since = "1.0.0")]
2899 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2900 #[must_use = "this returns the result of the operation, \
2901 without modifying the original"]
2903 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
2904 let (a, b) = self.overflowing_sub(rhs);
2905 if b {None} else {Some(a)}
2910 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2911 `None` if overflow occurred.
2918 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2919 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2921 #[stable(feature = "rust1", since = "1.0.0")]
2922 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2923 #[must_use = "this returns the result of the operation, \
2924 without modifying the original"]
2926 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
2927 let (a, b) = self.overflowing_mul(rhs);
2928 if b {None} else {Some(a)}
2933 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2941 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2942 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2944 #[stable(feature = "rust1", since = "1.0.0")]
2945 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2946 #[must_use = "this returns the result of the operation, \
2947 without modifying the original"]
2949 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
2952 // SAFETY: div by zero has been checked above and unsigned types have no other
2953 // failure modes for division
2954 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2960 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2968 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
2969 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
2971 #[stable(feature = "euclidean_division", since = "1.38.0")]
2972 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2973 #[must_use = "this returns the result of the operation, \
2974 without modifying the original"]
2976 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
2980 Some(self.div_euclid(rhs))
2987 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2995 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2996 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2998 #[stable(feature = "wrapping", since = "1.7.0")]
2999 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3000 #[must_use = "this returns the result of the operation, \
3001 without modifying the original"]
3003 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
3007 // SAFETY: div by zero has been checked above and unsigned types have no other
3008 // failure modes for division
3009 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3015 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3023 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3024 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3026 #[stable(feature = "euclidean_division", since = "1.38.0")]
3027 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3028 #[must_use = "this returns the result of the operation, \
3029 without modifying the original"]
3031 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3035 Some(self.rem_euclid(rhs))
3041 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3044 Note that negating any positive integer will overflow.
3051 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3052 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3054 #[stable(feature = "wrapping", since = "1.7.0")]
3055 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3057 pub const fn checked_neg(self) -> Option<Self> {
3058 let (a, b) = self.overflowing_neg();
3059 if b {None} else {Some(a)}
3064 concat!("Checked shift left. Computes `self << rhs`, returning `None`
3065 if `rhs` is larger than or equal to the number of bits in `self`.
3072 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3073 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3075 #[stable(feature = "wrapping", since = "1.7.0")]
3076 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3077 #[must_use = "this returns the result of the operation, \
3078 without modifying the original"]
3080 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
3081 let (a, b) = self.overflowing_shl(rhs);
3082 if b {None} else {Some(a)}
3087 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3088 if `rhs` is larger than or equal to the number of bits in `self`.
3095 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3096 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3098 #[stable(feature = "wrapping", since = "1.7.0")]
3099 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3100 #[must_use = "this returns the result of the operation, \
3101 without modifying the original"]
3103 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
3104 let (a, b) = self.overflowing_shr(rhs);
3105 if b {None} else {Some(a)}
3110 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3118 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3119 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
3121 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3122 #[must_use = "this returns the result of the operation, \
3123 without modifying the original"]
3125 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
3126 let mut base = self;
3127 let mut acc: Self = 1;
3131 acc = acc.checked_mul(base)?;
3134 base = base.checked_mul(base)?;
3137 // Deal with the final bit of the exponent separately, since
3138 // squaring the base afterwards is not necessary and may cause a
3139 // needless overflow.
3141 acc = acc.checked_mul(base)?;
3149 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3150 the numeric bounds instead of overflowing.
3157 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3158 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
3161 #[stable(feature = "rust1", since = "1.0.0")]
3162 #[must_use = "this returns the result of the operation, \
3163 without modifying the original"]
3164 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3166 pub const fn saturating_add(self, rhs: Self) -> Self {
3167 intrinsics::saturating_add(self, rhs)
3172 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3173 at the numeric bounds instead of overflowing.
3180 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3181 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3183 #[stable(feature = "rust1", since = "1.0.0")]
3184 #[must_use = "this returns the result of the operation, \
3185 without modifying the original"]
3186 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3188 pub const fn saturating_sub(self, rhs: Self) -> Self {
3189 intrinsics::saturating_sub(self, rhs)
3194 concat!("Saturating integer multiplication. Computes `self * rhs`,
3195 saturating at the numeric bounds instead of overflowing.
3202 ", $Feature, "use std::", stringify!($SelfT), ";
3204 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3205 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3206 "::MAX);", $EndFeature, "
3208 #[stable(feature = "wrapping", since = "1.7.0")]
3209 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3210 #[must_use = "this returns the result of the operation, \
3211 without modifying the original"]
3213 pub const fn saturating_mul(self, rhs: Self) -> Self {
3214 match self.checked_mul(rhs) {
3216 None => Self::max_value(),
3222 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3223 saturating at the numeric bounds instead of overflowing.
3230 ", $Feature, "use std::", stringify!($SelfT), ";
3232 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3233 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3236 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3237 #[must_use = "this returns the result of the operation, \
3238 without modifying the original"]
3240 pub fn saturating_pow(self, exp: u32) -> Self {
3241 match self.checked_pow(exp) {
3243 None => Self::max_value(),
3249 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3250 wrapping around at the boundary of the type.
3257 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3258 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
3261 #[stable(feature = "rust1", since = "1.0.0")]
3262 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3263 #[must_use = "this returns the result of the operation, \
3264 without modifying the original"]
3266 pub const fn wrapping_add(self, rhs: Self) -> Self {
3267 intrinsics::wrapping_add(self, rhs)
3272 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3273 wrapping around at the boundary of the type.
3280 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3281 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
3284 #[stable(feature = "rust1", since = "1.0.0")]
3285 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3286 #[must_use = "this returns the result of the operation, \
3287 without modifying the original"]
3289 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3290 intrinsics::wrapping_sub(self, rhs)
3294 /// Wrapping (modular) multiplication. Computes `self *
3295 /// rhs`, wrapping around at the boundary of the type.
3301 /// Please note that this example is shared between integer types.
3302 /// Which explains why `u8` is used here.
3305 /// assert_eq!(10u8.wrapping_mul(12), 120);
3306 /// assert_eq!(25u8.wrapping_mul(12), 44);
3308 #[stable(feature = "rust1", since = "1.0.0")]
3309 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3310 #[must_use = "this returns the result of the operation, \
3311 without modifying the original"]
3313 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3314 intrinsics::wrapping_mul(self, rhs)
3318 concat!("Wrapping (modular) division. Computes `self / rhs`.
3319 Wrapped division on unsigned types is just normal division.
3320 There's no way wrapping could ever happen.
3321 This function exists, so that all operations
3322 are accounted for in the wrapping operations.
3329 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3331 #[stable(feature = "num_wrapping", since = "1.2.0")]
3332 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3333 #[must_use = "this returns the result of the operation, \
3334 without modifying the original"]
3336 pub const fn wrapping_div(self, rhs: Self) -> Self {
3342 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3343 Wrapped division on unsigned types is just normal division.
3344 There's no way wrapping could ever happen.
3345 This function exists, so that all operations
3346 are accounted for in the wrapping operations.
3347 Since, for the positive integers, all common
3348 definitions of division are equal, this
3349 is exactly equal to `self.wrapping_div(rhs)`.
3356 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3358 #[stable(feature = "euclidean_division", since = "1.38.0")]
3359 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3360 #[must_use = "this returns the result of the operation, \
3361 without modifying the original"]
3363 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
3369 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3370 Wrapped remainder calculation on unsigned types is
3371 just the regular remainder calculation.
3372 There's no way wrapping could ever happen.
3373 This function exists, so that all operations
3374 are accounted for in the wrapping operations.
3381 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3383 #[stable(feature = "num_wrapping", since = "1.2.0")]
3384 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3385 #[must_use = "this returns the result of the operation, \
3386 without modifying the original"]
3388 pub const fn wrapping_rem(self, rhs: Self) -> Self {
3394 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3395 Wrapped modulo calculation on unsigned types is
3396 just the regular remainder calculation.
3397 There's no way wrapping could ever happen.
3398 This function exists, so that all operations
3399 are accounted for in the wrapping operations.
3400 Since, for the positive integers, all common
3401 definitions of division are equal, this
3402 is exactly equal to `self.wrapping_rem(rhs)`.
3409 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3411 #[stable(feature = "euclidean_division", since = "1.38.0")]
3412 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3413 #[must_use = "this returns the result of the operation, \
3414 without modifying the original"]
3416 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3421 /// Wrapping (modular) negation. Computes `-self`,
3422 /// wrapping around at the boundary of the type.
3424 /// Since unsigned types do not have negative equivalents
3425 /// all applications of this function will wrap (except for `-0`).
3426 /// For values smaller than the corresponding signed type's maximum
3427 /// the result is the same as casting the corresponding signed value.
3428 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3429 /// `MAX` is the corresponding signed type's maximum.
3435 /// Please note that this example is shared between integer types.
3436 /// Which explains why `i8` is used here.
3439 /// assert_eq!(100i8.wrapping_neg(), -100);
3440 /// assert_eq!((-128i8).wrapping_neg(), -128);
3442 #[stable(feature = "num_wrapping", since = "1.2.0")]
3443 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3445 pub const fn wrapping_neg(self) -> Self {
3446 self.overflowing_neg().0
3450 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3451 where `mask` removes any high-order bits of `rhs` that
3452 would cause the shift to exceed the bitwidth of the type.
3454 Note that this is *not* the same as a rotate-left; the
3455 RHS of a wrapping shift-left is restricted to the range
3456 of the type, rather than the bits shifted out of the LHS
3457 being returned to the other end. The primitive integer
3458 types all implement a `rotate_left` function, which may
3459 be what you want instead.
3466 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3467 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3469 #[stable(feature = "num_wrapping", since = "1.2.0")]
3470 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3471 #[must_use = "this returns the result of the operation, \
3472 without modifying the original"]
3474 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3475 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3478 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3484 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3485 where `mask` removes any high-order bits of `rhs` that
3486 would cause the shift to exceed the bitwidth of the type.
3488 Note that this is *not* the same as a rotate-right; the
3489 RHS of a wrapping shift-right is restricted to the range
3490 of the type, rather than the bits shifted out of the LHS
3491 being returned to the other end. The primitive integer
3492 types all implement a `rotate_right` function, which may
3493 be what you want instead.
3500 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3501 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3503 #[stable(feature = "num_wrapping", since = "1.2.0")]
3504 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3505 #[must_use = "this returns the result of the operation, \
3506 without modifying the original"]
3508 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3509 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3512 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3518 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3519 wrapping around at the boundary of the type.
3526 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3527 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3529 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3530 #[must_use = "this returns the result of the operation, \
3531 without modifying the original"]
3533 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3534 let mut base = self;
3535 let mut acc: Self = 1;
3539 acc = acc.wrapping_mul(base);
3542 base = base.wrapping_mul(base);
3545 // Deal with the final bit of the exponent separately, since
3546 // squaring the base afterwards is not necessary and may cause a
3547 // needless overflow.
3549 acc = acc.wrapping_mul(base);
3557 concat!("Calculates `self` + `rhs`
3559 Returns a tuple of the addition along with a boolean indicating
3560 whether an arithmetic overflow would occur. If an overflow would
3561 have occurred then the wrapped value is returned.
3568 ", $Feature, "use std::", stringify!($SelfT), ";
3570 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3571 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3573 #[stable(feature = "wrapping", since = "1.7.0")]
3574 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3575 #[must_use = "this returns the result of the operation, \
3576 without modifying the original"]
3578 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3579 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3585 concat!("Calculates `self` - `rhs`
3587 Returns a tuple of the subtraction along with a boolean indicating
3588 whether an arithmetic overflow would occur. If an overflow would
3589 have occurred then the wrapped value is returned.
3596 ", $Feature, "use std::", stringify!($SelfT), ";
3598 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3599 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3602 #[stable(feature = "wrapping", since = "1.7.0")]
3603 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3604 #[must_use = "this returns the result of the operation, \
3605 without modifying the original"]
3607 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3608 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3613 /// Calculates the multiplication of `self` and `rhs`.
3615 /// Returns a tuple of the multiplication along with a boolean
3616 /// indicating whether an arithmetic overflow would occur. If an
3617 /// overflow would have occurred then the wrapped value is returned.
3623 /// Please note that this example is shared between integer types.
3624 /// Which explains why `u32` is used here.
3627 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3628 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3630 #[stable(feature = "wrapping", since = "1.7.0")]
3631 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3632 #[must_use = "this returns the result of the operation, \
3633 without modifying the original"]
3635 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3636 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3641 concat!("Calculates the divisor when `self` is divided by `rhs`.
3643 Returns a tuple of the divisor along with a boolean indicating
3644 whether an arithmetic overflow would occur. Note that for unsigned
3645 integers overflow never occurs, so the second value is always
3650 This function will panic if `rhs` is 0.
3657 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3660 #[stable(feature = "wrapping", since = "1.7.0")]
3661 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3662 #[must_use = "this returns the result of the operation, \
3663 without modifying the original"]
3664 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3670 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3672 Returns a tuple of the divisor along with a boolean indicating
3673 whether an arithmetic overflow would occur. Note that for unsigned
3674 integers overflow never occurs, so the second value is always
3676 Since, for the positive integers, all common
3677 definitions of division are equal, this
3678 is exactly equal to `self.overflowing_div(rhs)`.
3682 This function will panic if `rhs` is 0.
3689 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3692 #[stable(feature = "euclidean_division", since = "1.38.0")]
3693 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3694 #[must_use = "this returns the result of the operation, \
3695 without modifying the original"]
3696 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3702 concat!("Calculates the remainder when `self` is divided by `rhs`.
3704 Returns a tuple of the remainder after dividing along with a boolean
3705 indicating whether an arithmetic overflow would occur. Note that for
3706 unsigned integers overflow never occurs, so the second value is
3711 This function will panic if `rhs` is 0.
3718 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3721 #[stable(feature = "wrapping", since = "1.7.0")]
3722 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3723 #[must_use = "this returns the result of the operation, \
3724 without modifying the original"]
3725 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3731 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3733 Returns a tuple of the modulo after dividing along with a boolean
3734 indicating whether an arithmetic overflow would occur. Note that for
3735 unsigned integers overflow never occurs, so the second value is
3737 Since, for the positive integers, all common
3738 definitions of division are equal, this operation
3739 is exactly equal to `self.overflowing_rem(rhs)`.
3743 This function will panic if `rhs` is 0.
3750 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3753 #[stable(feature = "euclidean_division", since = "1.38.0")]
3754 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3755 #[must_use = "this returns the result of the operation, \
3756 without modifying the original"]
3757 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3763 concat!("Negates self in an overflowing fashion.
3765 Returns `!self + 1` using wrapping operations to return the value
3766 that represents the negation of this unsigned value. Note that for
3767 positive unsigned values overflow always occurs, but negating 0 does
3775 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3776 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3777 ", true));", $EndFeature, "
3780 #[stable(feature = "wrapping", since = "1.7.0")]
3781 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3782 pub const fn overflowing_neg(self) -> (Self, bool) {
3783 ((!self).wrapping_add(1), self != 0)
3788 concat!("Shifts self left by `rhs` bits.
3790 Returns a tuple of the shifted version of self along with a boolean
3791 indicating whether the shift value was larger than or equal to the
3792 number of bits. If the shift value is too large, then value is
3793 masked (N-1) where N is the number of bits, and this value is then
3794 used to perform the shift.
3801 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3802 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3804 #[stable(feature = "wrapping", since = "1.7.0")]
3805 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3806 #[must_use = "this returns the result of the operation, \
3807 without modifying the original"]
3809 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3810 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3815 concat!("Shifts self right by `rhs` bits.
3817 Returns a tuple of the shifted version of self along with a boolean
3818 indicating whether the shift value was larger than or equal to the
3819 number of bits. If the shift value is too large, then value is
3820 masked (N-1) where N is the number of bits, and this value is then
3821 used to perform the shift.
3828 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3829 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3831 #[stable(feature = "wrapping", since = "1.7.0")]
3832 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3833 #[must_use = "this returns the result of the operation, \
3834 without modifying the original"]
3836 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3837 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3842 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3844 Returns a tuple of the exponentiation along with a bool indicating
3845 whether an overflow happened.
3852 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3853 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3855 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3856 #[must_use = "this returns the result of the operation, \
3857 without modifying the original"]
3859 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3860 let mut base = self;
3861 let mut acc: Self = 1;
3862 let mut overflown = false;
3863 // Scratch space for storing results of overflowing_mul.
3868 r = acc.overflowing_mul(base);
3873 r = base.overflowing_mul(base);
3878 // Deal with the final bit of the exponent separately, since
3879 // squaring the base afterwards is not necessary and may cause a
3880 // needless overflow.
3882 r = acc.overflowing_mul(base);
3892 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3899 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3901 #[stable(feature = "rust1", since = "1.0.0")]
3902 #[must_use = "this returns the result of the operation, \
3903 without modifying the original"]
3905 #[rustc_inherit_overflow_checks]
3906 pub fn pow(self, mut exp: u32) -> Self {
3907 let mut base = self;
3918 // Deal with the final bit of the exponent separately, since
3919 // squaring the base afterwards is not necessary and may cause a
3920 // needless overflow.
3930 concat!("Performs Euclidean division.
3932 Since, for the positive integers, all common
3933 definitions of division are equal, this
3934 is exactly equal to `self / rhs`.
3938 This function will panic if `rhs` is 0.
3945 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
3947 #[stable(feature = "euclidean_division", since = "1.38.0")]
3948 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3949 #[must_use = "this returns the result of the operation, \
3950 without modifying the original"]
3952 #[rustc_inherit_overflow_checks]
3953 pub const fn div_euclid(self, rhs: Self) -> Self {
3960 concat!("Calculates the least remainder of `self (mod rhs)`.
3962 Since, for the positive integers, all common
3963 definitions of division are equal, this
3964 is exactly equal to `self % rhs`.
3968 This function will panic if `rhs` is 0.
3975 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
3977 #[stable(feature = "euclidean_division", since = "1.38.0")]
3978 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3979 #[must_use = "this returns the result of the operation, \
3980 without modifying the original"]
3982 #[rustc_inherit_overflow_checks]
3983 pub const fn rem_euclid(self, rhs: Self) -> Self {
3989 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3996 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3997 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3999 #[stable(feature = "rust1", since = "1.0.0")]
4000 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
4002 pub const fn is_power_of_two(self) -> bool {
4003 self.count_ones() == 1
4007 // Returns one less than next power of two.
4008 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
4010 // 8u8.one_less_than_next_power_of_two() == 7
4011 // 6u8.one_less_than_next_power_of_two() == 7
4013 // This method cannot overflow, as in the `next_power_of_two`
4014 // overflow cases it instead ends up returning the maximum value
4015 // of the type, and can return 0 for 0.
4017 fn one_less_than_next_power_of_two(self) -> Self {
4018 if self <= 1 { return 0; }
4021 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4022 // That means the shift is always in-bounds, and some processors
4023 // (such as intel pre-haswell) have more efficient ctlz
4024 // intrinsics when the argument is non-zero.
4025 let z = unsafe { intrinsics::ctlz_nonzero(p) };
4026 <$SelfT>::max_value() >> z
4030 concat!("Returns the smallest power of two greater than or equal to `self`.
4032 When return value overflows (i.e., `self > (1 << (N-1))` for type
4033 `uN`), it panics in debug mode and return value is wrapped to 0 in
4034 release mode (the only situation in which method can return 0).
4041 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4042 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4044 #[stable(feature = "rust1", since = "1.0.0")]
4046 pub fn next_power_of_two(self) -> Self {
4047 // Call the trait to get overflow checks
4048 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
4053 concat!("Returns the smallest power of two greater than or equal to `n`. If
4054 the next power of two is greater than the type's maximum value,
4055 `None` is returned, otherwise the power of two is wrapped in `Some`.
4062 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4063 ".checked_next_power_of_two(), Some(2));
4064 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4065 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
4069 #[stable(feature = "rust1", since = "1.0.0")]
4070 pub fn checked_next_power_of_two(self) -> Option<Self> {
4071 self.one_less_than_next_power_of_two().checked_add(1)
4076 concat!("Returns the smallest power of two greater than or equal to `n`. If
4077 the next power of two is greater than the type's maximum value,
4078 the return value is wrapped to `0`.
4085 #![feature(wrapping_next_power_of_two)]
4087 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4088 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4089 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
4092 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4093 reason = "needs decision on wrapping behaviour")]
4094 pub fn wrapping_next_power_of_two(self) -> Self {
4095 self.one_less_than_next_power_of_two().wrapping_add(1)
4100 concat!("Return the memory representation of this integer as a byte array in
4101 big-endian (network) byte order.
4108 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4109 assert_eq!(bytes, ", $be_bytes, ");
4111 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4112 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4114 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4115 self.to_be().to_ne_bytes()
4120 concat!("Return the memory representation of this integer as a byte array in
4121 little-endian byte order.
4128 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4129 assert_eq!(bytes, ", $le_bytes, ");
4131 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4132 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4134 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4135 self.to_le().to_ne_bytes()
4141 Return the memory representation of this integer as a byte array in
4144 As the target platform's native endianness is used, portable code
4145 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4150 [`to_be_bytes`]: #method.to_be_bytes
4151 [`to_le_bytes`]: #method.to_le_bytes
4156 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4159 if cfg!(target_endian = \"big\") {
4166 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4167 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4169 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4170 // SAFETY: integers are plain old datatypes so we can always transmute them to
4172 unsafe { mem::transmute(self) }
4177 concat!("Create an integer value from its representation as a byte array in
4185 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4186 assert_eq!(value, ", $swap_op, ");
4189 When starting from a slice rather than an array, fallible conversion APIs can be used:
4192 use std::convert::TryInto;
4194 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4195 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4197 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4200 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4201 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4203 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4204 Self::from_be(Self::from_ne_bytes(bytes))
4210 Create an integer value from its representation as a byte array in
4218 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4219 assert_eq!(value, ", $swap_op, ");
4222 When starting from a slice rather than an array, fallible conversion APIs can be used:
4225 use std::convert::TryInto;
4227 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4228 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4230 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4233 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4234 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4236 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4237 Self::from_le(Self::from_ne_bytes(bytes))
4242 concat!("Create an integer value from its memory representation as a byte
4243 array in native endianness.
4245 As the target platform's native endianness is used, portable code
4246 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4247 appropriate instead.
4249 [`from_be_bytes`]: #method.from_be_bytes
4250 [`from_le_bytes`]: #method.from_le_bytes
4257 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4262 assert_eq!(value, ", $swap_op, ");
4265 When starting from a slice rather than an array, fallible conversion APIs can be used:
4268 use std::convert::TryInto;
4270 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4271 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4273 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4276 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4277 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4279 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4280 // SAFETY: integers are plain old datatypes so we can always transmute to them
4281 unsafe { mem::transmute(bytes) }
4289 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4292 /// Checks if the value is within the ASCII range.
4297 /// let ascii = 97u8;
4298 /// let non_ascii = 150u8;
4300 /// assert!(ascii.is_ascii());
4301 /// assert!(!non_ascii.is_ascii());
4303 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4305 pub fn is_ascii(&self) -> bool {
4309 /// Makes a copy of the value in its ASCII upper case equivalent.
4311 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4312 /// but non-ASCII letters are unchanged.
4314 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4319 /// let lowercase_a = 97u8;
4321 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4324 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4325 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4327 pub fn to_ascii_uppercase(&self) -> u8 {
4328 // Unset the fith bit if this is a lowercase letter
4329 *self & !((self.is_ascii_lowercase() as u8) << 5)
4332 /// Makes a copy of the value in its ASCII lower case equivalent.
4334 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4335 /// but non-ASCII letters are unchanged.
4337 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4342 /// let uppercase_a = 65u8;
4344 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4347 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4348 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4350 pub fn to_ascii_lowercase(&self) -> u8 {
4351 // Set the fith bit if this is an uppercase letter
4352 *self | ((self.is_ascii_uppercase() as u8) << 5)
4355 /// Checks that two values are an ASCII case-insensitive match.
4357 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4362 /// let lowercase_a = 97u8;
4363 /// let uppercase_a = 65u8;
4365 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4367 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4369 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4370 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4373 /// Converts this value to its ASCII upper case equivalent in-place.
4375 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4376 /// but non-ASCII letters are unchanged.
4378 /// To return a new uppercased value without modifying the existing one, use
4379 /// [`to_ascii_uppercase`].
4384 /// let mut byte = b'a';
4386 /// byte.make_ascii_uppercase();
4388 /// assert_eq!(b'A', byte);
4391 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4392 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4394 pub fn make_ascii_uppercase(&mut self) {
4395 *self = self.to_ascii_uppercase();
4398 /// Converts this value to its ASCII lower case equivalent in-place.
4400 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4401 /// but non-ASCII letters are unchanged.
4403 /// To return a new lowercased value without modifying the existing one, use
4404 /// [`to_ascii_lowercase`].
4409 /// let mut byte = b'A';
4411 /// byte.make_ascii_lowercase();
4413 /// assert_eq!(b'a', byte);
4416 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4417 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4419 pub fn make_ascii_lowercase(&mut self) {
4420 *self = self.to_ascii_lowercase();
4423 /// Checks if the value is an ASCII alphabetic character:
4425 /// - U+0041 'A' ..= U+005A 'Z', or
4426 /// - U+0061 'a' ..= U+007A 'z'.
4431 /// let uppercase_a = b'A';
4432 /// let uppercase_g = b'G';
4435 /// let zero = b'0';
4436 /// let percent = b'%';
4437 /// let space = b' ';
4439 /// let esc = 0x1b_u8;
4441 /// assert!(uppercase_a.is_ascii_alphabetic());
4442 /// assert!(uppercase_g.is_ascii_alphabetic());
4443 /// assert!(a.is_ascii_alphabetic());
4444 /// assert!(g.is_ascii_alphabetic());
4445 /// assert!(!zero.is_ascii_alphabetic());
4446 /// assert!(!percent.is_ascii_alphabetic());
4447 /// assert!(!space.is_ascii_alphabetic());
4448 /// assert!(!lf.is_ascii_alphabetic());
4449 /// assert!(!esc.is_ascii_alphabetic());
4451 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4452 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4454 pub const fn is_ascii_alphabetic(&self) -> bool {
4455 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
4458 /// Checks if the value is an ASCII uppercase character:
4459 /// U+0041 'A' ..= U+005A 'Z'.
4464 /// let uppercase_a = b'A';
4465 /// let uppercase_g = b'G';
4468 /// let zero = b'0';
4469 /// let percent = b'%';
4470 /// let space = b' ';
4472 /// let esc = 0x1b_u8;
4474 /// assert!(uppercase_a.is_ascii_uppercase());
4475 /// assert!(uppercase_g.is_ascii_uppercase());
4476 /// assert!(!a.is_ascii_uppercase());
4477 /// assert!(!g.is_ascii_uppercase());
4478 /// assert!(!zero.is_ascii_uppercase());
4479 /// assert!(!percent.is_ascii_uppercase());
4480 /// assert!(!space.is_ascii_uppercase());
4481 /// assert!(!lf.is_ascii_uppercase());
4482 /// assert!(!esc.is_ascii_uppercase());
4484 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4485 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4487 pub const fn is_ascii_uppercase(&self) -> bool {
4488 matches!(*self, b'A'..=b'Z')
4491 /// Checks if the value is an ASCII lowercase character:
4492 /// U+0061 'a' ..= U+007A 'z'.
4497 /// let uppercase_a = b'A';
4498 /// let uppercase_g = b'G';
4501 /// let zero = b'0';
4502 /// let percent = b'%';
4503 /// let space = b' ';
4505 /// let esc = 0x1b_u8;
4507 /// assert!(!uppercase_a.is_ascii_lowercase());
4508 /// assert!(!uppercase_g.is_ascii_lowercase());
4509 /// assert!(a.is_ascii_lowercase());
4510 /// assert!(g.is_ascii_lowercase());
4511 /// assert!(!zero.is_ascii_lowercase());
4512 /// assert!(!percent.is_ascii_lowercase());
4513 /// assert!(!space.is_ascii_lowercase());
4514 /// assert!(!lf.is_ascii_lowercase());
4515 /// assert!(!esc.is_ascii_lowercase());
4517 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4518 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4520 pub const fn is_ascii_lowercase(&self) -> bool {
4521 matches!(*self, b'a'..=b'z')
4524 /// Checks if the value is an ASCII alphanumeric character:
4526 /// - U+0041 'A' ..= U+005A 'Z', or
4527 /// - U+0061 'a' ..= U+007A 'z', or
4528 /// - U+0030 '0' ..= U+0039 '9'.
4533 /// let uppercase_a = b'A';
4534 /// let uppercase_g = b'G';
4537 /// let zero = b'0';
4538 /// let percent = b'%';
4539 /// let space = b' ';
4541 /// let esc = 0x1b_u8;
4543 /// assert!(uppercase_a.is_ascii_alphanumeric());
4544 /// assert!(uppercase_g.is_ascii_alphanumeric());
4545 /// assert!(a.is_ascii_alphanumeric());
4546 /// assert!(g.is_ascii_alphanumeric());
4547 /// assert!(zero.is_ascii_alphanumeric());
4548 /// assert!(!percent.is_ascii_alphanumeric());
4549 /// assert!(!space.is_ascii_alphanumeric());
4550 /// assert!(!lf.is_ascii_alphanumeric());
4551 /// assert!(!esc.is_ascii_alphanumeric());
4553 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4554 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4556 pub const fn is_ascii_alphanumeric(&self) -> bool {
4557 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
4560 /// Checks if the value is an ASCII decimal digit:
4561 /// U+0030 '0' ..= U+0039 '9'.
4566 /// let uppercase_a = b'A';
4567 /// let uppercase_g = b'G';
4570 /// let zero = b'0';
4571 /// let percent = b'%';
4572 /// let space = b' ';
4574 /// let esc = 0x1b_u8;
4576 /// assert!(!uppercase_a.is_ascii_digit());
4577 /// assert!(!uppercase_g.is_ascii_digit());
4578 /// assert!(!a.is_ascii_digit());
4579 /// assert!(!g.is_ascii_digit());
4580 /// assert!(zero.is_ascii_digit());
4581 /// assert!(!percent.is_ascii_digit());
4582 /// assert!(!space.is_ascii_digit());
4583 /// assert!(!lf.is_ascii_digit());
4584 /// assert!(!esc.is_ascii_digit());
4586 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4587 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4589 pub const fn is_ascii_digit(&self) -> bool {
4590 matches!(*self, b'0'..=b'9')
4593 /// Checks if the value is an ASCII hexadecimal digit:
4595 /// - U+0030 '0' ..= U+0039 '9', or
4596 /// - U+0041 'A' ..= U+0046 'F', or
4597 /// - U+0061 'a' ..= U+0066 'f'.
4602 /// let uppercase_a = b'A';
4603 /// let uppercase_g = b'G';
4606 /// let zero = b'0';
4607 /// let percent = b'%';
4608 /// let space = b' ';
4610 /// let esc = 0x1b_u8;
4612 /// assert!(uppercase_a.is_ascii_hexdigit());
4613 /// assert!(!uppercase_g.is_ascii_hexdigit());
4614 /// assert!(a.is_ascii_hexdigit());
4615 /// assert!(!g.is_ascii_hexdigit());
4616 /// assert!(zero.is_ascii_hexdigit());
4617 /// assert!(!percent.is_ascii_hexdigit());
4618 /// assert!(!space.is_ascii_hexdigit());
4619 /// assert!(!lf.is_ascii_hexdigit());
4620 /// assert!(!esc.is_ascii_hexdigit());
4622 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4623 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4625 pub const fn is_ascii_hexdigit(&self) -> bool {
4626 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
4629 /// Checks if the value is an ASCII punctuation character:
4631 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4632 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4633 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4634 /// - U+007B ..= U+007E `{ | } ~`
4639 /// let uppercase_a = b'A';
4640 /// let uppercase_g = b'G';
4643 /// let zero = b'0';
4644 /// let percent = b'%';
4645 /// let space = b' ';
4647 /// let esc = 0x1b_u8;
4649 /// assert!(!uppercase_a.is_ascii_punctuation());
4650 /// assert!(!uppercase_g.is_ascii_punctuation());
4651 /// assert!(!a.is_ascii_punctuation());
4652 /// assert!(!g.is_ascii_punctuation());
4653 /// assert!(!zero.is_ascii_punctuation());
4654 /// assert!(percent.is_ascii_punctuation());
4655 /// assert!(!space.is_ascii_punctuation());
4656 /// assert!(!lf.is_ascii_punctuation());
4657 /// assert!(!esc.is_ascii_punctuation());
4659 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4660 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4662 pub const fn is_ascii_punctuation(&self) -> bool {
4663 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
4666 /// Checks if the value is an ASCII graphic character:
4667 /// U+0021 '!' ..= U+007E '~'.
4672 /// let uppercase_a = b'A';
4673 /// let uppercase_g = b'G';
4676 /// let zero = b'0';
4677 /// let percent = b'%';
4678 /// let space = b' ';
4680 /// let esc = 0x1b_u8;
4682 /// assert!(uppercase_a.is_ascii_graphic());
4683 /// assert!(uppercase_g.is_ascii_graphic());
4684 /// assert!(a.is_ascii_graphic());
4685 /// assert!(g.is_ascii_graphic());
4686 /// assert!(zero.is_ascii_graphic());
4687 /// assert!(percent.is_ascii_graphic());
4688 /// assert!(!space.is_ascii_graphic());
4689 /// assert!(!lf.is_ascii_graphic());
4690 /// assert!(!esc.is_ascii_graphic());
4692 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4693 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4695 pub const fn is_ascii_graphic(&self) -> bool {
4696 matches!(*self, b'!'..=b'~')
4699 /// Checks if the value is an ASCII whitespace character:
4700 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4701 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4703 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4704 /// whitespace][infra-aw]. There are several other definitions in
4705 /// wide use. For instance, [the POSIX locale][pct] includes
4706 /// U+000B VERTICAL TAB as well as all the above characters,
4707 /// but—from the very same specification—[the default rule for
4708 /// "field splitting" in the Bourne shell][bfs] considers *only*
4709 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4711 /// If you are writing a program that will process an existing
4712 /// file format, check what that format's definition of whitespace is
4713 /// before using this function.
4715 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4716 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4717 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4722 /// let uppercase_a = b'A';
4723 /// let uppercase_g = b'G';
4726 /// let zero = b'0';
4727 /// let percent = b'%';
4728 /// let space = b' ';
4730 /// let esc = 0x1b_u8;
4732 /// assert!(!uppercase_a.is_ascii_whitespace());
4733 /// assert!(!uppercase_g.is_ascii_whitespace());
4734 /// assert!(!a.is_ascii_whitespace());
4735 /// assert!(!g.is_ascii_whitespace());
4736 /// assert!(!zero.is_ascii_whitespace());
4737 /// assert!(!percent.is_ascii_whitespace());
4738 /// assert!(space.is_ascii_whitespace());
4739 /// assert!(lf.is_ascii_whitespace());
4740 /// assert!(!esc.is_ascii_whitespace());
4742 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4743 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4745 pub const fn is_ascii_whitespace(&self) -> bool {
4746 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
4749 /// Checks if the value is an ASCII control character:
4750 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4751 /// Note that most ASCII whitespace characters are control
4752 /// characters, but SPACE is not.
4757 /// let uppercase_a = b'A';
4758 /// let uppercase_g = b'G';
4761 /// let zero = b'0';
4762 /// let percent = b'%';
4763 /// let space = b' ';
4765 /// let esc = 0x1b_u8;
4767 /// assert!(!uppercase_a.is_ascii_control());
4768 /// assert!(!uppercase_g.is_ascii_control());
4769 /// assert!(!a.is_ascii_control());
4770 /// assert!(!g.is_ascii_control());
4771 /// assert!(!zero.is_ascii_control());
4772 /// assert!(!percent.is_ascii_control());
4773 /// assert!(!space.is_ascii_control());
4774 /// assert!(lf.is_ascii_control());
4775 /// assert!(esc.is_ascii_control());
4777 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4778 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4780 pub const fn is_ascii_control(&self) -> bool {
4781 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
4787 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4788 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4793 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4794 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4799 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4800 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4801 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4802 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4808 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4809 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4810 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4811 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4812 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4813 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4814 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4818 #[cfg(target_pointer_width = "16")]
4821 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4822 "[0x34, 0x12]", "[0x12, 0x34]",
4823 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4825 #[cfg(target_pointer_width = "32")]
4828 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4829 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4830 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4833 #[cfg(target_pointer_width = "64")]
4836 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4837 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4838 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4839 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4840 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4843 /// A classification of floating point numbers.
4845 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4846 /// their documentation for more.
4848 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4849 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4854 /// use std::num::FpCategory;
4857 /// let num = 12.4_f32;
4858 /// let inf = f32::INFINITY;
4859 /// let zero = 0f32;
4860 /// let sub: f32 = 1.1754942e-38;
4861 /// let nan = f32::NAN;
4863 /// assert_eq!(num.classify(), FpCategory::Normal);
4864 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4865 /// assert_eq!(zero.classify(), FpCategory::Zero);
4866 /// assert_eq!(nan.classify(), FpCategory::Nan);
4867 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4869 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4870 #[stable(feature = "rust1", since = "1.0.0")]
4871 pub enum FpCategory {
4872 /// "Not a Number", often obtained by dividing by zero.
4873 #[stable(feature = "rust1", since = "1.0.0")]
4876 /// Positive or negative infinity.
4877 #[stable(feature = "rust1", since = "1.0.0")]
4880 /// Positive or negative zero.
4881 #[stable(feature = "rust1", since = "1.0.0")]
4884 /// De-normalized floating point representation (less precise than `Normal`).
4885 #[stable(feature = "rust1", since = "1.0.0")]
4888 /// A regular floating point number.
4889 #[stable(feature = "rust1", since = "1.0.0")]
4893 macro_rules! from_str_radix_int_impl {
4895 #[stable(feature = "rust1", since = "1.0.0")]
4896 impl FromStr for $t {
4897 type Err = ParseIntError;
4898 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4899 from_str_radix(src, 10)
4904 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4906 /// The error type returned when a checked integral type conversion fails.
4907 #[stable(feature = "try_from", since = "1.34.0")]
4908 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4909 pub struct TryFromIntError(pub(crate) ());
4911 impl TryFromIntError {
4913 feature = "int_error_internals",
4914 reason = "available through Error trait and this method should \
4915 not be exposed publicly",
4919 pub fn __description(&self) -> &str {
4920 "out of range integral type conversion attempted"
4924 #[stable(feature = "try_from", since = "1.34.0")]
4925 impl fmt::Display for TryFromIntError {
4926 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4927 self.__description().fmt(fmt)
4931 #[stable(feature = "try_from", since = "1.34.0")]
4932 impl From<Infallible> for TryFromIntError {
4933 fn from(x: Infallible) -> TryFromIntError {
4938 #[unstable(feature = "never_type", issue = "35121")]
4939 impl From<!> for TryFromIntError {
4940 fn from(never: !) -> TryFromIntError {
4941 // Match rather than coerce to make sure that code like
4942 // `From<Infallible> for TryFromIntError` above will keep working
4943 // when `Infallible` becomes an alias to `!`.
4949 trait FromStrRadixHelper: PartialOrd + Copy {
4950 fn min_value() -> Self;
4951 fn max_value() -> Self;
4952 fn from_u32(u: u32) -> Self;
4953 fn checked_mul(&self, other: u32) -> Option<Self>;
4954 fn checked_sub(&self, other: u32) -> Option<Self>;
4955 fn checked_add(&self, other: u32) -> Option<Self>;
4959 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4961 fn min_value() -> Self { Self::min_value() }
4963 fn max_value() -> Self { Self::max_value() }
4965 fn from_u32(u: u32) -> Self { u as Self }
4967 fn checked_mul(&self, other: u32) -> Option<Self> {
4968 Self::checked_mul(*self, other as Self)
4971 fn checked_sub(&self, other: u32) -> Option<Self> {
4972 Self::checked_sub(*self, other as Self)
4975 fn checked_add(&self, other: u32) -> Option<Self> {
4976 Self::checked_add(*self, other as Self)
4980 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4982 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4983 use self::IntErrorKind::*;
4984 use self::ParseIntError as PIE;
4987 radix >= 2 && radix <= 36,
4988 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4993 return Err(PIE { kind: Empty });
4996 let is_signed_ty = T::from_u32(0) > T::min_value();
4998 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4999 // and cast them to chars. .to_digit() will safely return None for anything
5000 // other than a valid ascii digit for the given radix, including the first-byte
5001 // of multi-byte sequences
5002 let src = src.as_bytes();
5004 let (is_positive, digits) = match src[0] {
5005 b'+' => (true, &src[1..]),
5006 b'-' if is_signed_ty => (false, &src[1..]),
5010 if digits.is_empty() {
5011 return Err(PIE { kind: Empty });
5014 let mut result = T::from_u32(0);
5016 // The number is positive
5018 let x = match (c as char).to_digit(radix) {
5020 None => return Err(PIE { kind: InvalidDigit }),
5022 result = match result.checked_mul(radix) {
5023 Some(result) => result,
5024 None => return Err(PIE { kind: Overflow }),
5026 result = match result.checked_add(x) {
5027 Some(result) => result,
5028 None => return Err(PIE { kind: Overflow }),
5032 // The number is negative
5034 let x = match (c as char).to_digit(radix) {
5036 None => return Err(PIE { kind: InvalidDigit }),
5038 result = match result.checked_mul(radix) {
5039 Some(result) => result,
5040 None => return Err(PIE { kind: Underflow }),
5042 result = match result.checked_sub(x) {
5043 Some(result) => result,
5044 None => return Err(PIE { kind: Underflow }),
5051 /// An error which can be returned when parsing an integer.
5053 /// This error is used as the error type for the `from_str_radix()` functions
5054 /// on the primitive integer types, such as [`i8::from_str_radix`].
5056 /// # Potential causes
5058 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5059 /// in the string e.g., when it is obtained from the standard input.
5060 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5062 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5063 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5064 #[derive(Debug, Clone, PartialEq, Eq)]
5065 #[stable(feature = "rust1", since = "1.0.0")]
5066 pub struct ParseIntError {
5070 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5072 feature = "int_error_matching",
5073 reason = "it can be useful to match errors when making error messages \
5074 for integer parsing",
5077 #[derive(Debug, Clone, PartialEq, Eq)]
5079 pub enum IntErrorKind {
5080 /// Value being parsed is empty.
5082 /// Among other causes, this variant will be constructed when parsing an empty string.
5084 /// Contains an invalid digit.
5086 /// Among other causes, this variant will be constructed when parsing a string that
5087 /// contains a letter.
5089 /// Integer is too large to store in target integer type.
5091 /// Integer is too small to store in target integer type.
5095 /// This variant will be emitted when the parsing string has a value of zero, which
5096 /// would be illegal for non-zero types.
5100 impl ParseIntError {
5101 /// Outputs the detailed cause of parsing an integer failing.
5103 feature = "int_error_matching",
5104 reason = "it can be useful to match errors when making error messages \
5105 for integer parsing",
5108 pub fn kind(&self) -> &IntErrorKind {
5112 feature = "int_error_internals",
5113 reason = "available through Error trait and this method should \
5114 not be exposed publicly",
5118 pub fn __description(&self) -> &str {
5120 IntErrorKind::Empty => "cannot parse integer from empty string",
5121 IntErrorKind::InvalidDigit => "invalid digit found in string",
5122 IntErrorKind::Overflow => "number too large to fit in target type",
5123 IntErrorKind::Underflow => "number too small to fit in target type",
5124 IntErrorKind::Zero => "number would be zero for non-zero type",
5129 #[stable(feature = "rust1", since = "1.0.0")]
5130 impl fmt::Display for ParseIntError {
5131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5132 self.__description().fmt(f)
5136 #[stable(feature = "rust1", since = "1.0.0")]
5137 pub use crate::num::dec2flt::ParseFloatError;