1 // ignore-tidy-filelength
3 //! Numeric traits and functions for the built-in numeric types.
5 #![stable(feature = "rust1", since = "1.0.0")]
7 use crate::convert::Infallible;
11 use crate::ops::{BitOr, BitOrAssign};
12 use crate::str::FromStr;
14 // Used because the `?` operator is not allowed in a const context.
15 macro_rules! try_opt {
24 macro_rules! impl_nonzero_fmt {
25 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
28 impl fmt::$Trait for $Ty {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 macro_rules! doc_comment {
39 ($x:expr, $($tt:tt)*) => {
45 macro_rules! nonzero_integers {
46 ( $( #[$stability: meta] $Ty: ident($Int: ty); )+ ) => {
49 concat!("An integer that is known not to equal zero.
51 This enables some memory layout optimization.
52 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
55 use std::mem::size_of;
56 assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
60 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
62 #[rustc_layout_scalar_valid_range_start(1)]
63 #[rustc_nonnull_optimization_guaranteed]
68 /// Creates a non-zero without checking the value.
72 /// The value must not be zero.
74 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
76 pub const unsafe fn new_unchecked(n: $Int) -> Self {
80 /// Creates a non-zero if the given value is not zero.
82 #[rustc_const_unstable(feature = "const_nonzero_int_methods", issue = "53718")]
84 pub const fn new(n: $Int) -> Option<Self> {
86 // SAFETY: we just checked that there's no `0`
87 Some(unsafe { Self(n) })
93 /// Returns the value as a primitive type.
96 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
97 pub const fn get(self) -> $Int {
103 #[stable(feature = "from_nonzero", since = "1.31.0")]
104 impl From<$Ty> for $Int {
107 "Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`"),
108 fn from(nonzero: $Ty) -> Self {
114 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
118 fn bitor(self, rhs: Self) -> Self::Output {
119 // Safety: since `self` and `rhs` are both nonzero, the
120 // result of the bitwise-or will be nonzero.
121 unsafe { $Ty::new_unchecked(self.get() | rhs.get()) }
125 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
126 impl BitOr<$Int> for $Ty {
129 fn bitor(self, rhs: $Int) -> Self::Output {
130 // Safety: since `self` is nonzero, the result of the
131 // bitwise-or will be nonzero regardless of the value of
133 unsafe { $Ty::new_unchecked(self.get() | rhs) }
137 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
138 impl BitOr<$Ty> for $Int {
141 fn bitor(self, rhs: $Ty) -> Self::Output {
142 // Safety: since `rhs` is nonzero, the result of the
143 // bitwise-or will be nonzero regardless of the value of
145 unsafe { $Ty::new_unchecked(self | rhs.get()) }
149 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
150 impl BitOrAssign for $Ty {
152 fn bitor_assign(&mut self, rhs: Self) {
157 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
158 impl BitOrAssign<$Int> for $Ty {
160 fn bitor_assign(&mut self, rhs: $Int) {
166 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
173 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
174 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
175 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
176 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
177 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
178 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
179 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
180 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
181 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
182 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
183 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
184 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
187 macro_rules! from_str_radix_nzint_impl {
189 #[stable(feature = "nonzero_parse", since = "1.35.0")]
190 impl FromStr for $t {
191 type Err = ParseIntError;
192 fn from_str(src: &str) -> Result<Self, Self::Err> {
193 Self::new(from_str_radix(src, 10)?)
194 .ok_or(ParseIntError {
195 kind: IntErrorKind::Zero
202 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
203 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
205 /// Provides intentionally-wrapped arithmetic on `T`.
207 /// Operations like `+` on `u32` values are intended to never overflow,
208 /// and in some debug configurations overflow is detected and results
209 /// in a panic. While most arithmetic falls into this category, some
210 /// code explicitly expects and relies upon modular arithmetic (e.g.,
213 /// Wrapping arithmetic can be achieved either through methods like
214 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
215 /// all standard arithmetic operations on the underlying value are
216 /// intended to have wrapping semantics.
218 /// The underlying value can be retrieved through the `.0` index of the
219 /// `Wrapping` tuple.
224 /// use std::num::Wrapping;
226 /// let zero = Wrapping(0u32);
227 /// let one = Wrapping(1u32);
229 /// assert_eq!(u32::MAX, (zero - one).0);
231 #[stable(feature = "rust1", since = "1.0.0")]
232 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
234 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
236 #[stable(feature = "rust1", since = "1.0.0")]
237 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243 #[stable(feature = "wrapping_display", since = "1.10.0")]
244 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
245 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
251 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
258 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
265 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
272 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
273 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278 // All these modules are technically private and only exposed for coretests:
286 macro_rules! usize_isize_to_xe_bytes_doc {
290 **Note**: This function returns an array of length 2, 4 or 8 bytes
291 depending on the target pointer size.
297 macro_rules! usize_isize_from_xe_bytes_doc {
301 **Note**: This function takes an array of length 2, 4 or 8 bytes
302 depending on the target pointer size.
308 macro_rules! int_impl {
309 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
310 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
311 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
312 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
314 concat!("The smallest value that can be represented by this integer type.
321 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, ", stringify!($Min), ");",
324 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
325 pub const MIN: Self = !0 ^ ((!0 as $UnsignedT) >> 1) as Self;
329 concat!("The largest value that can be represented by this integer type.
336 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");",
339 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
340 pub const MAX: Self = !Self::MIN;
344 concat!("Converts a string slice in a given base to an integer.
346 The string is expected to be an optional `+` or `-` sign followed by digits.
347 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
348 depending on `radix`:
356 This function panics if `radix` is not in the range from 2 to 36.
363 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
366 #[stable(feature = "rust1", since = "1.0.0")]
367 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
368 from_str_radix(src, radix)
373 concat!("Returns the number of ones in the binary representation of `self`.
380 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
382 assert_eq!(n.count_ones(), 1);",
386 #[stable(feature = "rust1", since = "1.0.0")]
387 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
389 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
393 concat!("Returns the number of zeros in the binary representation of `self`.
400 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 1);", $EndFeature, "
402 #[stable(feature = "rust1", since = "1.0.0")]
403 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
405 pub const fn count_zeros(self) -> u32 {
411 concat!("Returns the number of leading zeros in the binary representation of `self`.
418 ", $Feature, "let n = -1", stringify!($SelfT), ";
420 assert_eq!(n.leading_zeros(), 0);",
423 #[stable(feature = "rust1", since = "1.0.0")]
424 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
426 pub const fn leading_zeros(self) -> u32 {
427 (self as $UnsignedT).leading_zeros()
432 concat!("Returns the number of trailing zeros in the binary representation of `self`.
439 ", $Feature, "let n = -4", stringify!($SelfT), ";
441 assert_eq!(n.trailing_zeros(), 2);",
444 #[stable(feature = "rust1", since = "1.0.0")]
445 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
447 pub const fn trailing_zeros(self) -> u32 {
448 (self as $UnsignedT).trailing_zeros()
453 concat!("Returns the number of leading ones in the binary representation of `self`.
460 ", $Feature, "#![feature(leading_trailing_ones)]
461 let n = -1", stringify!($SelfT), ";
463 assert_eq!(n.leading_ones(), ", stringify!($BITS), ");",
466 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
468 pub const fn leading_ones(self) -> u32 {
469 (self as $UnsignedT).leading_ones()
474 concat!("Returns the number of trailing ones in the binary representation of `self`.
481 ", $Feature, "#![feature(leading_trailing_ones)]
482 let n = 3", stringify!($SelfT), ";
484 assert_eq!(n.trailing_ones(), 2);",
487 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
489 pub const fn trailing_ones(self) -> u32 {
490 (self as $UnsignedT).trailing_ones()
495 concat!("Shifts the bits to the left by a specified amount, `n`,
496 wrapping the truncated bits to the end of the resulting integer.
498 Please note this isn't the same operation as the `<<` shifting operator!
505 let n = ", $rot_op, stringify!($SelfT), ";
506 let m = ", $rot_result, ";
508 assert_eq!(n.rotate_left(", $rot, "), m);
510 #[stable(feature = "rust1", since = "1.0.0")]
511 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
512 #[must_use = "this returns the result of the operation, \
513 without modifying the original"]
515 pub const fn rotate_left(self, n: u32) -> Self {
516 (self as $UnsignedT).rotate_left(n) as Self
521 concat!("Shifts the bits to the right by a specified amount, `n`,
522 wrapping the truncated bits to the beginning of the resulting
525 Please note this isn't the same operation as the `>>` shifting operator!
532 let n = ", $rot_result, stringify!($SelfT), ";
533 let m = ", $rot_op, ";
535 assert_eq!(n.rotate_right(", $rot, "), m);
537 #[stable(feature = "rust1", since = "1.0.0")]
538 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
539 #[must_use = "this returns the result of the operation, \
540 without modifying the original"]
542 pub const fn rotate_right(self, n: u32) -> Self {
543 (self as $UnsignedT).rotate_right(n) as Self
548 concat!("Reverses the byte order of the integer.
555 let n = ", $swap_op, stringify!($SelfT), ";
557 let m = n.swap_bytes();
559 assert_eq!(m, ", $swapped, ");
561 #[stable(feature = "rust1", since = "1.0.0")]
562 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
564 pub const fn swap_bytes(self) -> Self {
565 (self as $UnsignedT).swap_bytes() as Self
570 concat!("Reverses the bit pattern of the integer.
577 let n = ", $swap_op, stringify!($SelfT), ";
578 let m = n.reverse_bits();
580 assert_eq!(m, ", $reversed, ");
582 #[stable(feature = "reverse_bits", since = "1.37.0")]
583 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
586 pub const fn reverse_bits(self) -> Self {
587 (self as $UnsignedT).reverse_bits() as Self
592 concat!("Converts an integer from big endian to the target's endianness.
594 On big endian this is a no-op. On little endian the bytes are swapped.
601 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
603 if cfg!(target_endian = \"big\") {
604 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
606 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
610 #[stable(feature = "rust1", since = "1.0.0")]
611 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
613 pub const fn from_be(x: Self) -> Self {
614 #[cfg(target_endian = "big")]
618 #[cfg(not(target_endian = "big"))]
626 concat!("Converts an integer from little endian to the target's endianness.
628 On little endian this is a no-op. On big endian the bytes are swapped.
635 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
637 if cfg!(target_endian = \"little\") {
638 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
640 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
644 #[stable(feature = "rust1", since = "1.0.0")]
645 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
647 pub const fn from_le(x: Self) -> Self {
648 #[cfg(target_endian = "little")]
652 #[cfg(not(target_endian = "little"))]
660 concat!("Converts `self` to big endian from the target's endianness.
662 On big endian this is a no-op. On little endian the bytes are swapped.
669 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
671 if cfg!(target_endian = \"big\") {
672 assert_eq!(n.to_be(), n)
674 assert_eq!(n.to_be(), n.swap_bytes())
678 #[stable(feature = "rust1", since = "1.0.0")]
679 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
681 pub const fn to_be(self) -> Self { // or not to be?
682 #[cfg(target_endian = "big")]
686 #[cfg(not(target_endian = "big"))]
694 concat!("Converts `self` to little endian from the target's endianness.
696 On little endian this is a no-op. On big endian the bytes are swapped.
703 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
705 if cfg!(target_endian = \"little\") {
706 assert_eq!(n.to_le(), n)
708 assert_eq!(n.to_le(), n.swap_bytes())
712 #[stable(feature = "rust1", since = "1.0.0")]
713 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
715 pub const fn to_le(self) -> Self {
716 #[cfg(target_endian = "little")]
720 #[cfg(not(target_endian = "little"))]
728 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
729 if overflow occurred.
736 ", $Feature, "assert_eq!((", stringify!($SelfT),
737 "::MAX - 2).checked_add(1), Some(", stringify!($SelfT), "::MAX - 1));
738 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);",
741 #[stable(feature = "rust1", since = "1.0.0")]
742 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
743 #[must_use = "this returns the result of the operation, \
744 without modifying the original"]
746 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
747 let (a, b) = self.overflowing_add(rhs);
748 if b {None} else {Some(a)}
753 concat!("Unchecked integer addition. Computes `self + rhs`, assuming overflow
754 cannot occur. This results in undefined behavior when `self + rhs > ", stringify!($SelfT),
755 "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`."),
757 feature = "unchecked_math",
758 reason = "niche optimization path",
761 #[must_use = "this returns the result of the operation, \
762 without modifying the original"]
764 pub unsafe fn unchecked_add(self, rhs: Self) -> Self {
765 intrinsics::unchecked_add(self, rhs)
770 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
778 ", $Feature, "assert_eq!((", stringify!($SelfT),
779 "::MIN + 2).checked_sub(1), Some(", stringify!($SelfT), "::MIN + 1));
780 assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(3), None);",
783 #[stable(feature = "rust1", since = "1.0.0")]
784 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
785 #[must_use = "this returns the result of the operation, \
786 without modifying the original"]
788 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
789 let (a, b) = self.overflowing_sub(rhs);
790 if b {None} else {Some(a)}
795 concat!("Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
796 cannot occur. This results in undefined behavior when `self - rhs > ", stringify!($SelfT),
797 "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`."),
799 feature = "unchecked_math",
800 reason = "niche optimization path",
803 #[must_use = "this returns the result of the operation, \
804 without modifying the original"]
806 pub unsafe fn unchecked_sub(self, rhs: Self) -> Self {
807 intrinsics::unchecked_sub(self, rhs)
812 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
820 ", $Feature, "assert_eq!(", stringify!($SelfT),
821 "::MAX.checked_mul(1), Some(", stringify!($SelfT), "::MAX));
822 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);",
825 #[stable(feature = "rust1", since = "1.0.0")]
826 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
827 #[must_use = "this returns the result of the operation, \
828 without modifying the original"]
830 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
831 let (a, b) = self.overflowing_mul(rhs);
832 if b {None} else {Some(a)}
837 concat!("Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
838 cannot occur. This results in undefined behavior when `self * rhs > ", stringify!($SelfT),
839 "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`."),
841 feature = "unchecked_math",
842 reason = "niche optimization path",
845 #[must_use = "this returns the result of the operation, \
846 without modifying the original"]
848 pub unsafe fn unchecked_mul(self, rhs: Self) -> Self {
849 intrinsics::unchecked_mul(self, rhs)
854 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
855 or the division results in overflow.
862 ", $Feature, "assert_eq!((", stringify!($SelfT),
863 "::MIN + 1).checked_div(-1), Some(", stringify!($Max), "));
864 assert_eq!(", stringify!($SelfT), "::MIN.checked_div(-1), None);
865 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
868 #[stable(feature = "rust1", since = "1.0.0")]
869 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
870 #[must_use = "this returns the result of the operation, \
871 without modifying the original"]
873 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
874 if rhs == 0 || (self == Self::MIN && rhs == -1) {
877 // SAFETY: div by zero and by INT_MIN have been checked above
878 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
884 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
885 returning `None` if `rhs == 0` or the division results in overflow.
892 assert_eq!((", stringify!($SelfT),
893 "::MIN + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
894 assert_eq!(", stringify!($SelfT), "::MIN.checked_div_euclid(-1), None);
895 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
897 #[stable(feature = "euclidean_division", since = "1.38.0")]
898 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
899 #[must_use = "this returns the result of the operation, \
900 without modifying the original"]
902 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
903 if rhs == 0 || (self == Self::MIN && rhs == -1) {
906 Some(self.div_euclid(rhs))
912 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
913 `rhs == 0` or the division results in overflow.
921 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
922 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
923 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
926 #[stable(feature = "wrapping", since = "1.7.0")]
927 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
928 #[must_use = "this returns the result of the operation, \
929 without modifying the original"]
931 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
932 if rhs == 0 || (self == Self::MIN && rhs == -1) {
935 // SAFETY: div by zero and by INT_MIN have been checked above
936 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
942 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
943 if `rhs == 0` or the division results in overflow.
950 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
951 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
952 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
954 #[stable(feature = "euclidean_division", since = "1.38.0")]
955 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
956 #[must_use = "this returns the result of the operation, \
957 without modifying the original"]
959 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
960 if rhs == 0 || (self == Self::MIN && rhs == -1) {
963 Some(self.rem_euclid(rhs))
969 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
977 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
978 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
981 #[stable(feature = "wrapping", since = "1.7.0")]
982 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
984 pub const fn checked_neg(self) -> Option<Self> {
985 let (a, b) = self.overflowing_neg();
986 if b {None} else {Some(a)}
991 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
992 than or equal to the number of bits in `self`.
999 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
1000 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
1003 #[stable(feature = "wrapping", since = "1.7.0")]
1004 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
1005 #[must_use = "this returns the result of the operation, \
1006 without modifying the original"]
1008 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
1009 let (a, b) = self.overflowing_shl(rhs);
1010 if b {None} else {Some(a)}
1015 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
1016 larger than or equal to the number of bits in `self`.
1023 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
1024 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
1027 #[stable(feature = "wrapping", since = "1.7.0")]
1028 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
1029 #[must_use = "this returns the result of the operation, \
1030 without modifying the original"]
1032 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
1033 let (a, b) = self.overflowing_shr(rhs);
1034 if b {None} else {Some(a)}
1039 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
1048 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
1049 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
1052 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1053 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
1055 pub const fn checked_abs(self) -> Option<Self> {
1056 if self.is_negative() {
1065 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
1073 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
1074 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);",
1078 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1079 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1080 #[must_use = "this returns the result of the operation, \
1081 without modifying the original"]
1083 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
1084 let mut base = self;
1085 let mut acc: Self = 1;
1089 acc = try_opt!(acc.checked_mul(base));
1092 base = try_opt!(base.checked_mul(base));
1095 // Deal with the final bit of the exponent separately, since
1096 // squaring the base afterwards is not necessary and may cause a
1097 // needless overflow.
1099 acc = try_opt!(acc.checked_mul(base));
1107 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
1108 bounds instead of overflowing.
1115 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
1116 assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT),
1118 assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT),
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1125 #[must_use = "this returns the result of the operation, \
1126 without modifying the original"]
1128 pub const fn saturating_add(self, rhs: Self) -> Self {
1129 intrinsics::saturating_add(self, rhs)
1134 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
1135 numeric bounds instead of overflowing.
1142 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
1143 assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT),
1145 assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT),
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1151 #[must_use = "this returns the result of the operation, \
1152 without modifying the original"]
1154 pub const fn saturating_sub(self, rhs: Self) -> Self {
1155 intrinsics::saturating_sub(self, rhs)
1160 concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
1161 instead of overflowing.
1168 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
1169 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
1170 assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT),
1172 assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT),
1177 #[stable(feature = "saturating_neg", since = "1.45.0")]
1178 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1180 pub const fn saturating_neg(self) -> Self {
1181 intrinsics::saturating_sub(0, self)
1186 concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1187 MIN` instead of overflowing.
1194 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
1195 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
1196 assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT),
1198 assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT),
1203 #[stable(feature = "saturating_neg", since = "1.45.0")]
1204 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1206 pub const fn saturating_abs(self) -> Self {
1207 if self.is_negative() {
1208 self.saturating_neg()
1216 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1217 numeric bounds instead of overflowing.
1225 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1226 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1227 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1230 #[stable(feature = "wrapping", since = "1.7.0")]
1231 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1232 #[must_use = "this returns the result of the operation, \
1233 without modifying the original"]
1235 pub const fn saturating_mul(self, rhs: Self) -> Self {
1236 match self.checked_mul(rhs) {
1238 None => if (self < 0) == (rhs < 0) {
1248 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1249 saturating at the numeric bounds instead of overflowing.
1257 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1258 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1259 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1262 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1263 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1264 #[must_use = "this returns the result of the operation, \
1265 without modifying the original"]
1267 pub const fn saturating_pow(self, exp: u32) -> Self {
1268 match self.checked_pow(exp) {
1270 None if self < 0 && exp % 2 == 1 => Self::MIN,
1277 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1278 boundary of the type.
1285 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1286 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT),
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1292 #[must_use = "this returns the result of the operation, \
1293 without modifying the original"]
1295 pub const fn wrapping_add(self, rhs: Self) -> Self {
1296 intrinsics::wrapping_add(self, rhs)
1301 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1302 boundary of the type.
1309 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1310 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ",
1311 stringify!($SelfT), "::MAX);",
1314 #[stable(feature = "rust1", since = "1.0.0")]
1315 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1316 #[must_use = "this returns the result of the operation, \
1317 without modifying the original"]
1319 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1320 intrinsics::wrapping_sub(self, rhs)
1325 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1326 the boundary of the type.
1333 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1334 assert_eq!(11i8.wrapping_mul(12), -124);",
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1339 #[must_use = "this returns the result of the operation, \
1340 without modifying the original"]
1342 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1343 intrinsics::wrapping_mul(self, rhs)
1348 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1349 boundary of the type.
1351 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1352 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1353 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1357 This function will panic if `rhs` is 0.
1364 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1365 assert_eq!((-128i8).wrapping_div(-1), -128);",
1368 #[stable(feature = "num_wrapping", since = "1.2.0")]
1369 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1370 #[must_use = "this returns the result of the operation, \
1371 without modifying the original"]
1373 pub const fn wrapping_div(self, rhs: Self) -> Self {
1374 self.overflowing_div(rhs).0
1379 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1380 wrapping around at the boundary of the type.
1382 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1383 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1384 type. In this case, this method returns `MIN` itself.
1388 This function will panic if `rhs` is 0.
1395 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1396 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1398 #[stable(feature = "euclidean_division", since = "1.38.0")]
1399 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1400 #[must_use = "this returns the result of the operation, \
1401 without modifying the original"]
1403 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1404 self.overflowing_div_euclid(rhs).0
1409 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1410 boundary of the type.
1412 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1413 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1414 this function returns `0`.
1418 This function will panic if `rhs` is 0.
1425 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1426 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1429 #[stable(feature = "num_wrapping", since = "1.2.0")]
1430 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1431 #[must_use = "this returns the result of the operation, \
1432 without modifying the original"]
1434 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1435 self.overflowing_rem(rhs).0
1440 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1441 at the boundary of the type.
1443 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1444 for the type). In this case, this method returns 0.
1448 This function will panic if `rhs` is 0.
1455 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1456 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1458 #[stable(feature = "euclidean_division", since = "1.38.0")]
1459 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1460 #[must_use = "this returns the result of the operation, \
1461 without modifying the original"]
1463 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1464 self.overflowing_rem_euclid(rhs).0
1469 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1472 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1473 is the negative minimal value for the type); this is a positive value that is too large to represent
1474 in the type. In such a case, this function returns `MIN` itself.
1481 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1482 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT),
1486 #[stable(feature = "num_wrapping", since = "1.2.0")]
1487 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1489 pub const fn wrapping_neg(self) -> Self {
1490 self.overflowing_neg().0
1495 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1496 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1498 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1499 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1500 The primitive integer types all implement a `[`rotate_left`](#method.rotate_left) function,
1501 which may be what you want instead.
1508 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1509 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1512 #[stable(feature = "num_wrapping", since = "1.2.0")]
1513 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1514 #[must_use = "this returns the result of the operation, \
1515 without modifying the original"]
1517 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1518 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1521 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1527 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1528 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1530 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1531 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1532 end. The primitive integer types all implement a [`rotate_right`](#method.rotate_right) function,
1533 which may be what you want instead.
1540 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1541 assert_eq!((-128i16).wrapping_shr(64), -128);",
1544 #[stable(feature = "num_wrapping", since = "1.2.0")]
1545 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1546 #[must_use = "this returns the result of the operation, \
1547 without modifying the original"]
1549 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1550 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1553 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1559 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1560 the boundary of the type.
1562 The only case where such wrapping can occur is when one takes the absolute value of the negative
1563 minimal value for the type this is a positive value that is too large to represent in the type. In
1564 such a case, this function returns `MIN` itself.
1571 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1572 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1573 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT),
1575 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1578 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1579 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1580 #[allow(unused_attributes)]
1581 #[allow_internal_unstable(const_if_match)]
1583 pub const fn wrapping_abs(self) -> Self {
1584 if self.is_negative() {
1593 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1594 wrapping around at the boundary of the type.
1601 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1602 assert_eq!(3i8.wrapping_pow(5), -13);
1603 assert_eq!(3i8.wrapping_pow(6), -39);",
1606 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1607 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1608 #[must_use = "this returns the result of the operation, \
1609 without modifying the original"]
1611 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1612 let mut base = self;
1613 let mut acc: Self = 1;
1617 acc = acc.wrapping_mul(base);
1620 base = base.wrapping_mul(base);
1623 // Deal with the final bit of the exponent separately, since
1624 // squaring the base afterwards is not necessary and may cause a
1625 // needless overflow.
1627 acc = acc.wrapping_mul(base);
1635 concat!("Calculates `self` + `rhs`
1637 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1638 occur. If an overflow would have occurred then the wrapped value is returned.
1646 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1647 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1648 "::MIN, true));", $EndFeature, "
1650 #[stable(feature = "wrapping", since = "1.7.0")]
1651 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1652 #[must_use = "this returns the result of the operation, \
1653 without modifying the original"]
1655 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1656 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1662 concat!("Calculates `self` - `rhs`
1664 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1665 would occur. If an overflow would have occurred then the wrapped value is returned.
1673 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1674 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1675 "::MAX, true));", $EndFeature, "
1677 #[stable(feature = "wrapping", since = "1.7.0")]
1678 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1679 #[must_use = "this returns the result of the operation, \
1680 without modifying the original"]
1682 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1683 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1689 concat!("Calculates the multiplication of `self` and `rhs`.
1691 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1692 would occur. If an overflow would have occurred then the wrapped value is returned.
1699 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1700 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1703 #[stable(feature = "wrapping", since = "1.7.0")]
1704 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1705 #[must_use = "this returns the result of the operation, \
1706 without modifying the original"]
1708 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1709 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1715 concat!("Calculates the divisor when `self` is divided by `rhs`.
1717 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1718 occur. If an overflow would occur then self is returned.
1722 This function will panic if `rhs` is 0.
1730 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1731 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1736 #[stable(feature = "wrapping", since = "1.7.0")]
1737 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1738 #[must_use = "this returns the result of the operation, \
1739 without modifying the original"]
1740 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1741 if self == Self::MIN && rhs == -1 {
1750 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1752 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1753 occur. If an overflow would occur then `self` is returned.
1757 This function will panic if `rhs` is 0.
1764 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1765 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1769 #[stable(feature = "euclidean_division", since = "1.38.0")]
1770 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1771 #[must_use = "this returns the result of the operation, \
1772 without modifying the original"]
1773 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1774 if self == Self::MIN && rhs == -1 {
1777 (self.div_euclid(rhs), false)
1783 concat!("Calculates the remainder when `self` is divided by `rhs`.
1785 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1786 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1790 This function will panic if `rhs` is 0.
1798 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1799 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1803 #[stable(feature = "wrapping", since = "1.7.0")]
1804 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1805 #[must_use = "this returns the result of the operation, \
1806 without modifying the original"]
1807 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1808 if self == Self::MIN && rhs == -1 {
1818 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1820 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1821 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1825 This function will panic if `rhs` is 0.
1832 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1833 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1835 #[stable(feature = "euclidean_division", since = "1.38.0")]
1836 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1837 #[must_use = "this returns the result of the operation, \
1838 without modifying the original"]
1840 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1841 if self == Self::MIN && rhs == -1 {
1844 (self.rem_euclid(rhs), false)
1851 concat!("Negates self, overflowing if this is equal to the minimum value.
1853 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1854 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1855 minimum value will be returned again and `true` will be returned for an overflow happening.
1862 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1863 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1864 "::MIN, true));", $EndFeature, "
1867 #[stable(feature = "wrapping", since = "1.7.0")]
1868 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1869 #[allow(unused_attributes)]
1870 #[allow_internal_unstable(const_if_match)]
1871 pub const fn overflowing_neg(self) -> (Self, bool) {
1872 if self == Self::MIN {
1881 concat!("Shifts self left by `rhs` bits.
1883 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1884 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1885 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1892 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1893 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1896 #[stable(feature = "wrapping", since = "1.7.0")]
1897 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1898 #[must_use = "this returns the result of the operation, \
1899 without modifying the original"]
1901 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1902 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1907 concat!("Shifts self right by `rhs` bits.
1909 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1910 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1911 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1918 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1919 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1922 #[stable(feature = "wrapping", since = "1.7.0")]
1923 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1924 #[must_use = "this returns the result of the operation, \
1925 without modifying the original"]
1927 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1928 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1933 concat!("Computes the absolute value of `self`.
1935 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1936 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1937 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1938 for an overflow happening.
1945 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1946 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1947 assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT),
1951 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1952 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1954 pub const fn overflowing_abs(self) -> (Self, bool) {
1955 (self.wrapping_abs(), self == Self::MIN)
1960 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1962 Returns a tuple of the exponentiation along with a bool indicating
1963 whether an overflow happened.
1970 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1971 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1974 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1975 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1976 #[must_use = "this returns the result of the operation, \
1977 without modifying the original"]
1979 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1980 let mut base = self;
1981 let mut acc: Self = 1;
1982 let mut overflown = false;
1983 // Scratch space for storing results of overflowing_mul.
1988 r = acc.overflowing_mul(base);
1993 r = base.overflowing_mul(base);
1998 // Deal with the final bit of the exponent separately, since
1999 // squaring the base afterwards is not necessary and may cause a
2000 // needless overflow.
2002 r = acc.overflowing_mul(base);
2012 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2019 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
2021 assert_eq!(x.pow(5), 32);",
2024 #[stable(feature = "rust1", since = "1.0.0")]
2025 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
2026 #[must_use = "this returns the result of the operation, \
2027 without modifying the original"]
2029 #[rustc_inherit_overflow_checks]
2030 pub const fn pow(self, mut exp: u32) -> Self {
2031 let mut base = self;
2042 // Deal with the final bit of the exponent separately, since
2043 // squaring the base afterwards is not necessary and may cause a
2044 // needless overflow.
2054 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
2056 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
2057 with `0 <= self.rem_euclid(rhs) < rhs`.
2059 In other words, the result is `self / rhs` rounded to the integer `n`
2060 such that `self >= n * rhs`.
2061 If `self > 0`, this is equal to round towards zero (the default in Rust);
2062 if `self < 0`, this is equal to round towards +/- infinity.
2066 This function will panic if `rhs` is 0 or the division results in overflow.
2073 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2076 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
2077 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
2078 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
2079 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
2081 #[stable(feature = "euclidean_division", since = "1.38.0")]
2082 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2083 #[must_use = "this returns the result of the operation, \
2084 without modifying the original"]
2086 #[rustc_inherit_overflow_checks]
2087 pub const fn div_euclid(self, rhs: Self) -> Self {
2090 return if rhs > 0 { q - 1 } else { q + 1 }
2098 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
2100 This is done as if by the Euclidean division algorithm -- given
2101 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
2102 `0 <= r < abs(rhs)`.
2106 This function will panic if `rhs` is 0 or the division results in overflow.
2113 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2116 assert_eq!(a.rem_euclid(b), 3);
2117 assert_eq!((-a).rem_euclid(b), 1);
2118 assert_eq!(a.rem_euclid(-b), 3);
2119 assert_eq!((-a).rem_euclid(-b), 1);
2121 #[stable(feature = "euclidean_division", since = "1.38.0")]
2122 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2123 #[must_use = "this returns the result of the operation, \
2124 without modifying the original"]
2126 #[rustc_inherit_overflow_checks]
2127 pub const fn rem_euclid(self, rhs: Self) -> Self {
2142 concat!("Computes the absolute value of `self`.
2146 The absolute value of `", stringify!($SelfT), "::MIN` cannot be represented as an
2147 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
2148 code in debug mode will trigger a panic on this case and optimized code will return `",
2149 stringify!($SelfT), "::MIN` without a panic.
2156 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
2157 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
2160 #[stable(feature = "rust1", since = "1.0.0")]
2161 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2162 #[allow(unused_attributes)]
2163 #[allow_internal_unstable(const_if_match)]
2165 #[rustc_inherit_overflow_checks]
2166 pub const fn abs(self) -> Self {
2167 // Note that the #[inline] above means that the overflow
2168 // semantics of the subtraction depend on the crate we're being
2170 if self.is_negative() {
2179 concat!("Returns a number representing sign of `self`.
2181 - `0` if the number is zero
2182 - `1` if the number is positive
2183 - `-1` if the number is negative
2190 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
2191 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
2192 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
2195 #[stable(feature = "rust1", since = "1.0.0")]
2196 #[rustc_const_unstable(feature = "const_int_sign", issue = "53718")]
2198 pub const fn signum(self) -> Self {
2208 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2216 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2217 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2220 #[stable(feature = "rust1", since = "1.0.0")]
2221 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2223 pub const fn is_positive(self) -> bool { self > 0 }
2227 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2235 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2236 assert!(!10", stringify!($SelfT), ".is_negative());",
2239 #[stable(feature = "rust1", since = "1.0.0")]
2240 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2242 pub const fn is_negative(self) -> bool { self < 0 }
2246 concat!("Return the memory representation of this integer as a byte array in
2247 big-endian (network) byte order.
2254 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2255 assert_eq!(bytes, ", $be_bytes, ");
2257 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2258 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2260 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2261 self.to_be().to_ne_bytes()
2266 concat!("Return the memory representation of this integer as a byte array in
2267 little-endian byte order.
2274 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2275 assert_eq!(bytes, ", $le_bytes, ");
2277 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2278 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2280 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2281 self.to_le().to_ne_bytes()
2287 Return the memory representation of this integer as a byte array in
2290 As the target platform's native endianness is used, portable code
2291 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2296 [`to_be_bytes`]: #method.to_be_bytes
2297 [`to_le_bytes`]: #method.to_le_bytes
2302 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2305 if cfg!(target_endian = \"big\") {
2312 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2313 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2314 // SAFETY: const sound because integers are plain old datatypes so we can always
2315 // transmute them to arrays of bytes
2316 #[allow_internal_unstable(const_fn_union)]
2318 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2322 bytes: [u8; mem::size_of::<$SelfT>()],
2324 // SAFETY: integers are plain old datatypes so we can always transmute them to
2326 unsafe { Bytes { val: self }.bytes }
2331 concat!("Create an integer value from its representation as a byte array in
2339 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2340 assert_eq!(value, ", $swap_op, ");
2343 When starting from a slice rather than an array, fallible conversion APIs can be used:
2346 use std::convert::TryInto;
2348 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2349 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2351 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2354 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2355 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2357 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2358 Self::from_be(Self::from_ne_bytes(bytes))
2364 Create an integer value from its representation as a byte array in
2372 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2373 assert_eq!(value, ", $swap_op, ");
2376 When starting from a slice rather than an array, fallible conversion APIs can be used:
2379 use std::convert::TryInto;
2381 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2382 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2384 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2387 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2388 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2390 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2391 Self::from_le(Self::from_ne_bytes(bytes))
2396 concat!("Create an integer value from its memory representation as a byte
2397 array in native endianness.
2399 As the target platform's native endianness is used, portable code
2400 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2401 appropriate instead.
2403 [`from_be_bytes`]: #method.from_be_bytes
2404 [`from_le_bytes`]: #method.from_le_bytes
2411 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2416 assert_eq!(value, ", $swap_op, ");
2419 When starting from a slice rather than an array, fallible conversion APIs can be used:
2422 use std::convert::TryInto;
2424 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2425 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2427 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2430 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2431 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2432 // SAFETY: const sound because integers are plain old datatypes so we can always
2433 // transmute to them
2434 #[allow_internal_unstable(const_fn_union)]
2436 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2440 bytes: [u8; mem::size_of::<$SelfT>()],
2442 // SAFETY: integers are plain old datatypes so we can always transmute to them
2443 unsafe { Bytes { bytes }.val }
2448 concat!("**This method is soft-deprecated.**
2450 Although using it won’t cause compilation warning,
2451 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
2453 Returns the smallest value that can be represented by this integer type."),
2454 #[stable(feature = "rust1", since = "1.0.0")]
2457 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2458 pub const fn min_value() -> Self {
2464 concat!("**This method is soft-deprecated.**
2466 Although using it won’t cause compilation warning,
2467 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
2469 Returns the largest value that can be represented by this integer type."),
2470 #[stable(feature = "rust1", since = "1.0.0")]
2473 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2474 pub const fn max_value() -> Self {
2483 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2484 "[0x12]", "[0x12]", "", "" }
2489 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2490 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2495 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2496 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2497 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2502 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2503 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2504 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2505 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2510 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2511 170141183460469231731687303715884105727, "", "", 16,
2512 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2513 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2514 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2515 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2516 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2517 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2520 #[cfg(target_pointer_width = "16")]
2523 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2524 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2525 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2528 #[cfg(target_pointer_width = "32")]
2531 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2532 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2533 "[0x12, 0x34, 0x56, 0x78]",
2534 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2537 #[cfg(target_pointer_width = "64")]
2540 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2541 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2542 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2543 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2544 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2547 macro_rules! uint_impl {
2548 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2549 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2550 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2551 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2553 concat!("The smallest value that can be represented by this integer type.
2560 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, 0);", $EndFeature, "
2562 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2563 pub const MIN: Self = 0;
2567 concat!("The largest value that can be represented by this integer type.
2574 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");",
2577 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2578 pub const MAX: Self = !0;
2582 concat!("Converts a string slice in a given base to an integer.
2584 The string is expected to be an optional `+` sign
2586 Leading and trailing whitespace represent an error.
2587 Digits are a subset of these characters, depending on `radix`:
2595 This function panics if `radix` is not in the range from 2 to 36.
2602 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2605 #[stable(feature = "rust1", since = "1.0.0")]
2606 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2607 from_str_radix(src, radix)
2612 concat!("Returns the number of ones in the binary representation of `self`.
2619 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2621 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2623 #[stable(feature = "rust1", since = "1.0.0")]
2624 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2626 pub const fn count_ones(self) -> u32 {
2627 intrinsics::ctpop(self as $ActualT) as u32
2632 concat!("Returns the number of zeros in the binary representation of `self`.
2639 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);", $EndFeature, "
2641 #[stable(feature = "rust1", since = "1.0.0")]
2642 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2644 pub const fn count_zeros(self) -> u32 {
2645 (!self).count_ones()
2650 concat!("Returns the number of leading zeros in the binary representation of `self`.
2657 ", $Feature, "let n = ", stringify!($SelfT), "::MAX >> 2;
2659 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2661 #[stable(feature = "rust1", since = "1.0.0")]
2662 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2664 pub const fn leading_zeros(self) -> u32 {
2665 intrinsics::ctlz(self as $ActualT) as u32
2670 concat!("Returns the number of trailing zeros in the binary representation
2678 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2680 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2682 #[stable(feature = "rust1", since = "1.0.0")]
2683 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2685 pub const fn trailing_zeros(self) -> u32 {
2686 intrinsics::cttz(self) as u32
2691 concat!("Returns the number of leading ones in the binary representation of `self`.
2698 ", $Feature, "#![feature(leading_trailing_ones)]
2699 let n = !(", stringify!($SelfT), "::MAX >> 2);
2701 assert_eq!(n.leading_ones(), 2);", $EndFeature, "
2703 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2705 pub const fn leading_ones(self) -> u32 {
2706 (!self).leading_zeros()
2711 concat!("Returns the number of trailing ones in the binary representation
2719 ", $Feature, "#![feature(leading_trailing_ones)]
2720 let n = 0b1010111", stringify!($SelfT), ";
2722 assert_eq!(n.trailing_ones(), 3);", $EndFeature, "
2724 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2726 pub const fn trailing_ones(self) -> u32 {
2727 (!self).trailing_zeros()
2732 concat!("Shifts the bits to the left by a specified amount, `n`,
2733 wrapping the truncated bits to the end of the resulting integer.
2735 Please note this isn't the same operation as the `<<` shifting operator!
2742 let n = ", $rot_op, stringify!($SelfT), ";
2743 let m = ", $rot_result, ";
2745 assert_eq!(n.rotate_left(", $rot, "), m);
2747 #[stable(feature = "rust1", since = "1.0.0")]
2748 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2749 #[must_use = "this returns the result of the operation, \
2750 without modifying the original"]
2752 pub const fn rotate_left(self, n: u32) -> Self {
2753 intrinsics::rotate_left(self, n as $SelfT)
2758 concat!("Shifts the bits to the right by a specified amount, `n`,
2759 wrapping the truncated bits to the beginning of the resulting
2762 Please note this isn't the same operation as the `>>` shifting operator!
2769 let n = ", $rot_result, stringify!($SelfT), ";
2770 let m = ", $rot_op, ";
2772 assert_eq!(n.rotate_right(", $rot, "), m);
2774 #[stable(feature = "rust1", since = "1.0.0")]
2775 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2776 #[must_use = "this returns the result of the operation, \
2777 without modifying the original"]
2779 pub const fn rotate_right(self, n: u32) -> Self {
2780 intrinsics::rotate_right(self, n as $SelfT)
2786 Reverses the byte order of the integer.
2793 let n = ", $swap_op, stringify!($SelfT), ";
2794 let m = n.swap_bytes();
2796 assert_eq!(m, ", $swapped, ");
2798 #[stable(feature = "rust1", since = "1.0.0")]
2799 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2801 pub const fn swap_bytes(self) -> Self {
2802 intrinsics::bswap(self as $ActualT) as Self
2807 concat!("Reverses the bit pattern of the integer.
2814 let n = ", $swap_op, stringify!($SelfT), ";
2815 let m = n.reverse_bits();
2817 assert_eq!(m, ", $reversed, ");
2819 #[stable(feature = "reverse_bits", since = "1.37.0")]
2820 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2823 pub const fn reverse_bits(self) -> Self {
2824 intrinsics::bitreverse(self as $ActualT) as Self
2829 concat!("Converts an integer from big endian to the target's endianness.
2831 On big endian this is a no-op. On little endian the bytes are
2839 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2841 if cfg!(target_endian = \"big\") {
2842 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2844 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2847 #[stable(feature = "rust1", since = "1.0.0")]
2848 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2850 pub const fn from_be(x: Self) -> Self {
2851 #[cfg(target_endian = "big")]
2855 #[cfg(not(target_endian = "big"))]
2863 concat!("Converts an integer from little endian to the target's endianness.
2865 On little endian this is a no-op. On big endian the bytes are
2873 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2875 if cfg!(target_endian = \"little\") {
2876 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2878 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2881 #[stable(feature = "rust1", since = "1.0.0")]
2882 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2884 pub const fn from_le(x: Self) -> Self {
2885 #[cfg(target_endian = "little")]
2889 #[cfg(not(target_endian = "little"))]
2897 concat!("Converts `self` to big endian from the target's endianness.
2899 On big endian this is a no-op. On little endian the bytes are
2907 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2909 if cfg!(target_endian = \"big\") {
2910 assert_eq!(n.to_be(), n)
2912 assert_eq!(n.to_be(), n.swap_bytes())
2915 #[stable(feature = "rust1", since = "1.0.0")]
2916 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2918 pub const fn to_be(self) -> Self { // or not to be?
2919 #[cfg(target_endian = "big")]
2923 #[cfg(not(target_endian = "big"))]
2931 concat!("Converts `self` to little endian from the target's endianness.
2933 On little endian this is a no-op. On big endian the bytes are
2941 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2943 if cfg!(target_endian = \"little\") {
2944 assert_eq!(n.to_le(), n)
2946 assert_eq!(n.to_le(), n.swap_bytes())
2949 #[stable(feature = "rust1", since = "1.0.0")]
2950 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2952 pub const fn to_le(self) -> Self {
2953 #[cfg(target_endian = "little")]
2957 #[cfg(not(target_endian = "little"))]
2965 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2966 if overflow occurred.
2973 ", $Feature, "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
2974 "Some(", stringify!($SelfT), "::MAX - 1));
2975 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);", $EndFeature, "
2977 #[stable(feature = "rust1", since = "1.0.0")]
2978 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2979 #[must_use = "this returns the result of the operation, \
2980 without modifying the original"]
2982 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
2983 let (a, b) = self.overflowing_add(rhs);
2984 if b {None} else {Some(a)}
2989 concat!("Unchecked integer addition. Computes `self + rhs`, assuming overflow
2990 cannot occur. This results in undefined behavior when `self + rhs > ", stringify!($SelfT),
2991 "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`."),
2993 feature = "unchecked_math",
2994 reason = "niche optimization path",
2997 #[must_use = "this returns the result of the operation, \
2998 without modifying the original"]
3000 pub unsafe fn unchecked_add(self, rhs: Self) -> Self {
3001 intrinsics::unchecked_add(self, rhs)
3006 concat!("Checked integer subtraction. Computes `self - rhs`, returning
3007 `None` if overflow occurred.
3014 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
3015 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
3017 #[stable(feature = "rust1", since = "1.0.0")]
3018 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3019 #[must_use = "this returns the result of the operation, \
3020 without modifying the original"]
3022 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
3023 let (a, b) = self.overflowing_sub(rhs);
3024 if b {None} else {Some(a)}
3029 concat!("Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
3030 cannot occur. This results in undefined behavior when `self - rhs > ", stringify!($SelfT),
3031 "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`."),
3033 feature = "unchecked_math",
3034 reason = "niche optimization path",
3037 #[must_use = "this returns the result of the operation, \
3038 without modifying the original"]
3040 pub unsafe fn unchecked_sub(self, rhs: Self) -> Self {
3041 intrinsics::unchecked_sub(self, rhs)
3046 concat!("Checked integer multiplication. Computes `self * rhs`, returning
3047 `None` if overflow occurred.
3054 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
3055 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);", $EndFeature, "
3057 #[stable(feature = "rust1", since = "1.0.0")]
3058 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3059 #[must_use = "this returns the result of the operation, \
3060 without modifying the original"]
3062 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
3063 let (a, b) = self.overflowing_mul(rhs);
3064 if b {None} else {Some(a)}
3069 concat!("Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
3070 cannot occur. This results in undefined behavior when `self * rhs > ", stringify!($SelfT),
3071 "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`."),
3073 feature = "unchecked_math",
3074 reason = "niche optimization path",
3077 #[must_use = "this returns the result of the operation, \
3078 without modifying the original"]
3080 pub unsafe fn unchecked_mul(self, rhs: Self) -> Self {
3081 intrinsics::unchecked_mul(self, rhs)
3086 concat!("Checked integer division. Computes `self / rhs`, returning `None`
3094 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
3095 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
3097 #[stable(feature = "rust1", since = "1.0.0")]
3098 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3099 #[must_use = "this returns the result of the operation, \
3100 without modifying the original"]
3102 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
3105 // SAFETY: div by zero has been checked above and unsigned types have no other
3106 // failure modes for division
3107 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
3113 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
3121 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
3122 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
3124 #[stable(feature = "euclidean_division", since = "1.38.0")]
3125 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3126 #[must_use = "this returns the result of the operation, \
3127 without modifying the original"]
3129 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
3133 Some(self.div_euclid(rhs))
3140 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
3148 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
3149 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
3151 #[stable(feature = "wrapping", since = "1.7.0")]
3152 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3153 #[must_use = "this returns the result of the operation, \
3154 without modifying the original"]
3156 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
3160 // SAFETY: div by zero has been checked above and unsigned types have no other
3161 // failure modes for division
3162 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3168 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3176 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3177 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3179 #[stable(feature = "euclidean_division", since = "1.38.0")]
3180 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3181 #[must_use = "this returns the result of the operation, \
3182 without modifying the original"]
3184 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3188 Some(self.rem_euclid(rhs))
3194 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3197 Note that negating any positive integer will overflow.
3204 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3205 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3207 #[stable(feature = "wrapping", since = "1.7.0")]
3208 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3210 pub const fn checked_neg(self) -> Option<Self> {
3211 let (a, b) = self.overflowing_neg();
3212 if b {None} else {Some(a)}
3217 concat!("Checked shift left. Computes `self << rhs`, returning `None`
3218 if `rhs` is larger than or equal to the number of bits in `self`.
3225 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3226 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3228 #[stable(feature = "wrapping", since = "1.7.0")]
3229 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3230 #[must_use = "this returns the result of the operation, \
3231 without modifying the original"]
3233 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
3234 let (a, b) = self.overflowing_shl(rhs);
3235 if b {None} else {Some(a)}
3240 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3241 if `rhs` is larger than or equal to the number of bits in `self`.
3248 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3249 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3251 #[stable(feature = "wrapping", since = "1.7.0")]
3252 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3253 #[must_use = "this returns the result of the operation, \
3254 without modifying the original"]
3256 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
3257 let (a, b) = self.overflowing_shr(rhs);
3258 if b {None} else {Some(a)}
3263 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3271 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3272 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);", $EndFeature, "
3274 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3275 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3276 #[must_use = "this returns the result of the operation, \
3277 without modifying the original"]
3279 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
3280 let mut base = self;
3281 let mut acc: Self = 1;
3285 acc = try_opt!(acc.checked_mul(base));
3288 base = try_opt!(base.checked_mul(base));
3291 // Deal with the final bit of the exponent separately, since
3292 // squaring the base afterwards is not necessary and may cause a
3293 // needless overflow.
3295 acc = try_opt!(acc.checked_mul(base));
3303 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3304 the numeric bounds instead of overflowing.
3311 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3312 assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);",
3316 #[stable(feature = "rust1", since = "1.0.0")]
3317 #[must_use = "this returns the result of the operation, \
3318 without modifying the original"]
3319 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3321 pub const fn saturating_add(self, rhs: Self) -> Self {
3322 intrinsics::saturating_add(self, rhs)
3327 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3328 at the numeric bounds instead of overflowing.
3335 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3336 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3338 #[stable(feature = "rust1", since = "1.0.0")]
3339 #[must_use = "this returns the result of the operation, \
3340 without modifying the original"]
3341 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3343 pub const fn saturating_sub(self, rhs: Self) -> Self {
3344 intrinsics::saturating_sub(self, rhs)
3349 concat!("Saturating integer multiplication. Computes `self * rhs`,
3350 saturating at the numeric bounds instead of overflowing.
3358 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3359 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3360 "::MAX);", $EndFeature, "
3362 #[stable(feature = "wrapping", since = "1.7.0")]
3363 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3364 #[must_use = "this returns the result of the operation, \
3365 without modifying the original"]
3367 pub const fn saturating_mul(self, rhs: Self) -> Self {
3368 match self.checked_mul(rhs) {
3376 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3377 saturating at the numeric bounds instead of overflowing.
3385 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3386 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3389 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3390 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3391 #[must_use = "this returns the result of the operation, \
3392 without modifying the original"]
3394 pub const fn saturating_pow(self, exp: u32) -> Self {
3395 match self.checked_pow(exp) {
3403 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3404 wrapping around at the boundary of the type.
3411 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3412 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);",
3415 #[stable(feature = "rust1", since = "1.0.0")]
3416 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3417 #[must_use = "this returns the result of the operation, \
3418 without modifying the original"]
3420 pub const fn wrapping_add(self, rhs: Self) -> Self {
3421 intrinsics::wrapping_add(self, rhs)
3426 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3427 wrapping around at the boundary of the type.
3434 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3435 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);",
3438 #[stable(feature = "rust1", since = "1.0.0")]
3439 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3440 #[must_use = "this returns the result of the operation, \
3441 without modifying the original"]
3443 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3444 intrinsics::wrapping_sub(self, rhs)
3448 /// Wrapping (modular) multiplication. Computes `self *
3449 /// rhs`, wrapping around at the boundary of the type.
3455 /// Please note that this example is shared between integer types.
3456 /// Which explains why `u8` is used here.
3459 /// assert_eq!(10u8.wrapping_mul(12), 120);
3460 /// assert_eq!(25u8.wrapping_mul(12), 44);
3462 #[stable(feature = "rust1", since = "1.0.0")]
3463 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3464 #[must_use = "this returns the result of the operation, \
3465 without modifying the original"]
3467 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3468 intrinsics::wrapping_mul(self, rhs)
3472 concat!("Wrapping (modular) division. Computes `self / rhs`.
3473 Wrapped division on unsigned types is just normal division.
3474 There's no way wrapping could ever happen.
3475 This function exists, so that all operations
3476 are accounted for in the wrapping operations.
3483 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3485 #[stable(feature = "num_wrapping", since = "1.2.0")]
3486 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3487 #[must_use = "this returns the result of the operation, \
3488 without modifying the original"]
3490 pub const fn wrapping_div(self, rhs: Self) -> Self {
3496 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3497 Wrapped division on unsigned types is just normal division.
3498 There's no way wrapping could ever happen.
3499 This function exists, so that all operations
3500 are accounted for in the wrapping operations.
3501 Since, for the positive integers, all common
3502 definitions of division are equal, this
3503 is exactly equal to `self.wrapping_div(rhs)`.
3510 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3512 #[stable(feature = "euclidean_division", since = "1.38.0")]
3513 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3514 #[must_use = "this returns the result of the operation, \
3515 without modifying the original"]
3517 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
3523 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3524 Wrapped remainder calculation on unsigned types is
3525 just the regular remainder calculation.
3526 There's no way wrapping could ever happen.
3527 This function exists, so that all operations
3528 are accounted for in the wrapping operations.
3535 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3537 #[stable(feature = "num_wrapping", since = "1.2.0")]
3538 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3539 #[must_use = "this returns the result of the operation, \
3540 without modifying the original"]
3542 pub const fn wrapping_rem(self, rhs: Self) -> Self {
3548 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3549 Wrapped modulo calculation on unsigned types is
3550 just the regular remainder calculation.
3551 There's no way wrapping could ever happen.
3552 This function exists, so that all operations
3553 are accounted for in the wrapping operations.
3554 Since, for the positive integers, all common
3555 definitions of division are equal, this
3556 is exactly equal to `self.wrapping_rem(rhs)`.
3563 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3565 #[stable(feature = "euclidean_division", since = "1.38.0")]
3566 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3567 #[must_use = "this returns the result of the operation, \
3568 without modifying the original"]
3570 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3575 /// Wrapping (modular) negation. Computes `-self`,
3576 /// wrapping around at the boundary of the type.
3578 /// Since unsigned types do not have negative equivalents
3579 /// all applications of this function will wrap (except for `-0`).
3580 /// For values smaller than the corresponding signed type's maximum
3581 /// the result is the same as casting the corresponding signed value.
3582 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3583 /// `MAX` is the corresponding signed type's maximum.
3589 /// Please note that this example is shared between integer types.
3590 /// Which explains why `i8` is used here.
3593 /// assert_eq!(100i8.wrapping_neg(), -100);
3594 /// assert_eq!((-128i8).wrapping_neg(), -128);
3596 #[stable(feature = "num_wrapping", since = "1.2.0")]
3597 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3599 pub const fn wrapping_neg(self) -> Self {
3600 self.overflowing_neg().0
3604 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3605 where `mask` removes any high-order bits of `rhs` that
3606 would cause the shift to exceed the bitwidth of the type.
3608 Note that this is *not* the same as a rotate-left; the
3609 RHS of a wrapping shift-left is restricted to the range
3610 of the type, rather than the bits shifted out of the LHS
3611 being returned to the other end. The primitive integer
3612 types all implement a [`rotate_left`](#method.rotate_left) function,
3613 which may be what you want instead.
3620 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3621 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3623 #[stable(feature = "num_wrapping", since = "1.2.0")]
3624 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3625 #[must_use = "this returns the result of the operation, \
3626 without modifying the original"]
3628 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3629 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3632 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3638 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3639 where `mask` removes any high-order bits of `rhs` that
3640 would cause the shift to exceed the bitwidth of the type.
3642 Note that this is *not* the same as a rotate-right; the
3643 RHS of a wrapping shift-right is restricted to the range
3644 of the type, rather than the bits shifted out of the LHS
3645 being returned to the other end. The primitive integer
3646 types all implement a [`rotate_right`](#method.rotate_right) function,
3647 which may be what you want instead.
3654 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3655 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3657 #[stable(feature = "num_wrapping", since = "1.2.0")]
3658 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3659 #[must_use = "this returns the result of the operation, \
3660 without modifying the original"]
3662 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3663 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3666 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3672 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3673 wrapping around at the boundary of the type.
3680 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3681 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3683 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3684 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3685 #[must_use = "this returns the result of the operation, \
3686 without modifying the original"]
3688 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
3689 let mut base = self;
3690 let mut acc: Self = 1;
3694 acc = acc.wrapping_mul(base);
3697 base = base.wrapping_mul(base);
3700 // Deal with the final bit of the exponent separately, since
3701 // squaring the base afterwards is not necessary and may cause a
3702 // needless overflow.
3704 acc = acc.wrapping_mul(base);
3712 concat!("Calculates `self` + `rhs`
3714 Returns a tuple of the addition along with a boolean indicating
3715 whether an arithmetic overflow would occur. If an overflow would
3716 have occurred then the wrapped value is returned.
3724 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3725 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3727 #[stable(feature = "wrapping", since = "1.7.0")]
3728 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3729 #[must_use = "this returns the result of the operation, \
3730 without modifying the original"]
3732 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3733 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3739 concat!("Calculates `self` - `rhs`
3741 Returns a tuple of the subtraction along with a boolean indicating
3742 whether an arithmetic overflow would occur. If an overflow would
3743 have occurred then the wrapped value is returned.
3751 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3752 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3755 #[stable(feature = "wrapping", since = "1.7.0")]
3756 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3757 #[must_use = "this returns the result of the operation, \
3758 without modifying the original"]
3760 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3761 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3766 /// Calculates the multiplication of `self` and `rhs`.
3768 /// Returns a tuple of the multiplication along with a boolean
3769 /// indicating whether an arithmetic overflow would occur. If an
3770 /// overflow would have occurred then the wrapped value is returned.
3776 /// Please note that this example is shared between integer types.
3777 /// Which explains why `u32` is used here.
3780 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3781 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3783 #[stable(feature = "wrapping", since = "1.7.0")]
3784 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3785 #[must_use = "this returns the result of the operation, \
3786 without modifying the original"]
3788 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3789 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3794 concat!("Calculates the divisor when `self` is divided by `rhs`.
3796 Returns a tuple of the divisor along with a boolean indicating
3797 whether an arithmetic overflow would occur. Note that for unsigned
3798 integers overflow never occurs, so the second value is always
3803 This function will panic if `rhs` is 0.
3810 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3813 #[stable(feature = "wrapping", since = "1.7.0")]
3814 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3815 #[must_use = "this returns the result of the operation, \
3816 without modifying the original"]
3817 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3823 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3825 Returns a tuple of the divisor along with a boolean indicating
3826 whether an arithmetic overflow would occur. Note that for unsigned
3827 integers overflow never occurs, so the second value is always
3829 Since, for the positive integers, all common
3830 definitions of division are equal, this
3831 is exactly equal to `self.overflowing_div(rhs)`.
3835 This function will panic if `rhs` is 0.
3842 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3845 #[stable(feature = "euclidean_division", since = "1.38.0")]
3846 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3847 #[must_use = "this returns the result of the operation, \
3848 without modifying the original"]
3849 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3855 concat!("Calculates the remainder when `self` is divided by `rhs`.
3857 Returns a tuple of the remainder after dividing along with a boolean
3858 indicating whether an arithmetic overflow would occur. Note that for
3859 unsigned integers overflow never occurs, so the second value is
3864 This function will panic if `rhs` is 0.
3871 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3874 #[stable(feature = "wrapping", since = "1.7.0")]
3875 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3876 #[must_use = "this returns the result of the operation, \
3877 without modifying the original"]
3878 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3884 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3886 Returns a tuple of the modulo after dividing along with a boolean
3887 indicating whether an arithmetic overflow would occur. Note that for
3888 unsigned integers overflow never occurs, so the second value is
3890 Since, for the positive integers, all common
3891 definitions of division are equal, this operation
3892 is exactly equal to `self.overflowing_rem(rhs)`.
3896 This function will panic if `rhs` is 0.
3903 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3906 #[stable(feature = "euclidean_division", since = "1.38.0")]
3907 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3908 #[must_use = "this returns the result of the operation, \
3909 without modifying the original"]
3910 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3916 concat!("Negates self in an overflowing fashion.
3918 Returns `!self + 1` using wrapping operations to return the value
3919 that represents the negation of this unsigned value. Note that for
3920 positive unsigned values overflow always occurs, but negating 0 does
3928 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3929 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3930 ", true));", $EndFeature, "
3933 #[stable(feature = "wrapping", since = "1.7.0")]
3934 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3935 pub const fn overflowing_neg(self) -> (Self, bool) {
3936 ((!self).wrapping_add(1), self != 0)
3941 concat!("Shifts self left by `rhs` bits.
3943 Returns a tuple of the shifted version of self along with a boolean
3944 indicating whether the shift value was larger than or equal to the
3945 number of bits. If the shift value is too large, then value is
3946 masked (N-1) where N is the number of bits, and this value is then
3947 used to perform the shift.
3954 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3955 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3957 #[stable(feature = "wrapping", since = "1.7.0")]
3958 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3959 #[must_use = "this returns the result of the operation, \
3960 without modifying the original"]
3962 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3963 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3968 concat!("Shifts self right by `rhs` bits.
3970 Returns a tuple of the shifted version of self along with a boolean
3971 indicating whether the shift value was larger than or equal to the
3972 number of bits. If the shift value is too large, then value is
3973 masked (N-1) where N is the number of bits, and this value is then
3974 used to perform the shift.
3981 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3982 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3984 #[stable(feature = "wrapping", since = "1.7.0")]
3985 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3986 #[must_use = "this returns the result of the operation, \
3987 without modifying the original"]
3989 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3990 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3995 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3997 Returns a tuple of the exponentiation along with a bool indicating
3998 whether an overflow happened.
4005 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
4006 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
4008 #[stable(feature = "no_panic_pow", since = "1.34.0")]
4009 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4010 #[must_use = "this returns the result of the operation, \
4011 without modifying the original"]
4013 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
4014 let mut base = self;
4015 let mut acc: Self = 1;
4016 let mut overflown = false;
4017 // Scratch space for storing results of overflowing_mul.
4022 r = acc.overflowing_mul(base);
4027 r = base.overflowing_mul(base);
4032 // Deal with the final bit of the exponent separately, since
4033 // squaring the base afterwards is not necessary and may cause a
4034 // needless overflow.
4036 r = acc.overflowing_mul(base);
4046 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
4053 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
4055 #[stable(feature = "rust1", since = "1.0.0")]
4056 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4057 #[must_use = "this returns the result of the operation, \
4058 without modifying the original"]
4060 #[rustc_inherit_overflow_checks]
4061 pub const fn pow(self, mut exp: u32) -> Self {
4062 let mut base = self;
4073 // Deal with the final bit of the exponent separately, since
4074 // squaring the base afterwards is not necessary and may cause a
4075 // needless overflow.
4085 concat!("Performs Euclidean division.
4087 Since, for the positive integers, all common
4088 definitions of division are equal, this
4089 is exactly equal to `self / rhs`.
4093 This function will panic if `rhs` is 0.
4100 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
4102 #[stable(feature = "euclidean_division", since = "1.38.0")]
4103 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
4104 #[must_use = "this returns the result of the operation, \
4105 without modifying the original"]
4107 #[rustc_inherit_overflow_checks]
4108 pub const fn div_euclid(self, rhs: Self) -> Self {
4115 concat!("Calculates the least remainder of `self (mod rhs)`.
4117 Since, for the positive integers, all common
4118 definitions of division are equal, this
4119 is exactly equal to `self % rhs`.
4123 This function will panic if `rhs` is 0.
4130 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
4132 #[stable(feature = "euclidean_division", since = "1.38.0")]
4133 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
4134 #[must_use = "this returns the result of the operation, \
4135 without modifying the original"]
4137 #[rustc_inherit_overflow_checks]
4138 pub const fn rem_euclid(self, rhs: Self) -> Self {
4144 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
4151 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
4152 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
4154 #[stable(feature = "rust1", since = "1.0.0")]
4155 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
4157 pub const fn is_power_of_two(self) -> bool {
4158 self.count_ones() == 1
4162 // Returns one less than next power of two.
4163 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
4165 // 8u8.one_less_than_next_power_of_two() == 7
4166 // 6u8.one_less_than_next_power_of_two() == 7
4168 // This method cannot overflow, as in the `next_power_of_two`
4169 // overflow cases it instead ends up returning the maximum value
4170 // of the type, and can return 0 for 0.
4172 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4173 const fn one_less_than_next_power_of_two(self) -> Self {
4174 if self <= 1 { return 0; }
4177 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4178 // That means the shift is always in-bounds, and some processors
4179 // (such as intel pre-haswell) have more efficient ctlz
4180 // intrinsics when the argument is non-zero.
4181 let z = unsafe { intrinsics::ctlz_nonzero(p) };
4186 concat!("Returns the smallest power of two greater than or equal to `self`.
4188 When return value overflows (i.e., `self > (1 << (N-1))` for type
4189 `uN`), it panics in debug mode and return value is wrapped to 0 in
4190 release mode (the only situation in which method can return 0).
4197 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4198 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4200 #[stable(feature = "rust1", since = "1.0.0")]
4201 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4203 #[rustc_inherit_overflow_checks]
4204 pub const fn next_power_of_two(self) -> Self {
4205 self.one_less_than_next_power_of_two() + 1
4210 concat!("Returns the smallest power of two greater than or equal to `n`. If
4211 the next power of two is greater than the type's maximum value,
4212 `None` is returned, otherwise the power of two is wrapped in `Some`.
4219 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4220 ".checked_next_power_of_two(), Some(2));
4221 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4222 assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);",
4226 #[stable(feature = "rust1", since = "1.0.0")]
4227 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4228 pub const fn checked_next_power_of_two(self) -> Option<Self> {
4229 self.one_less_than_next_power_of_two().checked_add(1)
4234 concat!("Returns the smallest power of two greater than or equal to `n`. If
4235 the next power of two is greater than the type's maximum value,
4236 the return value is wrapped to `0`.
4243 #![feature(wrapping_next_power_of_two)]
4245 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4246 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4247 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);",
4250 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4251 reason = "needs decision on wrapping behaviour")]
4252 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4253 pub const fn wrapping_next_power_of_two(self) -> Self {
4254 self.one_less_than_next_power_of_two().wrapping_add(1)
4259 concat!("Return the memory representation of this integer as a byte array in
4260 big-endian (network) byte order.
4267 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4268 assert_eq!(bytes, ", $be_bytes, ");
4270 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4271 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4273 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4274 self.to_be().to_ne_bytes()
4279 concat!("Return the memory representation of this integer as a byte array in
4280 little-endian byte order.
4287 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4288 assert_eq!(bytes, ", $le_bytes, ");
4290 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4291 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4293 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4294 self.to_le().to_ne_bytes()
4300 Return the memory representation of this integer as a byte array in
4303 As the target platform's native endianness is used, portable code
4304 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4309 [`to_be_bytes`]: #method.to_be_bytes
4310 [`to_le_bytes`]: #method.to_le_bytes
4315 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4318 if cfg!(target_endian = \"big\") {
4325 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4326 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4327 // SAFETY: const sound because integers are plain old datatypes so we can always
4328 // transmute them to arrays of bytes
4329 #[allow_internal_unstable(const_fn_union)]
4331 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4335 bytes: [u8; mem::size_of::<$SelfT>()],
4337 // SAFETY: integers are plain old datatypes so we can always transmute them to
4339 unsafe { Bytes { val: self }.bytes }
4344 concat!("Create an integer value from its representation as a byte array in
4352 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4353 assert_eq!(value, ", $swap_op, ");
4356 When starting from a slice rather than an array, fallible conversion APIs can be used:
4359 use std::convert::TryInto;
4361 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4362 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4364 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4367 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4368 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4370 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4371 Self::from_be(Self::from_ne_bytes(bytes))
4377 Create an integer value from its representation as a byte array in
4385 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4386 assert_eq!(value, ", $swap_op, ");
4389 When starting from a slice rather than an array, fallible conversion APIs can be used:
4392 use std::convert::TryInto;
4394 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4395 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4397 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4400 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4401 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4403 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4404 Self::from_le(Self::from_ne_bytes(bytes))
4409 concat!("Create an integer value from its memory representation as a byte
4410 array in native endianness.
4412 As the target platform's native endianness is used, portable code
4413 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4414 appropriate instead.
4416 [`from_be_bytes`]: #method.from_be_bytes
4417 [`from_le_bytes`]: #method.from_le_bytes
4424 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4429 assert_eq!(value, ", $swap_op, ");
4432 When starting from a slice rather than an array, fallible conversion APIs can be used:
4435 use std::convert::TryInto;
4437 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4438 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4440 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4443 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4444 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4445 // SAFETY: const sound because integers are plain old datatypes so we can always
4446 // transmute to them
4447 #[allow_internal_unstable(const_fn_union)]
4449 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4453 bytes: [u8; mem::size_of::<$SelfT>()],
4455 // SAFETY: integers are plain old datatypes so we can always transmute to them
4456 unsafe { Bytes { bytes }.val }
4461 concat!("**This method is soft-deprecated.**
4463 Although using it won’t cause compilation warning,
4464 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
4466 Returns the smallest value that can be represented by this integer type."),
4467 #[stable(feature = "rust1", since = "1.0.0")]
4470 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4471 pub const fn min_value() -> Self { Self::MIN }
4475 concat!("**This method is soft-deprecated.**
4477 Although using it won’t cause compilation warning,
4478 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
4480 Returns the largest value that can be represented by this integer type."),
4481 #[stable(feature = "rust1", since = "1.0.0")]
4484 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4485 pub const fn max_value() -> Self { Self::MAX }
4492 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4495 /// Checks if the value is within the ASCII range.
4500 /// let ascii = 97u8;
4501 /// let non_ascii = 150u8;
4503 /// assert!(ascii.is_ascii());
4504 /// assert!(!non_ascii.is_ascii());
4506 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4507 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.43.0")]
4509 pub const fn is_ascii(&self) -> bool {
4513 /// Makes a copy of the value in its ASCII upper case equivalent.
4515 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4516 /// but non-ASCII letters are unchanged.
4518 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4523 /// let lowercase_a = 97u8;
4525 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4528 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4529 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4531 pub fn to_ascii_uppercase(&self) -> u8 {
4532 // Unset the fifth bit if this is a lowercase letter
4533 *self & !((self.is_ascii_lowercase() as u8) << 5)
4536 /// Makes a copy of the value in its ASCII lower case equivalent.
4538 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4539 /// but non-ASCII letters are unchanged.
4541 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4546 /// let uppercase_a = 65u8;
4548 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4551 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4552 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4554 pub fn to_ascii_lowercase(&self) -> u8 {
4555 // Set the fifth bit if this is an uppercase letter
4556 *self | ((self.is_ascii_uppercase() as u8) << 5)
4559 /// Checks that two values are an ASCII case-insensitive match.
4561 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4566 /// let lowercase_a = 97u8;
4567 /// let uppercase_a = 65u8;
4569 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4571 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4573 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4574 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4577 /// Converts this value to its ASCII upper case equivalent in-place.
4579 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4580 /// but non-ASCII letters are unchanged.
4582 /// To return a new uppercased value without modifying the existing one, use
4583 /// [`to_ascii_uppercase`].
4588 /// let mut byte = b'a';
4590 /// byte.make_ascii_uppercase();
4592 /// assert_eq!(b'A', byte);
4595 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4596 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4598 pub fn make_ascii_uppercase(&mut self) {
4599 *self = self.to_ascii_uppercase();
4602 /// Converts this value to its ASCII lower case equivalent in-place.
4604 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4605 /// but non-ASCII letters are unchanged.
4607 /// To return a new lowercased value without modifying the existing one, use
4608 /// [`to_ascii_lowercase`].
4613 /// let mut byte = b'A';
4615 /// byte.make_ascii_lowercase();
4617 /// assert_eq!(b'a', byte);
4620 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4621 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4623 pub fn make_ascii_lowercase(&mut self) {
4624 *self = self.to_ascii_lowercase();
4627 /// Checks if the value is an ASCII alphabetic character:
4629 /// - U+0041 'A' ..= U+005A 'Z', or
4630 /// - U+0061 'a' ..= U+007A 'z'.
4635 /// let uppercase_a = b'A';
4636 /// let uppercase_g = b'G';
4639 /// let zero = b'0';
4640 /// let percent = b'%';
4641 /// let space = b' ';
4643 /// let esc = 0x1b_u8;
4645 /// assert!(uppercase_a.is_ascii_alphabetic());
4646 /// assert!(uppercase_g.is_ascii_alphabetic());
4647 /// assert!(a.is_ascii_alphabetic());
4648 /// assert!(g.is_ascii_alphabetic());
4649 /// assert!(!zero.is_ascii_alphabetic());
4650 /// assert!(!percent.is_ascii_alphabetic());
4651 /// assert!(!space.is_ascii_alphabetic());
4652 /// assert!(!lf.is_ascii_alphabetic());
4653 /// assert!(!esc.is_ascii_alphabetic());
4655 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4656 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4658 pub const fn is_ascii_alphabetic(&self) -> bool {
4659 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
4662 /// Checks if the value is an ASCII uppercase character:
4663 /// U+0041 'A' ..= U+005A 'Z'.
4668 /// let uppercase_a = b'A';
4669 /// let uppercase_g = b'G';
4672 /// let zero = b'0';
4673 /// let percent = b'%';
4674 /// let space = b' ';
4676 /// let esc = 0x1b_u8;
4678 /// assert!(uppercase_a.is_ascii_uppercase());
4679 /// assert!(uppercase_g.is_ascii_uppercase());
4680 /// assert!(!a.is_ascii_uppercase());
4681 /// assert!(!g.is_ascii_uppercase());
4682 /// assert!(!zero.is_ascii_uppercase());
4683 /// assert!(!percent.is_ascii_uppercase());
4684 /// assert!(!space.is_ascii_uppercase());
4685 /// assert!(!lf.is_ascii_uppercase());
4686 /// assert!(!esc.is_ascii_uppercase());
4688 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4689 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4691 pub const fn is_ascii_uppercase(&self) -> bool {
4692 matches!(*self, b'A'..=b'Z')
4695 /// Checks if the value is an ASCII lowercase character:
4696 /// U+0061 'a' ..= U+007A 'z'.
4701 /// let uppercase_a = b'A';
4702 /// let uppercase_g = b'G';
4705 /// let zero = b'0';
4706 /// let percent = b'%';
4707 /// let space = b' ';
4709 /// let esc = 0x1b_u8;
4711 /// assert!(!uppercase_a.is_ascii_lowercase());
4712 /// assert!(!uppercase_g.is_ascii_lowercase());
4713 /// assert!(a.is_ascii_lowercase());
4714 /// assert!(g.is_ascii_lowercase());
4715 /// assert!(!zero.is_ascii_lowercase());
4716 /// assert!(!percent.is_ascii_lowercase());
4717 /// assert!(!space.is_ascii_lowercase());
4718 /// assert!(!lf.is_ascii_lowercase());
4719 /// assert!(!esc.is_ascii_lowercase());
4721 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4722 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4724 pub const fn is_ascii_lowercase(&self) -> bool {
4725 matches!(*self, b'a'..=b'z')
4728 /// Checks if the value is an ASCII alphanumeric character:
4730 /// - U+0041 'A' ..= U+005A 'Z', or
4731 /// - U+0061 'a' ..= U+007A 'z', or
4732 /// - U+0030 '0' ..= U+0039 '9'.
4737 /// let uppercase_a = b'A';
4738 /// let uppercase_g = b'G';
4741 /// let zero = b'0';
4742 /// let percent = b'%';
4743 /// let space = b' ';
4745 /// let esc = 0x1b_u8;
4747 /// assert!(uppercase_a.is_ascii_alphanumeric());
4748 /// assert!(uppercase_g.is_ascii_alphanumeric());
4749 /// assert!(a.is_ascii_alphanumeric());
4750 /// assert!(g.is_ascii_alphanumeric());
4751 /// assert!(zero.is_ascii_alphanumeric());
4752 /// assert!(!percent.is_ascii_alphanumeric());
4753 /// assert!(!space.is_ascii_alphanumeric());
4754 /// assert!(!lf.is_ascii_alphanumeric());
4755 /// assert!(!esc.is_ascii_alphanumeric());
4757 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4758 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4760 pub const fn is_ascii_alphanumeric(&self) -> bool {
4761 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
4764 /// Checks if the value is an ASCII decimal digit:
4765 /// U+0030 '0' ..= U+0039 '9'.
4770 /// let uppercase_a = b'A';
4771 /// let uppercase_g = b'G';
4774 /// let zero = b'0';
4775 /// let percent = b'%';
4776 /// let space = b' ';
4778 /// let esc = 0x1b_u8;
4780 /// assert!(!uppercase_a.is_ascii_digit());
4781 /// assert!(!uppercase_g.is_ascii_digit());
4782 /// assert!(!a.is_ascii_digit());
4783 /// assert!(!g.is_ascii_digit());
4784 /// assert!(zero.is_ascii_digit());
4785 /// assert!(!percent.is_ascii_digit());
4786 /// assert!(!space.is_ascii_digit());
4787 /// assert!(!lf.is_ascii_digit());
4788 /// assert!(!esc.is_ascii_digit());
4790 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4791 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4793 pub const fn is_ascii_digit(&self) -> bool {
4794 matches!(*self, b'0'..=b'9')
4797 /// Checks if the value is an ASCII hexadecimal digit:
4799 /// - U+0030 '0' ..= U+0039 '9', or
4800 /// - U+0041 'A' ..= U+0046 'F', or
4801 /// - U+0061 'a' ..= U+0066 'f'.
4806 /// let uppercase_a = b'A';
4807 /// let uppercase_g = b'G';
4810 /// let zero = b'0';
4811 /// let percent = b'%';
4812 /// let space = b' ';
4814 /// let esc = 0x1b_u8;
4816 /// assert!(uppercase_a.is_ascii_hexdigit());
4817 /// assert!(!uppercase_g.is_ascii_hexdigit());
4818 /// assert!(a.is_ascii_hexdigit());
4819 /// assert!(!g.is_ascii_hexdigit());
4820 /// assert!(zero.is_ascii_hexdigit());
4821 /// assert!(!percent.is_ascii_hexdigit());
4822 /// assert!(!space.is_ascii_hexdigit());
4823 /// assert!(!lf.is_ascii_hexdigit());
4824 /// assert!(!esc.is_ascii_hexdigit());
4826 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4827 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4829 pub const fn is_ascii_hexdigit(&self) -> bool {
4830 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
4833 /// Checks if the value is an ASCII punctuation character:
4835 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4836 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4837 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4838 /// - U+007B ..= U+007E `{ | } ~`
4843 /// let uppercase_a = b'A';
4844 /// let uppercase_g = b'G';
4847 /// let zero = b'0';
4848 /// let percent = b'%';
4849 /// let space = b' ';
4851 /// let esc = 0x1b_u8;
4853 /// assert!(!uppercase_a.is_ascii_punctuation());
4854 /// assert!(!uppercase_g.is_ascii_punctuation());
4855 /// assert!(!a.is_ascii_punctuation());
4856 /// assert!(!g.is_ascii_punctuation());
4857 /// assert!(!zero.is_ascii_punctuation());
4858 /// assert!(percent.is_ascii_punctuation());
4859 /// assert!(!space.is_ascii_punctuation());
4860 /// assert!(!lf.is_ascii_punctuation());
4861 /// assert!(!esc.is_ascii_punctuation());
4863 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4864 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4866 pub const fn is_ascii_punctuation(&self) -> bool {
4867 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
4870 /// Checks if the value is an ASCII graphic character:
4871 /// U+0021 '!' ..= U+007E '~'.
4876 /// let uppercase_a = b'A';
4877 /// let uppercase_g = b'G';
4880 /// let zero = b'0';
4881 /// let percent = b'%';
4882 /// let space = b' ';
4884 /// let esc = 0x1b_u8;
4886 /// assert!(uppercase_a.is_ascii_graphic());
4887 /// assert!(uppercase_g.is_ascii_graphic());
4888 /// assert!(a.is_ascii_graphic());
4889 /// assert!(g.is_ascii_graphic());
4890 /// assert!(zero.is_ascii_graphic());
4891 /// assert!(percent.is_ascii_graphic());
4892 /// assert!(!space.is_ascii_graphic());
4893 /// assert!(!lf.is_ascii_graphic());
4894 /// assert!(!esc.is_ascii_graphic());
4896 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4897 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4899 pub const fn is_ascii_graphic(&self) -> bool {
4900 matches!(*self, b'!'..=b'~')
4903 /// Checks if the value is an ASCII whitespace character:
4904 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4905 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4907 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4908 /// whitespace][infra-aw]. There are several other definitions in
4909 /// wide use. For instance, [the POSIX locale][pct] includes
4910 /// U+000B VERTICAL TAB as well as all the above characters,
4911 /// but—from the very same specification—[the default rule for
4912 /// "field splitting" in the Bourne shell][bfs] considers *only*
4913 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4915 /// If you are writing a program that will process an existing
4916 /// file format, check what that format's definition of whitespace is
4917 /// before using this function.
4919 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4920 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4921 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4926 /// let uppercase_a = b'A';
4927 /// let uppercase_g = b'G';
4930 /// let zero = b'0';
4931 /// let percent = b'%';
4932 /// let space = b' ';
4934 /// let esc = 0x1b_u8;
4936 /// assert!(!uppercase_a.is_ascii_whitespace());
4937 /// assert!(!uppercase_g.is_ascii_whitespace());
4938 /// assert!(!a.is_ascii_whitespace());
4939 /// assert!(!g.is_ascii_whitespace());
4940 /// assert!(!zero.is_ascii_whitespace());
4941 /// assert!(!percent.is_ascii_whitespace());
4942 /// assert!(space.is_ascii_whitespace());
4943 /// assert!(lf.is_ascii_whitespace());
4944 /// assert!(!esc.is_ascii_whitespace());
4946 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4947 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4949 pub const fn is_ascii_whitespace(&self) -> bool {
4950 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
4953 /// Checks if the value is an ASCII control character:
4954 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4955 /// Note that most ASCII whitespace characters are control
4956 /// characters, but SPACE is not.
4961 /// let uppercase_a = b'A';
4962 /// let uppercase_g = b'G';
4965 /// let zero = b'0';
4966 /// let percent = b'%';
4967 /// let space = b' ';
4969 /// let esc = 0x1b_u8;
4971 /// assert!(!uppercase_a.is_ascii_control());
4972 /// assert!(!uppercase_g.is_ascii_control());
4973 /// assert!(!a.is_ascii_control());
4974 /// assert!(!g.is_ascii_control());
4975 /// assert!(!zero.is_ascii_control());
4976 /// assert!(!percent.is_ascii_control());
4977 /// assert!(!space.is_ascii_control());
4978 /// assert!(lf.is_ascii_control());
4979 /// assert!(esc.is_ascii_control());
4981 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4982 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4984 pub const fn is_ascii_control(&self) -> bool {
4985 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
4991 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4992 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4997 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4998 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
5003 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
5004 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
5005 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
5006 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
5012 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
5013 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
5014 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
5015 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
5016 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
5017 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
5018 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
5022 #[cfg(target_pointer_width = "16")]
5025 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
5026 "[0x34, 0x12]", "[0x12, 0x34]",
5027 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
5029 #[cfg(target_pointer_width = "32")]
5032 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
5033 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
5034 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
5037 #[cfg(target_pointer_width = "64")]
5040 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
5041 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
5042 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
5043 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
5044 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
5047 /// A classification of floating point numbers.
5049 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
5050 /// their documentation for more.
5052 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
5053 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
5058 /// use std::num::FpCategory;
5060 /// let num = 12.4_f32;
5061 /// let inf = f32::INFINITY;
5062 /// let zero = 0f32;
5063 /// let sub: f32 = 1.1754942e-38;
5064 /// let nan = f32::NAN;
5066 /// assert_eq!(num.classify(), FpCategory::Normal);
5067 /// assert_eq!(inf.classify(), FpCategory::Infinite);
5068 /// assert_eq!(zero.classify(), FpCategory::Zero);
5069 /// assert_eq!(nan.classify(), FpCategory::Nan);
5070 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
5072 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
5073 #[stable(feature = "rust1", since = "1.0.0")]
5074 pub enum FpCategory {
5075 /// "Not a Number", often obtained by dividing by zero.
5076 #[stable(feature = "rust1", since = "1.0.0")]
5079 /// Positive or negative infinity.
5080 #[stable(feature = "rust1", since = "1.0.0")]
5083 /// Positive or negative zero.
5084 #[stable(feature = "rust1", since = "1.0.0")]
5087 /// De-normalized floating point representation (less precise than `Normal`).
5088 #[stable(feature = "rust1", since = "1.0.0")]
5091 /// A regular floating point number.
5092 #[stable(feature = "rust1", since = "1.0.0")]
5096 macro_rules! from_str_radix_int_impl {
5098 #[stable(feature = "rust1", since = "1.0.0")]
5099 impl FromStr for $t {
5100 type Err = ParseIntError;
5101 fn from_str(src: &str) -> Result<Self, ParseIntError> {
5102 from_str_radix(src, 10)
5107 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
5109 /// The error type returned when a checked integral type conversion fails.
5110 #[stable(feature = "try_from", since = "1.34.0")]
5111 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
5112 pub struct TryFromIntError(pub(crate) ());
5114 impl TryFromIntError {
5116 feature = "int_error_internals",
5117 reason = "available through Error trait and this method should \
5118 not be exposed publicly",
5122 pub fn __description(&self) -> &str {
5123 "out of range integral type conversion attempted"
5127 #[stable(feature = "try_from", since = "1.34.0")]
5128 impl fmt::Display for TryFromIntError {
5129 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
5130 self.__description().fmt(fmt)
5134 #[stable(feature = "try_from", since = "1.34.0")]
5135 impl From<Infallible> for TryFromIntError {
5136 fn from(x: Infallible) -> TryFromIntError {
5141 #[unstable(feature = "never_type", issue = "35121")]
5142 impl From<!> for TryFromIntError {
5143 fn from(never: !) -> TryFromIntError {
5144 // Match rather than coerce to make sure that code like
5145 // `From<Infallible> for TryFromIntError` above will keep working
5146 // when `Infallible` becomes an alias to `!`.
5152 trait FromStrRadixHelper: PartialOrd + Copy {
5153 fn min_value() -> Self;
5154 fn max_value() -> Self;
5155 fn from_u32(u: u32) -> Self;
5156 fn checked_mul(&self, other: u32) -> Option<Self>;
5157 fn checked_sub(&self, other: u32) -> Option<Self>;
5158 fn checked_add(&self, other: u32) -> Option<Self>;
5162 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
5164 fn min_value() -> Self { Self::MIN }
5166 fn max_value() -> Self { Self::MAX }
5168 fn from_u32(u: u32) -> Self { u as Self }
5170 fn checked_mul(&self, other: u32) -> Option<Self> {
5171 Self::checked_mul(*self, other as Self)
5174 fn checked_sub(&self, other: u32) -> Option<Self> {
5175 Self::checked_sub(*self, other as Self)
5178 fn checked_add(&self, other: u32) -> Option<Self> {
5179 Self::checked_add(*self, other as Self)
5183 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5185 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5186 use self::IntErrorKind::*;
5187 use self::ParseIntError as PIE;
5190 radix >= 2 && radix <= 36,
5191 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5196 return Err(PIE { kind: Empty });
5199 let is_signed_ty = T::from_u32(0) > T::min_value();
5201 // all valid digits are ascii, so we will just iterate over the utf8 bytes
5202 // and cast them to chars. .to_digit() will safely return None for anything
5203 // other than a valid ascii digit for the given radix, including the first-byte
5204 // of multi-byte sequences
5205 let src = src.as_bytes();
5207 let (is_positive, digits) = match src[0] {
5208 b'+' => (true, &src[1..]),
5209 b'-' if is_signed_ty => (false, &src[1..]),
5213 if digits.is_empty() {
5214 return Err(PIE { kind: Empty });
5217 let mut result = T::from_u32(0);
5219 // The number is positive
5221 let x = match (c as char).to_digit(radix) {
5223 None => return Err(PIE { kind: InvalidDigit }),
5225 result = match result.checked_mul(radix) {
5226 Some(result) => result,
5227 None => return Err(PIE { kind: Overflow }),
5229 result = match result.checked_add(x) {
5230 Some(result) => result,
5231 None => return Err(PIE { kind: Overflow }),
5235 // The number is negative
5237 let x = match (c as char).to_digit(radix) {
5239 None => return Err(PIE { kind: InvalidDigit }),
5241 result = match result.checked_mul(radix) {
5242 Some(result) => result,
5243 None => return Err(PIE { kind: Underflow }),
5245 result = match result.checked_sub(x) {
5246 Some(result) => result,
5247 None => return Err(PIE { kind: Underflow }),
5254 /// An error which can be returned when parsing an integer.
5256 /// This error is used as the error type for the `from_str_radix()` functions
5257 /// on the primitive integer types, such as [`i8::from_str_radix`].
5259 /// # Potential causes
5261 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5262 /// in the string e.g., when it is obtained from the standard input.
5263 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5265 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5266 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5267 #[derive(Debug, Clone, PartialEq, Eq)]
5268 #[stable(feature = "rust1", since = "1.0.0")]
5269 pub struct ParseIntError {
5273 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5275 feature = "int_error_matching",
5276 reason = "it can be useful to match errors when making error messages \
5277 for integer parsing",
5280 #[derive(Debug, Clone, PartialEq, Eq)]
5282 pub enum IntErrorKind {
5283 /// Value being parsed is empty.
5285 /// Among other causes, this variant will be constructed when parsing an empty string.
5287 /// Contains an invalid digit.
5289 /// Among other causes, this variant will be constructed when parsing a string that
5290 /// contains a letter.
5292 /// Integer is too large to store in target integer type.
5294 /// Integer is too small to store in target integer type.
5298 /// This variant will be emitted when the parsing string has a value of zero, which
5299 /// would be illegal for non-zero types.
5303 impl ParseIntError {
5304 /// Outputs the detailed cause of parsing an integer failing.
5306 feature = "int_error_matching",
5307 reason = "it can be useful to match errors when making error messages \
5308 for integer parsing",
5311 pub fn kind(&self) -> &IntErrorKind {
5315 feature = "int_error_internals",
5316 reason = "available through Error trait and this method should \
5317 not be exposed publicly",
5321 pub fn __description(&self) -> &str {
5323 IntErrorKind::Empty => "cannot parse integer from empty string",
5324 IntErrorKind::InvalidDigit => "invalid digit found in string",
5325 IntErrorKind::Overflow => "number too large to fit in target type",
5326 IntErrorKind::Underflow => "number too small to fit in target type",
5327 IntErrorKind::Zero => "number would be zero for non-zero type",
5332 #[stable(feature = "rust1", since = "1.0.0")]
5333 impl fmt::Display for ParseIntError {
5334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5335 self.__description().fmt(f)
5339 #[stable(feature = "rust1", since = "1.0.0")]
5340 pub use crate::num::dec2flt::ParseFloatError;