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 {
77 // SAFETY: this is guaranteed to be safe by the caller.
81 /// Creates a non-zero if the given value is not zero.
83 #[rustc_const_unstable(feature = "const_nonzero_int_methods", issue = "53718")]
85 pub const fn new(n: $Int) -> Option<Self> {
87 // SAFETY: we just checked that there's no `0`
88 Some(unsafe { Self(n) })
94 /// Returns the value as a primitive type.
97 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
98 pub const fn get(self) -> $Int {
104 #[stable(feature = "from_nonzero", since = "1.31.0")]
105 impl From<$Ty> for $Int {
108 "Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`"),
109 fn from(nonzero: $Ty) -> Self {
115 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
119 fn bitor(self, rhs: Self) -> Self::Output {
120 // Safety: since `self` and `rhs` are both nonzero, the
121 // result of the bitwise-or will be nonzero.
122 unsafe { $Ty::new_unchecked(self.get() | rhs.get()) }
126 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
127 impl BitOr<$Int> for $Ty {
130 fn bitor(self, rhs: $Int) -> Self::Output {
131 // Safety: since `self` is nonzero, the result of the
132 // bitwise-or will be nonzero regardless of the value of
134 unsafe { $Ty::new_unchecked(self.get() | rhs) }
138 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
139 impl BitOr<$Ty> for $Int {
142 fn bitor(self, rhs: $Ty) -> Self::Output {
143 // Safety: since `rhs` is nonzero, the result of the
144 // bitwise-or will be nonzero regardless of the value of
146 unsafe { $Ty::new_unchecked(self | rhs.get()) }
150 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
151 impl BitOrAssign for $Ty {
153 fn bitor_assign(&mut self, rhs: Self) {
158 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
159 impl BitOrAssign<$Int> for $Ty {
161 fn bitor_assign(&mut self, rhs: $Int) {
167 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
174 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
175 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
176 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
177 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
178 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
179 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
180 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
181 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
182 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
183 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
184 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
185 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
188 macro_rules! from_str_radix_nzint_impl {
190 #[stable(feature = "nonzero_parse", since = "1.35.0")]
191 impl FromStr for $t {
192 type Err = ParseIntError;
193 fn from_str(src: &str) -> Result<Self, Self::Err> {
194 Self::new(from_str_radix(src, 10)?)
195 .ok_or(ParseIntError {
196 kind: IntErrorKind::Zero
203 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
204 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
206 /// Provides intentionally-wrapped arithmetic on `T`.
208 /// Operations like `+` on `u32` values are intended to never overflow,
209 /// and in some debug configurations overflow is detected and results
210 /// in a panic. While most arithmetic falls into this category, some
211 /// code explicitly expects and relies upon modular arithmetic (e.g.,
214 /// Wrapping arithmetic can be achieved either through methods like
215 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
216 /// all standard arithmetic operations on the underlying value are
217 /// intended to have wrapping semantics.
219 /// The underlying value can be retrieved through the `.0` index of the
220 /// `Wrapping` tuple.
225 /// use std::num::Wrapping;
227 /// let zero = Wrapping(0u32);
228 /// let one = Wrapping(1u32);
230 /// assert_eq!(u32::MAX, (zero - one).0);
232 #[stable(feature = "rust1", since = "1.0.0")]
233 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
235 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
237 #[stable(feature = "rust1", since = "1.0.0")]
238 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
239 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244 #[stable(feature = "wrapping_display", since = "1.10.0")]
245 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
252 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
259 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
266 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
273 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279 // All these modules are technically private and only exposed for coretests:
287 macro_rules! usize_isize_to_xe_bytes_doc {
291 **Note**: This function returns an array of length 2, 4 or 8 bytes
292 depending on the target pointer size.
298 macro_rules! usize_isize_from_xe_bytes_doc {
302 **Note**: This function takes an array of length 2, 4 or 8 bytes
303 depending on the target pointer size.
309 macro_rules! int_impl {
310 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
311 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
312 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
313 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
315 concat!("The smallest value that can be represented by this integer type.
322 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, ", stringify!($Min), ");",
325 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
326 pub const MIN: Self = !0 ^ ((!0 as $UnsignedT) >> 1) as Self;
330 concat!("The largest value that can be represented by this integer type.
337 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");",
340 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
341 pub const MAX: Self = !Self::MIN;
345 concat!("Converts a string slice in a given base to an integer.
347 The string is expected to be an optional `+` or `-` sign followed by digits.
348 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
349 depending on `radix`:
357 This function panics if `radix` is not in the range from 2 to 36.
364 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
367 #[stable(feature = "rust1", since = "1.0.0")]
368 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
369 from_str_radix(src, radix)
374 concat!("Returns the number of ones in the binary representation of `self`.
381 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
383 assert_eq!(n.count_ones(), 1);",
387 #[stable(feature = "rust1", since = "1.0.0")]
388 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
390 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
394 concat!("Returns the number of zeros in the binary representation of `self`.
401 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 1);", $EndFeature, "
403 #[stable(feature = "rust1", since = "1.0.0")]
404 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
406 pub const fn count_zeros(self) -> u32 {
412 concat!("Returns the number of leading zeros in the binary representation of `self`.
419 ", $Feature, "let n = -1", stringify!($SelfT), ";
421 assert_eq!(n.leading_zeros(), 0);",
424 #[stable(feature = "rust1", since = "1.0.0")]
425 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
427 pub const fn leading_zeros(self) -> u32 {
428 (self as $UnsignedT).leading_zeros()
433 concat!("Returns the number of trailing zeros in the binary representation of `self`.
440 ", $Feature, "let n = -4", stringify!($SelfT), ";
442 assert_eq!(n.trailing_zeros(), 2);",
445 #[stable(feature = "rust1", since = "1.0.0")]
446 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
448 pub const fn trailing_zeros(self) -> u32 {
449 (self as $UnsignedT).trailing_zeros()
454 concat!("Returns the number of leading ones in the binary representation of `self`.
461 ", $Feature, "let n = -1", stringify!($SelfT), ";
463 assert_eq!(n.leading_ones(), ", stringify!($BITS), ");",
466 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
467 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
469 pub const fn leading_ones(self) -> u32 {
470 (self as $UnsignedT).leading_ones()
475 concat!("Returns the number of trailing ones in the binary representation of `self`.
482 ", $Feature, "let n = 3", stringify!($SelfT), ";
484 assert_eq!(n.trailing_ones(), 2);",
487 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
488 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
490 pub const fn trailing_ones(self) -> u32 {
491 (self as $UnsignedT).trailing_ones()
496 concat!("Shifts the bits to the left by a specified amount, `n`,
497 wrapping the truncated bits to the end of the resulting integer.
499 Please note this isn't the same operation as the `<<` shifting operator!
506 let n = ", $rot_op, stringify!($SelfT), ";
507 let m = ", $rot_result, ";
509 assert_eq!(n.rotate_left(", $rot, "), m);
511 #[stable(feature = "rust1", since = "1.0.0")]
512 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
513 #[must_use = "this returns the result of the operation, \
514 without modifying the original"]
516 pub const fn rotate_left(self, n: u32) -> Self {
517 (self as $UnsignedT).rotate_left(n) as Self
522 concat!("Shifts the bits to the right by a specified amount, `n`,
523 wrapping the truncated bits to the beginning of the resulting
526 Please note this isn't the same operation as the `>>` shifting operator!
533 let n = ", $rot_result, stringify!($SelfT), ";
534 let m = ", $rot_op, ";
536 assert_eq!(n.rotate_right(", $rot, "), m);
538 #[stable(feature = "rust1", since = "1.0.0")]
539 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
540 #[must_use = "this returns the result of the operation, \
541 without modifying the original"]
543 pub const fn rotate_right(self, n: u32) -> Self {
544 (self as $UnsignedT).rotate_right(n) as Self
549 concat!("Reverses the byte order of the integer.
556 let n = ", $swap_op, stringify!($SelfT), ";
558 let m = n.swap_bytes();
560 assert_eq!(m, ", $swapped, ");
562 #[stable(feature = "rust1", since = "1.0.0")]
563 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
565 pub const fn swap_bytes(self) -> Self {
566 (self as $UnsignedT).swap_bytes() as Self
571 concat!("Reverses the bit pattern of the integer.
578 let n = ", $swap_op, stringify!($SelfT), ";
579 let m = n.reverse_bits();
581 assert_eq!(m, ", $reversed, ");
583 #[stable(feature = "reverse_bits", since = "1.37.0")]
584 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
587 pub const fn reverse_bits(self) -> Self {
588 (self as $UnsignedT).reverse_bits() as Self
593 concat!("Converts an integer from big endian to the target's endianness.
595 On big endian this is a no-op. On little endian the bytes are swapped.
602 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
604 if cfg!(target_endian = \"big\") {
605 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
607 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
611 #[stable(feature = "rust1", since = "1.0.0")]
612 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
614 pub const fn from_be(x: Self) -> Self {
615 #[cfg(target_endian = "big")]
619 #[cfg(not(target_endian = "big"))]
627 concat!("Converts an integer from little endian to the target's endianness.
629 On little endian this is a no-op. On big endian the bytes are swapped.
636 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
638 if cfg!(target_endian = \"little\") {
639 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
641 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
645 #[stable(feature = "rust1", since = "1.0.0")]
646 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
648 pub const fn from_le(x: Self) -> Self {
649 #[cfg(target_endian = "little")]
653 #[cfg(not(target_endian = "little"))]
661 concat!("Converts `self` to big endian from the target's endianness.
663 On big endian this is a no-op. On little endian the bytes are swapped.
670 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
672 if cfg!(target_endian = \"big\") {
673 assert_eq!(n.to_be(), n)
675 assert_eq!(n.to_be(), n.swap_bytes())
679 #[stable(feature = "rust1", since = "1.0.0")]
680 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
682 pub const fn to_be(self) -> Self { // or not to be?
683 #[cfg(target_endian = "big")]
687 #[cfg(not(target_endian = "big"))]
695 concat!("Converts `self` to little endian from the target's endianness.
697 On little endian this is a no-op. On big endian the bytes are swapped.
704 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
706 if cfg!(target_endian = \"little\") {
707 assert_eq!(n.to_le(), n)
709 assert_eq!(n.to_le(), n.swap_bytes())
713 #[stable(feature = "rust1", since = "1.0.0")]
714 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
716 pub const fn to_le(self) -> Self {
717 #[cfg(target_endian = "little")]
721 #[cfg(not(target_endian = "little"))]
729 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
730 if overflow occurred.
737 ", $Feature, "assert_eq!((", stringify!($SelfT),
738 "::MAX - 2).checked_add(1), Some(", stringify!($SelfT), "::MAX - 1));
739 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);",
742 #[stable(feature = "rust1", since = "1.0.0")]
743 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
744 #[must_use = "this returns the result of the operation, \
745 without modifying the original"]
747 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
748 let (a, b) = self.overflowing_add(rhs);
749 if b {None} else {Some(a)}
754 concat!("Unchecked integer addition. Computes `self + rhs`, assuming overflow
755 cannot occur. This results in undefined behavior when `self + rhs > ", stringify!($SelfT),
756 "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`."),
758 feature = "unchecked_math",
759 reason = "niche optimization path",
762 #[must_use = "this returns the result of the operation, \
763 without modifying the original"]
765 pub unsafe fn unchecked_add(self, rhs: Self) -> Self {
766 // SAFETY: the caller must uphold the safety contract for
768 unsafe { intrinsics::unchecked_add(self, rhs) }
773 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
781 ", $Feature, "assert_eq!((", stringify!($SelfT),
782 "::MIN + 2).checked_sub(1), Some(", stringify!($SelfT), "::MIN + 1));
783 assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(3), None);",
786 #[stable(feature = "rust1", since = "1.0.0")]
787 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
788 #[must_use = "this returns the result of the operation, \
789 without modifying the original"]
791 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
792 let (a, b) = self.overflowing_sub(rhs);
793 if b {None} else {Some(a)}
798 concat!("Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
799 cannot occur. This results in undefined behavior when `self - rhs > ", stringify!($SelfT),
800 "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`."),
802 feature = "unchecked_math",
803 reason = "niche optimization path",
806 #[must_use = "this returns the result of the operation, \
807 without modifying the original"]
809 pub unsafe fn unchecked_sub(self, rhs: Self) -> Self {
810 // SAFETY: the caller must uphold the safety contract for
812 unsafe { intrinsics::unchecked_sub(self, rhs) }
817 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
825 ", $Feature, "assert_eq!(", stringify!($SelfT),
826 "::MAX.checked_mul(1), Some(", stringify!($SelfT), "::MAX));
827 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);",
830 #[stable(feature = "rust1", since = "1.0.0")]
831 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
832 #[must_use = "this returns the result of the operation, \
833 without modifying the original"]
835 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
836 let (a, b) = self.overflowing_mul(rhs);
837 if b {None} else {Some(a)}
842 concat!("Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
843 cannot occur. This results in undefined behavior when `self * rhs > ", stringify!($SelfT),
844 "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`."),
846 feature = "unchecked_math",
847 reason = "niche optimization path",
850 #[must_use = "this returns the result of the operation, \
851 without modifying the original"]
853 pub unsafe fn unchecked_mul(self, rhs: Self) -> Self {
854 // SAFETY: the caller must uphold the safety contract for
856 unsafe { intrinsics::unchecked_mul(self, rhs) }
861 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
862 or the division results in overflow.
869 ", $Feature, "assert_eq!((", stringify!($SelfT),
870 "::MIN + 1).checked_div(-1), Some(", stringify!($Max), "));
871 assert_eq!(", stringify!($SelfT), "::MIN.checked_div(-1), None);
872 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
875 #[stable(feature = "rust1", since = "1.0.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_div(self, rhs: Self) -> Option<Self> {
881 if rhs == 0 || (self == Self::MIN && rhs == -1) {
884 // SAFETY: div by zero and by INT_MIN have been checked above
885 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
891 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
892 returning `None` if `rhs == 0` or the division results in overflow.
899 assert_eq!((", stringify!($SelfT),
900 "::MIN + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
901 assert_eq!(", stringify!($SelfT), "::MIN.checked_div_euclid(-1), None);
902 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
904 #[stable(feature = "euclidean_division", since = "1.38.0")]
905 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
906 #[must_use = "this returns the result of the operation, \
907 without modifying the original"]
909 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
910 if rhs == 0 || (self == Self::MIN && rhs == -1) {
913 Some(self.div_euclid(rhs))
919 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
920 `rhs == 0` or the division results in overflow.
928 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
929 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
930 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
933 #[stable(feature = "wrapping", since = "1.7.0")]
934 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
935 #[must_use = "this returns the result of the operation, \
936 without modifying the original"]
938 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
939 if rhs == 0 || (self == Self::MIN && rhs == -1) {
942 // SAFETY: div by zero and by INT_MIN have been checked above
943 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
949 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
950 if `rhs == 0` or the division results in overflow.
957 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
958 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
959 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
961 #[stable(feature = "euclidean_division", since = "1.38.0")]
962 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
963 #[must_use = "this returns the result of the operation, \
964 without modifying the original"]
966 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
967 if rhs == 0 || (self == Self::MIN && rhs == -1) {
970 Some(self.rem_euclid(rhs))
976 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
984 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
985 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
988 #[stable(feature = "wrapping", since = "1.7.0")]
989 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
991 pub const fn checked_neg(self) -> Option<Self> {
992 let (a, b) = self.overflowing_neg();
993 if b {None} else {Some(a)}
998 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
999 than or equal to the number of bits in `self`.
1006 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
1007 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
1010 #[stable(feature = "wrapping", since = "1.7.0")]
1011 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
1012 #[must_use = "this returns the result of the operation, \
1013 without modifying the original"]
1015 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
1016 let (a, b) = self.overflowing_shl(rhs);
1017 if b {None} else {Some(a)}
1022 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
1023 larger than or equal to the number of bits in `self`.
1030 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
1031 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
1034 #[stable(feature = "wrapping", since = "1.7.0")]
1035 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
1036 #[must_use = "this returns the result of the operation, \
1037 without modifying the original"]
1039 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
1040 let (a, b) = self.overflowing_shr(rhs);
1041 if b {None} else {Some(a)}
1046 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
1055 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
1056 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
1059 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1060 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
1062 pub const fn checked_abs(self) -> Option<Self> {
1063 if self.is_negative() {
1072 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
1080 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
1081 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);",
1085 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1086 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1087 #[must_use = "this returns the result of the operation, \
1088 without modifying the original"]
1090 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
1091 let mut base = self;
1092 let mut acc: Self = 1;
1096 acc = try_opt!(acc.checked_mul(base));
1099 base = try_opt!(base.checked_mul(base));
1102 // Deal with the final bit of the exponent separately, since
1103 // squaring the base afterwards is not necessary and may cause a
1104 // needless overflow.
1106 acc = try_opt!(acc.checked_mul(base));
1114 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
1115 bounds instead of overflowing.
1122 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
1123 assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT),
1125 assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT),
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1132 #[must_use = "this returns the result of the operation, \
1133 without modifying the original"]
1135 pub const fn saturating_add(self, rhs: Self) -> Self {
1136 intrinsics::saturating_add(self, rhs)
1141 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
1142 numeric bounds instead of overflowing.
1149 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
1150 assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT),
1152 assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT),
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1158 #[must_use = "this returns the result of the operation, \
1159 without modifying the original"]
1161 pub const fn saturating_sub(self, rhs: Self) -> Self {
1162 intrinsics::saturating_sub(self, rhs)
1167 concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
1168 instead of overflowing.
1175 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
1176 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
1177 assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT),
1179 assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT),
1184 #[stable(feature = "saturating_neg", since = "1.45.0")]
1185 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1187 pub const fn saturating_neg(self) -> Self {
1188 intrinsics::saturating_sub(0, self)
1193 concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1194 MIN` instead of overflowing.
1201 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
1202 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
1203 assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT),
1205 assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT),
1210 #[stable(feature = "saturating_neg", since = "1.45.0")]
1211 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1213 pub const fn saturating_abs(self) -> Self {
1214 if self.is_negative() {
1215 self.saturating_neg()
1223 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1224 numeric bounds instead of overflowing.
1232 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1233 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1234 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1237 #[stable(feature = "wrapping", since = "1.7.0")]
1238 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1239 #[must_use = "this returns the result of the operation, \
1240 without modifying the original"]
1242 pub const fn saturating_mul(self, rhs: Self) -> Self {
1243 match self.checked_mul(rhs) {
1245 None => if (self < 0) == (rhs < 0) {
1255 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1256 saturating at the numeric bounds instead of overflowing.
1264 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1265 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1266 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1269 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1270 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1271 #[must_use = "this returns the result of the operation, \
1272 without modifying the original"]
1274 pub const fn saturating_pow(self, exp: u32) -> Self {
1275 match self.checked_pow(exp) {
1277 None if self < 0 && exp % 2 == 1 => Self::MIN,
1284 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1285 boundary of the type.
1292 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1293 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT),
1297 #[stable(feature = "rust1", since = "1.0.0")]
1298 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1299 #[must_use = "this returns the result of the operation, \
1300 without modifying the original"]
1302 pub const fn wrapping_add(self, rhs: Self) -> Self {
1303 intrinsics::wrapping_add(self, rhs)
1308 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1309 boundary of the type.
1316 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1317 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ",
1318 stringify!($SelfT), "::MAX);",
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1323 #[must_use = "this returns the result of the operation, \
1324 without modifying the original"]
1326 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1327 intrinsics::wrapping_sub(self, rhs)
1332 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1333 the boundary of the type.
1340 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1341 assert_eq!(11i8.wrapping_mul(12), -124);",
1344 #[stable(feature = "rust1", since = "1.0.0")]
1345 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1346 #[must_use = "this returns the result of the operation, \
1347 without modifying the original"]
1349 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1350 intrinsics::wrapping_mul(self, rhs)
1355 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1356 boundary of the type.
1358 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1359 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1360 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1364 This function will panic if `rhs` is 0.
1371 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1372 assert_eq!((-128i8).wrapping_div(-1), -128);",
1375 #[stable(feature = "num_wrapping", since = "1.2.0")]
1376 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1377 #[must_use = "this returns the result of the operation, \
1378 without modifying the original"]
1380 pub const fn wrapping_div(self, rhs: Self) -> Self {
1381 self.overflowing_div(rhs).0
1386 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1387 wrapping around at the boundary of the type.
1389 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1390 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1391 type. In this case, this method returns `MIN` itself.
1395 This function will panic if `rhs` is 0.
1402 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1403 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1405 #[stable(feature = "euclidean_division", since = "1.38.0")]
1406 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1407 #[must_use = "this returns the result of the operation, \
1408 without modifying the original"]
1410 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1411 self.overflowing_div_euclid(rhs).0
1416 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1417 boundary of the type.
1419 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1420 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1421 this function returns `0`.
1425 This function will panic if `rhs` is 0.
1432 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1433 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1436 #[stable(feature = "num_wrapping", since = "1.2.0")]
1437 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1438 #[must_use = "this returns the result of the operation, \
1439 without modifying the original"]
1441 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1442 self.overflowing_rem(rhs).0
1447 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1448 at the boundary of the type.
1450 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1451 for the type). In this case, this method returns 0.
1455 This function will panic if `rhs` is 0.
1462 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1463 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1465 #[stable(feature = "euclidean_division", since = "1.38.0")]
1466 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1467 #[must_use = "this returns the result of the operation, \
1468 without modifying the original"]
1470 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1471 self.overflowing_rem_euclid(rhs).0
1476 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1479 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1480 is the negative minimal value for the type); this is a positive value that is too large to represent
1481 in the type. In such a case, this function returns `MIN` itself.
1488 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1489 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT),
1493 #[stable(feature = "num_wrapping", since = "1.2.0")]
1494 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1496 pub const fn wrapping_neg(self) -> Self {
1497 self.overflowing_neg().0
1502 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1503 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1505 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1506 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1507 The primitive integer types all implement a `[`rotate_left`](#method.rotate_left) function,
1508 which may be what you want instead.
1515 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1516 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1519 #[stable(feature = "num_wrapping", since = "1.2.0")]
1520 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1521 #[must_use = "this returns the result of the operation, \
1522 without modifying the original"]
1524 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1525 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1528 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1534 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1535 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1537 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1538 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1539 end. The primitive integer types all implement a [`rotate_right`](#method.rotate_right) function,
1540 which may be what you want instead.
1547 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1548 assert_eq!((-128i16).wrapping_shr(64), -128);",
1551 #[stable(feature = "num_wrapping", since = "1.2.0")]
1552 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1553 #[must_use = "this returns the result of the operation, \
1554 without modifying the original"]
1556 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1557 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1560 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1566 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1567 the boundary of the type.
1569 The only case where such wrapping can occur is when one takes the absolute value of the negative
1570 minimal value for the type this is a positive value that is too large to represent in the type. In
1571 such a case, this function returns `MIN` itself.
1578 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1579 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1580 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT),
1582 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1585 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1586 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1587 #[allow(unused_attributes)]
1588 #[cfg_attr(bootstrap, allow_internal_unstable(const_if_match))]
1590 pub const fn wrapping_abs(self) -> Self {
1591 if self.is_negative() {
1600 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1601 wrapping around at the boundary of the type.
1608 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1609 assert_eq!(3i8.wrapping_pow(5), -13);
1610 assert_eq!(3i8.wrapping_pow(6), -39);",
1613 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1614 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1615 #[must_use = "this returns the result of the operation, \
1616 without modifying the original"]
1618 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1619 let mut base = self;
1620 let mut acc: Self = 1;
1624 acc = acc.wrapping_mul(base);
1627 base = base.wrapping_mul(base);
1630 // Deal with the final bit of the exponent separately, since
1631 // squaring the base afterwards is not necessary and may cause a
1632 // needless overflow.
1634 acc = acc.wrapping_mul(base);
1642 concat!("Calculates `self` + `rhs`
1644 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1645 occur. If an overflow would have occurred then the wrapped value is returned.
1653 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1654 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1655 "::MIN, true));", $EndFeature, "
1657 #[stable(feature = "wrapping", since = "1.7.0")]
1658 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1659 #[must_use = "this returns the result of the operation, \
1660 without modifying the original"]
1662 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1663 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1669 concat!("Calculates `self` - `rhs`
1671 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1672 would occur. If an overflow would have occurred then the wrapped value is returned.
1680 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1681 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1682 "::MAX, true));", $EndFeature, "
1684 #[stable(feature = "wrapping", since = "1.7.0")]
1685 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1686 #[must_use = "this returns the result of the operation, \
1687 without modifying the original"]
1689 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1690 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1696 concat!("Calculates the multiplication of `self` and `rhs`.
1698 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1699 would occur. If an overflow would have occurred then the wrapped value is returned.
1706 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1707 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1710 #[stable(feature = "wrapping", since = "1.7.0")]
1711 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1712 #[must_use = "this returns the result of the operation, \
1713 without modifying the original"]
1715 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1716 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1722 concat!("Calculates the divisor when `self` is divided by `rhs`.
1724 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1725 occur. If an overflow would occur then self is returned.
1729 This function will panic if `rhs` is 0.
1737 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1738 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1743 #[stable(feature = "wrapping", since = "1.7.0")]
1744 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1745 #[must_use = "this returns the result of the operation, \
1746 without modifying the original"]
1747 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1748 if self == Self::MIN && rhs == -1 {
1757 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1759 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1760 occur. If an overflow would occur then `self` is returned.
1764 This function will panic if `rhs` is 0.
1771 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1772 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1776 #[stable(feature = "euclidean_division", since = "1.38.0")]
1777 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1778 #[must_use = "this returns the result of the operation, \
1779 without modifying the original"]
1780 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1781 if self == Self::MIN && rhs == -1 {
1784 (self.div_euclid(rhs), false)
1790 concat!("Calculates the remainder when `self` is divided by `rhs`.
1792 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1793 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1797 This function will panic if `rhs` is 0.
1805 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1806 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1810 #[stable(feature = "wrapping", since = "1.7.0")]
1811 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1812 #[must_use = "this returns the result of the operation, \
1813 without modifying the original"]
1814 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1815 if self == Self::MIN && rhs == -1 {
1825 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1827 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1828 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1832 This function will panic if `rhs` is 0.
1839 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1840 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1842 #[stable(feature = "euclidean_division", since = "1.38.0")]
1843 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1844 #[must_use = "this returns the result of the operation, \
1845 without modifying the original"]
1847 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1848 if self == Self::MIN && rhs == -1 {
1851 (self.rem_euclid(rhs), false)
1858 concat!("Negates self, overflowing if this is equal to the minimum value.
1860 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1861 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1862 minimum value will be returned again and `true` will be returned for an overflow happening.
1869 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1870 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1871 "::MIN, true));", $EndFeature, "
1874 #[stable(feature = "wrapping", since = "1.7.0")]
1875 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1876 #[allow(unused_attributes)]
1877 #[cfg_attr(bootstrap, allow_internal_unstable(const_if_match))]
1878 pub const fn overflowing_neg(self) -> (Self, bool) {
1879 if self == Self::MIN {
1888 concat!("Shifts self left by `rhs` bits.
1890 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1891 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1892 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1899 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1900 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1903 #[stable(feature = "wrapping", since = "1.7.0")]
1904 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1905 #[must_use = "this returns the result of the operation, \
1906 without modifying the original"]
1908 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1909 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1914 concat!("Shifts self right by `rhs` bits.
1916 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1917 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1918 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1925 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1926 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1929 #[stable(feature = "wrapping", since = "1.7.0")]
1930 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1931 #[must_use = "this returns the result of the operation, \
1932 without modifying the original"]
1934 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1935 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1940 concat!("Computes the absolute value of `self`.
1942 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1943 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1944 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1945 for an overflow happening.
1952 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1953 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1954 assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT),
1958 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1959 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1961 pub const fn overflowing_abs(self) -> (Self, bool) {
1962 (self.wrapping_abs(), self == Self::MIN)
1967 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1969 Returns a tuple of the exponentiation along with a bool indicating
1970 whether an overflow happened.
1977 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1978 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1981 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1982 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1983 #[must_use = "this returns the result of the operation, \
1984 without modifying the original"]
1986 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1987 let mut base = self;
1988 let mut acc: Self = 1;
1989 let mut overflown = false;
1990 // Scratch space for storing results of overflowing_mul.
1995 r = acc.overflowing_mul(base);
2000 r = base.overflowing_mul(base);
2005 // Deal with the final bit of the exponent separately, since
2006 // squaring the base afterwards is not necessary and may cause a
2007 // needless overflow.
2009 r = acc.overflowing_mul(base);
2019 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2026 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
2028 assert_eq!(x.pow(5), 32);",
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
2033 #[must_use = "this returns the result of the operation, \
2034 without modifying the original"]
2036 #[rustc_inherit_overflow_checks]
2037 pub const fn pow(self, mut exp: u32) -> Self {
2038 let mut base = self;
2049 // Deal with the final bit of the exponent separately, since
2050 // squaring the base afterwards is not necessary and may cause a
2051 // needless overflow.
2061 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
2063 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
2064 with `0 <= self.rem_euclid(rhs) < rhs`.
2066 In other words, the result is `self / rhs` rounded to the integer `n`
2067 such that `self >= n * rhs`.
2068 If `self > 0`, this is equal to round towards zero (the default in Rust);
2069 if `self < 0`, this is equal to round towards +/- infinity.
2073 This function will panic if `rhs` is 0 or the division results in overflow.
2080 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2083 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
2084 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
2085 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
2086 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
2088 #[stable(feature = "euclidean_division", since = "1.38.0")]
2089 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2090 #[must_use = "this returns the result of the operation, \
2091 without modifying the original"]
2093 #[rustc_inherit_overflow_checks]
2094 pub const fn div_euclid(self, rhs: Self) -> Self {
2097 return if rhs > 0 { q - 1 } else { q + 1 }
2105 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
2107 This is done as if by the Euclidean division algorithm -- given
2108 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
2109 `0 <= r < abs(rhs)`.
2113 This function will panic if `rhs` is 0 or the division results in overflow.
2120 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2123 assert_eq!(a.rem_euclid(b), 3);
2124 assert_eq!((-a).rem_euclid(b), 1);
2125 assert_eq!(a.rem_euclid(-b), 3);
2126 assert_eq!((-a).rem_euclid(-b), 1);
2128 #[stable(feature = "euclidean_division", since = "1.38.0")]
2129 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2130 #[must_use = "this returns the result of the operation, \
2131 without modifying the original"]
2133 #[rustc_inherit_overflow_checks]
2134 pub const fn rem_euclid(self, rhs: Self) -> Self {
2149 concat!("Computes the absolute value of `self`.
2153 The absolute value of `", stringify!($SelfT), "::MIN` cannot be represented as an
2154 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
2155 code in debug mode will trigger a panic on this case and optimized code will return `",
2156 stringify!($SelfT), "::MIN` without a panic.
2163 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
2164 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
2167 #[stable(feature = "rust1", since = "1.0.0")]
2168 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2169 #[allow(unused_attributes)]
2170 #[cfg_attr(bootstrap, allow_internal_unstable(const_if_match))]
2172 #[rustc_inherit_overflow_checks]
2173 pub const fn abs(self) -> Self {
2174 // Note that the #[inline] above means that the overflow
2175 // semantics of the subtraction depend on the crate we're being
2177 if self.is_negative() {
2186 concat!("Returns a number representing sign of `self`.
2188 - `0` if the number is zero
2189 - `1` if the number is positive
2190 - `-1` if the number is negative
2197 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
2198 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
2199 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
2202 #[stable(feature = "rust1", since = "1.0.0")]
2203 #[rustc_const_unstable(feature = "const_int_sign", issue = "53718")]
2205 pub const fn signum(self) -> Self {
2215 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2223 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2224 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2227 #[stable(feature = "rust1", since = "1.0.0")]
2228 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2230 pub const fn is_positive(self) -> bool { self > 0 }
2234 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2242 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2243 assert!(!10", stringify!($SelfT), ".is_negative());",
2246 #[stable(feature = "rust1", since = "1.0.0")]
2247 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2249 pub const fn is_negative(self) -> bool { self < 0 }
2253 concat!("Return the memory representation of this integer as a byte array in
2254 big-endian (network) byte order.
2261 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2262 assert_eq!(bytes, ", $be_bytes, ");
2264 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2265 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2267 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2268 self.to_be().to_ne_bytes()
2273 concat!("Return the memory representation of this integer as a byte array in
2274 little-endian byte order.
2281 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2282 assert_eq!(bytes, ", $le_bytes, ");
2284 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2285 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2287 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2288 self.to_le().to_ne_bytes()
2294 Return the memory representation of this integer as a byte array in
2297 As the target platform's native endianness is used, portable code
2298 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2303 [`to_be_bytes`]: #method.to_be_bytes
2304 [`to_le_bytes`]: #method.to_le_bytes
2309 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2312 if cfg!(target_endian = \"big\") {
2319 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2320 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2321 // SAFETY: const sound because integers are plain old datatypes so we can always
2322 // transmute them to arrays of bytes
2323 #[allow_internal_unstable(const_fn_union)]
2325 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2329 bytes: [u8; mem::size_of::<$SelfT>()],
2331 // SAFETY: integers are plain old datatypes so we can always transmute them to
2333 unsafe { Bytes { val: self }.bytes }
2338 concat!("Create an integer value from its representation as a byte array in
2346 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2347 assert_eq!(value, ", $swap_op, ");
2350 When starting from a slice rather than an array, fallible conversion APIs can be used:
2353 use std::convert::TryInto;
2355 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2356 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2358 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2361 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2362 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2364 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2365 Self::from_be(Self::from_ne_bytes(bytes))
2371 Create an integer value from its representation as a byte array in
2379 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2380 assert_eq!(value, ", $swap_op, ");
2383 When starting from a slice rather than an array, fallible conversion APIs can be used:
2386 use std::convert::TryInto;
2388 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2389 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2391 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2394 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2395 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2397 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2398 Self::from_le(Self::from_ne_bytes(bytes))
2403 concat!("Create an integer value from its memory representation as a byte
2404 array in native endianness.
2406 As the target platform's native endianness is used, portable code
2407 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2408 appropriate instead.
2410 [`from_be_bytes`]: #method.from_be_bytes
2411 [`from_le_bytes`]: #method.from_le_bytes
2418 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2423 assert_eq!(value, ", $swap_op, ");
2426 When starting from a slice rather than an array, fallible conversion APIs can be used:
2429 use std::convert::TryInto;
2431 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2432 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2434 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2437 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2438 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2439 // SAFETY: const sound because integers are plain old datatypes so we can always
2440 // transmute to them
2441 #[allow_internal_unstable(const_fn_union)]
2443 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2447 bytes: [u8; mem::size_of::<$SelfT>()],
2449 // SAFETY: integers are plain old datatypes so we can always transmute to them
2450 unsafe { Bytes { bytes }.val }
2455 concat!("**This method is soft-deprecated.**
2457 Although using it won’t cause compilation warning,
2458 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
2460 Returns the smallest value that can be represented by this integer type."),
2461 #[stable(feature = "rust1", since = "1.0.0")]
2464 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2465 pub const fn min_value() -> Self {
2471 concat!("**This method is soft-deprecated.**
2473 Although using it won’t cause compilation warning,
2474 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
2476 Returns the largest value that can be represented by this integer type."),
2477 #[stable(feature = "rust1", since = "1.0.0")]
2480 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2481 pub const fn max_value() -> Self {
2490 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2491 "[0x12]", "[0x12]", "", "" }
2496 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2497 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2502 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2503 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2504 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2509 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2510 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2511 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2512 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2517 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2518 170141183460469231731687303715884105727, "", "", 16,
2519 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2520 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2521 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2522 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2523 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2524 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2527 #[cfg(target_pointer_width = "16")]
2530 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2531 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2532 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2535 #[cfg(target_pointer_width = "32")]
2538 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2539 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2540 "[0x12, 0x34, 0x56, 0x78]",
2541 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2544 #[cfg(target_pointer_width = "64")]
2547 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2548 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2549 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2550 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2551 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2554 macro_rules! uint_impl {
2555 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2556 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2557 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2558 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2560 concat!("The smallest value that can be represented by this integer type.
2567 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, 0);", $EndFeature, "
2569 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2570 pub const MIN: Self = 0;
2574 concat!("The largest value that can be represented by this integer type.
2581 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");",
2584 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2585 pub const MAX: Self = !0;
2589 concat!("Converts a string slice in a given base to an integer.
2591 The string is expected to be an optional `+` sign
2593 Leading and trailing whitespace represent an error.
2594 Digits are a subset of these characters, depending on `radix`:
2602 This function panics if `radix` is not in the range from 2 to 36.
2609 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2612 #[stable(feature = "rust1", since = "1.0.0")]
2613 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2614 from_str_radix(src, radix)
2619 concat!("Returns the number of ones in the binary representation of `self`.
2626 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2628 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2630 #[stable(feature = "rust1", since = "1.0.0")]
2631 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2633 pub const fn count_ones(self) -> u32 {
2634 intrinsics::ctpop(self as $ActualT) as u32
2639 concat!("Returns the number of zeros in the binary representation of `self`.
2646 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);", $EndFeature, "
2648 #[stable(feature = "rust1", since = "1.0.0")]
2649 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2651 pub const fn count_zeros(self) -> u32 {
2652 (!self).count_ones()
2657 concat!("Returns the number of leading zeros in the binary representation of `self`.
2664 ", $Feature, "let n = ", stringify!($SelfT), "::MAX >> 2;
2666 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2668 #[stable(feature = "rust1", since = "1.0.0")]
2669 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2671 pub const fn leading_zeros(self) -> u32 {
2672 intrinsics::ctlz(self as $ActualT) as u32
2677 concat!("Returns the number of trailing zeros in the binary representation
2685 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2687 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2689 #[stable(feature = "rust1", since = "1.0.0")]
2690 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2692 pub const fn trailing_zeros(self) -> u32 {
2693 intrinsics::cttz(self) as u32
2698 concat!("Returns the number of leading ones in the binary representation of `self`.
2705 ", $Feature, "let n = !(", stringify!($SelfT), "::MAX >> 2);
2707 assert_eq!(n.leading_ones(), 2);", $EndFeature, "
2709 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
2710 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
2712 pub const fn leading_ones(self) -> u32 {
2713 (!self).leading_zeros()
2718 concat!("Returns the number of trailing ones in the binary representation
2726 ", $Feature, "let n = 0b1010111", stringify!($SelfT), ";
2728 assert_eq!(n.trailing_ones(), 3);", $EndFeature, "
2730 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
2731 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
2733 pub const fn trailing_ones(self) -> u32 {
2734 (!self).trailing_zeros()
2739 concat!("Shifts the bits to the left by a specified amount, `n`,
2740 wrapping the truncated bits to the end of the resulting integer.
2742 Please note this isn't the same operation as the `<<` shifting operator!
2749 let n = ", $rot_op, stringify!($SelfT), ";
2750 let m = ", $rot_result, ";
2752 assert_eq!(n.rotate_left(", $rot, "), m);
2754 #[stable(feature = "rust1", since = "1.0.0")]
2755 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2756 #[must_use = "this returns the result of the operation, \
2757 without modifying the original"]
2759 pub const fn rotate_left(self, n: u32) -> Self {
2760 intrinsics::rotate_left(self, n as $SelfT)
2765 concat!("Shifts the bits to the right by a specified amount, `n`,
2766 wrapping the truncated bits to the beginning of the resulting
2769 Please note this isn't the same operation as the `>>` shifting operator!
2776 let n = ", $rot_result, stringify!($SelfT), ";
2777 let m = ", $rot_op, ";
2779 assert_eq!(n.rotate_right(", $rot, "), m);
2781 #[stable(feature = "rust1", since = "1.0.0")]
2782 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2783 #[must_use = "this returns the result of the operation, \
2784 without modifying the original"]
2786 pub const fn rotate_right(self, n: u32) -> Self {
2787 intrinsics::rotate_right(self, n as $SelfT)
2793 Reverses the byte order of the integer.
2800 let n = ", $swap_op, stringify!($SelfT), ";
2801 let m = n.swap_bytes();
2803 assert_eq!(m, ", $swapped, ");
2805 #[stable(feature = "rust1", since = "1.0.0")]
2806 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2808 pub const fn swap_bytes(self) -> Self {
2809 intrinsics::bswap(self as $ActualT) as Self
2814 concat!("Reverses the bit pattern of the integer.
2821 let n = ", $swap_op, stringify!($SelfT), ";
2822 let m = n.reverse_bits();
2824 assert_eq!(m, ", $reversed, ");
2826 #[stable(feature = "reverse_bits", since = "1.37.0")]
2827 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2830 pub const fn reverse_bits(self) -> Self {
2831 intrinsics::bitreverse(self as $ActualT) as Self
2836 concat!("Converts an integer from big endian to the target's endianness.
2838 On big endian this is a no-op. On little endian the bytes are
2846 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2848 if cfg!(target_endian = \"big\") {
2849 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2851 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2854 #[stable(feature = "rust1", since = "1.0.0")]
2855 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2857 pub const fn from_be(x: Self) -> Self {
2858 #[cfg(target_endian = "big")]
2862 #[cfg(not(target_endian = "big"))]
2870 concat!("Converts an integer from little endian to the target's endianness.
2872 On little endian this is a no-op. On big endian the bytes are
2880 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2882 if cfg!(target_endian = \"little\") {
2883 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2885 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2888 #[stable(feature = "rust1", since = "1.0.0")]
2889 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2891 pub const fn from_le(x: Self) -> Self {
2892 #[cfg(target_endian = "little")]
2896 #[cfg(not(target_endian = "little"))]
2904 concat!("Converts `self` to big endian from the target's endianness.
2906 On big endian this is a no-op. On little endian the bytes are
2914 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2916 if cfg!(target_endian = \"big\") {
2917 assert_eq!(n.to_be(), n)
2919 assert_eq!(n.to_be(), n.swap_bytes())
2922 #[stable(feature = "rust1", since = "1.0.0")]
2923 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2925 pub const fn to_be(self) -> Self { // or not to be?
2926 #[cfg(target_endian = "big")]
2930 #[cfg(not(target_endian = "big"))]
2938 concat!("Converts `self` to little endian from the target's endianness.
2940 On little endian this is a no-op. On big endian the bytes are
2948 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2950 if cfg!(target_endian = \"little\") {
2951 assert_eq!(n.to_le(), n)
2953 assert_eq!(n.to_le(), n.swap_bytes())
2956 #[stable(feature = "rust1", since = "1.0.0")]
2957 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2959 pub const fn to_le(self) -> Self {
2960 #[cfg(target_endian = "little")]
2964 #[cfg(not(target_endian = "little"))]
2972 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2973 if overflow occurred.
2980 ", $Feature, "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
2981 "Some(", stringify!($SelfT), "::MAX - 1));
2982 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);", $EndFeature, "
2984 #[stable(feature = "rust1", since = "1.0.0")]
2985 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2986 #[must_use = "this returns the result of the operation, \
2987 without modifying the original"]
2989 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
2990 let (a, b) = self.overflowing_add(rhs);
2991 if b {None} else {Some(a)}
2996 concat!("Unchecked integer addition. Computes `self + rhs`, assuming overflow
2997 cannot occur. This results in undefined behavior when `self + rhs > ", stringify!($SelfT),
2998 "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`."),
3000 feature = "unchecked_math",
3001 reason = "niche optimization path",
3004 #[must_use = "this returns the result of the operation, \
3005 without modifying the original"]
3007 pub unsafe fn unchecked_add(self, rhs: Self) -> Self {
3008 // SAFETY: the caller must uphold the safety contract for
3010 unsafe { intrinsics::unchecked_add(self, rhs) }
3015 concat!("Checked integer subtraction. Computes `self - rhs`, returning
3016 `None` if overflow occurred.
3023 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
3024 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
3026 #[stable(feature = "rust1", since = "1.0.0")]
3027 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3028 #[must_use = "this returns the result of the operation, \
3029 without modifying the original"]
3031 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
3032 let (a, b) = self.overflowing_sub(rhs);
3033 if b {None} else {Some(a)}
3038 concat!("Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
3039 cannot occur. This results in undefined behavior when `self - rhs > ", stringify!($SelfT),
3040 "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`."),
3042 feature = "unchecked_math",
3043 reason = "niche optimization path",
3046 #[must_use = "this returns the result of the operation, \
3047 without modifying the original"]
3049 pub unsafe fn unchecked_sub(self, rhs: Self) -> Self {
3050 // SAFETY: the caller must uphold the safety contract for
3052 unsafe { intrinsics::unchecked_sub(self, rhs) }
3057 concat!("Checked integer multiplication. Computes `self * rhs`, returning
3058 `None` if overflow occurred.
3065 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
3066 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);", $EndFeature, "
3068 #[stable(feature = "rust1", since = "1.0.0")]
3069 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3070 #[must_use = "this returns the result of the operation, \
3071 without modifying the original"]
3073 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
3074 let (a, b) = self.overflowing_mul(rhs);
3075 if b {None} else {Some(a)}
3080 concat!("Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
3081 cannot occur. This results in undefined behavior when `self * rhs > ", stringify!($SelfT),
3082 "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`."),
3084 feature = "unchecked_math",
3085 reason = "niche optimization path",
3088 #[must_use = "this returns the result of the operation, \
3089 without modifying the original"]
3091 pub unsafe fn unchecked_mul(self, rhs: Self) -> Self {
3092 // SAFETY: the caller must uphold the safety contract for
3094 unsafe { intrinsics::unchecked_mul(self, rhs) }
3099 concat!("Checked integer division. Computes `self / rhs`, returning `None`
3107 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
3108 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
3110 #[stable(feature = "rust1", since = "1.0.0")]
3111 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3112 #[must_use = "this returns the result of the operation, \
3113 without modifying the original"]
3115 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
3118 // SAFETY: div by zero has been checked above and unsigned types have no other
3119 // failure modes for division
3120 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
3126 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
3134 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
3135 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
3137 #[stable(feature = "euclidean_division", since = "1.38.0")]
3138 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3139 #[must_use = "this returns the result of the operation, \
3140 without modifying the original"]
3142 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
3146 Some(self.div_euclid(rhs))
3153 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
3161 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
3162 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
3164 #[stable(feature = "wrapping", since = "1.7.0")]
3165 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3166 #[must_use = "this returns the result of the operation, \
3167 without modifying the original"]
3169 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
3173 // SAFETY: div by zero has been checked above and unsigned types have no other
3174 // failure modes for division
3175 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3181 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3189 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3190 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3192 #[stable(feature = "euclidean_division", since = "1.38.0")]
3193 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3194 #[must_use = "this returns the result of the operation, \
3195 without modifying the original"]
3197 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3201 Some(self.rem_euclid(rhs))
3207 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3210 Note that negating any positive integer will overflow.
3217 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3218 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3220 #[stable(feature = "wrapping", since = "1.7.0")]
3221 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3223 pub const fn checked_neg(self) -> Option<Self> {
3224 let (a, b) = self.overflowing_neg();
3225 if b {None} else {Some(a)}
3230 concat!("Checked shift left. Computes `self << rhs`, returning `None`
3231 if `rhs` is larger than or equal to the number of bits in `self`.
3238 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3239 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3241 #[stable(feature = "wrapping", since = "1.7.0")]
3242 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3243 #[must_use = "this returns the result of the operation, \
3244 without modifying the original"]
3246 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
3247 let (a, b) = self.overflowing_shl(rhs);
3248 if b {None} else {Some(a)}
3253 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3254 if `rhs` is larger than or equal to the number of bits in `self`.
3261 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3262 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3264 #[stable(feature = "wrapping", since = "1.7.0")]
3265 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3266 #[must_use = "this returns the result of the operation, \
3267 without modifying the original"]
3269 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
3270 let (a, b) = self.overflowing_shr(rhs);
3271 if b {None} else {Some(a)}
3276 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3284 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3285 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);", $EndFeature, "
3287 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3288 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3289 #[must_use = "this returns the result of the operation, \
3290 without modifying the original"]
3292 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
3293 let mut base = self;
3294 let mut acc: Self = 1;
3298 acc = try_opt!(acc.checked_mul(base));
3301 base = try_opt!(base.checked_mul(base));
3304 // Deal with the final bit of the exponent separately, since
3305 // squaring the base afterwards is not necessary and may cause a
3306 // needless overflow.
3308 acc = try_opt!(acc.checked_mul(base));
3316 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3317 the numeric bounds instead of overflowing.
3324 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3325 assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);",
3329 #[stable(feature = "rust1", since = "1.0.0")]
3330 #[must_use = "this returns the result of the operation, \
3331 without modifying the original"]
3332 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3334 pub const fn saturating_add(self, rhs: Self) -> Self {
3335 intrinsics::saturating_add(self, rhs)
3340 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3341 at the numeric bounds instead of overflowing.
3348 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3349 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3351 #[stable(feature = "rust1", since = "1.0.0")]
3352 #[must_use = "this returns the result of the operation, \
3353 without modifying the original"]
3354 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3356 pub const fn saturating_sub(self, rhs: Self) -> Self {
3357 intrinsics::saturating_sub(self, rhs)
3362 concat!("Saturating integer multiplication. Computes `self * rhs`,
3363 saturating at the numeric bounds instead of overflowing.
3371 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3372 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3373 "::MAX);", $EndFeature, "
3375 #[stable(feature = "wrapping", since = "1.7.0")]
3376 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3377 #[must_use = "this returns the result of the operation, \
3378 without modifying the original"]
3380 pub const fn saturating_mul(self, rhs: Self) -> Self {
3381 match self.checked_mul(rhs) {
3389 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3390 saturating at the numeric bounds instead of overflowing.
3398 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3399 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3402 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3403 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3404 #[must_use = "this returns the result of the operation, \
3405 without modifying the original"]
3407 pub const fn saturating_pow(self, exp: u32) -> Self {
3408 match self.checked_pow(exp) {
3416 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3417 wrapping around at the boundary of the type.
3424 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3425 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);",
3428 #[stable(feature = "rust1", since = "1.0.0")]
3429 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3430 #[must_use = "this returns the result of the operation, \
3431 without modifying the original"]
3433 pub const fn wrapping_add(self, rhs: Self) -> Self {
3434 intrinsics::wrapping_add(self, rhs)
3439 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3440 wrapping around at the boundary of the type.
3447 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3448 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);",
3451 #[stable(feature = "rust1", since = "1.0.0")]
3452 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3453 #[must_use = "this returns the result of the operation, \
3454 without modifying the original"]
3456 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3457 intrinsics::wrapping_sub(self, rhs)
3461 /// Wrapping (modular) multiplication. Computes `self *
3462 /// rhs`, wrapping around at the boundary of the type.
3468 /// Please note that this example is shared between integer types.
3469 /// Which explains why `u8` is used here.
3472 /// assert_eq!(10u8.wrapping_mul(12), 120);
3473 /// assert_eq!(25u8.wrapping_mul(12), 44);
3475 #[stable(feature = "rust1", since = "1.0.0")]
3476 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3477 #[must_use = "this returns the result of the operation, \
3478 without modifying the original"]
3480 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3481 intrinsics::wrapping_mul(self, rhs)
3485 concat!("Wrapping (modular) division. Computes `self / rhs`.
3486 Wrapped division on unsigned types is just normal division.
3487 There's no way wrapping could ever happen.
3488 This function exists, so that all operations
3489 are accounted for in the wrapping operations.
3496 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3498 #[stable(feature = "num_wrapping", since = "1.2.0")]
3499 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3500 #[must_use = "this returns the result of the operation, \
3501 without modifying the original"]
3503 pub const fn wrapping_div(self, rhs: Self) -> Self {
3509 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3510 Wrapped division on unsigned types is just normal division.
3511 There's no way wrapping could ever happen.
3512 This function exists, so that all operations
3513 are accounted for in the wrapping operations.
3514 Since, for the positive integers, all common
3515 definitions of division are equal, this
3516 is exactly equal to `self.wrapping_div(rhs)`.
3523 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3525 #[stable(feature = "euclidean_division", since = "1.38.0")]
3526 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3527 #[must_use = "this returns the result of the operation, \
3528 without modifying the original"]
3530 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
3536 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3537 Wrapped remainder calculation on unsigned types is
3538 just the regular remainder calculation.
3539 There's no way wrapping could ever happen.
3540 This function exists, so that all operations
3541 are accounted for in the wrapping operations.
3548 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3550 #[stable(feature = "num_wrapping", since = "1.2.0")]
3551 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3552 #[must_use = "this returns the result of the operation, \
3553 without modifying the original"]
3555 pub const fn wrapping_rem(self, rhs: Self) -> Self {
3561 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3562 Wrapped modulo calculation on unsigned types is
3563 just the regular remainder calculation.
3564 There's no way wrapping could ever happen.
3565 This function exists, so that all operations
3566 are accounted for in the wrapping operations.
3567 Since, for the positive integers, all common
3568 definitions of division are equal, this
3569 is exactly equal to `self.wrapping_rem(rhs)`.
3576 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3578 #[stable(feature = "euclidean_division", since = "1.38.0")]
3579 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3580 #[must_use = "this returns the result of the operation, \
3581 without modifying the original"]
3583 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3588 /// Wrapping (modular) negation. Computes `-self`,
3589 /// wrapping around at the boundary of the type.
3591 /// Since unsigned types do not have negative equivalents
3592 /// all applications of this function will wrap (except for `-0`).
3593 /// For values smaller than the corresponding signed type's maximum
3594 /// the result is the same as casting the corresponding signed value.
3595 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3596 /// `MAX` is the corresponding signed type's maximum.
3602 /// Please note that this example is shared between integer types.
3603 /// Which explains why `i8` is used here.
3606 /// assert_eq!(100i8.wrapping_neg(), -100);
3607 /// assert_eq!((-128i8).wrapping_neg(), -128);
3609 #[stable(feature = "num_wrapping", since = "1.2.0")]
3610 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3612 pub const fn wrapping_neg(self) -> Self {
3613 self.overflowing_neg().0
3617 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3618 where `mask` removes any high-order bits of `rhs` that
3619 would cause the shift to exceed the bitwidth of the type.
3621 Note that this is *not* the same as a rotate-left; the
3622 RHS of a wrapping shift-left is restricted to the range
3623 of the type, rather than the bits shifted out of the LHS
3624 being returned to the other end. The primitive integer
3625 types all implement a [`rotate_left`](#method.rotate_left) function,
3626 which may be what you want instead.
3633 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3634 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3636 #[stable(feature = "num_wrapping", since = "1.2.0")]
3637 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3638 #[must_use = "this returns the result of the operation, \
3639 without modifying the original"]
3641 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3642 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3645 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3651 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3652 where `mask` removes any high-order bits of `rhs` that
3653 would cause the shift to exceed the bitwidth of the type.
3655 Note that this is *not* the same as a rotate-right; the
3656 RHS of a wrapping shift-right is restricted to the range
3657 of the type, rather than the bits shifted out of the LHS
3658 being returned to the other end. The primitive integer
3659 types all implement a [`rotate_right`](#method.rotate_right) function,
3660 which may be what you want instead.
3667 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3668 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3670 #[stable(feature = "num_wrapping", since = "1.2.0")]
3671 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3672 #[must_use = "this returns the result of the operation, \
3673 without modifying the original"]
3675 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3676 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3679 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3685 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3686 wrapping around at the boundary of the type.
3693 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3694 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3696 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3697 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3698 #[must_use = "this returns the result of the operation, \
3699 without modifying the original"]
3701 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
3702 let mut base = self;
3703 let mut acc: Self = 1;
3707 acc = acc.wrapping_mul(base);
3710 base = base.wrapping_mul(base);
3713 // Deal with the final bit of the exponent separately, since
3714 // squaring the base afterwards is not necessary and may cause a
3715 // needless overflow.
3717 acc = acc.wrapping_mul(base);
3725 concat!("Calculates `self` + `rhs`
3727 Returns a tuple of the addition along with a boolean indicating
3728 whether an arithmetic overflow would occur. If an overflow would
3729 have occurred then the wrapped value is returned.
3737 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3738 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3740 #[stable(feature = "wrapping", since = "1.7.0")]
3741 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3742 #[must_use = "this returns the result of the operation, \
3743 without modifying the original"]
3745 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3746 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3752 concat!("Calculates `self` - `rhs`
3754 Returns a tuple of the subtraction along with a boolean indicating
3755 whether an arithmetic overflow would occur. If an overflow would
3756 have occurred then the wrapped value is returned.
3764 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3765 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3768 #[stable(feature = "wrapping", since = "1.7.0")]
3769 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3770 #[must_use = "this returns the result of the operation, \
3771 without modifying the original"]
3773 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3774 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3779 /// Calculates the multiplication of `self` and `rhs`.
3781 /// Returns a tuple of the multiplication along with a boolean
3782 /// indicating whether an arithmetic overflow would occur. If an
3783 /// overflow would have occurred then the wrapped value is returned.
3789 /// Please note that this example is shared between integer types.
3790 /// Which explains why `u32` is used here.
3793 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3794 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3796 #[stable(feature = "wrapping", since = "1.7.0")]
3797 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3798 #[must_use = "this returns the result of the operation, \
3799 without modifying the original"]
3801 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3802 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3807 concat!("Calculates the divisor when `self` is divided by `rhs`.
3809 Returns a tuple of the divisor along with a boolean indicating
3810 whether an arithmetic overflow would occur. Note that for unsigned
3811 integers overflow never occurs, so the second value is always
3816 This function will panic if `rhs` is 0.
3823 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3826 #[stable(feature = "wrapping", since = "1.7.0")]
3827 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3828 #[must_use = "this returns the result of the operation, \
3829 without modifying the original"]
3830 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3836 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3838 Returns a tuple of the divisor along with a boolean indicating
3839 whether an arithmetic overflow would occur. Note that for unsigned
3840 integers overflow never occurs, so the second value is always
3842 Since, for the positive integers, all common
3843 definitions of division are equal, this
3844 is exactly equal to `self.overflowing_div(rhs)`.
3848 This function will panic if `rhs` is 0.
3855 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3858 #[stable(feature = "euclidean_division", since = "1.38.0")]
3859 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3860 #[must_use = "this returns the result of the operation, \
3861 without modifying the original"]
3862 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3868 concat!("Calculates the remainder when `self` is divided by `rhs`.
3870 Returns a tuple of the remainder after dividing along with a boolean
3871 indicating whether an arithmetic overflow would occur. Note that for
3872 unsigned integers overflow never occurs, so the second value is
3877 This function will panic if `rhs` is 0.
3884 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3887 #[stable(feature = "wrapping", since = "1.7.0")]
3888 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3889 #[must_use = "this returns the result of the operation, \
3890 without modifying the original"]
3891 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3897 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3899 Returns a tuple of the modulo after dividing along with a boolean
3900 indicating whether an arithmetic overflow would occur. Note that for
3901 unsigned integers overflow never occurs, so the second value is
3903 Since, for the positive integers, all common
3904 definitions of division are equal, this operation
3905 is exactly equal to `self.overflowing_rem(rhs)`.
3909 This function will panic if `rhs` is 0.
3916 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3919 #[stable(feature = "euclidean_division", since = "1.38.0")]
3920 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3921 #[must_use = "this returns the result of the operation, \
3922 without modifying the original"]
3923 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3929 concat!("Negates self in an overflowing fashion.
3931 Returns `!self + 1` using wrapping operations to return the value
3932 that represents the negation of this unsigned value. Note that for
3933 positive unsigned values overflow always occurs, but negating 0 does
3941 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3942 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3943 ", true));", $EndFeature, "
3946 #[stable(feature = "wrapping", since = "1.7.0")]
3947 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3948 pub const fn overflowing_neg(self) -> (Self, bool) {
3949 ((!self).wrapping_add(1), self != 0)
3954 concat!("Shifts self left by `rhs` bits.
3956 Returns a tuple of the shifted version of self along with a boolean
3957 indicating whether the shift value was larger than or equal to the
3958 number of bits. If the shift value is too large, then value is
3959 masked (N-1) where N is the number of bits, and this value is then
3960 used to perform the shift.
3967 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3968 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3970 #[stable(feature = "wrapping", since = "1.7.0")]
3971 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3972 #[must_use = "this returns the result of the operation, \
3973 without modifying the original"]
3975 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3976 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3981 concat!("Shifts self right by `rhs` bits.
3983 Returns a tuple of the shifted version of self along with a boolean
3984 indicating whether the shift value was larger than or equal to the
3985 number of bits. If the shift value is too large, then value is
3986 masked (N-1) where N is the number of bits, and this value is then
3987 used to perform the shift.
3994 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3995 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3997 #[stable(feature = "wrapping", since = "1.7.0")]
3998 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3999 #[must_use = "this returns the result of the operation, \
4000 without modifying the original"]
4002 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
4003 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
4008 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
4010 Returns a tuple of the exponentiation along with a bool indicating
4011 whether an overflow happened.
4018 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
4019 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
4021 #[stable(feature = "no_panic_pow", since = "1.34.0")]
4022 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4023 #[must_use = "this returns the result of the operation, \
4024 without modifying the original"]
4026 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
4027 let mut base = self;
4028 let mut acc: Self = 1;
4029 let mut overflown = false;
4030 // Scratch space for storing results of overflowing_mul.
4035 r = acc.overflowing_mul(base);
4040 r = base.overflowing_mul(base);
4045 // Deal with the final bit of the exponent separately, since
4046 // squaring the base afterwards is not necessary and may cause a
4047 // needless overflow.
4049 r = acc.overflowing_mul(base);
4059 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
4066 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
4068 #[stable(feature = "rust1", since = "1.0.0")]
4069 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4070 #[must_use = "this returns the result of the operation, \
4071 without modifying the original"]
4073 #[rustc_inherit_overflow_checks]
4074 pub const fn pow(self, mut exp: u32) -> Self {
4075 let mut base = self;
4086 // Deal with the final bit of the exponent separately, since
4087 // squaring the base afterwards is not necessary and may cause a
4088 // needless overflow.
4098 concat!("Performs Euclidean division.
4100 Since, for the positive integers, all common
4101 definitions of division are equal, this
4102 is exactly equal to `self / rhs`.
4106 This function will panic if `rhs` is 0.
4113 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
4115 #[stable(feature = "euclidean_division", since = "1.38.0")]
4116 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
4117 #[must_use = "this returns the result of the operation, \
4118 without modifying the original"]
4120 #[rustc_inherit_overflow_checks]
4121 pub const fn div_euclid(self, rhs: Self) -> Self {
4128 concat!("Calculates the least remainder of `self (mod rhs)`.
4130 Since, for the positive integers, all common
4131 definitions of division are equal, this
4132 is exactly equal to `self % rhs`.
4136 This function will panic if `rhs` is 0.
4143 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
4145 #[stable(feature = "euclidean_division", since = "1.38.0")]
4146 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
4147 #[must_use = "this returns the result of the operation, \
4148 without modifying the original"]
4150 #[rustc_inherit_overflow_checks]
4151 pub const fn rem_euclid(self, rhs: Self) -> Self {
4157 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
4164 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
4165 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
4167 #[stable(feature = "rust1", since = "1.0.0")]
4168 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
4170 pub const fn is_power_of_two(self) -> bool {
4171 self.count_ones() == 1
4175 // Returns one less than next power of two.
4176 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
4178 // 8u8.one_less_than_next_power_of_two() == 7
4179 // 6u8.one_less_than_next_power_of_two() == 7
4181 // This method cannot overflow, as in the `next_power_of_two`
4182 // overflow cases it instead ends up returning the maximum value
4183 // of the type, and can return 0 for 0.
4185 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4186 const fn one_less_than_next_power_of_two(self) -> Self {
4187 if self <= 1 { return 0; }
4190 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4191 // That means the shift is always in-bounds, and some processors
4192 // (such as intel pre-haswell) have more efficient ctlz
4193 // intrinsics when the argument is non-zero.
4194 let z = unsafe { intrinsics::ctlz_nonzero(p) };
4199 concat!("Returns the smallest power of two greater than or equal to `self`.
4201 When return value overflows (i.e., `self > (1 << (N-1))` for type
4202 `uN`), it panics in debug mode and return value is wrapped to 0 in
4203 release mode (the only situation in which method can return 0).
4210 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4211 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4213 #[stable(feature = "rust1", since = "1.0.0")]
4214 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4216 #[rustc_inherit_overflow_checks]
4217 pub const fn next_power_of_two(self) -> Self {
4218 self.one_less_than_next_power_of_two() + 1
4223 concat!("Returns the smallest power of two greater than or equal to `n`. If
4224 the next power of two is greater than the type's maximum value,
4225 `None` is returned, otherwise the power of two is wrapped in `Some`.
4232 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4233 ".checked_next_power_of_two(), Some(2));
4234 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4235 assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);",
4239 #[stable(feature = "rust1", since = "1.0.0")]
4240 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4241 pub const fn checked_next_power_of_two(self) -> Option<Self> {
4242 self.one_less_than_next_power_of_two().checked_add(1)
4247 concat!("Returns the smallest power of two greater than or equal to `n`. If
4248 the next power of two is greater than the type's maximum value,
4249 the return value is wrapped to `0`.
4256 #![feature(wrapping_next_power_of_two)]
4258 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4259 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4260 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);",
4263 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4264 reason = "needs decision on wrapping behaviour")]
4265 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4266 pub const fn wrapping_next_power_of_two(self) -> Self {
4267 self.one_less_than_next_power_of_two().wrapping_add(1)
4272 concat!("Return the memory representation of this integer as a byte array in
4273 big-endian (network) byte order.
4280 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4281 assert_eq!(bytes, ", $be_bytes, ");
4283 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4284 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4286 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4287 self.to_be().to_ne_bytes()
4292 concat!("Return the memory representation of this integer as a byte array in
4293 little-endian byte order.
4300 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4301 assert_eq!(bytes, ", $le_bytes, ");
4303 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4304 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4306 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4307 self.to_le().to_ne_bytes()
4313 Return the memory representation of this integer as a byte array in
4316 As the target platform's native endianness is used, portable code
4317 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4322 [`to_be_bytes`]: #method.to_be_bytes
4323 [`to_le_bytes`]: #method.to_le_bytes
4328 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4331 if cfg!(target_endian = \"big\") {
4338 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4339 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4340 // SAFETY: const sound because integers are plain old datatypes so we can always
4341 // transmute them to arrays of bytes
4342 #[allow_internal_unstable(const_fn_union)]
4344 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4348 bytes: [u8; mem::size_of::<$SelfT>()],
4350 // SAFETY: integers are plain old datatypes so we can always transmute them to
4352 unsafe { Bytes { val: self }.bytes }
4357 concat!("Create an integer value from its representation as a byte array in
4365 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4366 assert_eq!(value, ", $swap_op, ");
4369 When starting from a slice rather than an array, fallible conversion APIs can be used:
4372 use std::convert::TryInto;
4374 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4375 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4377 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4380 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4381 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4383 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4384 Self::from_be(Self::from_ne_bytes(bytes))
4390 Create an integer value from its representation as a byte array in
4398 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4399 assert_eq!(value, ", $swap_op, ");
4402 When starting from a slice rather than an array, fallible conversion APIs can be used:
4405 use std::convert::TryInto;
4407 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4408 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4410 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4413 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4414 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4416 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4417 Self::from_le(Self::from_ne_bytes(bytes))
4422 concat!("Create an integer value from its memory representation as a byte
4423 array in native endianness.
4425 As the target platform's native endianness is used, portable code
4426 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4427 appropriate instead.
4429 [`from_be_bytes`]: #method.from_be_bytes
4430 [`from_le_bytes`]: #method.from_le_bytes
4437 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4442 assert_eq!(value, ", $swap_op, ");
4445 When starting from a slice rather than an array, fallible conversion APIs can be used:
4448 use std::convert::TryInto;
4450 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4451 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4453 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4456 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4457 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4458 // SAFETY: const sound because integers are plain old datatypes so we can always
4459 // transmute to them
4460 #[allow_internal_unstable(const_fn_union)]
4462 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4466 bytes: [u8; mem::size_of::<$SelfT>()],
4468 // SAFETY: integers are plain old datatypes so we can always transmute to them
4469 unsafe { Bytes { bytes }.val }
4474 concat!("**This method is soft-deprecated.**
4476 Although using it won’t cause compilation warning,
4477 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
4479 Returns the smallest value that can be represented by this integer type."),
4480 #[stable(feature = "rust1", since = "1.0.0")]
4483 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4484 pub const fn min_value() -> Self { Self::MIN }
4488 concat!("**This method is soft-deprecated.**
4490 Although using it won’t cause compilation warning,
4491 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
4493 Returns the largest value that can be represented by this integer type."),
4494 #[stable(feature = "rust1", since = "1.0.0")]
4497 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4498 pub const fn max_value() -> Self { Self::MAX }
4505 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4508 /// Checks if the value is within the ASCII range.
4513 /// let ascii = 97u8;
4514 /// let non_ascii = 150u8;
4516 /// assert!(ascii.is_ascii());
4517 /// assert!(!non_ascii.is_ascii());
4519 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4520 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.43.0")]
4522 pub const fn is_ascii(&self) -> bool {
4526 /// Makes a copy of the value in its ASCII upper case equivalent.
4528 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4529 /// but non-ASCII letters are unchanged.
4531 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4536 /// let lowercase_a = 97u8;
4538 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4541 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4542 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4544 pub fn to_ascii_uppercase(&self) -> u8 {
4545 // Unset the fifth bit if this is a lowercase letter
4546 *self & !((self.is_ascii_lowercase() as u8) << 5)
4549 /// Makes a copy of the value in its ASCII lower case equivalent.
4551 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4552 /// but non-ASCII letters are unchanged.
4554 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4559 /// let uppercase_a = 65u8;
4561 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4564 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4565 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4567 pub fn to_ascii_lowercase(&self) -> u8 {
4568 // Set the fifth bit if this is an uppercase letter
4569 *self | ((self.is_ascii_uppercase() as u8) << 5)
4572 /// Checks that two values are an ASCII case-insensitive match.
4574 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4579 /// let lowercase_a = 97u8;
4580 /// let uppercase_a = 65u8;
4582 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4584 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4586 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4587 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4590 /// Converts this value to its ASCII upper case equivalent in-place.
4592 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4593 /// but non-ASCII letters are unchanged.
4595 /// To return a new uppercased value without modifying the existing one, use
4596 /// [`to_ascii_uppercase`].
4601 /// let mut byte = b'a';
4603 /// byte.make_ascii_uppercase();
4605 /// assert_eq!(b'A', byte);
4608 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4609 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4611 pub fn make_ascii_uppercase(&mut self) {
4612 *self = self.to_ascii_uppercase();
4615 /// Converts this value to its ASCII lower case equivalent in-place.
4617 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4618 /// but non-ASCII letters are unchanged.
4620 /// To return a new lowercased value without modifying the existing one, use
4621 /// [`to_ascii_lowercase`].
4626 /// let mut byte = b'A';
4628 /// byte.make_ascii_lowercase();
4630 /// assert_eq!(b'a', byte);
4633 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4634 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4636 pub fn make_ascii_lowercase(&mut self) {
4637 *self = self.to_ascii_lowercase();
4640 /// Checks if the value is an ASCII alphabetic character:
4642 /// - U+0041 'A' ..= U+005A 'Z', or
4643 /// - U+0061 'a' ..= U+007A 'z'.
4648 /// let uppercase_a = b'A';
4649 /// let uppercase_g = b'G';
4652 /// let zero = b'0';
4653 /// let percent = b'%';
4654 /// let space = b' ';
4656 /// let esc = 0x1b_u8;
4658 /// assert!(uppercase_a.is_ascii_alphabetic());
4659 /// assert!(uppercase_g.is_ascii_alphabetic());
4660 /// assert!(a.is_ascii_alphabetic());
4661 /// assert!(g.is_ascii_alphabetic());
4662 /// assert!(!zero.is_ascii_alphabetic());
4663 /// assert!(!percent.is_ascii_alphabetic());
4664 /// assert!(!space.is_ascii_alphabetic());
4665 /// assert!(!lf.is_ascii_alphabetic());
4666 /// assert!(!esc.is_ascii_alphabetic());
4668 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4669 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4671 pub const fn is_ascii_alphabetic(&self) -> bool {
4672 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
4675 /// Checks if the value is an ASCII uppercase character:
4676 /// U+0041 'A' ..= U+005A 'Z'.
4681 /// let uppercase_a = b'A';
4682 /// let uppercase_g = b'G';
4685 /// let zero = b'0';
4686 /// let percent = b'%';
4687 /// let space = b' ';
4689 /// let esc = 0x1b_u8;
4691 /// assert!(uppercase_a.is_ascii_uppercase());
4692 /// assert!(uppercase_g.is_ascii_uppercase());
4693 /// assert!(!a.is_ascii_uppercase());
4694 /// assert!(!g.is_ascii_uppercase());
4695 /// assert!(!zero.is_ascii_uppercase());
4696 /// assert!(!percent.is_ascii_uppercase());
4697 /// assert!(!space.is_ascii_uppercase());
4698 /// assert!(!lf.is_ascii_uppercase());
4699 /// assert!(!esc.is_ascii_uppercase());
4701 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4702 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4704 pub const fn is_ascii_uppercase(&self) -> bool {
4705 matches!(*self, b'A'..=b'Z')
4708 /// Checks if the value is an ASCII lowercase character:
4709 /// U+0061 'a' ..= U+007A 'z'.
4714 /// let uppercase_a = b'A';
4715 /// let uppercase_g = b'G';
4718 /// let zero = b'0';
4719 /// let percent = b'%';
4720 /// let space = b' ';
4722 /// let esc = 0x1b_u8;
4724 /// assert!(!uppercase_a.is_ascii_lowercase());
4725 /// assert!(!uppercase_g.is_ascii_lowercase());
4726 /// assert!(a.is_ascii_lowercase());
4727 /// assert!(g.is_ascii_lowercase());
4728 /// assert!(!zero.is_ascii_lowercase());
4729 /// assert!(!percent.is_ascii_lowercase());
4730 /// assert!(!space.is_ascii_lowercase());
4731 /// assert!(!lf.is_ascii_lowercase());
4732 /// assert!(!esc.is_ascii_lowercase());
4734 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4735 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4737 pub const fn is_ascii_lowercase(&self) -> bool {
4738 matches!(*self, b'a'..=b'z')
4741 /// Checks if the value is an ASCII alphanumeric character:
4743 /// - U+0041 'A' ..= U+005A 'Z', or
4744 /// - U+0061 'a' ..= U+007A 'z', or
4745 /// - U+0030 '0' ..= U+0039 '9'.
4750 /// let uppercase_a = b'A';
4751 /// let uppercase_g = b'G';
4754 /// let zero = b'0';
4755 /// let percent = b'%';
4756 /// let space = b' ';
4758 /// let esc = 0x1b_u8;
4760 /// assert!(uppercase_a.is_ascii_alphanumeric());
4761 /// assert!(uppercase_g.is_ascii_alphanumeric());
4762 /// assert!(a.is_ascii_alphanumeric());
4763 /// assert!(g.is_ascii_alphanumeric());
4764 /// assert!(zero.is_ascii_alphanumeric());
4765 /// assert!(!percent.is_ascii_alphanumeric());
4766 /// assert!(!space.is_ascii_alphanumeric());
4767 /// assert!(!lf.is_ascii_alphanumeric());
4768 /// assert!(!esc.is_ascii_alphanumeric());
4770 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4771 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4773 pub const fn is_ascii_alphanumeric(&self) -> bool {
4774 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
4777 /// Checks if the value is an ASCII decimal digit:
4778 /// U+0030 '0' ..= U+0039 '9'.
4783 /// let uppercase_a = b'A';
4784 /// let uppercase_g = b'G';
4787 /// let zero = b'0';
4788 /// let percent = b'%';
4789 /// let space = b' ';
4791 /// let esc = 0x1b_u8;
4793 /// assert!(!uppercase_a.is_ascii_digit());
4794 /// assert!(!uppercase_g.is_ascii_digit());
4795 /// assert!(!a.is_ascii_digit());
4796 /// assert!(!g.is_ascii_digit());
4797 /// assert!(zero.is_ascii_digit());
4798 /// assert!(!percent.is_ascii_digit());
4799 /// assert!(!space.is_ascii_digit());
4800 /// assert!(!lf.is_ascii_digit());
4801 /// assert!(!esc.is_ascii_digit());
4803 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4804 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4806 pub const fn is_ascii_digit(&self) -> bool {
4807 matches!(*self, b'0'..=b'9')
4810 /// Checks if the value is an ASCII hexadecimal digit:
4812 /// - U+0030 '0' ..= U+0039 '9', or
4813 /// - U+0041 'A' ..= U+0046 'F', or
4814 /// - U+0061 'a' ..= U+0066 'f'.
4819 /// let uppercase_a = b'A';
4820 /// let uppercase_g = b'G';
4823 /// let zero = b'0';
4824 /// let percent = b'%';
4825 /// let space = b' ';
4827 /// let esc = 0x1b_u8;
4829 /// assert!(uppercase_a.is_ascii_hexdigit());
4830 /// assert!(!uppercase_g.is_ascii_hexdigit());
4831 /// assert!(a.is_ascii_hexdigit());
4832 /// assert!(!g.is_ascii_hexdigit());
4833 /// assert!(zero.is_ascii_hexdigit());
4834 /// assert!(!percent.is_ascii_hexdigit());
4835 /// assert!(!space.is_ascii_hexdigit());
4836 /// assert!(!lf.is_ascii_hexdigit());
4837 /// assert!(!esc.is_ascii_hexdigit());
4839 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4840 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4842 pub const fn is_ascii_hexdigit(&self) -> bool {
4843 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
4846 /// Checks if the value is an ASCII punctuation character:
4848 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4849 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4850 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4851 /// - U+007B ..= U+007E `{ | } ~`
4856 /// let uppercase_a = b'A';
4857 /// let uppercase_g = b'G';
4860 /// let zero = b'0';
4861 /// let percent = b'%';
4862 /// let space = b' ';
4864 /// let esc = 0x1b_u8;
4866 /// assert!(!uppercase_a.is_ascii_punctuation());
4867 /// assert!(!uppercase_g.is_ascii_punctuation());
4868 /// assert!(!a.is_ascii_punctuation());
4869 /// assert!(!g.is_ascii_punctuation());
4870 /// assert!(!zero.is_ascii_punctuation());
4871 /// assert!(percent.is_ascii_punctuation());
4872 /// assert!(!space.is_ascii_punctuation());
4873 /// assert!(!lf.is_ascii_punctuation());
4874 /// assert!(!esc.is_ascii_punctuation());
4876 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4877 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4879 pub const fn is_ascii_punctuation(&self) -> bool {
4880 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
4883 /// Checks if the value is an ASCII graphic character:
4884 /// U+0021 '!' ..= U+007E '~'.
4889 /// let uppercase_a = b'A';
4890 /// let uppercase_g = b'G';
4893 /// let zero = b'0';
4894 /// let percent = b'%';
4895 /// let space = b' ';
4897 /// let esc = 0x1b_u8;
4899 /// assert!(uppercase_a.is_ascii_graphic());
4900 /// assert!(uppercase_g.is_ascii_graphic());
4901 /// assert!(a.is_ascii_graphic());
4902 /// assert!(g.is_ascii_graphic());
4903 /// assert!(zero.is_ascii_graphic());
4904 /// assert!(percent.is_ascii_graphic());
4905 /// assert!(!space.is_ascii_graphic());
4906 /// assert!(!lf.is_ascii_graphic());
4907 /// assert!(!esc.is_ascii_graphic());
4909 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4910 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4912 pub const fn is_ascii_graphic(&self) -> bool {
4913 matches!(*self, b'!'..=b'~')
4916 /// Checks if the value is an ASCII whitespace character:
4917 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4918 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4920 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4921 /// whitespace][infra-aw]. There are several other definitions in
4922 /// wide use. For instance, [the POSIX locale][pct] includes
4923 /// U+000B VERTICAL TAB as well as all the above characters,
4924 /// but—from the very same specification—[the default rule for
4925 /// "field splitting" in the Bourne shell][bfs] considers *only*
4926 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4928 /// If you are writing a program that will process an existing
4929 /// file format, check what that format's definition of whitespace is
4930 /// before using this function.
4932 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4933 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4934 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4939 /// let uppercase_a = b'A';
4940 /// let uppercase_g = b'G';
4943 /// let zero = b'0';
4944 /// let percent = b'%';
4945 /// let space = b' ';
4947 /// let esc = 0x1b_u8;
4949 /// assert!(!uppercase_a.is_ascii_whitespace());
4950 /// assert!(!uppercase_g.is_ascii_whitespace());
4951 /// assert!(!a.is_ascii_whitespace());
4952 /// assert!(!g.is_ascii_whitespace());
4953 /// assert!(!zero.is_ascii_whitespace());
4954 /// assert!(!percent.is_ascii_whitespace());
4955 /// assert!(space.is_ascii_whitespace());
4956 /// assert!(lf.is_ascii_whitespace());
4957 /// assert!(!esc.is_ascii_whitespace());
4959 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4960 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4962 pub const fn is_ascii_whitespace(&self) -> bool {
4963 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
4966 /// Checks if the value is an ASCII control character:
4967 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4968 /// Note that most ASCII whitespace characters are control
4969 /// characters, but SPACE is not.
4974 /// let uppercase_a = b'A';
4975 /// let uppercase_g = b'G';
4978 /// let zero = b'0';
4979 /// let percent = b'%';
4980 /// let space = b' ';
4982 /// let esc = 0x1b_u8;
4984 /// assert!(!uppercase_a.is_ascii_control());
4985 /// assert!(!uppercase_g.is_ascii_control());
4986 /// assert!(!a.is_ascii_control());
4987 /// assert!(!g.is_ascii_control());
4988 /// assert!(!zero.is_ascii_control());
4989 /// assert!(!percent.is_ascii_control());
4990 /// assert!(!space.is_ascii_control());
4991 /// assert!(lf.is_ascii_control());
4992 /// assert!(esc.is_ascii_control());
4994 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4995 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4997 pub const fn is_ascii_control(&self) -> bool {
4998 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
5004 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
5005 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
5010 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
5011 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
5016 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
5017 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
5018 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
5019 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
5025 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
5026 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
5027 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
5028 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
5029 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
5030 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
5031 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
5035 #[cfg(target_pointer_width = "16")]
5038 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
5039 "[0x34, 0x12]", "[0x12, 0x34]",
5040 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
5042 #[cfg(target_pointer_width = "32")]
5045 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
5046 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
5047 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
5050 #[cfg(target_pointer_width = "64")]
5053 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
5054 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
5055 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
5056 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
5057 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
5060 /// A classification of floating point numbers.
5062 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
5063 /// their documentation for more.
5065 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
5066 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
5071 /// use std::num::FpCategory;
5073 /// let num = 12.4_f32;
5074 /// let inf = f32::INFINITY;
5075 /// let zero = 0f32;
5076 /// let sub: f32 = 1.1754942e-38;
5077 /// let nan = f32::NAN;
5079 /// assert_eq!(num.classify(), FpCategory::Normal);
5080 /// assert_eq!(inf.classify(), FpCategory::Infinite);
5081 /// assert_eq!(zero.classify(), FpCategory::Zero);
5082 /// assert_eq!(nan.classify(), FpCategory::Nan);
5083 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
5085 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
5086 #[stable(feature = "rust1", since = "1.0.0")]
5087 pub enum FpCategory {
5088 /// "Not a Number", often obtained by dividing by zero.
5089 #[stable(feature = "rust1", since = "1.0.0")]
5092 /// Positive or negative infinity.
5093 #[stable(feature = "rust1", since = "1.0.0")]
5096 /// Positive or negative zero.
5097 #[stable(feature = "rust1", since = "1.0.0")]
5100 /// De-normalized floating point representation (less precise than `Normal`).
5101 #[stable(feature = "rust1", since = "1.0.0")]
5104 /// A regular floating point number.
5105 #[stable(feature = "rust1", since = "1.0.0")]
5109 macro_rules! from_str_radix_int_impl {
5111 #[stable(feature = "rust1", since = "1.0.0")]
5112 impl FromStr for $t {
5113 type Err = ParseIntError;
5114 fn from_str(src: &str) -> Result<Self, ParseIntError> {
5115 from_str_radix(src, 10)
5120 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
5122 /// The error type returned when a checked integral type conversion fails.
5123 #[stable(feature = "try_from", since = "1.34.0")]
5124 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
5125 pub struct TryFromIntError(pub(crate) ());
5127 impl TryFromIntError {
5129 feature = "int_error_internals",
5130 reason = "available through Error trait and this method should \
5131 not be exposed publicly",
5135 pub fn __description(&self) -> &str {
5136 "out of range integral type conversion attempted"
5140 #[stable(feature = "try_from", since = "1.34.0")]
5141 impl fmt::Display for TryFromIntError {
5142 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
5143 self.__description().fmt(fmt)
5147 #[stable(feature = "try_from", since = "1.34.0")]
5148 impl From<Infallible> for TryFromIntError {
5149 fn from(x: Infallible) -> TryFromIntError {
5154 #[unstable(feature = "never_type", issue = "35121")]
5155 impl From<!> for TryFromIntError {
5156 fn from(never: !) -> TryFromIntError {
5157 // Match rather than coerce to make sure that code like
5158 // `From<Infallible> for TryFromIntError` above will keep working
5159 // when `Infallible` becomes an alias to `!`.
5165 trait FromStrRadixHelper: PartialOrd + Copy {
5166 fn min_value() -> Self;
5167 fn max_value() -> Self;
5168 fn from_u32(u: u32) -> Self;
5169 fn checked_mul(&self, other: u32) -> Option<Self>;
5170 fn checked_sub(&self, other: u32) -> Option<Self>;
5171 fn checked_add(&self, other: u32) -> Option<Self>;
5175 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
5177 fn min_value() -> Self { Self::MIN }
5179 fn max_value() -> Self { Self::MAX }
5181 fn from_u32(u: u32) -> Self { u as Self }
5183 fn checked_mul(&self, other: u32) -> Option<Self> {
5184 Self::checked_mul(*self, other as Self)
5187 fn checked_sub(&self, other: u32) -> Option<Self> {
5188 Self::checked_sub(*self, other as Self)
5191 fn checked_add(&self, other: u32) -> Option<Self> {
5192 Self::checked_add(*self, other as Self)
5196 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5198 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5199 use self::IntErrorKind::*;
5200 use self::ParseIntError as PIE;
5203 radix >= 2 && radix <= 36,
5204 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5209 return Err(PIE { kind: Empty });
5212 let is_signed_ty = T::from_u32(0) > T::min_value();
5214 // all valid digits are ascii, so we will just iterate over the utf8 bytes
5215 // and cast them to chars. .to_digit() will safely return None for anything
5216 // other than a valid ascii digit for the given radix, including the first-byte
5217 // of multi-byte sequences
5218 let src = src.as_bytes();
5220 let (is_positive, digits) = match src[0] {
5221 b'+' => (true, &src[1..]),
5222 b'-' if is_signed_ty => (false, &src[1..]),
5226 if digits.is_empty() {
5227 return Err(PIE { kind: Empty });
5230 let mut result = T::from_u32(0);
5232 // The number is positive
5234 let x = match (c as char).to_digit(radix) {
5236 None => return Err(PIE { kind: InvalidDigit }),
5238 result = match result.checked_mul(radix) {
5239 Some(result) => result,
5240 None => return Err(PIE { kind: Overflow }),
5242 result = match result.checked_add(x) {
5243 Some(result) => result,
5244 None => return Err(PIE { kind: Overflow }),
5248 // The number is negative
5250 let x = match (c as char).to_digit(radix) {
5252 None => return Err(PIE { kind: InvalidDigit }),
5254 result = match result.checked_mul(radix) {
5255 Some(result) => result,
5256 None => return Err(PIE { kind: Underflow }),
5258 result = match result.checked_sub(x) {
5259 Some(result) => result,
5260 None => return Err(PIE { kind: Underflow }),
5267 /// An error which can be returned when parsing an integer.
5269 /// This error is used as the error type for the `from_str_radix()` functions
5270 /// on the primitive integer types, such as [`i8::from_str_radix`].
5272 /// # Potential causes
5274 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5275 /// in the string e.g., when it is obtained from the standard input.
5276 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5278 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5279 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5280 #[derive(Debug, Clone, PartialEq, Eq)]
5281 #[stable(feature = "rust1", since = "1.0.0")]
5282 pub struct ParseIntError {
5286 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5288 feature = "int_error_matching",
5289 reason = "it can be useful to match errors when making error messages \
5290 for integer parsing",
5293 #[derive(Debug, Clone, PartialEq, Eq)]
5295 pub enum IntErrorKind {
5296 /// Value being parsed is empty.
5298 /// Among other causes, this variant will be constructed when parsing an empty string.
5300 /// Contains an invalid digit.
5302 /// Among other causes, this variant will be constructed when parsing a string that
5303 /// contains a letter.
5305 /// Integer is too large to store in target integer type.
5307 /// Integer is too small to store in target integer type.
5311 /// This variant will be emitted when the parsing string has a value of zero, which
5312 /// would be illegal for non-zero types.
5316 impl ParseIntError {
5317 /// Outputs the detailed cause of parsing an integer failing.
5319 feature = "int_error_matching",
5320 reason = "it can be useful to match errors when making error messages \
5321 for integer parsing",
5324 pub fn kind(&self) -> &IntErrorKind {
5328 feature = "int_error_internals",
5329 reason = "available through Error trait and this method should \
5330 not be exposed publicly",
5334 pub fn __description(&self) -> &str {
5336 IntErrorKind::Empty => "cannot parse integer from empty string",
5337 IntErrorKind::InvalidDigit => "invalid digit found in string",
5338 IntErrorKind::Overflow => "number too large to fit in target type",
5339 IntErrorKind::Underflow => "number too small to fit in target type",
5340 IntErrorKind::Zero => "number would be zero for non-zero type",
5345 #[stable(feature = "rust1", since = "1.0.0")]
5346 impl fmt::Display for ParseIntError {
5347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5348 self.__description().fmt(f)
5352 #[stable(feature = "rust1", since = "1.0.0")]
5353 pub use crate::num::dec2flt::ParseFloatError;