1 // ignore-tidy-filelength
3 //! Numeric traits and functions for the built-in numeric types.
5 #![stable(feature = "rust1", since = "1.0.0")]
7 use crate::convert::Infallible;
11 use crate::ops::{BitOr, BitOrAssign};
12 use crate::str::FromStr;
14 // Used because the `?` operator is not allowed in a const context.
15 macro_rules! try_opt {
24 macro_rules! impl_nonzero_fmt {
25 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
28 impl fmt::$Trait for $Ty {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 macro_rules! doc_comment {
39 ($x:expr, $($tt:tt)*) => {
45 macro_rules! nonzero_integers {
46 ( $( #[$stability: meta] $Ty: ident($Int: ty); )+ ) => {
49 concat!("An integer that is known not to equal zero.
51 This enables some memory layout optimization.
52 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
55 use std::mem::size_of;
56 assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
60 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
62 #[rustc_layout_scalar_valid_range_start(1)]
63 #[rustc_nonnull_optimization_guaranteed]
68 /// Creates a non-zero without checking the value.
72 /// The value must not be zero.
74 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
76 pub const unsafe fn new_unchecked(n: $Int) -> Self {
80 /// Creates a non-zero if the given value is not zero.
82 #[rustc_const_unstable(feature = "const_nonzero_int_methods", issue = "53718")]
84 pub const fn new(n: $Int) -> Option<Self> {
86 // SAFETY: we just checked that there's no `0`
87 Some(unsafe { Self(n) })
93 /// Returns the value as a primitive type.
96 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
97 pub const fn get(self) -> $Int {
103 #[stable(feature = "from_nonzero", since = "1.31.0")]
104 impl From<$Ty> for $Int {
107 "Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`"),
108 fn from(nonzero: $Ty) -> Self {
114 #[stable(feature = "nonzero_bitor", since = "1.43.0")]
118 fn bitor(self, rhs: Self) -> Self::Output {
119 // Safety: since `self` and `rhs` are both nonzero, the
120 // result of the bitwise-or will be nonzero.
121 unsafe { $Ty::new_unchecked(self.get() | rhs.get()) }
125 #[stable(feature = "nonzero_bitor", since = "1.43.0")]
126 impl BitOr<$Int> for $Ty {
129 fn bitor(self, rhs: $Int) -> Self::Output {
130 // Safety: since `self` is nonzero, the result of the
131 // bitwise-or will be nonzero regardless of the value of
133 unsafe { $Ty::new_unchecked(self.get() | rhs) }
137 #[stable(feature = "nonzero_bitor", since = "1.43.0")]
138 impl BitOr<$Ty> for $Int {
141 fn bitor(self, rhs: $Ty) -> Self::Output {
142 // Safety: since `rhs` is nonzero, the result of the
143 // bitwise-or will be nonzero regardless of the value of
145 unsafe { $Ty::new_unchecked(self | rhs.get()) }
149 #[stable(feature = "nonzero_bitor", since = "1.43.0")]
150 impl BitOrAssign for $Ty {
152 fn bitor_assign(&mut self, rhs: Self) {
157 #[stable(feature = "nonzero_bitor", since = "1.43.0")]
158 impl BitOrAssign<$Int> for $Ty {
160 fn bitor_assign(&mut self, rhs: $Int) {
166 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
173 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
174 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
175 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
176 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
177 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
178 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
179 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
180 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
181 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
182 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
183 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
184 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
187 macro_rules! from_str_radix_nzint_impl {
189 #[stable(feature = "nonzero_parse", since = "1.35.0")]
190 impl FromStr for $t {
191 type Err = ParseIntError;
192 fn from_str(src: &str) -> Result<Self, Self::Err> {
193 Self::new(from_str_radix(src, 10)?)
194 .ok_or(ParseIntError {
195 kind: IntErrorKind::Zero
202 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
203 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
205 /// Provides intentionally-wrapped arithmetic on `T`.
207 /// Operations like `+` on `u32` values are intended to never overflow,
208 /// and in some debug configurations overflow is detected and results
209 /// in a panic. While most arithmetic falls into this category, some
210 /// code explicitly expects and relies upon modular arithmetic (e.g.,
213 /// Wrapping arithmetic can be achieved either through methods like
214 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
215 /// all standard arithmetic operations on the underlying value are
216 /// intended to have wrapping semantics.
218 /// The underlying value can be retrieved through the `.0` index of the
219 /// `Wrapping` tuple.
224 /// use std::num::Wrapping;
226 /// let zero = Wrapping(0u32);
227 /// let one = Wrapping(1u32);
229 /// assert_eq!(std::u32::MAX, (zero - one).0);
231 #[stable(feature = "rust1", since = "1.0.0")]
232 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
234 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
236 #[stable(feature = "rust1", since = "1.0.0")]
237 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243 #[stable(feature = "wrapping_display", since = "1.10.0")]
244 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
245 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
251 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
258 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
265 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
272 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
273 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278 // All these modules are technically private and only exposed for coretests:
286 macro_rules! usize_isize_to_xe_bytes_doc {
290 **Note**: This function returns an array of length 2, 4 or 8 bytes
291 depending on the target pointer size.
297 macro_rules! usize_isize_from_xe_bytes_doc {
301 **Note**: This function takes an array of length 2, 4 or 8 bytes
302 depending on the target pointer size.
308 macro_rules! int_impl {
309 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
310 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
311 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
312 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
314 concat!("The smallest value that can be represented by this integer type.
321 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, ", stringify!($Min), ");",
324 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
325 pub const MIN: Self = !0 ^ ((!0 as $UnsignedT) >> 1) as Self;
329 concat!("The largest value that can be represented by this integer type.
336 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");",
339 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
340 pub const MAX: Self = !Self::MIN;
344 concat!("Converts a string slice in a given base to an integer.
346 The string is expected to be an optional `+` or `-` sign followed by digits.
347 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
348 depending on `radix`:
356 This function panics if `radix` is not in the range from 2 to 36.
363 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
366 #[stable(feature = "rust1", since = "1.0.0")]
367 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
368 from_str_radix(src, radix)
373 concat!("Returns the number of ones in the binary representation of `self`.
380 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
382 assert_eq!(n.count_ones(), 1);",
386 #[stable(feature = "rust1", since = "1.0.0")]
387 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
389 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
393 concat!("Returns the number of zeros in the binary representation of `self`.
400 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 1);", $EndFeature, "
402 #[stable(feature = "rust1", since = "1.0.0")]
403 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
405 pub const fn count_zeros(self) -> u32 {
411 concat!("Returns the number of leading zeros in the binary representation of `self`.
418 ", $Feature, "let n = -1", stringify!($SelfT), ";
420 assert_eq!(n.leading_zeros(), 0);",
423 #[stable(feature = "rust1", since = "1.0.0")]
424 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
426 pub const fn leading_zeros(self) -> u32 {
427 (self as $UnsignedT).leading_zeros()
432 concat!("Returns the number of trailing zeros in the binary representation of `self`.
439 ", $Feature, "let n = -4", stringify!($SelfT), ";
441 assert_eq!(n.trailing_zeros(), 2);",
444 #[stable(feature = "rust1", since = "1.0.0")]
445 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
447 pub const fn trailing_zeros(self) -> u32 {
448 (self as $UnsignedT).trailing_zeros()
453 concat!("Returns the number of leading ones in the binary representation of `self`.
460 ", $Feature, "#![feature(leading_trailing_ones)]
461 let n = -1", stringify!($SelfT), ";
463 assert_eq!(n.leading_ones(), ", stringify!($BITS), ");",
466 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
468 pub const fn leading_ones(self) -> u32 {
469 (self as $UnsignedT).leading_ones()
474 concat!("Returns the number of trailing ones in the binary representation of `self`.
481 ", $Feature, "#![feature(leading_trailing_ones)]
482 let n = 3", stringify!($SelfT), ";
484 assert_eq!(n.trailing_ones(), 2);",
487 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
489 pub const fn trailing_ones(self) -> u32 {
490 (self as $UnsignedT).trailing_ones()
495 concat!("Shifts the bits to the left by a specified amount, `n`,
496 wrapping the truncated bits to the end of the resulting integer.
498 Please note this isn't the same operation as the `<<` shifting operator!
505 let n = ", $rot_op, stringify!($SelfT), ";
506 let m = ", $rot_result, ";
508 assert_eq!(n.rotate_left(", $rot, "), m);
510 #[stable(feature = "rust1", since = "1.0.0")]
511 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
512 #[must_use = "this returns the result of the operation, \
513 without modifying the original"]
515 pub const fn rotate_left(self, n: u32) -> Self {
516 (self as $UnsignedT).rotate_left(n) as Self
521 concat!("Shifts the bits to the right by a specified amount, `n`,
522 wrapping the truncated bits to the beginning of the resulting
525 Please note this isn't the same operation as the `>>` shifting operator!
532 let n = ", $rot_result, stringify!($SelfT), ";
533 let m = ", $rot_op, ";
535 assert_eq!(n.rotate_right(", $rot, "), m);
537 #[stable(feature = "rust1", since = "1.0.0")]
538 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
539 #[must_use = "this returns the result of the operation, \
540 without modifying the original"]
542 pub const fn rotate_right(self, n: u32) -> Self {
543 (self as $UnsignedT).rotate_right(n) as Self
548 concat!("Reverses the byte order of the integer.
555 let n = ", $swap_op, stringify!($SelfT), ";
557 let m = n.swap_bytes();
559 assert_eq!(m, ", $swapped, ");
561 #[stable(feature = "rust1", since = "1.0.0")]
562 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
564 pub const fn swap_bytes(self) -> Self {
565 (self as $UnsignedT).swap_bytes() as Self
570 concat!("Reverses the bit pattern of the integer.
577 let n = ", $swap_op, stringify!($SelfT), ";
578 let m = n.reverse_bits();
580 assert_eq!(m, ", $reversed, ");
582 #[stable(feature = "reverse_bits", since = "1.37.0")]
583 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
586 pub const fn reverse_bits(self) -> Self {
587 (self as $UnsignedT).reverse_bits() as Self
592 concat!("Converts an integer from big endian to the target's endianness.
594 On big endian this is a no-op. On little endian the bytes are swapped.
601 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
603 if cfg!(target_endian = \"big\") {
604 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
606 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
610 #[stable(feature = "rust1", since = "1.0.0")]
611 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
613 pub const fn from_be(x: Self) -> Self {
614 #[cfg(target_endian = "big")]
618 #[cfg(not(target_endian = "big"))]
626 concat!("Converts an integer from little endian to the target's endianness.
628 On little endian this is a no-op. On big endian the bytes are swapped.
635 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
637 if cfg!(target_endian = \"little\") {
638 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
640 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
644 #[stable(feature = "rust1", since = "1.0.0")]
645 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
647 pub const fn from_le(x: Self) -> Self {
648 #[cfg(target_endian = "little")]
652 #[cfg(not(target_endian = "little"))]
660 concat!("Converts `self` to big endian from the target's endianness.
662 On big endian this is a no-op. On little endian the bytes are swapped.
669 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
671 if cfg!(target_endian = \"big\") {
672 assert_eq!(n.to_be(), n)
674 assert_eq!(n.to_be(), n.swap_bytes())
678 #[stable(feature = "rust1", since = "1.0.0")]
679 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
681 pub const fn to_be(self) -> Self { // or not to be?
682 #[cfg(target_endian = "big")]
686 #[cfg(not(target_endian = "big"))]
694 concat!("Converts `self` to little endian from the target's endianness.
696 On little endian this is a no-op. On big endian the bytes are swapped.
703 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
705 if cfg!(target_endian = \"little\") {
706 assert_eq!(n.to_le(), n)
708 assert_eq!(n.to_le(), n.swap_bytes())
712 #[stable(feature = "rust1", since = "1.0.0")]
713 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
715 pub const fn to_le(self) -> Self {
716 #[cfg(target_endian = "little")]
720 #[cfg(not(target_endian = "little"))]
728 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
729 if overflow occurred.
736 ", $Feature, "assert_eq!((", stringify!($SelfT),
737 "::MAX - 2).checked_add(1), Some(", stringify!($SelfT), "::MAX - 1));
738 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);",
741 #[stable(feature = "rust1", since = "1.0.0")]
742 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
743 #[must_use = "this returns the result of the operation, \
744 without modifying the original"]
746 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
747 let (a, b) = self.overflowing_add(rhs);
748 if b {None} else {Some(a)}
753 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
761 ", $Feature, "assert_eq!((", stringify!($SelfT),
762 "::MIN + 2).checked_sub(1), Some(", stringify!($SelfT), "::MIN + 1));
763 assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(3), None);",
766 #[stable(feature = "rust1", since = "1.0.0")]
767 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
768 #[must_use = "this returns the result of the operation, \
769 without modifying the original"]
771 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
772 let (a, b) = self.overflowing_sub(rhs);
773 if b {None} else {Some(a)}
778 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
786 ", $Feature, "assert_eq!(", stringify!($SelfT),
787 "::MAX.checked_mul(1), Some(", stringify!($SelfT), "::MAX));
788 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);",
791 #[stable(feature = "rust1", since = "1.0.0")]
792 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
793 #[must_use = "this returns the result of the operation, \
794 without modifying the original"]
796 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
797 let (a, b) = self.overflowing_mul(rhs);
798 if b {None} else {Some(a)}
803 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
804 or the division results in overflow.
811 ", $Feature, "assert_eq!((", stringify!($SelfT),
812 "::MIN + 1).checked_div(-1), Some(", stringify!($Max), "));
813 assert_eq!(", stringify!($SelfT), "::MIN.checked_div(-1), None);
814 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
817 #[stable(feature = "rust1", since = "1.0.0")]
818 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
819 #[must_use = "this returns the result of the operation, \
820 without modifying the original"]
822 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
823 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
826 // SAFETY: div by zero and by INT_MIN have been checked above
827 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
833 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
834 returning `None` if `rhs == 0` or the division results in overflow.
841 assert_eq!((", stringify!($SelfT),
842 "::MIN + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
843 assert_eq!(", stringify!($SelfT), "::MIN.checked_div_euclid(-1), None);
844 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
846 #[stable(feature = "euclidean_division", since = "1.38.0")]
847 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
848 #[must_use = "this returns the result of the operation, \
849 without modifying the original"]
851 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
852 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
855 Some(self.div_euclid(rhs))
861 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
862 `rhs == 0` or the division results in overflow.
870 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
871 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
872 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
875 #[stable(feature = "wrapping", since = "1.7.0")]
876 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
877 #[must_use = "this returns the result of the operation, \
878 without modifying the original"]
880 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
881 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
884 // SAFETY: div by zero and by INT_MIN have been checked above
885 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
891 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
892 if `rhs == 0` or the division results in overflow.
899 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
900 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
901 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
903 #[stable(feature = "euclidean_division", since = "1.38.0")]
904 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
905 #[must_use = "this returns the result of the operation, \
906 without modifying the original"]
908 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
909 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
912 Some(self.rem_euclid(rhs))
918 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
926 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
927 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
930 #[stable(feature = "wrapping", since = "1.7.0")]
931 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
933 pub const fn checked_neg(self) -> Option<Self> {
934 let (a, b) = self.overflowing_neg();
935 if b {None} else {Some(a)}
940 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
941 than or equal to the number of bits in `self`.
948 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
949 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
952 #[stable(feature = "wrapping", since = "1.7.0")]
953 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
954 #[must_use = "this returns the result of the operation, \
955 without modifying the original"]
957 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
958 let (a, b) = self.overflowing_shl(rhs);
959 if b {None} else {Some(a)}
964 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
965 larger than or equal to the number of bits in `self`.
972 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
973 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
976 #[stable(feature = "wrapping", since = "1.7.0")]
977 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
978 #[must_use = "this returns the result of the operation, \
979 without modifying the original"]
981 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
982 let (a, b) = self.overflowing_shr(rhs);
983 if b {None} else {Some(a)}
988 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
997 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
998 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
1001 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1002 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
1004 pub const fn checked_abs(self) -> Option<Self> {
1005 if self.is_negative() {
1014 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
1022 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
1023 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);",
1027 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1028 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1029 #[must_use = "this returns the result of the operation, \
1030 without modifying the original"]
1032 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
1033 let mut base = self;
1034 let mut acc: Self = 1;
1038 acc = try_opt!(acc.checked_mul(base));
1041 base = try_opt!(base.checked_mul(base));
1044 // Deal with the final bit of the exponent separately, since
1045 // squaring the base afterwards is not necessary and may cause a
1046 // needless overflow.
1048 acc = try_opt!(acc.checked_mul(base));
1056 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
1057 bounds instead of overflowing.
1064 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
1065 assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT),
1067 assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT),
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1074 #[must_use = "this returns the result of the operation, \
1075 without modifying the original"]
1077 pub const fn saturating_add(self, rhs: Self) -> Self {
1078 intrinsics::saturating_add(self, rhs)
1083 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
1084 numeric bounds instead of overflowing.
1091 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
1092 assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT),
1094 assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT),
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1100 #[must_use = "this returns the result of the operation, \
1101 without modifying the original"]
1103 pub const fn saturating_sub(self, rhs: Self) -> Self {
1104 intrinsics::saturating_sub(self, rhs)
1109 concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
1110 instead of overflowing.
1117 ", $Feature, "#![feature(saturating_neg)]
1118 assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
1119 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
1120 assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT),
1122 assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT),
1127 #[unstable(feature = "saturating_neg", issue = "59983")]
1128 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1130 pub const fn saturating_neg(self) -> Self {
1131 intrinsics::saturating_sub(0, self)
1136 concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1137 MIN` instead of overflowing.
1144 ", $Feature, "#![feature(saturating_neg)]
1145 assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
1146 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
1147 assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT),
1149 assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT),
1154 #[unstable(feature = "saturating_neg", issue = "59983")]
1155 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1157 pub const fn saturating_abs(self) -> Self {
1158 if self.is_negative() {
1159 self.saturating_neg()
1167 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1168 numeric bounds instead of overflowing.
1176 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1177 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1178 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1181 #[stable(feature = "wrapping", since = "1.7.0")]
1182 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1183 #[must_use = "this returns the result of the operation, \
1184 without modifying the original"]
1186 pub const fn saturating_mul(self, rhs: Self) -> Self {
1187 match self.checked_mul(rhs) {
1189 None => if (self < 0) == (rhs < 0) {
1199 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1200 saturating at the numeric bounds instead of overflowing.
1208 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1209 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1210 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1213 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1214 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1215 #[must_use = "this returns the result of the operation, \
1216 without modifying the original"]
1218 pub const fn saturating_pow(self, exp: u32) -> Self {
1219 match self.checked_pow(exp) {
1221 None if self < 0 && exp % 2 == 1 => Self::min_value(),
1222 None => Self::max_value(),
1228 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1229 boundary of the type.
1236 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1237 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT),
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1243 #[must_use = "this returns the result of the operation, \
1244 without modifying the original"]
1246 pub const fn wrapping_add(self, rhs: Self) -> Self {
1247 intrinsics::wrapping_add(self, rhs)
1252 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1253 boundary of the type.
1260 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1261 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ",
1262 stringify!($SelfT), "::MAX);",
1265 #[stable(feature = "rust1", since = "1.0.0")]
1266 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1267 #[must_use = "this returns the result of the operation, \
1268 without modifying the original"]
1270 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1271 intrinsics::wrapping_sub(self, rhs)
1276 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1277 the boundary of the type.
1284 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1285 assert_eq!(11i8.wrapping_mul(12), -124);",
1288 #[stable(feature = "rust1", since = "1.0.0")]
1289 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1290 #[must_use = "this returns the result of the operation, \
1291 without modifying the original"]
1293 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1294 intrinsics::wrapping_mul(self, rhs)
1299 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1300 boundary of the type.
1302 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1303 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1304 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1308 This function will panic if `rhs` is 0.
1315 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1316 assert_eq!((-128i8).wrapping_div(-1), -128);",
1319 #[stable(feature = "num_wrapping", since = "1.2.0")]
1320 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1321 #[must_use = "this returns the result of the operation, \
1322 without modifying the original"]
1324 pub const fn wrapping_div(self, rhs: Self) -> Self {
1325 self.overflowing_div(rhs).0
1330 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1331 wrapping around at the boundary of the type.
1333 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1334 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1335 type. In this case, this method returns `MIN` itself.
1339 This function will panic if `rhs` is 0.
1346 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1347 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1349 #[stable(feature = "euclidean_division", since = "1.38.0")]
1350 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1351 #[must_use = "this returns the result of the operation, \
1352 without modifying the original"]
1354 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1355 self.overflowing_div_euclid(rhs).0
1360 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1361 boundary of the type.
1363 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1364 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1365 this function returns `0`.
1369 This function will panic if `rhs` is 0.
1376 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1377 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1380 #[stable(feature = "num_wrapping", since = "1.2.0")]
1381 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1382 #[must_use = "this returns the result of the operation, \
1383 without modifying the original"]
1385 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1386 self.overflowing_rem(rhs).0
1391 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1392 at the boundary of the type.
1394 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1395 for the type). In this case, this method returns 0.
1399 This function will panic if `rhs` is 0.
1406 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1407 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1409 #[stable(feature = "euclidean_division", since = "1.38.0")]
1410 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1411 #[must_use = "this returns the result of the operation, \
1412 without modifying the original"]
1414 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1415 self.overflowing_rem_euclid(rhs).0
1420 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1423 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1424 is the negative minimal value for the type); this is a positive value that is too large to represent
1425 in the type. In such a case, this function returns `MIN` itself.
1432 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1433 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT),
1437 #[stable(feature = "num_wrapping", since = "1.2.0")]
1438 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1440 pub const fn wrapping_neg(self) -> Self {
1441 self.overflowing_neg().0
1446 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1447 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-left; the RHS of a wrapping shift-left is restricted to
1450 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1451 The primitive integer types all implement a `rotate_left` function, which may be what you want
1459 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1460 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
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_shl(self, rhs: u32) -> Self {
1469 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1472 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1478 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1479 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1481 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1482 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1483 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1491 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1492 assert_eq!((-128i16).wrapping_shr(64), -128);",
1495 #[stable(feature = "num_wrapping", since = "1.2.0")]
1496 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1497 #[must_use = "this returns the result of the operation, \
1498 without modifying the original"]
1500 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1501 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1504 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1510 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1511 the boundary of the type.
1513 The only case where such wrapping can occur is when one takes the absolute value of the negative
1514 minimal value for the type this is a positive value that is too large to represent in the type. In
1515 such a case, this function returns `MIN` itself.
1522 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1523 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1524 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT),
1526 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1529 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1530 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1531 #[allow(unused_attributes)]
1532 #[allow_internal_unstable(const_if_match)]
1534 pub const fn wrapping_abs(self) -> Self {
1535 if self.is_negative() {
1544 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1545 wrapping around at the boundary of the type.
1552 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1553 assert_eq!(3i8.wrapping_pow(5), -13);
1554 assert_eq!(3i8.wrapping_pow(6), -39);",
1557 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1558 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1559 #[must_use = "this returns the result of the operation, \
1560 without modifying the original"]
1562 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1563 let mut base = self;
1564 let mut acc: Self = 1;
1568 acc = acc.wrapping_mul(base);
1571 base = base.wrapping_mul(base);
1574 // Deal with the final bit of the exponent separately, since
1575 // squaring the base afterwards is not necessary and may cause a
1576 // needless overflow.
1578 acc = acc.wrapping_mul(base);
1586 concat!("Calculates `self` + `rhs`
1588 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1589 occur. If an overflow would have occurred then the wrapped value is returned.
1597 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1598 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1599 "::MIN, true));", $EndFeature, "
1601 #[stable(feature = "wrapping", since = "1.7.0")]
1602 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1603 #[must_use = "this returns the result of the operation, \
1604 without modifying the original"]
1606 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1607 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1613 concat!("Calculates `self` - `rhs`
1615 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1616 would occur. If an overflow would have occurred then the wrapped value is returned.
1624 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1625 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1626 "::MAX, true));", $EndFeature, "
1628 #[stable(feature = "wrapping", since = "1.7.0")]
1629 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1630 #[must_use = "this returns the result of the operation, \
1631 without modifying the original"]
1633 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1634 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1640 concat!("Calculates the multiplication of `self` and `rhs`.
1642 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1643 would occur. If an overflow would have occurred then the wrapped value is returned.
1650 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1651 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1654 #[stable(feature = "wrapping", since = "1.7.0")]
1655 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1656 #[must_use = "this returns the result of the operation, \
1657 without modifying the original"]
1659 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1660 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1666 concat!("Calculates the divisor when `self` is divided by `rhs`.
1668 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1669 occur. If an overflow would occur then self is returned.
1673 This function will panic if `rhs` is 0.
1681 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1682 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1687 #[stable(feature = "wrapping", since = "1.7.0")]
1688 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1689 #[must_use = "this returns the result of the operation, \
1690 without modifying the original"]
1691 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1692 if self == Self::min_value() && rhs == -1 {
1701 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1703 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1704 occur. If an overflow would occur then `self` is returned.
1708 This function will panic if `rhs` is 0.
1715 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1716 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1720 #[stable(feature = "euclidean_division", since = "1.38.0")]
1721 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1722 #[must_use = "this returns the result of the operation, \
1723 without modifying the original"]
1724 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1725 if self == Self::min_value() && rhs == -1 {
1728 (self.div_euclid(rhs), false)
1734 concat!("Calculates the remainder when `self` is divided by `rhs`.
1736 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1737 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1741 This function will panic if `rhs` is 0.
1749 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1750 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1754 #[stable(feature = "wrapping", since = "1.7.0")]
1755 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1756 #[must_use = "this returns the result of the operation, \
1757 without modifying the original"]
1758 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1759 if self == Self::min_value() && rhs == -1 {
1769 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1771 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1772 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1776 This function will panic if `rhs` is 0.
1783 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1784 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1786 #[stable(feature = "euclidean_division", since = "1.38.0")]
1787 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1788 #[must_use = "this returns the result of the operation, \
1789 without modifying the original"]
1791 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1792 if self == Self::min_value() && rhs == -1 {
1795 (self.rem_euclid(rhs), false)
1802 concat!("Negates self, overflowing if this is equal to the minimum value.
1804 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1805 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1806 minimum value will be returned again and `true` will be returned for an overflow happening.
1813 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1814 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1815 "::MIN, true));", $EndFeature, "
1818 #[stable(feature = "wrapping", since = "1.7.0")]
1819 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1820 #[allow(unused_attributes)]
1821 #[allow_internal_unstable(const_if_match)]
1822 pub const fn overflowing_neg(self) -> (Self, bool) {
1823 if self == Self::min_value() {
1824 (Self::min_value(), true)
1832 concat!("Shifts self left by `rhs` bits.
1834 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1835 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1836 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1843 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1844 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1847 #[stable(feature = "wrapping", since = "1.7.0")]
1848 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1849 #[must_use = "this returns the result of the operation, \
1850 without modifying the original"]
1852 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1853 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1858 concat!("Shifts self right by `rhs` bits.
1860 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1861 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1862 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1869 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1870 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1873 #[stable(feature = "wrapping", since = "1.7.0")]
1874 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1875 #[must_use = "this returns the result of the operation, \
1876 without modifying the original"]
1878 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1879 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1884 concat!("Computes the absolute value of `self`.
1886 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1887 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1888 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1889 for an overflow happening.
1896 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1897 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1898 assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT),
1902 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1903 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1905 pub const fn overflowing_abs(self) -> (Self, bool) {
1906 (self.wrapping_abs(), self == Self::min_value())
1911 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1913 Returns a tuple of the exponentiation along with a bool indicating
1914 whether an overflow happened.
1921 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1922 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1925 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1926 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1927 #[must_use = "this returns the result of the operation, \
1928 without modifying the original"]
1930 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1931 let mut base = self;
1932 let mut acc: Self = 1;
1933 let mut overflown = false;
1934 // Scratch space for storing results of overflowing_mul.
1939 r = acc.overflowing_mul(base);
1944 r = base.overflowing_mul(base);
1949 // Deal with the final bit of the exponent separately, since
1950 // squaring the base afterwards is not necessary and may cause a
1951 // needless overflow.
1953 r = acc.overflowing_mul(base);
1963 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1970 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1972 assert_eq!(x.pow(5), 32);",
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1977 #[must_use = "this returns the result of the operation, \
1978 without modifying the original"]
1980 #[rustc_inherit_overflow_checks]
1981 pub const fn pow(self, mut exp: u32) -> Self {
1982 let mut base = self;
1993 // Deal with the final bit of the exponent separately, since
1994 // squaring the base afterwards is not necessary and may cause a
1995 // needless overflow.
2005 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
2007 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
2008 with `0 <= self.rem_euclid(rhs) < rhs`.
2010 In other words, the result is `self / rhs` rounded to the integer `n`
2011 such that `self >= n * rhs`.
2012 If `self > 0`, this is equal to round towards zero (the default in Rust);
2013 if `self < 0`, this is equal to round towards +/- infinity.
2017 This function will panic if `rhs` is 0 or the division results in overflow.
2024 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2027 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
2028 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
2029 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
2030 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
2032 #[stable(feature = "euclidean_division", since = "1.38.0")]
2033 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2034 #[must_use = "this returns the result of the operation, \
2035 without modifying the original"]
2037 #[rustc_inherit_overflow_checks]
2038 pub const fn div_euclid(self, rhs: Self) -> Self {
2041 return if rhs > 0 { q - 1 } else { q + 1 }
2049 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
2051 This is done as if by the Euclidean division algorithm -- given
2052 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
2053 `0 <= r < abs(rhs)`.
2057 This function will panic if `rhs` is 0 or the division results in overflow.
2064 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2067 assert_eq!(a.rem_euclid(b), 3);
2068 assert_eq!((-a).rem_euclid(b), 1);
2069 assert_eq!(a.rem_euclid(-b), 3);
2070 assert_eq!((-a).rem_euclid(-b), 1);
2072 #[stable(feature = "euclidean_division", since = "1.38.0")]
2073 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2074 #[must_use = "this returns the result of the operation, \
2075 without modifying the original"]
2077 #[rustc_inherit_overflow_checks]
2078 pub const fn rem_euclid(self, rhs: Self) -> Self {
2093 concat!("Computes the absolute value of `self`.
2097 The absolute value of `", stringify!($SelfT), "::MIN` cannot be represented as an
2098 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
2099 code in debug mode will trigger a panic on this case and optimized code will return `",
2100 stringify!($SelfT), "::MIN` without a panic.
2107 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
2108 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
2111 #[stable(feature = "rust1", since = "1.0.0")]
2112 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2113 #[allow(unused_attributes)]
2114 #[allow_internal_unstable(const_if_match)]
2116 #[rustc_inherit_overflow_checks]
2117 pub const fn abs(self) -> Self {
2118 // Note that the #[inline] above means that the overflow
2119 // semantics of the subtraction depend on the crate we're being
2121 if self.is_negative() {
2130 concat!("Returns a number representing sign of `self`.
2132 - `0` if the number is zero
2133 - `1` if the number is positive
2134 - `-1` if the number is negative
2141 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
2142 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
2143 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 #[rustc_const_unstable(feature = "const_int_sign", issue = "53718")]
2149 pub const fn signum(self) -> Self {
2159 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2167 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2168 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2171 #[stable(feature = "rust1", since = "1.0.0")]
2172 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2174 pub const fn is_positive(self) -> bool { self > 0 }
2178 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2186 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2187 assert!(!10", stringify!($SelfT), ".is_negative());",
2190 #[stable(feature = "rust1", since = "1.0.0")]
2191 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2193 pub const fn is_negative(self) -> bool { self < 0 }
2197 concat!("Return the memory representation of this integer as a byte array in
2198 big-endian (network) byte order.
2205 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2206 assert_eq!(bytes, ", $be_bytes, ");
2208 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2209 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2211 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2212 self.to_be().to_ne_bytes()
2217 concat!("Return the memory representation of this integer as a byte array in
2218 little-endian byte order.
2225 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2226 assert_eq!(bytes, ", $le_bytes, ");
2228 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2229 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2231 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2232 self.to_le().to_ne_bytes()
2238 Return the memory representation of this integer as a byte array in
2241 As the target platform's native endianness is used, portable code
2242 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2247 [`to_be_bytes`]: #method.to_be_bytes
2248 [`to_le_bytes`]: #method.to_le_bytes
2253 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2256 if cfg!(target_endian = \"big\") {
2263 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2264 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2266 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2267 // SAFETY: integers are plain old datatypes so we can always transmute them to
2269 unsafe { mem::transmute(self) }
2274 concat!("Create an integer value from its representation as a byte array in
2282 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2283 assert_eq!(value, ", $swap_op, ");
2286 When starting from a slice rather than an array, fallible conversion APIs can be used:
2289 use std::convert::TryInto;
2291 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2292 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2294 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2297 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2298 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2300 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2301 Self::from_be(Self::from_ne_bytes(bytes))
2307 Create an integer value from its representation as a byte array in
2315 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2316 assert_eq!(value, ", $swap_op, ");
2319 When starting from a slice rather than an array, fallible conversion APIs can be used:
2322 use std::convert::TryInto;
2324 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2325 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2327 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2330 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2331 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2333 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2334 Self::from_le(Self::from_ne_bytes(bytes))
2339 concat!("Create an integer value from its memory representation as a byte
2340 array in native endianness.
2342 As the target platform's native endianness is used, portable code
2343 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2344 appropriate instead.
2346 [`from_be_bytes`]: #method.from_be_bytes
2347 [`from_le_bytes`]: #method.from_le_bytes
2354 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2359 assert_eq!(value, ", $swap_op, ");
2362 When starting from a slice rather than an array, fallible conversion APIs can be used:
2365 use std::convert::TryInto;
2367 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2368 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2370 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2373 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2374 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
2376 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2377 // SAFETY: integers are plain old datatypes so we can always transmute to them
2378 unsafe { mem::transmute(bytes) }
2383 concat!("**This method is soft-deprecated.**
2385 Although using it won’t cause compilation warning,
2386 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
2388 Returns the smallest value that can be represented by this integer type."),
2389 #[stable(feature = "rust1", since = "1.0.0")]
2392 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2393 pub const fn min_value() -> Self {
2399 concat!("**This method is soft-deprecated.**
2401 Although using it won’t cause compilation warning,
2402 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
2404 Returns the largest value that can be represented by this integer type."),
2405 #[stable(feature = "rust1", since = "1.0.0")]
2408 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2409 pub const fn max_value() -> Self {
2418 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2419 "[0x12]", "[0x12]", "", "" }
2424 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2425 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2430 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2431 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2432 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2437 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2438 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2439 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2440 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2445 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2446 170141183460469231731687303715884105727, "", "", 16,
2447 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2448 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2449 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2450 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2451 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2452 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2455 #[cfg(target_pointer_width = "16")]
2458 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2459 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2460 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2463 #[cfg(target_pointer_width = "32")]
2466 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2467 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2468 "[0x12, 0x34, 0x56, 0x78]",
2469 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2472 #[cfg(target_pointer_width = "64")]
2475 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2476 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2477 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2478 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2479 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2482 macro_rules! uint_impl {
2483 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2484 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2485 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2486 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2488 concat!("The smallest value that can be represented by this integer type.
2495 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, 0);", $EndFeature, "
2497 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2498 pub const MIN: Self = 0;
2502 concat!("The largest value that can be represented by this integer type.
2509 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");",
2512 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2513 pub const MAX: Self = !0;
2517 concat!("Converts a string slice in a given base to an integer.
2519 The string is expected to be an optional `+` sign
2521 Leading and trailing whitespace represent an error.
2522 Digits are a subset of these characters, depending on `radix`:
2530 This function panics if `radix` is not in the range from 2 to 36.
2537 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2540 #[stable(feature = "rust1", since = "1.0.0")]
2541 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2542 from_str_radix(src, radix)
2547 concat!("Returns the number of ones in the binary representation of `self`.
2554 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2556 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2558 #[stable(feature = "rust1", since = "1.0.0")]
2559 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2561 pub const fn count_ones(self) -> u32 {
2562 intrinsics::ctpop(self as $ActualT) as u32
2567 concat!("Returns the number of zeros in the binary representation of `self`.
2574 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);", $EndFeature, "
2576 #[stable(feature = "rust1", since = "1.0.0")]
2577 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2579 pub const fn count_zeros(self) -> u32 {
2580 (!self).count_ones()
2585 concat!("Returns the number of leading zeros in the binary representation of `self`.
2592 ", $Feature, "let n = ", stringify!($SelfT), "::MAX >> 2;
2594 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2596 #[stable(feature = "rust1", since = "1.0.0")]
2597 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2599 pub const fn leading_zeros(self) -> u32 {
2600 intrinsics::ctlz(self as $ActualT) as u32
2605 concat!("Returns the number of trailing zeros in the binary representation
2613 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2615 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2617 #[stable(feature = "rust1", since = "1.0.0")]
2618 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2620 pub const fn trailing_zeros(self) -> u32 {
2621 intrinsics::cttz(self) as u32
2626 concat!("Returns the number of leading ones in the binary representation of `self`.
2633 ", $Feature, "#![feature(leading_trailing_ones)]
2634 let n = !(", stringify!($SelfT), "::MAX >> 2);
2636 assert_eq!(n.leading_ones(), 2);", $EndFeature, "
2638 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2640 pub const fn leading_ones(self) -> u32 {
2641 (!self).leading_zeros()
2646 concat!("Returns the number of trailing ones in the binary representation
2654 ", $Feature, "#![feature(leading_trailing_ones)]
2655 let n = 0b1010111", stringify!($SelfT), ";
2657 assert_eq!(n.trailing_ones(), 3);", $EndFeature, "
2659 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2661 pub const fn trailing_ones(self) -> u32 {
2662 (!self).trailing_zeros()
2667 concat!("Shifts the bits to the left by a specified amount, `n`,
2668 wrapping the truncated bits to the end of the resulting integer.
2670 Please note this isn't the same operation as the `<<` shifting operator!
2677 let n = ", $rot_op, stringify!($SelfT), ";
2678 let m = ", $rot_result, ";
2680 assert_eq!(n.rotate_left(", $rot, "), m);
2682 #[stable(feature = "rust1", since = "1.0.0")]
2683 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2684 #[must_use = "this returns the result of the operation, \
2685 without modifying the original"]
2687 pub const fn rotate_left(self, n: u32) -> Self {
2688 intrinsics::rotate_left(self, n as $SelfT)
2693 concat!("Shifts the bits to the right by a specified amount, `n`,
2694 wrapping the truncated bits to the beginning of the resulting
2697 Please note this isn't the same operation as the `>>` shifting operator!
2704 let n = ", $rot_result, stringify!($SelfT), ";
2705 let m = ", $rot_op, ";
2707 assert_eq!(n.rotate_right(", $rot, "), m);
2709 #[stable(feature = "rust1", since = "1.0.0")]
2710 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2711 #[must_use = "this returns the result of the operation, \
2712 without modifying the original"]
2714 pub const fn rotate_right(self, n: u32) -> Self {
2715 intrinsics::rotate_right(self, n as $SelfT)
2721 Reverses the byte order of the integer.
2728 let n = ", $swap_op, stringify!($SelfT), ";
2729 let m = n.swap_bytes();
2731 assert_eq!(m, ", $swapped, ");
2733 #[stable(feature = "rust1", since = "1.0.0")]
2734 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2736 pub const fn swap_bytes(self) -> Self {
2737 intrinsics::bswap(self as $ActualT) as Self
2742 concat!("Reverses the bit pattern of the integer.
2749 let n = ", $swap_op, stringify!($SelfT), ";
2750 let m = n.reverse_bits();
2752 assert_eq!(m, ", $reversed, ");
2754 #[stable(feature = "reverse_bits", since = "1.37.0")]
2755 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2758 pub const fn reverse_bits(self) -> Self {
2759 intrinsics::bitreverse(self as $ActualT) as Self
2764 concat!("Converts an integer from big endian to the target's endianness.
2766 On big endian this is a no-op. On little endian the bytes are
2774 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2776 if cfg!(target_endian = \"big\") {
2777 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2779 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2782 #[stable(feature = "rust1", since = "1.0.0")]
2783 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2785 pub const fn from_be(x: Self) -> Self {
2786 #[cfg(target_endian = "big")]
2790 #[cfg(not(target_endian = "big"))]
2798 concat!("Converts an integer from little endian to the target's endianness.
2800 On little endian this is a no-op. On big endian the bytes are
2808 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2810 if cfg!(target_endian = \"little\") {
2811 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2813 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2816 #[stable(feature = "rust1", since = "1.0.0")]
2817 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2819 pub const fn from_le(x: Self) -> Self {
2820 #[cfg(target_endian = "little")]
2824 #[cfg(not(target_endian = "little"))]
2832 concat!("Converts `self` to big endian from the target's endianness.
2834 On big endian this is a no-op. On little endian the bytes are
2842 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2844 if cfg!(target_endian = \"big\") {
2845 assert_eq!(n.to_be(), n)
2847 assert_eq!(n.to_be(), n.swap_bytes())
2850 #[stable(feature = "rust1", since = "1.0.0")]
2851 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2853 pub const fn to_be(self) -> Self { // or not to be?
2854 #[cfg(target_endian = "big")]
2858 #[cfg(not(target_endian = "big"))]
2866 concat!("Converts `self` to little endian from the target's endianness.
2868 On little endian this is a no-op. On big endian the bytes are
2876 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2878 if cfg!(target_endian = \"little\") {
2879 assert_eq!(n.to_le(), n)
2881 assert_eq!(n.to_le(), n.swap_bytes())
2884 #[stable(feature = "rust1", since = "1.0.0")]
2885 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2887 pub const fn to_le(self) -> Self {
2888 #[cfg(target_endian = "little")]
2892 #[cfg(not(target_endian = "little"))]
2900 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2901 if overflow occurred.
2908 ", $Feature, "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
2909 "Some(", stringify!($SelfT), "::MAX - 1));
2910 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);", $EndFeature, "
2912 #[stable(feature = "rust1", since = "1.0.0")]
2913 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2914 #[must_use = "this returns the result of the operation, \
2915 without modifying the original"]
2917 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
2918 let (a, b) = self.overflowing_add(rhs);
2919 if b {None} else {Some(a)}
2924 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2925 `None` if overflow occurred.
2932 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2933 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2935 #[stable(feature = "rust1", since = "1.0.0")]
2936 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2937 #[must_use = "this returns the result of the operation, \
2938 without modifying the original"]
2940 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
2941 let (a, b) = self.overflowing_sub(rhs);
2942 if b {None} else {Some(a)}
2947 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2948 `None` if overflow occurred.
2955 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2956 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);", $EndFeature, "
2958 #[stable(feature = "rust1", since = "1.0.0")]
2959 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2960 #[must_use = "this returns the result of the operation, \
2961 without modifying the original"]
2963 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
2964 let (a, b) = self.overflowing_mul(rhs);
2965 if b {None} else {Some(a)}
2970 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2978 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2979 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2981 #[stable(feature = "rust1", since = "1.0.0")]
2982 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2983 #[must_use = "this returns the result of the operation, \
2984 without modifying the original"]
2986 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
2989 // SAFETY: div by zero has been checked above and unsigned types have no other
2990 // failure modes for division
2991 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2997 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
3005 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
3006 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
3008 #[stable(feature = "euclidean_division", since = "1.38.0")]
3009 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3010 #[must_use = "this returns the result of the operation, \
3011 without modifying the original"]
3013 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
3017 Some(self.div_euclid(rhs))
3024 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
3032 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
3033 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
3035 #[stable(feature = "wrapping", since = "1.7.0")]
3036 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3037 #[must_use = "this returns the result of the operation, \
3038 without modifying the original"]
3040 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
3044 // SAFETY: div by zero has been checked above and unsigned types have no other
3045 // failure modes for division
3046 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3052 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3060 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3061 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3063 #[stable(feature = "euclidean_division", since = "1.38.0")]
3064 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3065 #[must_use = "this returns the result of the operation, \
3066 without modifying the original"]
3068 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3072 Some(self.rem_euclid(rhs))
3078 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3081 Note that negating any positive integer will overflow.
3088 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3089 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3091 #[stable(feature = "wrapping", since = "1.7.0")]
3092 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3094 pub const fn checked_neg(self) -> Option<Self> {
3095 let (a, b) = self.overflowing_neg();
3096 if b {None} else {Some(a)}
3101 concat!("Checked shift left. Computes `self << rhs`, returning `None`
3102 if `rhs` is larger than or equal to the number of bits in `self`.
3109 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3110 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3112 #[stable(feature = "wrapping", since = "1.7.0")]
3113 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3114 #[must_use = "this returns the result of the operation, \
3115 without modifying the original"]
3117 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
3118 let (a, b) = self.overflowing_shl(rhs);
3119 if b {None} else {Some(a)}
3124 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3125 if `rhs` is larger than or equal to the number of bits in `self`.
3132 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3133 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3135 #[stable(feature = "wrapping", since = "1.7.0")]
3136 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3137 #[must_use = "this returns the result of the operation, \
3138 without modifying the original"]
3140 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
3141 let (a, b) = self.overflowing_shr(rhs);
3142 if b {None} else {Some(a)}
3147 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3155 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3156 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);", $EndFeature, "
3158 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3159 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3160 #[must_use = "this returns the result of the operation, \
3161 without modifying the original"]
3163 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
3164 let mut base = self;
3165 let mut acc: Self = 1;
3169 acc = try_opt!(acc.checked_mul(base));
3172 base = try_opt!(base.checked_mul(base));
3175 // Deal with the final bit of the exponent separately, since
3176 // squaring the base afterwards is not necessary and may cause a
3177 // needless overflow.
3179 acc = try_opt!(acc.checked_mul(base));
3187 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3188 the numeric bounds instead of overflowing.
3195 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3196 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
3199 #[stable(feature = "rust1", since = "1.0.0")]
3200 #[must_use = "this returns the result of the operation, \
3201 without modifying the original"]
3202 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3204 pub const fn saturating_add(self, rhs: Self) -> Self {
3205 intrinsics::saturating_add(self, rhs)
3210 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3211 at the numeric bounds instead of overflowing.
3218 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3219 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3221 #[stable(feature = "rust1", since = "1.0.0")]
3222 #[must_use = "this returns the result of the operation, \
3223 without modifying the original"]
3224 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3226 pub const fn saturating_sub(self, rhs: Self) -> Self {
3227 intrinsics::saturating_sub(self, rhs)
3232 concat!("Saturating integer multiplication. Computes `self * rhs`,
3233 saturating at the numeric bounds instead of overflowing.
3241 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3242 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3243 "::MAX);", $EndFeature, "
3245 #[stable(feature = "wrapping", since = "1.7.0")]
3246 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3247 #[must_use = "this returns the result of the operation, \
3248 without modifying the original"]
3250 pub const fn saturating_mul(self, rhs: Self) -> Self {
3251 match self.checked_mul(rhs) {
3253 None => Self::max_value(),
3259 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3260 saturating at the numeric bounds instead of overflowing.
3268 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3269 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3272 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3273 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3274 #[must_use = "this returns the result of the operation, \
3275 without modifying the original"]
3277 pub const fn saturating_pow(self, exp: u32) -> Self {
3278 match self.checked_pow(exp) {
3280 None => Self::max_value(),
3286 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3287 wrapping around at the boundary of the type.
3294 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3295 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);",
3298 #[stable(feature = "rust1", since = "1.0.0")]
3299 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3300 #[must_use = "this returns the result of the operation, \
3301 without modifying the original"]
3303 pub const fn wrapping_add(self, rhs: Self) -> Self {
3304 intrinsics::wrapping_add(self, rhs)
3309 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3310 wrapping around at the boundary of the type.
3317 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3318 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);",
3321 #[stable(feature = "rust1", since = "1.0.0")]
3322 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3323 #[must_use = "this returns the result of the operation, \
3324 without modifying the original"]
3326 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3327 intrinsics::wrapping_sub(self, rhs)
3331 /// Wrapping (modular) multiplication. Computes `self *
3332 /// rhs`, wrapping around at the boundary of the type.
3338 /// Please note that this example is shared between integer types.
3339 /// Which explains why `u8` is used here.
3342 /// assert_eq!(10u8.wrapping_mul(12), 120);
3343 /// assert_eq!(25u8.wrapping_mul(12), 44);
3345 #[stable(feature = "rust1", since = "1.0.0")]
3346 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3347 #[must_use = "this returns the result of the operation, \
3348 without modifying the original"]
3350 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3351 intrinsics::wrapping_mul(self, rhs)
3355 concat!("Wrapping (modular) division. Computes `self / rhs`.
3356 Wrapped division on unsigned types is just normal division.
3357 There's no way wrapping could ever happen.
3358 This function exists, so that all operations
3359 are accounted for in the wrapping operations.
3366 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3368 #[stable(feature = "num_wrapping", since = "1.2.0")]
3369 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3370 #[must_use = "this returns the result of the operation, \
3371 without modifying the original"]
3373 pub const fn wrapping_div(self, rhs: Self) -> Self {
3379 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3380 Wrapped division on unsigned types is just normal division.
3381 There's no way wrapping could ever happen.
3382 This function exists, so that all operations
3383 are accounted for in the wrapping operations.
3384 Since, for the positive integers, all common
3385 definitions of division are equal, this
3386 is exactly equal to `self.wrapping_div(rhs)`.
3393 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3395 #[stable(feature = "euclidean_division", since = "1.38.0")]
3396 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3397 #[must_use = "this returns the result of the operation, \
3398 without modifying the original"]
3400 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
3406 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3407 Wrapped remainder calculation on unsigned types is
3408 just the regular remainder calculation.
3409 There's no way wrapping could ever happen.
3410 This function exists, so that all operations
3411 are accounted for in the wrapping operations.
3418 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3420 #[stable(feature = "num_wrapping", since = "1.2.0")]
3421 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3422 #[must_use = "this returns the result of the operation, \
3423 without modifying the original"]
3425 pub const fn wrapping_rem(self, rhs: Self) -> Self {
3431 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3432 Wrapped modulo calculation on unsigned types is
3433 just the regular remainder calculation.
3434 There's no way wrapping could ever happen.
3435 This function exists, so that all operations
3436 are accounted for in the wrapping operations.
3437 Since, for the positive integers, all common
3438 definitions of division are equal, this
3439 is exactly equal to `self.wrapping_rem(rhs)`.
3446 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3448 #[stable(feature = "euclidean_division", since = "1.38.0")]
3449 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3450 #[must_use = "this returns the result of the operation, \
3451 without modifying the original"]
3453 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3458 /// Wrapping (modular) negation. Computes `-self`,
3459 /// wrapping around at the boundary of the type.
3461 /// Since unsigned types do not have negative equivalents
3462 /// all applications of this function will wrap (except for `-0`).
3463 /// For values smaller than the corresponding signed type's maximum
3464 /// the result is the same as casting the corresponding signed value.
3465 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3466 /// `MAX` is the corresponding signed type's maximum.
3472 /// Please note that this example is shared between integer types.
3473 /// Which explains why `i8` is used here.
3476 /// assert_eq!(100i8.wrapping_neg(), -100);
3477 /// assert_eq!((-128i8).wrapping_neg(), -128);
3479 #[stable(feature = "num_wrapping", since = "1.2.0")]
3480 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3482 pub const fn wrapping_neg(self) -> Self {
3483 self.overflowing_neg().0
3487 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3488 where `mask` removes any high-order bits of `rhs` that
3489 would cause the shift to exceed the bitwidth of the type.
3491 Note that this is *not* the same as a rotate-left; the
3492 RHS of a wrapping shift-left is restricted to the range
3493 of the type, rather than the bits shifted out of the LHS
3494 being returned to the other end. The primitive integer
3495 types all implement a `rotate_left` function, which may
3496 be what you want instead.
3503 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3504 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3506 #[stable(feature = "num_wrapping", since = "1.2.0")]
3507 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3508 #[must_use = "this returns the result of the operation, \
3509 without modifying the original"]
3511 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3512 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3515 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3521 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3522 where `mask` removes any high-order bits of `rhs` that
3523 would cause the shift to exceed the bitwidth of the type.
3525 Note that this is *not* the same as a rotate-right; the
3526 RHS of a wrapping shift-right is restricted to the range
3527 of the type, rather than the bits shifted out of the LHS
3528 being returned to the other end. The primitive integer
3529 types all implement a `rotate_right` function, which may
3530 be what you want instead.
3537 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3538 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3540 #[stable(feature = "num_wrapping", since = "1.2.0")]
3541 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3542 #[must_use = "this returns the result of the operation, \
3543 without modifying the original"]
3545 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3546 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3549 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3555 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3556 wrapping around at the boundary of the type.
3563 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3564 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3566 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3567 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3568 #[must_use = "this returns the result of the operation, \
3569 without modifying the original"]
3571 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
3572 let mut base = self;
3573 let mut acc: Self = 1;
3577 acc = acc.wrapping_mul(base);
3580 base = base.wrapping_mul(base);
3583 // Deal with the final bit of the exponent separately, since
3584 // squaring the base afterwards is not necessary and may cause a
3585 // needless overflow.
3587 acc = acc.wrapping_mul(base);
3595 concat!("Calculates `self` + `rhs`
3597 Returns a tuple of the addition along with a boolean indicating
3598 whether an arithmetic overflow would occur. If an overflow would
3599 have occurred then the wrapped value is returned.
3607 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3608 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3610 #[stable(feature = "wrapping", since = "1.7.0")]
3611 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3612 #[must_use = "this returns the result of the operation, \
3613 without modifying the original"]
3615 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3616 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3622 concat!("Calculates `self` - `rhs`
3624 Returns a tuple of the subtraction along with a boolean indicating
3625 whether an arithmetic overflow would occur. If an overflow would
3626 have occurred then the wrapped value is returned.
3634 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3635 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3638 #[stable(feature = "wrapping", since = "1.7.0")]
3639 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3640 #[must_use = "this returns the result of the operation, \
3641 without modifying the original"]
3643 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3644 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3649 /// Calculates the multiplication of `self` and `rhs`.
3651 /// Returns a tuple of the multiplication along with a boolean
3652 /// indicating whether an arithmetic overflow would occur. If an
3653 /// overflow would have occurred then the wrapped value is returned.
3659 /// Please note that this example is shared between integer types.
3660 /// Which explains why `u32` is used here.
3663 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3664 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3666 #[stable(feature = "wrapping", since = "1.7.0")]
3667 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3668 #[must_use = "this returns the result of the operation, \
3669 without modifying the original"]
3671 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3672 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3677 concat!("Calculates the divisor when `self` is divided by `rhs`.
3679 Returns a tuple of the divisor along with a boolean indicating
3680 whether an arithmetic overflow would occur. Note that for unsigned
3681 integers overflow never occurs, so the second value is always
3686 This function will panic if `rhs` is 0.
3693 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3696 #[stable(feature = "wrapping", since = "1.7.0")]
3697 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3698 #[must_use = "this returns the result of the operation, \
3699 without modifying the original"]
3700 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3706 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3708 Returns a tuple of the divisor along with a boolean indicating
3709 whether an arithmetic overflow would occur. Note that for unsigned
3710 integers overflow never occurs, so the second value is always
3712 Since, for the positive integers, all common
3713 definitions of division are equal, this
3714 is exactly equal to `self.overflowing_div(rhs)`.
3718 This function will panic if `rhs` is 0.
3725 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3728 #[stable(feature = "euclidean_division", since = "1.38.0")]
3729 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3730 #[must_use = "this returns the result of the operation, \
3731 without modifying the original"]
3732 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3738 concat!("Calculates the remainder when `self` is divided by `rhs`.
3740 Returns a tuple of the remainder after dividing along with a boolean
3741 indicating whether an arithmetic overflow would occur. Note that for
3742 unsigned integers overflow never occurs, so the second value is
3747 This function will panic if `rhs` is 0.
3754 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3757 #[stable(feature = "wrapping", since = "1.7.0")]
3758 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3759 #[must_use = "this returns the result of the operation, \
3760 without modifying the original"]
3761 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3767 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3769 Returns a tuple of the modulo after dividing along with a boolean
3770 indicating whether an arithmetic overflow would occur. Note that for
3771 unsigned integers overflow never occurs, so the second value is
3773 Since, for the positive integers, all common
3774 definitions of division are equal, this operation
3775 is exactly equal to `self.overflowing_rem(rhs)`.
3779 This function will panic if `rhs` is 0.
3786 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3789 #[stable(feature = "euclidean_division", since = "1.38.0")]
3790 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3791 #[must_use = "this returns the result of the operation, \
3792 without modifying the original"]
3793 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3799 concat!("Negates self in an overflowing fashion.
3801 Returns `!self + 1` using wrapping operations to return the value
3802 that represents the negation of this unsigned value. Note that for
3803 positive unsigned values overflow always occurs, but negating 0 does
3811 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3812 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3813 ", true));", $EndFeature, "
3816 #[stable(feature = "wrapping", since = "1.7.0")]
3817 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3818 pub const fn overflowing_neg(self) -> (Self, bool) {
3819 ((!self).wrapping_add(1), self != 0)
3824 concat!("Shifts self left by `rhs` bits.
3826 Returns a tuple of the shifted version of self along with a boolean
3827 indicating whether the shift value was larger than or equal to the
3828 number of bits. If the shift value is too large, then value is
3829 masked (N-1) where N is the number of bits, and this value is then
3830 used to perform the shift.
3837 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3838 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3840 #[stable(feature = "wrapping", since = "1.7.0")]
3841 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3842 #[must_use = "this returns the result of the operation, \
3843 without modifying the original"]
3845 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3846 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3851 concat!("Shifts self right by `rhs` bits.
3853 Returns a tuple of the shifted version of self along with a boolean
3854 indicating whether the shift value was larger than or equal to the
3855 number of bits. If the shift value is too large, then value is
3856 masked (N-1) where N is the number of bits, and this value is then
3857 used to perform the shift.
3864 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3865 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3867 #[stable(feature = "wrapping", since = "1.7.0")]
3868 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3869 #[must_use = "this returns the result of the operation, \
3870 without modifying the original"]
3872 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3873 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3878 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3880 Returns a tuple of the exponentiation along with a bool indicating
3881 whether an overflow happened.
3888 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3889 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3891 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3892 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3893 #[must_use = "this returns the result of the operation, \
3894 without modifying the original"]
3896 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3897 let mut base = self;
3898 let mut acc: Self = 1;
3899 let mut overflown = false;
3900 // Scratch space for storing results of overflowing_mul.
3905 r = acc.overflowing_mul(base);
3910 r = base.overflowing_mul(base);
3915 // Deal with the final bit of the exponent separately, since
3916 // squaring the base afterwards is not necessary and may cause a
3917 // needless overflow.
3919 r = acc.overflowing_mul(base);
3929 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3936 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3938 #[stable(feature = "rust1", since = "1.0.0")]
3939 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3940 #[must_use = "this returns the result of the operation, \
3941 without modifying the original"]
3943 #[rustc_inherit_overflow_checks]
3944 pub const fn pow(self, mut exp: u32) -> Self {
3945 let mut base = self;
3956 // Deal with the final bit of the exponent separately, since
3957 // squaring the base afterwards is not necessary and may cause a
3958 // needless overflow.
3968 concat!("Performs Euclidean division.
3970 Since, for the positive integers, all common
3971 definitions of division are equal, this
3972 is exactly equal to `self / rhs`.
3976 This function will panic if `rhs` is 0.
3983 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
3985 #[stable(feature = "euclidean_division", since = "1.38.0")]
3986 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3987 #[must_use = "this returns the result of the operation, \
3988 without modifying the original"]
3990 #[rustc_inherit_overflow_checks]
3991 pub const fn div_euclid(self, rhs: Self) -> Self {
3998 concat!("Calculates the least remainder of `self (mod rhs)`.
4000 Since, for the positive integers, all common
4001 definitions of division are equal, this
4002 is exactly equal to `self % rhs`.
4006 This function will panic if `rhs` is 0.
4013 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
4015 #[stable(feature = "euclidean_division", since = "1.38.0")]
4016 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
4017 #[must_use = "this returns the result of the operation, \
4018 without modifying the original"]
4020 #[rustc_inherit_overflow_checks]
4021 pub const fn rem_euclid(self, rhs: Self) -> Self {
4027 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
4034 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
4035 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
4037 #[stable(feature = "rust1", since = "1.0.0")]
4038 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
4040 pub const fn is_power_of_two(self) -> bool {
4041 self.count_ones() == 1
4045 // Returns one less than next power of two.
4046 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
4048 // 8u8.one_less_than_next_power_of_two() == 7
4049 // 6u8.one_less_than_next_power_of_two() == 7
4051 // This method cannot overflow, as in the `next_power_of_two`
4052 // overflow cases it instead ends up returning the maximum value
4053 // of the type, and can return 0 for 0.
4055 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4056 const fn one_less_than_next_power_of_two(self) -> Self {
4057 if self <= 1 { return 0; }
4060 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4061 // That means the shift is always in-bounds, and some processors
4062 // (such as intel pre-haswell) have more efficient ctlz
4063 // intrinsics when the argument is non-zero.
4064 let z = unsafe { intrinsics::ctlz_nonzero(p) };
4065 <$SelfT>::max_value() >> z
4069 concat!("Returns the smallest power of two greater than or equal to `self`.
4071 When return value overflows (i.e., `self > (1 << (N-1))` for type
4072 `uN`), it panics in debug mode and return value is wrapped to 0 in
4073 release mode (the only situation in which method can return 0).
4080 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4081 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4083 #[stable(feature = "rust1", since = "1.0.0")]
4084 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4086 #[rustc_inherit_overflow_checks]
4087 pub const fn next_power_of_two(self) -> Self {
4088 self.one_less_than_next_power_of_two() + 1
4093 concat!("Returns the smallest power of two greater than or equal to `n`. If
4094 the next power of two is greater than the type's maximum value,
4095 `None` is returned, otherwise the power of two is wrapped in `Some`.
4102 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4103 ".checked_next_power_of_two(), Some(2));
4104 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4105 assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);",
4109 #[stable(feature = "rust1", since = "1.0.0")]
4110 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4111 pub const fn checked_next_power_of_two(self) -> Option<Self> {
4112 self.one_less_than_next_power_of_two().checked_add(1)
4117 concat!("Returns the smallest power of two greater than or equal to `n`. If
4118 the next power of two is greater than the type's maximum value,
4119 the return value is wrapped to `0`.
4126 #![feature(wrapping_next_power_of_two)]
4128 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4129 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4130 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);",
4133 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4134 reason = "needs decision on wrapping behaviour")]
4135 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4136 pub const fn wrapping_next_power_of_two(self) -> Self {
4137 self.one_less_than_next_power_of_two().wrapping_add(1)
4142 concat!("Return the memory representation of this integer as a byte array in
4143 big-endian (network) byte order.
4150 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4151 assert_eq!(bytes, ", $be_bytes, ");
4153 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4154 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4156 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4157 self.to_be().to_ne_bytes()
4162 concat!("Return the memory representation of this integer as a byte array in
4163 little-endian byte order.
4170 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4171 assert_eq!(bytes, ", $le_bytes, ");
4173 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4174 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4176 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4177 self.to_le().to_ne_bytes()
4183 Return the memory representation of this integer as a byte array in
4186 As the target platform's native endianness is used, portable code
4187 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4192 [`to_be_bytes`]: #method.to_be_bytes
4193 [`to_le_bytes`]: #method.to_le_bytes
4198 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4201 if cfg!(target_endian = \"big\") {
4208 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4209 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4211 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4212 // SAFETY: integers are plain old datatypes so we can always transmute them to
4214 unsafe { mem::transmute(self) }
4219 concat!("Create an integer value from its representation as a byte array in
4227 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4228 assert_eq!(value, ", $swap_op, ");
4231 When starting from a slice rather than an array, fallible conversion APIs can be used:
4234 use std::convert::TryInto;
4236 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4237 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4239 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4242 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4243 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4245 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4246 Self::from_be(Self::from_ne_bytes(bytes))
4252 Create an integer value from its representation as a byte array in
4260 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4261 assert_eq!(value, ", $swap_op, ");
4264 When starting from a slice rather than an array, fallible conversion APIs can be used:
4267 use std::convert::TryInto;
4269 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4270 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4272 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4275 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4276 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4278 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4279 Self::from_le(Self::from_ne_bytes(bytes))
4284 concat!("Create an integer value from its memory representation as a byte
4285 array in native endianness.
4287 As the target platform's native endianness is used, portable code
4288 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4289 appropriate instead.
4291 [`from_be_bytes`]: #method.from_be_bytes
4292 [`from_le_bytes`]: #method.from_le_bytes
4299 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4304 assert_eq!(value, ", $swap_op, ");
4307 When starting from a slice rather than an array, fallible conversion APIs can be used:
4310 use std::convert::TryInto;
4312 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4313 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4315 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4318 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4319 #[rustc_const_unstable(feature = "const_int_conversion", issue = "53718")]
4321 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4322 // SAFETY: integers are plain old datatypes so we can always transmute to them
4323 unsafe { mem::transmute(bytes) }
4328 concat!("**This method is soft-deprecated.**
4330 Although using it won’t cause compilation warning,
4331 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
4333 Returns the smallest value that can be represented by this integer type."),
4334 #[stable(feature = "rust1", since = "1.0.0")]
4337 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4338 pub const fn min_value() -> Self { Self::MIN }
4342 concat!("**This method is soft-deprecated.**
4344 Although using it won’t cause compilation warning,
4345 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
4347 Returns the largest value that can be represented by this integer type."),
4348 #[stable(feature = "rust1", since = "1.0.0")]
4351 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4352 pub const fn max_value() -> Self { Self::MAX }
4359 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4362 /// Checks if the value is within the ASCII range.
4367 /// let ascii = 97u8;
4368 /// let non_ascii = 150u8;
4370 /// assert!(ascii.is_ascii());
4371 /// assert!(!non_ascii.is_ascii());
4373 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4374 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.43.0")]
4376 pub const fn is_ascii(&self) -> bool {
4380 /// Makes a copy of the value in its ASCII upper case equivalent.
4382 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4383 /// but non-ASCII letters are unchanged.
4385 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4390 /// let lowercase_a = 97u8;
4392 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4395 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4396 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4398 pub fn to_ascii_uppercase(&self) -> u8 {
4399 // Unset the fith bit if this is a lowercase letter
4400 *self & !((self.is_ascii_lowercase() as u8) << 5)
4403 /// Makes a copy of the value in its ASCII lower case equivalent.
4405 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4406 /// but non-ASCII letters are unchanged.
4408 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4413 /// let uppercase_a = 65u8;
4415 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4418 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4419 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4421 pub fn to_ascii_lowercase(&self) -> u8 {
4422 // Set the fith bit if this is an uppercase letter
4423 *self | ((self.is_ascii_uppercase() as u8) << 5)
4426 /// Checks that two values are an ASCII case-insensitive match.
4428 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4433 /// let lowercase_a = 97u8;
4434 /// let uppercase_a = 65u8;
4436 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4438 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4440 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4441 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4444 /// Converts this value to its ASCII upper case equivalent in-place.
4446 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4447 /// but non-ASCII letters are unchanged.
4449 /// To return a new uppercased value without modifying the existing one, use
4450 /// [`to_ascii_uppercase`].
4455 /// let mut byte = b'a';
4457 /// byte.make_ascii_uppercase();
4459 /// assert_eq!(b'A', byte);
4462 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4463 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4465 pub fn make_ascii_uppercase(&mut self) {
4466 *self = self.to_ascii_uppercase();
4469 /// Converts this value to its ASCII lower case equivalent in-place.
4471 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4472 /// but non-ASCII letters are unchanged.
4474 /// To return a new lowercased value without modifying the existing one, use
4475 /// [`to_ascii_lowercase`].
4480 /// let mut byte = b'A';
4482 /// byte.make_ascii_lowercase();
4484 /// assert_eq!(b'a', byte);
4487 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4488 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4490 pub fn make_ascii_lowercase(&mut self) {
4491 *self = self.to_ascii_lowercase();
4494 /// Checks if the value is an ASCII alphabetic character:
4496 /// - U+0041 'A' ..= U+005A 'Z', or
4497 /// - U+0061 'a' ..= U+007A 'z'.
4502 /// let uppercase_a = b'A';
4503 /// let uppercase_g = b'G';
4506 /// let zero = b'0';
4507 /// let percent = b'%';
4508 /// let space = b' ';
4510 /// let esc = 0x1b_u8;
4512 /// assert!(uppercase_a.is_ascii_alphabetic());
4513 /// assert!(uppercase_g.is_ascii_alphabetic());
4514 /// assert!(a.is_ascii_alphabetic());
4515 /// assert!(g.is_ascii_alphabetic());
4516 /// assert!(!zero.is_ascii_alphabetic());
4517 /// assert!(!percent.is_ascii_alphabetic());
4518 /// assert!(!space.is_ascii_alphabetic());
4519 /// assert!(!lf.is_ascii_alphabetic());
4520 /// assert!(!esc.is_ascii_alphabetic());
4522 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4523 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4525 pub const fn is_ascii_alphabetic(&self) -> bool {
4526 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
4529 /// Checks if the value is an ASCII uppercase character:
4530 /// U+0041 'A' ..= U+005A 'Z'.
4535 /// let uppercase_a = b'A';
4536 /// let uppercase_g = b'G';
4539 /// let zero = b'0';
4540 /// let percent = b'%';
4541 /// let space = b' ';
4543 /// let esc = 0x1b_u8;
4545 /// assert!(uppercase_a.is_ascii_uppercase());
4546 /// assert!(uppercase_g.is_ascii_uppercase());
4547 /// assert!(!a.is_ascii_uppercase());
4548 /// assert!(!g.is_ascii_uppercase());
4549 /// assert!(!zero.is_ascii_uppercase());
4550 /// assert!(!percent.is_ascii_uppercase());
4551 /// assert!(!space.is_ascii_uppercase());
4552 /// assert!(!lf.is_ascii_uppercase());
4553 /// assert!(!esc.is_ascii_uppercase());
4555 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4556 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4558 pub const fn is_ascii_uppercase(&self) -> bool {
4559 matches!(*self, b'A'..=b'Z')
4562 /// Checks if the value is an ASCII lowercase character:
4563 /// U+0061 'a' ..= U+007A 'z'.
4568 /// let uppercase_a = b'A';
4569 /// let uppercase_g = b'G';
4572 /// let zero = b'0';
4573 /// let percent = b'%';
4574 /// let space = b' ';
4576 /// let esc = 0x1b_u8;
4578 /// assert!(!uppercase_a.is_ascii_lowercase());
4579 /// assert!(!uppercase_g.is_ascii_lowercase());
4580 /// assert!(a.is_ascii_lowercase());
4581 /// assert!(g.is_ascii_lowercase());
4582 /// assert!(!zero.is_ascii_lowercase());
4583 /// assert!(!percent.is_ascii_lowercase());
4584 /// assert!(!space.is_ascii_lowercase());
4585 /// assert!(!lf.is_ascii_lowercase());
4586 /// assert!(!esc.is_ascii_lowercase());
4588 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4589 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4591 pub const fn is_ascii_lowercase(&self) -> bool {
4592 matches!(*self, b'a'..=b'z')
4595 /// Checks if the value is an ASCII alphanumeric character:
4597 /// - U+0041 'A' ..= U+005A 'Z', or
4598 /// - U+0061 'a' ..= U+007A 'z', or
4599 /// - U+0030 '0' ..= U+0039 '9'.
4604 /// let uppercase_a = b'A';
4605 /// let uppercase_g = b'G';
4608 /// let zero = b'0';
4609 /// let percent = b'%';
4610 /// let space = b' ';
4612 /// let esc = 0x1b_u8;
4614 /// assert!(uppercase_a.is_ascii_alphanumeric());
4615 /// assert!(uppercase_g.is_ascii_alphanumeric());
4616 /// assert!(a.is_ascii_alphanumeric());
4617 /// assert!(g.is_ascii_alphanumeric());
4618 /// assert!(zero.is_ascii_alphanumeric());
4619 /// assert!(!percent.is_ascii_alphanumeric());
4620 /// assert!(!space.is_ascii_alphanumeric());
4621 /// assert!(!lf.is_ascii_alphanumeric());
4622 /// assert!(!esc.is_ascii_alphanumeric());
4624 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4625 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4627 pub const fn is_ascii_alphanumeric(&self) -> bool {
4628 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
4631 /// Checks if the value is an ASCII decimal digit:
4632 /// U+0030 '0' ..= U+0039 '9'.
4637 /// let uppercase_a = b'A';
4638 /// let uppercase_g = b'G';
4641 /// let zero = b'0';
4642 /// let percent = b'%';
4643 /// let space = b' ';
4645 /// let esc = 0x1b_u8;
4647 /// assert!(!uppercase_a.is_ascii_digit());
4648 /// assert!(!uppercase_g.is_ascii_digit());
4649 /// assert!(!a.is_ascii_digit());
4650 /// assert!(!g.is_ascii_digit());
4651 /// assert!(zero.is_ascii_digit());
4652 /// assert!(!percent.is_ascii_digit());
4653 /// assert!(!space.is_ascii_digit());
4654 /// assert!(!lf.is_ascii_digit());
4655 /// assert!(!esc.is_ascii_digit());
4657 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4658 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4660 pub const fn is_ascii_digit(&self) -> bool {
4661 matches!(*self, b'0'..=b'9')
4664 /// Checks if the value is an ASCII hexadecimal digit:
4666 /// - U+0030 '0' ..= U+0039 '9', or
4667 /// - U+0041 'A' ..= U+0046 'F', or
4668 /// - U+0061 'a' ..= U+0066 'f'.
4673 /// let uppercase_a = b'A';
4674 /// let uppercase_g = b'G';
4677 /// let zero = b'0';
4678 /// let percent = b'%';
4679 /// let space = b' ';
4681 /// let esc = 0x1b_u8;
4683 /// assert!(uppercase_a.is_ascii_hexdigit());
4684 /// assert!(!uppercase_g.is_ascii_hexdigit());
4685 /// assert!(a.is_ascii_hexdigit());
4686 /// assert!(!g.is_ascii_hexdigit());
4687 /// assert!(zero.is_ascii_hexdigit());
4688 /// assert!(!percent.is_ascii_hexdigit());
4689 /// assert!(!space.is_ascii_hexdigit());
4690 /// assert!(!lf.is_ascii_hexdigit());
4691 /// assert!(!esc.is_ascii_hexdigit());
4693 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4694 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4696 pub const fn is_ascii_hexdigit(&self) -> bool {
4697 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
4700 /// Checks if the value is an ASCII punctuation character:
4702 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4703 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4704 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4705 /// - U+007B ..= U+007E `{ | } ~`
4710 /// let uppercase_a = b'A';
4711 /// let uppercase_g = b'G';
4714 /// let zero = b'0';
4715 /// let percent = b'%';
4716 /// let space = b' ';
4718 /// let esc = 0x1b_u8;
4720 /// assert!(!uppercase_a.is_ascii_punctuation());
4721 /// assert!(!uppercase_g.is_ascii_punctuation());
4722 /// assert!(!a.is_ascii_punctuation());
4723 /// assert!(!g.is_ascii_punctuation());
4724 /// assert!(!zero.is_ascii_punctuation());
4725 /// assert!(percent.is_ascii_punctuation());
4726 /// assert!(!space.is_ascii_punctuation());
4727 /// assert!(!lf.is_ascii_punctuation());
4728 /// assert!(!esc.is_ascii_punctuation());
4730 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4731 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4733 pub const fn is_ascii_punctuation(&self) -> bool {
4734 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
4737 /// Checks if the value is an ASCII graphic character:
4738 /// U+0021 '!' ..= U+007E '~'.
4743 /// let uppercase_a = b'A';
4744 /// let uppercase_g = b'G';
4747 /// let zero = b'0';
4748 /// let percent = b'%';
4749 /// let space = b' ';
4751 /// let esc = 0x1b_u8;
4753 /// assert!(uppercase_a.is_ascii_graphic());
4754 /// assert!(uppercase_g.is_ascii_graphic());
4755 /// assert!(a.is_ascii_graphic());
4756 /// assert!(g.is_ascii_graphic());
4757 /// assert!(zero.is_ascii_graphic());
4758 /// assert!(percent.is_ascii_graphic());
4759 /// assert!(!space.is_ascii_graphic());
4760 /// assert!(!lf.is_ascii_graphic());
4761 /// assert!(!esc.is_ascii_graphic());
4763 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4764 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4766 pub const fn is_ascii_graphic(&self) -> bool {
4767 matches!(*self, b'!'..=b'~')
4770 /// Checks if the value is an ASCII whitespace character:
4771 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4772 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4774 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4775 /// whitespace][infra-aw]. There are several other definitions in
4776 /// wide use. For instance, [the POSIX locale][pct] includes
4777 /// U+000B VERTICAL TAB as well as all the above characters,
4778 /// but—from the very same specification—[the default rule for
4779 /// "field splitting" in the Bourne shell][bfs] considers *only*
4780 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4782 /// If you are writing a program that will process an existing
4783 /// file format, check what that format's definition of whitespace is
4784 /// before using this function.
4786 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4787 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4788 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4793 /// let uppercase_a = b'A';
4794 /// let uppercase_g = b'G';
4797 /// let zero = b'0';
4798 /// let percent = b'%';
4799 /// let space = b' ';
4801 /// let esc = 0x1b_u8;
4803 /// assert!(!uppercase_a.is_ascii_whitespace());
4804 /// assert!(!uppercase_g.is_ascii_whitespace());
4805 /// assert!(!a.is_ascii_whitespace());
4806 /// assert!(!g.is_ascii_whitespace());
4807 /// assert!(!zero.is_ascii_whitespace());
4808 /// assert!(!percent.is_ascii_whitespace());
4809 /// assert!(space.is_ascii_whitespace());
4810 /// assert!(lf.is_ascii_whitespace());
4811 /// assert!(!esc.is_ascii_whitespace());
4813 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4814 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4816 pub const fn is_ascii_whitespace(&self) -> bool {
4817 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
4820 /// Checks if the value is an ASCII control character:
4821 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4822 /// Note that most ASCII whitespace characters are control
4823 /// characters, but SPACE is not.
4828 /// let uppercase_a = b'A';
4829 /// let uppercase_g = b'G';
4832 /// let zero = b'0';
4833 /// let percent = b'%';
4834 /// let space = b' ';
4836 /// let esc = 0x1b_u8;
4838 /// assert!(!uppercase_a.is_ascii_control());
4839 /// assert!(!uppercase_g.is_ascii_control());
4840 /// assert!(!a.is_ascii_control());
4841 /// assert!(!g.is_ascii_control());
4842 /// assert!(!zero.is_ascii_control());
4843 /// assert!(!percent.is_ascii_control());
4844 /// assert!(!space.is_ascii_control());
4845 /// assert!(lf.is_ascii_control());
4846 /// assert!(esc.is_ascii_control());
4848 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4849 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4851 pub const fn is_ascii_control(&self) -> bool {
4852 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
4858 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4859 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4864 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4865 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4870 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4871 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4872 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4873 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4879 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4880 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4881 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4882 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4883 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4884 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4885 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4889 #[cfg(target_pointer_width = "16")]
4892 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4893 "[0x34, 0x12]", "[0x12, 0x34]",
4894 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4896 #[cfg(target_pointer_width = "32")]
4899 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4900 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4901 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4904 #[cfg(target_pointer_width = "64")]
4907 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4908 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4909 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4910 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4911 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4914 /// A classification of floating point numbers.
4916 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4917 /// their documentation for more.
4919 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4920 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4925 /// use std::num::FpCategory;
4927 /// let num = 12.4_f32;
4928 /// let inf = f32::INFINITY;
4929 /// let zero = 0f32;
4930 /// let sub: f32 = 1.1754942e-38;
4931 /// let nan = f32::NAN;
4933 /// assert_eq!(num.classify(), FpCategory::Normal);
4934 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4935 /// assert_eq!(zero.classify(), FpCategory::Zero);
4936 /// assert_eq!(nan.classify(), FpCategory::Nan);
4937 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4939 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4940 #[stable(feature = "rust1", since = "1.0.0")]
4941 pub enum FpCategory {
4942 /// "Not a Number", often obtained by dividing by zero.
4943 #[stable(feature = "rust1", since = "1.0.0")]
4946 /// Positive or negative infinity.
4947 #[stable(feature = "rust1", since = "1.0.0")]
4950 /// Positive or negative zero.
4951 #[stable(feature = "rust1", since = "1.0.0")]
4954 /// De-normalized floating point representation (less precise than `Normal`).
4955 #[stable(feature = "rust1", since = "1.0.0")]
4958 /// A regular floating point number.
4959 #[stable(feature = "rust1", since = "1.0.0")]
4963 macro_rules! from_str_radix_int_impl {
4965 #[stable(feature = "rust1", since = "1.0.0")]
4966 impl FromStr for $t {
4967 type Err = ParseIntError;
4968 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4969 from_str_radix(src, 10)
4974 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4976 /// The error type returned when a checked integral type conversion fails.
4977 #[stable(feature = "try_from", since = "1.34.0")]
4978 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4979 pub struct TryFromIntError(pub(crate) ());
4981 impl TryFromIntError {
4983 feature = "int_error_internals",
4984 reason = "available through Error trait and this method should \
4985 not be exposed publicly",
4989 pub fn __description(&self) -> &str {
4990 "out of range integral type conversion attempted"
4994 #[stable(feature = "try_from", since = "1.34.0")]
4995 impl fmt::Display for TryFromIntError {
4996 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4997 self.__description().fmt(fmt)
5001 #[stable(feature = "try_from", since = "1.34.0")]
5002 impl From<Infallible> for TryFromIntError {
5003 fn from(x: Infallible) -> TryFromIntError {
5008 #[unstable(feature = "never_type", issue = "35121")]
5009 impl From<!> for TryFromIntError {
5010 fn from(never: !) -> TryFromIntError {
5011 // Match rather than coerce to make sure that code like
5012 // `From<Infallible> for TryFromIntError` above will keep working
5013 // when `Infallible` becomes an alias to `!`.
5019 trait FromStrRadixHelper: PartialOrd + Copy {
5020 fn min_value() -> Self;
5021 fn max_value() -> Self;
5022 fn from_u32(u: u32) -> Self;
5023 fn checked_mul(&self, other: u32) -> Option<Self>;
5024 fn checked_sub(&self, other: u32) -> Option<Self>;
5025 fn checked_add(&self, other: u32) -> Option<Self>;
5029 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
5031 fn min_value() -> Self { Self::min_value() }
5033 fn max_value() -> Self { Self::max_value() }
5035 fn from_u32(u: u32) -> Self { u as Self }
5037 fn checked_mul(&self, other: u32) -> Option<Self> {
5038 Self::checked_mul(*self, other as Self)
5041 fn checked_sub(&self, other: u32) -> Option<Self> {
5042 Self::checked_sub(*self, other as Self)
5045 fn checked_add(&self, other: u32) -> Option<Self> {
5046 Self::checked_add(*self, other as Self)
5050 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5052 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5053 use self::IntErrorKind::*;
5054 use self::ParseIntError as PIE;
5057 radix >= 2 && radix <= 36,
5058 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5063 return Err(PIE { kind: Empty });
5066 let is_signed_ty = T::from_u32(0) > T::min_value();
5068 // all valid digits are ascii, so we will just iterate over the utf8 bytes
5069 // and cast them to chars. .to_digit() will safely return None for anything
5070 // other than a valid ascii digit for the given radix, including the first-byte
5071 // of multi-byte sequences
5072 let src = src.as_bytes();
5074 let (is_positive, digits) = match src[0] {
5075 b'+' => (true, &src[1..]),
5076 b'-' if is_signed_ty => (false, &src[1..]),
5080 if digits.is_empty() {
5081 return Err(PIE { kind: Empty });
5084 let mut result = T::from_u32(0);
5086 // The number is positive
5088 let x = match (c as char).to_digit(radix) {
5090 None => return Err(PIE { kind: InvalidDigit }),
5092 result = match result.checked_mul(radix) {
5093 Some(result) => result,
5094 None => return Err(PIE { kind: Overflow }),
5096 result = match result.checked_add(x) {
5097 Some(result) => result,
5098 None => return Err(PIE { kind: Overflow }),
5102 // The number is negative
5104 let x = match (c as char).to_digit(radix) {
5106 None => return Err(PIE { kind: InvalidDigit }),
5108 result = match result.checked_mul(radix) {
5109 Some(result) => result,
5110 None => return Err(PIE { kind: Underflow }),
5112 result = match result.checked_sub(x) {
5113 Some(result) => result,
5114 None => return Err(PIE { kind: Underflow }),
5121 /// An error which can be returned when parsing an integer.
5123 /// This error is used as the error type for the `from_str_radix()` functions
5124 /// on the primitive integer types, such as [`i8::from_str_radix`].
5126 /// # Potential causes
5128 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5129 /// in the string e.g., when it is obtained from the standard input.
5130 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5132 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5133 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5134 #[derive(Debug, Clone, PartialEq, Eq)]
5135 #[stable(feature = "rust1", since = "1.0.0")]
5136 pub struct ParseIntError {
5140 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5142 feature = "int_error_matching",
5143 reason = "it can be useful to match errors when making error messages \
5144 for integer parsing",
5147 #[derive(Debug, Clone, PartialEq, Eq)]
5149 pub enum IntErrorKind {
5150 /// Value being parsed is empty.
5152 /// Among other causes, this variant will be constructed when parsing an empty string.
5154 /// Contains an invalid digit.
5156 /// Among other causes, this variant will be constructed when parsing a string that
5157 /// contains a letter.
5159 /// Integer is too large to store in target integer type.
5161 /// Integer is too small to store in target integer type.
5165 /// This variant will be emitted when the parsing string has a value of zero, which
5166 /// would be illegal for non-zero types.
5170 impl ParseIntError {
5171 /// Outputs the detailed cause of parsing an integer failing.
5173 feature = "int_error_matching",
5174 reason = "it can be useful to match errors when making error messages \
5175 for integer parsing",
5178 pub fn kind(&self) -> &IntErrorKind {
5182 feature = "int_error_internals",
5183 reason = "available through Error trait and this method should \
5184 not be exposed publicly",
5188 pub fn __description(&self) -> &str {
5190 IntErrorKind::Empty => "cannot parse integer from empty string",
5191 IntErrorKind::InvalidDigit => "invalid digit found in string",
5192 IntErrorKind::Overflow => "number too large to fit in target type",
5193 IntErrorKind::Underflow => "number too small to fit in target type",
5194 IntErrorKind::Zero => "number would be zero for non-zero type",
5199 #[stable(feature = "rust1", since = "1.0.0")]
5200 impl fmt::Display for ParseIntError {
5201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5202 self.__description().fmt(f)
5206 #[stable(feature = "rust1", since = "1.0.0")]
5207 pub use crate::num::dec2flt::ParseFloatError;