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 #[allow_internal_unstable(const_likely)]
25 macro_rules! unlikely {
27 intrinsics::unlikely($e)
31 macro_rules! impl_nonzero_fmt {
32 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
35 impl fmt::$Trait for $Ty {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 macro_rules! doc_comment {
46 ($x:expr, $($tt:tt)*) => {
52 macro_rules! nonzero_integers {
53 ( $( #[$stability: meta] $Ty: ident($Int: ty); )+ ) => {
56 concat!("An integer that is known not to equal zero.
58 This enables some memory layout optimization.
59 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
62 use std::mem::size_of;
63 assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
67 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
69 #[rustc_layout_scalar_valid_range_start(1)]
70 #[rustc_nonnull_optimization_guaranteed]
75 /// Creates a non-zero without checking the value.
79 /// The value must not be zero.
81 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
83 pub const unsafe fn new_unchecked(n: $Int) -> Self {
84 // SAFETY: this is guaranteed to be safe by the caller.
88 /// Creates a non-zero if the given value is not zero.
90 #[rustc_const_stable(feature = "const_nonzero_int_methods", since = "1.47.0")]
92 pub const fn new(n: $Int) -> Option<Self> {
94 // SAFETY: we just checked that there's no `0`
95 Some(unsafe { Self(n) })
101 /// Returns the value as a primitive type.
104 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
105 pub const fn get(self) -> $Int {
111 #[stable(feature = "from_nonzero", since = "1.31.0")]
112 impl From<$Ty> for $Int {
115 "Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`"),
116 fn from(nonzero: $Ty) -> Self {
122 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
126 fn bitor(self, rhs: Self) -> Self::Output {
127 // Safety: since `self` and `rhs` are both nonzero, the
128 // result of the bitwise-or will be nonzero.
129 unsafe { $Ty::new_unchecked(self.get() | rhs.get()) }
133 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
134 impl BitOr<$Int> for $Ty {
137 fn bitor(self, rhs: $Int) -> Self::Output {
138 // Safety: since `self` is nonzero, the result of the
139 // bitwise-or will be nonzero regardless of the value of
141 unsafe { $Ty::new_unchecked(self.get() | rhs) }
145 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
146 impl BitOr<$Ty> for $Int {
149 fn bitor(self, rhs: $Ty) -> Self::Output {
150 // Safety: since `rhs` is nonzero, the result of the
151 // bitwise-or will be nonzero regardless of the value of
153 unsafe { $Ty::new_unchecked(self | rhs.get()) }
157 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
158 impl BitOrAssign for $Ty {
160 fn bitor_assign(&mut self, rhs: Self) {
165 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
166 impl BitOrAssign<$Int> for $Ty {
168 fn bitor_assign(&mut self, rhs: $Int) {
174 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
181 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
182 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
183 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
184 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
185 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
186 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
187 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
188 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
189 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
190 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
191 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
192 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
195 macro_rules! from_str_radix_nzint_impl {
197 #[stable(feature = "nonzero_parse", since = "1.35.0")]
198 impl FromStr for $t {
199 type Err = ParseIntError;
200 fn from_str(src: &str) -> Result<Self, Self::Err> {
201 Self::new(from_str_radix(src, 10)?)
202 .ok_or(ParseIntError {
203 kind: IntErrorKind::Zero
210 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
211 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
213 /// Provides intentionally-wrapped arithmetic on `T`.
215 /// Operations like `+` on `u32` values are intended to never overflow,
216 /// and in some debug configurations overflow is detected and results
217 /// in a panic. While most arithmetic falls into this category, some
218 /// code explicitly expects and relies upon modular arithmetic (e.g.,
221 /// Wrapping arithmetic can be achieved either through methods like
222 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
223 /// all standard arithmetic operations on the underlying value are
224 /// intended to have wrapping semantics.
226 /// The underlying value can be retrieved through the `.0` index of the
227 /// `Wrapping` tuple.
232 /// use std::num::Wrapping;
234 /// let zero = Wrapping(0u32);
235 /// let one = Wrapping(1u32);
237 /// assert_eq!(u32::MAX, (zero - one).0);
239 #[stable(feature = "rust1", since = "1.0.0")]
240 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
242 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
244 #[stable(feature = "rust1", since = "1.0.0")]
245 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251 #[stable(feature = "wrapping_display", since = "1.10.0")]
252 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
259 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
266 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
273 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
280 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286 // All these modules are technically private and only exposed for coretests:
294 macro_rules! usize_isize_to_xe_bytes_doc {
298 **Note**: This function returns an array of length 2, 4 or 8 bytes
299 depending on the target pointer size.
305 macro_rules! usize_isize_from_xe_bytes_doc {
309 **Note**: This function takes an array of length 2, 4 or 8 bytes
310 depending on the target pointer size.
316 macro_rules! int_impl {
317 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
318 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
319 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
320 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
322 concat!("The smallest value that can be represented by this integer type.
329 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, ", stringify!($Min), ");",
332 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
333 pub const MIN: Self = !0 ^ ((!0 as $UnsignedT) >> 1) as Self;
337 concat!("The largest value that can be represented by this integer type.
344 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");",
347 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
348 pub const MAX: Self = !Self::MIN;
352 concat!("Converts a string slice in a given base to an integer.
354 The string is expected to be an optional `+` or `-` sign followed by digits.
355 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
356 depending on `radix`:
364 This function panics if `radix` is not in the range from 2 to 36.
371 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
376 from_str_radix(src, radix)
381 concat!("Returns the number of ones in the binary representation of `self`.
388 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
390 assert_eq!(n.count_ones(), 1);",
394 #[stable(feature = "rust1", since = "1.0.0")]
395 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
397 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
401 concat!("Returns the number of zeros in the binary representation of `self`.
408 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 1);", $EndFeature, "
410 #[stable(feature = "rust1", since = "1.0.0")]
411 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
413 pub const fn count_zeros(self) -> u32 {
419 concat!("Returns the number of leading zeros in the binary representation of `self`.
426 ", $Feature, "let n = -1", stringify!($SelfT), ";
428 assert_eq!(n.leading_zeros(), 0);",
431 #[stable(feature = "rust1", since = "1.0.0")]
432 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
434 pub const fn leading_zeros(self) -> u32 {
435 (self as $UnsignedT).leading_zeros()
440 concat!("Returns the number of trailing zeros in the binary representation of `self`.
447 ", $Feature, "let n = -4", stringify!($SelfT), ";
449 assert_eq!(n.trailing_zeros(), 2);",
452 #[stable(feature = "rust1", since = "1.0.0")]
453 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
455 pub const fn trailing_zeros(self) -> u32 {
456 (self as $UnsignedT).trailing_zeros()
461 concat!("Returns the number of leading ones in the binary representation of `self`.
468 ", $Feature, "let n = -1", stringify!($SelfT), ";
470 assert_eq!(n.leading_ones(), ", stringify!($BITS), ");",
473 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
474 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
476 pub const fn leading_ones(self) -> u32 {
477 (self as $UnsignedT).leading_ones()
482 concat!("Returns the number of trailing ones in the binary representation of `self`.
489 ", $Feature, "let n = 3", stringify!($SelfT), ";
491 assert_eq!(n.trailing_ones(), 2);",
494 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
495 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
497 pub const fn trailing_ones(self) -> u32 {
498 (self as $UnsignedT).trailing_ones()
503 concat!("Shifts the bits to the left by a specified amount, `n`,
504 wrapping the truncated bits to the end of the resulting integer.
506 Please note this isn't the same operation as the `<<` shifting operator!
513 let n = ", $rot_op, stringify!($SelfT), ";
514 let m = ", $rot_result, ";
516 assert_eq!(n.rotate_left(", $rot, "), m);
518 #[stable(feature = "rust1", since = "1.0.0")]
519 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
520 #[must_use = "this returns the result of the operation, \
521 without modifying the original"]
523 pub const fn rotate_left(self, n: u32) -> Self {
524 (self as $UnsignedT).rotate_left(n) as Self
529 concat!("Shifts the bits to the right by a specified amount, `n`,
530 wrapping the truncated bits to the beginning of the resulting
533 Please note this isn't the same operation as the `>>` shifting operator!
540 let n = ", $rot_result, stringify!($SelfT), ";
541 let m = ", $rot_op, ";
543 assert_eq!(n.rotate_right(", $rot, "), m);
545 #[stable(feature = "rust1", since = "1.0.0")]
546 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
547 #[must_use = "this returns the result of the operation, \
548 without modifying the original"]
550 pub const fn rotate_right(self, n: u32) -> Self {
551 (self as $UnsignedT).rotate_right(n) as Self
556 concat!("Reverses the byte order of the integer.
563 let n = ", $swap_op, stringify!($SelfT), ";
565 let m = n.swap_bytes();
567 assert_eq!(m, ", $swapped, ");
569 #[stable(feature = "rust1", since = "1.0.0")]
570 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
572 pub const fn swap_bytes(self) -> Self {
573 (self as $UnsignedT).swap_bytes() as Self
578 concat!("Reverses the bit pattern of the integer.
585 let n = ", $swap_op, stringify!($SelfT), ";
586 let m = n.reverse_bits();
588 assert_eq!(m, ", $reversed, ");
590 #[stable(feature = "reverse_bits", since = "1.37.0")]
591 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
594 pub const fn reverse_bits(self) -> Self {
595 (self as $UnsignedT).reverse_bits() as Self
600 concat!("Converts an integer from big endian to the target's endianness.
602 On big endian this is a no-op. On little endian the bytes are swapped.
609 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
611 if cfg!(target_endian = \"big\") {
612 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
614 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
618 #[stable(feature = "rust1", since = "1.0.0")]
619 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
621 pub const fn from_be(x: Self) -> Self {
622 #[cfg(target_endian = "big")]
626 #[cfg(not(target_endian = "big"))]
634 concat!("Converts an integer from little endian to the target's endianness.
636 On little endian this is a no-op. On big endian the bytes are swapped.
643 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
645 if cfg!(target_endian = \"little\") {
646 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
648 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
652 #[stable(feature = "rust1", since = "1.0.0")]
653 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
655 pub const fn from_le(x: Self) -> Self {
656 #[cfg(target_endian = "little")]
660 #[cfg(not(target_endian = "little"))]
668 concat!("Converts `self` to big endian from the target's endianness.
670 On big endian this is a no-op. On little endian the bytes are swapped.
677 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
679 if cfg!(target_endian = \"big\") {
680 assert_eq!(n.to_be(), n)
682 assert_eq!(n.to_be(), n.swap_bytes())
686 #[stable(feature = "rust1", since = "1.0.0")]
687 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
689 pub const fn to_be(self) -> Self { // or not to be?
690 #[cfg(target_endian = "big")]
694 #[cfg(not(target_endian = "big"))]
702 concat!("Converts `self` to little endian from the target's endianness.
704 On little endian this is a no-op. On big endian the bytes are swapped.
711 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
713 if cfg!(target_endian = \"little\") {
714 assert_eq!(n.to_le(), n)
716 assert_eq!(n.to_le(), n.swap_bytes())
720 #[stable(feature = "rust1", since = "1.0.0")]
721 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
723 pub const fn to_le(self) -> Self {
724 #[cfg(target_endian = "little")]
728 #[cfg(not(target_endian = "little"))]
736 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
737 if overflow occurred.
744 ", $Feature, "assert_eq!((", stringify!($SelfT),
745 "::MAX - 2).checked_add(1), Some(", stringify!($SelfT), "::MAX - 1));
746 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);",
749 #[stable(feature = "rust1", since = "1.0.0")]
750 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
751 #[must_use = "this returns the result of the operation, \
752 without modifying the original"]
754 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
755 let (a, b) = self.overflowing_add(rhs);
756 if unlikely!(b) {None} else {Some(a)}
761 concat!("Unchecked integer addition. Computes `self + rhs`, assuming overflow
762 cannot occur. This results in undefined behavior when `self + rhs > ", stringify!($SelfT),
763 "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`."),
765 feature = "unchecked_math",
766 reason = "niche optimization path",
769 #[must_use = "this returns the result of the operation, \
770 without modifying the original"]
772 pub unsafe fn unchecked_add(self, rhs: Self) -> Self {
773 // SAFETY: the caller must uphold the safety contract for
775 unsafe { intrinsics::unchecked_add(self, rhs) }
780 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
788 ", $Feature, "assert_eq!((", stringify!($SelfT),
789 "::MIN + 2).checked_sub(1), Some(", stringify!($SelfT), "::MIN + 1));
790 assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(3), None);",
793 #[stable(feature = "rust1", since = "1.0.0")]
794 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
795 #[must_use = "this returns the result of the operation, \
796 without modifying the original"]
798 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
799 let (a, b) = self.overflowing_sub(rhs);
800 if unlikely!(b) {None} else {Some(a)}
805 concat!("Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
806 cannot occur. This results in undefined behavior when `self - rhs > ", stringify!($SelfT),
807 "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`."),
809 feature = "unchecked_math",
810 reason = "niche optimization path",
813 #[must_use = "this returns the result of the operation, \
814 without modifying the original"]
816 pub unsafe fn unchecked_sub(self, rhs: Self) -> Self {
817 // SAFETY: the caller must uphold the safety contract for
819 unsafe { intrinsics::unchecked_sub(self, rhs) }
824 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
832 ", $Feature, "assert_eq!(", stringify!($SelfT),
833 "::MAX.checked_mul(1), Some(", stringify!($SelfT), "::MAX));
834 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);",
837 #[stable(feature = "rust1", since = "1.0.0")]
838 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
839 #[must_use = "this returns the result of the operation, \
840 without modifying the original"]
842 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
843 let (a, b) = self.overflowing_mul(rhs);
844 if unlikely!(b) {None} else {Some(a)}
849 concat!("Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
850 cannot occur. This results in undefined behavior when `self * rhs > ", stringify!($SelfT),
851 "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`."),
853 feature = "unchecked_math",
854 reason = "niche optimization path",
857 #[must_use = "this returns the result of the operation, \
858 without modifying the original"]
860 pub unsafe fn unchecked_mul(self, rhs: Self) -> Self {
861 // SAFETY: the caller must uphold the safety contract for
863 unsafe { intrinsics::unchecked_mul(self, rhs) }
868 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
869 or the division results in overflow.
876 ", $Feature, "assert_eq!((", stringify!($SelfT),
877 "::MIN + 1).checked_div(-1), Some(", stringify!($Max), "));
878 assert_eq!(", stringify!($SelfT), "::MIN.checked_div(-1), None);
879 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
882 #[stable(feature = "rust1", since = "1.0.0")]
883 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
884 #[must_use = "this returns the result of the operation, \
885 without modifying the original"]
887 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
888 if unlikely!(rhs == 0 || (self == Self::MIN && rhs == -1)) {
891 // SAFETY: div by zero and by INT_MIN have been checked above
892 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
898 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
899 returning `None` if `rhs == 0` or the division results in overflow.
906 assert_eq!((", stringify!($SelfT),
907 "::MIN + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
908 assert_eq!(", stringify!($SelfT), "::MIN.checked_div_euclid(-1), None);
909 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
911 #[stable(feature = "euclidean_division", since = "1.38.0")]
912 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
913 #[must_use = "this returns the result of the operation, \
914 without modifying the original"]
916 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
917 if unlikely!(rhs == 0 || (self == Self::MIN && rhs == -1)) {
920 Some(self.div_euclid(rhs))
926 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
927 `rhs == 0` or the division results in overflow.
935 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
936 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
937 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
940 #[stable(feature = "wrapping", since = "1.7.0")]
941 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
942 #[must_use = "this returns the result of the operation, \
943 without modifying the original"]
945 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
946 if unlikely!(rhs == 0 || (self == Self::MIN && rhs == -1)) {
949 // SAFETY: div by zero and by INT_MIN have been checked above
950 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
956 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
957 if `rhs == 0` or the division results in overflow.
964 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
965 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
966 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
968 #[stable(feature = "euclidean_division", since = "1.38.0")]
969 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
970 #[must_use = "this returns the result of the operation, \
971 without modifying the original"]
973 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
974 if unlikely!(rhs == 0 || (self == Self::MIN && rhs == -1)) {
977 Some(self.rem_euclid(rhs))
983 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
991 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
992 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
995 #[stable(feature = "wrapping", since = "1.7.0")]
996 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
998 pub const fn checked_neg(self) -> Option<Self> {
999 let (a, b) = self.overflowing_neg();
1000 if unlikely!(b) {None} else {Some(a)}
1005 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
1006 than or equal to the number of bits in `self`.
1013 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
1014 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
1017 #[stable(feature = "wrapping", since = "1.7.0")]
1018 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1019 #[must_use = "this returns the result of the operation, \
1020 without modifying the original"]
1022 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
1023 let (a, b) = self.overflowing_shl(rhs);
1024 if unlikely!(b) {None} else {Some(a)}
1029 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
1030 larger than or equal to the number of bits in `self`.
1037 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
1038 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
1041 #[stable(feature = "wrapping", since = "1.7.0")]
1042 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1043 #[must_use = "this returns the result of the operation, \
1044 without modifying the original"]
1046 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
1047 let (a, b) = self.overflowing_shr(rhs);
1048 if unlikely!(b) {None} else {Some(a)}
1053 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
1062 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
1063 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
1066 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1067 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1069 pub const fn checked_abs(self) -> Option<Self> {
1070 if self.is_negative() {
1079 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
1087 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
1088 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);",
1092 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1093 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1094 #[must_use = "this returns the result of the operation, \
1095 without modifying the original"]
1097 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
1101 let mut base = self;
1102 let mut acc: Self = 1;
1106 acc = try_opt!(acc.checked_mul(base));
1109 base = try_opt!(base.checked_mul(base));
1111 // since exp!=0, finally the exp must be 1.
1112 // Deal with the final bit of the exponent separately, since
1113 // squaring the base afterwards is not necessary and may cause a
1114 // needless overflow.
1115 Some(try_opt!(acc.checked_mul(base)))
1120 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
1121 bounds instead of overflowing.
1128 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
1129 assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT),
1131 assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT),
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1138 #[must_use = "this returns the result of the operation, \
1139 without modifying the original"]
1141 pub const fn saturating_add(self, rhs: Self) -> Self {
1142 intrinsics::saturating_add(self, rhs)
1147 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
1148 numeric bounds instead of overflowing.
1155 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
1156 assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT),
1158 assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT),
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1164 #[must_use = "this returns the result of the operation, \
1165 without modifying the original"]
1167 pub const fn saturating_sub(self, rhs: Self) -> Self {
1168 intrinsics::saturating_sub(self, rhs)
1173 concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
1174 instead of overflowing.
1181 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
1182 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
1183 assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT),
1185 assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT),
1190 #[stable(feature = "saturating_neg", since = "1.45.0")]
1191 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1193 pub const fn saturating_neg(self) -> Self {
1194 intrinsics::saturating_sub(0, self)
1199 concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1200 MIN` instead of overflowing.
1207 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
1208 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
1209 assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT),
1211 assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT),
1216 #[stable(feature = "saturating_neg", since = "1.45.0")]
1217 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1219 pub const fn saturating_abs(self) -> Self {
1220 if self.is_negative() {
1221 self.saturating_neg()
1229 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1230 numeric bounds instead of overflowing.
1238 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1239 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1240 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1243 #[stable(feature = "wrapping", since = "1.7.0")]
1244 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1245 #[must_use = "this returns the result of the operation, \
1246 without modifying the original"]
1248 pub const fn saturating_mul(self, rhs: Self) -> Self {
1249 match self.checked_mul(rhs) {
1251 None => if (self < 0) == (rhs < 0) {
1261 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1262 saturating at the numeric bounds instead of overflowing.
1270 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1271 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1272 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1275 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1276 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1277 #[must_use = "this returns the result of the operation, \
1278 without modifying the original"]
1280 pub const fn saturating_pow(self, exp: u32) -> Self {
1281 match self.checked_pow(exp) {
1283 None if self < 0 && exp % 2 == 1 => Self::MIN,
1290 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1291 boundary of the type.
1298 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1299 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT),
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1305 #[must_use = "this returns the result of the operation, \
1306 without modifying the original"]
1308 pub const fn wrapping_add(self, rhs: Self) -> Self {
1309 intrinsics::wrapping_add(self, rhs)
1314 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1315 boundary of the type.
1322 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1323 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ",
1324 stringify!($SelfT), "::MAX);",
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1329 #[must_use = "this returns the result of the operation, \
1330 without modifying the original"]
1332 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1333 intrinsics::wrapping_sub(self, rhs)
1338 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1339 the boundary of the type.
1346 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1347 assert_eq!(11i8.wrapping_mul(12), -124);",
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1352 #[must_use = "this returns the result of the operation, \
1353 without modifying the original"]
1355 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1356 intrinsics::wrapping_mul(self, rhs)
1361 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1362 boundary of the type.
1364 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1365 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1366 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1370 This function will panic if `rhs` is 0.
1377 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1378 assert_eq!((-128i8).wrapping_div(-1), -128);",
1381 #[stable(feature = "num_wrapping", since = "1.2.0")]
1382 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1383 #[must_use = "this returns the result of the operation, \
1384 without modifying the original"]
1386 pub const fn wrapping_div(self, rhs: Self) -> Self {
1387 self.overflowing_div(rhs).0
1392 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1393 wrapping around at the boundary of the type.
1395 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1396 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1397 type. In this case, this method returns `MIN` itself.
1401 This function will panic if `rhs` is 0.
1408 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1409 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1411 #[stable(feature = "euclidean_division", since = "1.38.0")]
1412 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1413 #[must_use = "this returns the result of the operation, \
1414 without modifying the original"]
1416 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1417 self.overflowing_div_euclid(rhs).0
1422 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1423 boundary of the type.
1425 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1426 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1427 this function returns `0`.
1431 This function will panic if `rhs` is 0.
1438 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1439 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1442 #[stable(feature = "num_wrapping", since = "1.2.0")]
1443 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1444 #[must_use = "this returns the result of the operation, \
1445 without modifying the original"]
1447 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1448 self.overflowing_rem(rhs).0
1453 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1454 at the boundary of the type.
1456 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1457 for the type). In this case, this method returns 0.
1461 This function will panic if `rhs` is 0.
1468 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1469 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1471 #[stable(feature = "euclidean_division", since = "1.38.0")]
1472 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1473 #[must_use = "this returns the result of the operation, \
1474 without modifying the original"]
1476 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1477 self.overflowing_rem_euclid(rhs).0
1482 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1485 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1486 is the negative minimal value for the type); this is a positive value that is too large to represent
1487 in the type. In such a case, this function returns `MIN` itself.
1494 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1495 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT),
1499 #[stable(feature = "num_wrapping", since = "1.2.0")]
1500 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1502 pub const fn wrapping_neg(self) -> Self {
1503 self.overflowing_neg().0
1508 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1509 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1511 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1512 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1513 The primitive integer types all implement a `[`rotate_left`](#method.rotate_left) function,
1514 which may be what you want instead.
1521 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1522 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1525 #[stable(feature = "num_wrapping", since = "1.2.0")]
1526 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1527 #[must_use = "this returns the result of the operation, \
1528 without modifying the original"]
1530 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1531 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1534 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1540 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1541 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1543 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1544 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1545 end. The primitive integer types all implement a [`rotate_right`](#method.rotate_right) function,
1546 which may be what you want instead.
1553 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1554 assert_eq!((-128i16).wrapping_shr(64), -128);",
1557 #[stable(feature = "num_wrapping", since = "1.2.0")]
1558 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1559 #[must_use = "this returns the result of the operation, \
1560 without modifying the original"]
1562 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1563 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1566 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1572 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1573 the boundary of the type.
1575 The only case where such wrapping can occur is when one takes the absolute value of the negative
1576 minimal value for the type this is a positive value that is too large to represent in the type. In
1577 such a case, this function returns `MIN` itself.
1584 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1585 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1586 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT),
1588 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1591 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1592 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1593 #[allow(unused_attributes)]
1595 pub const fn wrapping_abs(self) -> Self {
1596 if self.is_negative() {
1605 concat!("Computes the absolute value of `self` without any wrapping
1614 ", $Feature, "#![feature(unsigned_abs)]
1615 assert_eq!(100", stringify!($SelfT), ".unsigned_abs(), 100", stringify!($UnsignedT), ");
1616 assert_eq!((-100", stringify!($SelfT), ").unsigned_abs(), 100", stringify!($UnsignedT), ");
1617 assert_eq!((-128i8).unsigned_abs(), 128u8);",
1620 #[unstable(feature = "unsigned_abs", issue = "74913")]
1622 pub const fn unsigned_abs(self) -> $UnsignedT {
1623 self.wrapping_abs() as $UnsignedT
1628 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1629 wrapping around at the boundary of the type.
1636 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1637 assert_eq!(3i8.wrapping_pow(5), -13);
1638 assert_eq!(3i8.wrapping_pow(6), -39);",
1641 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1642 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1643 #[must_use = "this returns the result of the operation, \
1644 without modifying the original"]
1646 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1650 let mut base = self;
1651 let mut acc: Self = 1;
1655 acc = acc.wrapping_mul(base);
1658 base = base.wrapping_mul(base);
1661 // since exp!=0, finally the exp must be 1.
1662 // Deal with the final bit of the exponent separately, since
1663 // squaring the base afterwards is not necessary and may cause a
1664 // needless overflow.
1665 acc.wrapping_mul(base)
1670 concat!("Calculates `self` + `rhs`
1672 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1673 occur. If an overflow would have occurred then the wrapped value is returned.
1681 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1682 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1683 "::MIN, true));", $EndFeature, "
1685 #[stable(feature = "wrapping", since = "1.7.0")]
1686 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1687 #[must_use = "this returns the result of the operation, \
1688 without modifying the original"]
1690 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1691 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1697 concat!("Calculates `self` - `rhs`
1699 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1700 would occur. If an overflow would have occurred then the wrapped value is returned.
1708 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1709 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1710 "::MAX, true));", $EndFeature, "
1712 #[stable(feature = "wrapping", since = "1.7.0")]
1713 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1714 #[must_use = "this returns the result of the operation, \
1715 without modifying the original"]
1717 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1718 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1724 concat!("Calculates the multiplication of `self` and `rhs`.
1726 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1727 would occur. If an overflow would have occurred then the wrapped value is returned.
1734 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1735 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1738 #[stable(feature = "wrapping", since = "1.7.0")]
1739 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1740 #[must_use = "this returns the result of the operation, \
1741 without modifying the original"]
1743 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1744 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1750 concat!("Calculates the divisor when `self` is divided by `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.
1765 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1766 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1771 #[stable(feature = "wrapping", since = "1.7.0")]
1772 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1773 #[must_use = "this returns the result of the operation, \
1774 without modifying the original"]
1775 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1776 if unlikely!(self == Self::MIN && rhs == -1) {
1785 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1787 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1788 occur. If an overflow would occur then `self` is returned.
1792 This function will panic if `rhs` is 0.
1799 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1800 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1804 #[stable(feature = "euclidean_division", since = "1.38.0")]
1805 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1806 #[must_use = "this returns the result of the operation, \
1807 without modifying the original"]
1808 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1809 if unlikely!(self == Self::MIN && rhs == -1) {
1812 (self.div_euclid(rhs), false)
1818 concat!("Calculates the remainder when `self` is divided by `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.
1833 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1834 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1838 #[stable(feature = "wrapping", since = "1.7.0")]
1839 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1840 #[must_use = "this returns the result of the operation, \
1841 without modifying the original"]
1842 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1843 if unlikely!(self == Self::MIN && rhs == -1) {
1853 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1855 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1856 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1860 This function will panic if `rhs` is 0.
1867 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1868 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1870 #[stable(feature = "euclidean_division", since = "1.38.0")]
1871 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1872 #[must_use = "this returns the result of the operation, \
1873 without modifying the original"]
1875 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1876 if unlikely!(self == Self::MIN && rhs == -1) {
1879 (self.rem_euclid(rhs), false)
1886 concat!("Negates self, overflowing if this is equal to the minimum value.
1888 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1889 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1890 minimum value will be returned again and `true` will be returned for an overflow happening.
1897 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1898 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1899 "::MIN, true));", $EndFeature, "
1902 #[stable(feature = "wrapping", since = "1.7.0")]
1903 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1904 #[allow(unused_attributes)]
1905 pub const fn overflowing_neg(self) -> (Self, bool) {
1906 if unlikely!(self == Self::MIN) {
1915 concat!("Shifts self left by `rhs` bits.
1917 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1918 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1919 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1926 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1927 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1930 #[stable(feature = "wrapping", since = "1.7.0")]
1931 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1932 #[must_use = "this returns the result of the operation, \
1933 without modifying the original"]
1935 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1936 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1941 concat!("Shifts self right by `rhs` bits.
1943 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1944 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1945 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1952 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1953 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1956 #[stable(feature = "wrapping", since = "1.7.0")]
1957 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1958 #[must_use = "this returns the result of the operation, \
1959 without modifying the original"]
1961 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1962 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1967 concat!("Computes the absolute value of `self`.
1969 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1970 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1971 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1972 for an overflow happening.
1979 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1980 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1981 assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT),
1985 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1986 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1988 pub const fn overflowing_abs(self) -> (Self, bool) {
1989 (self.wrapping_abs(), self == Self::MIN)
1994 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1996 Returns a tuple of the exponentiation along with a bool indicating
1997 whether an overflow happened.
2004 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
2005 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
2008 #[stable(feature = "no_panic_pow", since = "1.34.0")]
2009 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
2010 #[must_use = "this returns the result of the operation, \
2011 without modifying the original"]
2013 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
2017 let mut base = self;
2018 let mut acc: Self = 1;
2019 let mut overflown = false;
2020 // Scratch space for storing results of overflowing_mul.
2025 r = acc.overflowing_mul(base);
2030 r = base.overflowing_mul(base);
2035 // since exp!=0, finally the exp must be 1.
2036 // Deal with the final bit of the exponent separately, since
2037 // squaring the base afterwards is not necessary and may cause a
2038 // needless overflow.
2039 r = acc.overflowing_mul(base);
2046 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2053 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
2055 assert_eq!(x.pow(5), 32);",
2058 #[stable(feature = "rust1", since = "1.0.0")]
2059 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
2060 #[must_use = "this returns the result of the operation, \
2061 without modifying the original"]
2063 #[rustc_inherit_overflow_checks]
2064 pub const fn pow(self, mut exp: u32) -> Self {
2068 let mut base = self;
2079 // since exp!=0, finally the exp must be 1.
2080 // Deal with the final bit of the exponent separately, since
2081 // squaring the base afterwards is not necessary and may cause a
2082 // needless overflow.
2088 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
2090 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
2091 with `0 <= self.rem_euclid(rhs) < rhs`.
2093 In other words, the result is `self / rhs` rounded to the integer `n`
2094 such that `self >= n * rhs`.
2095 If `self > 0`, this is equal to round towards zero (the default in Rust);
2096 if `self < 0`, this is equal to round towards +/- infinity.
2100 This function will panic if `rhs` is 0 or the division results in overflow.
2107 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2110 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
2111 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
2112 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
2113 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
2115 #[stable(feature = "euclidean_division", since = "1.38.0")]
2116 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2117 #[must_use = "this returns the result of the operation, \
2118 without modifying the original"]
2120 #[rustc_inherit_overflow_checks]
2121 pub const fn div_euclid(self, rhs: Self) -> Self {
2124 return if rhs > 0 { q - 1 } else { q + 1 }
2132 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
2134 This is done as if by the Euclidean division algorithm -- given
2135 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
2136 `0 <= r < abs(rhs)`.
2140 This function will panic if `rhs` is 0 or the division results in overflow.
2147 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2150 assert_eq!(a.rem_euclid(b), 3);
2151 assert_eq!((-a).rem_euclid(b), 1);
2152 assert_eq!(a.rem_euclid(-b), 3);
2153 assert_eq!((-a).rem_euclid(-b), 1);
2155 #[stable(feature = "euclidean_division", since = "1.38.0")]
2156 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2157 #[must_use = "this returns the result of the operation, \
2158 without modifying the original"]
2160 #[rustc_inherit_overflow_checks]
2161 pub const fn rem_euclid(self, rhs: Self) -> Self {
2176 concat!("Computes the absolute value of `self`.
2180 The absolute value of `", stringify!($SelfT), "::MIN` cannot be represented as an
2181 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
2182 code in debug mode will trigger a panic on this case and optimized code will return `",
2183 stringify!($SelfT), "::MIN` without a panic.
2190 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
2191 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
2194 #[stable(feature = "rust1", since = "1.0.0")]
2195 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2196 #[allow(unused_attributes)]
2198 #[rustc_inherit_overflow_checks]
2199 pub const fn abs(self) -> Self {
2200 // Note that the #[inline] above means that the overflow
2201 // semantics of the subtraction depend on the crate we're being
2203 if self.is_negative() {
2212 concat!("Returns a number representing sign of `self`.
2214 - `0` if the number is zero
2215 - `1` if the number is positive
2216 - `-1` if the number is negative
2223 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
2224 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
2225 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
2228 #[stable(feature = "rust1", since = "1.0.0")]
2229 #[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
2231 pub const fn signum(self) -> Self {
2241 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2249 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2250 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2253 #[stable(feature = "rust1", since = "1.0.0")]
2254 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2256 pub const fn is_positive(self) -> bool { self > 0 }
2260 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2268 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2269 assert!(!10", stringify!($SelfT), ".is_negative());",
2272 #[stable(feature = "rust1", since = "1.0.0")]
2273 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2275 pub const fn is_negative(self) -> bool { self < 0 }
2279 concat!("Return the memory representation of this integer as a byte array in
2280 big-endian (network) byte order.
2287 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2288 assert_eq!(bytes, ", $be_bytes, ");
2290 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2291 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2293 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2294 self.to_be().to_ne_bytes()
2299 concat!("Return the memory representation of this integer as a byte array in
2300 little-endian byte order.
2307 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2308 assert_eq!(bytes, ", $le_bytes, ");
2310 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2311 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2313 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2314 self.to_le().to_ne_bytes()
2320 Return the memory representation of this integer as a byte array in
2323 As the target platform's native endianness is used, portable code
2324 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2329 [`to_be_bytes`]: #method.to_be_bytes
2330 [`to_le_bytes`]: #method.to_le_bytes
2335 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2338 if cfg!(target_endian = \"big\") {
2345 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2346 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2347 // SAFETY: const sound because integers are plain old datatypes so we can always
2348 // transmute them to arrays of bytes
2349 #[allow_internal_unstable(const_fn_transmute)]
2351 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2352 // SAFETY: integers are plain old datatypes so we can always transmute them to
2354 unsafe { mem::transmute(self) }
2359 concat!("Create an integer value from its representation as a byte array in
2367 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2368 assert_eq!(value, ", $swap_op, ");
2371 When starting from a slice rather than an array, fallible conversion APIs can be used:
2374 use std::convert::TryInto;
2376 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2377 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2379 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2382 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2383 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2385 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2386 Self::from_be(Self::from_ne_bytes(bytes))
2392 Create an integer value from its representation as a byte array in
2400 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2401 assert_eq!(value, ", $swap_op, ");
2404 When starting from a slice rather than an array, fallible conversion APIs can be used:
2407 use std::convert::TryInto;
2409 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2410 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2412 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2415 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2416 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2418 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2419 Self::from_le(Self::from_ne_bytes(bytes))
2424 concat!("Create an integer value from its memory representation as a byte
2425 array in native endianness.
2427 As the target platform's native endianness is used, portable code
2428 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2429 appropriate instead.
2431 [`from_be_bytes`]: #method.from_be_bytes
2432 [`from_le_bytes`]: #method.from_le_bytes
2439 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2444 assert_eq!(value, ", $swap_op, ");
2447 When starting from a slice rather than an array, fallible conversion APIs can be used:
2450 use std::convert::TryInto;
2452 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2453 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2455 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2458 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2459 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2460 // SAFETY: const sound because integers are plain old datatypes so we can always
2461 // transmute to them
2462 #[allow_internal_unstable(const_fn_transmute)]
2464 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2465 // SAFETY: integers are plain old datatypes so we can always transmute to them
2466 unsafe { mem::transmute(bytes) }
2471 concat!("**This method is soft-deprecated.**
2473 Although using it won’t cause compilation warning,
2474 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
2476 Returns the smallest value that can be represented by this integer type."),
2477 #[stable(feature = "rust1", since = "1.0.0")]
2480 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2481 pub const fn min_value() -> Self {
2487 concat!("**This method is soft-deprecated.**
2489 Although using it won’t cause compilation warning,
2490 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
2492 Returns the largest value that can be represented by this integer type."),
2493 #[stable(feature = "rust1", since = "1.0.0")]
2496 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2497 pub const fn max_value() -> Self {
2506 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2507 "[0x12]", "[0x12]", "", "" }
2512 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2513 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2518 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2519 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2520 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2525 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2526 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2527 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2528 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2533 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2534 170141183460469231731687303715884105727, "", "", 16,
2535 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2536 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2537 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2538 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2539 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2540 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2543 #[cfg(target_pointer_width = "16")]
2546 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2547 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2548 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2551 #[cfg(target_pointer_width = "32")]
2554 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2555 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2556 "[0x12, 0x34, 0x56, 0x78]",
2557 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2560 #[cfg(target_pointer_width = "64")]
2563 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2564 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2565 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2566 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2567 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2570 macro_rules! uint_impl {
2571 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2572 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2573 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2574 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2576 concat!("The smallest value that can be represented by this integer type.
2583 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, 0);", $EndFeature, "
2585 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2586 pub const MIN: Self = 0;
2590 concat!("The largest value that can be represented by this integer type.
2597 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");",
2600 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2601 pub const MAX: Self = !0;
2605 concat!("Converts a string slice in a given base to an integer.
2607 The string is expected to be an optional `+` sign
2609 Leading and trailing whitespace represent an error.
2610 Digits are a subset of these characters, depending on `radix`:
2618 This function panics if `radix` is not in the range from 2 to 36.
2625 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2628 #[stable(feature = "rust1", since = "1.0.0")]
2629 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2630 from_str_radix(src, radix)
2635 concat!("Returns the number of ones in the binary representation of `self`.
2642 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2644 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2646 #[stable(feature = "rust1", since = "1.0.0")]
2647 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2649 pub const fn count_ones(self) -> u32 {
2650 intrinsics::ctpop(self as $ActualT) as u32
2655 concat!("Returns the number of zeros in the binary representation of `self`.
2662 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);", $EndFeature, "
2664 #[stable(feature = "rust1", since = "1.0.0")]
2665 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2667 pub const fn count_zeros(self) -> u32 {
2668 (!self).count_ones()
2673 concat!("Returns the number of leading zeros in the binary representation of `self`.
2680 ", $Feature, "let n = ", stringify!($SelfT), "::MAX >> 2;
2682 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2684 #[stable(feature = "rust1", since = "1.0.0")]
2685 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2687 pub const fn leading_zeros(self) -> u32 {
2688 intrinsics::ctlz(self as $ActualT) as u32
2693 concat!("Returns the number of trailing zeros in the binary representation
2701 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2703 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2705 #[stable(feature = "rust1", since = "1.0.0")]
2706 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2708 pub const fn trailing_zeros(self) -> u32 {
2709 intrinsics::cttz(self) as u32
2714 concat!("Returns the number of leading ones in the binary representation of `self`.
2721 ", $Feature, "let n = !(", stringify!($SelfT), "::MAX >> 2);
2723 assert_eq!(n.leading_ones(), 2);", $EndFeature, "
2725 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
2726 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
2728 pub const fn leading_ones(self) -> u32 {
2729 (!self).leading_zeros()
2734 concat!("Returns the number of trailing ones in the binary representation
2742 ", $Feature, "let n = 0b1010111", stringify!($SelfT), ";
2744 assert_eq!(n.trailing_ones(), 3);", $EndFeature, "
2746 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
2747 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
2749 pub const fn trailing_ones(self) -> u32 {
2750 (!self).trailing_zeros()
2755 concat!("Shifts the bits to the left by a specified amount, `n`,
2756 wrapping the truncated bits to the end of the resulting integer.
2758 Please note this isn't the same operation as the `<<` shifting operator!
2765 let n = ", $rot_op, stringify!($SelfT), ";
2766 let m = ", $rot_result, ";
2768 assert_eq!(n.rotate_left(", $rot, "), m);
2770 #[stable(feature = "rust1", since = "1.0.0")]
2771 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2772 #[must_use = "this returns the result of the operation, \
2773 without modifying the original"]
2775 pub const fn rotate_left(self, n: u32) -> Self {
2776 intrinsics::rotate_left(self, n as $SelfT)
2781 concat!("Shifts the bits to the right by a specified amount, `n`,
2782 wrapping the truncated bits to the beginning of the resulting
2785 Please note this isn't the same operation as the `>>` shifting operator!
2792 let n = ", $rot_result, stringify!($SelfT), ";
2793 let m = ", $rot_op, ";
2795 assert_eq!(n.rotate_right(", $rot, "), m);
2797 #[stable(feature = "rust1", since = "1.0.0")]
2798 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2799 #[must_use = "this returns the result of the operation, \
2800 without modifying the original"]
2802 pub const fn rotate_right(self, n: u32) -> Self {
2803 intrinsics::rotate_right(self, n as $SelfT)
2809 Reverses the byte order of the integer.
2816 let n = ", $swap_op, stringify!($SelfT), ";
2817 let m = n.swap_bytes();
2819 assert_eq!(m, ", $swapped, ");
2821 #[stable(feature = "rust1", since = "1.0.0")]
2822 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2824 pub const fn swap_bytes(self) -> Self {
2825 intrinsics::bswap(self as $ActualT) as Self
2830 concat!("Reverses the bit pattern of the integer.
2837 let n = ", $swap_op, stringify!($SelfT), ";
2838 let m = n.reverse_bits();
2840 assert_eq!(m, ", $reversed, ");
2842 #[stable(feature = "reverse_bits", since = "1.37.0")]
2843 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2846 pub const fn reverse_bits(self) -> Self {
2847 intrinsics::bitreverse(self as $ActualT) as Self
2852 concat!("Converts an integer from big endian to the target's endianness.
2854 On big endian this is a no-op. On little endian the bytes are
2862 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2864 if cfg!(target_endian = \"big\") {
2865 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2867 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2870 #[stable(feature = "rust1", since = "1.0.0")]
2871 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2873 pub const fn from_be(x: Self) -> Self {
2874 #[cfg(target_endian = "big")]
2878 #[cfg(not(target_endian = "big"))]
2886 concat!("Converts an integer from little endian to the target's endianness.
2888 On little endian this is a no-op. On big endian the bytes are
2896 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2898 if cfg!(target_endian = \"little\") {
2899 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2901 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2904 #[stable(feature = "rust1", since = "1.0.0")]
2905 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2907 pub const fn from_le(x: Self) -> Self {
2908 #[cfg(target_endian = "little")]
2912 #[cfg(not(target_endian = "little"))]
2920 concat!("Converts `self` to big endian from the target's endianness.
2922 On big endian this is a no-op. On little endian the bytes are
2930 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2932 if cfg!(target_endian = \"big\") {
2933 assert_eq!(n.to_be(), n)
2935 assert_eq!(n.to_be(), n.swap_bytes())
2938 #[stable(feature = "rust1", since = "1.0.0")]
2939 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2941 pub const fn to_be(self) -> Self { // or not to be?
2942 #[cfg(target_endian = "big")]
2946 #[cfg(not(target_endian = "big"))]
2954 concat!("Converts `self` to little endian from the target's endianness.
2956 On little endian this is a no-op. On big endian the bytes are
2964 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2966 if cfg!(target_endian = \"little\") {
2967 assert_eq!(n.to_le(), n)
2969 assert_eq!(n.to_le(), n.swap_bytes())
2972 #[stable(feature = "rust1", since = "1.0.0")]
2973 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2975 pub const fn to_le(self) -> Self {
2976 #[cfg(target_endian = "little")]
2980 #[cfg(not(target_endian = "little"))]
2988 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2989 if overflow occurred.
2996 ", $Feature, "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
2997 "Some(", stringify!($SelfT), "::MAX - 1));
2998 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);", $EndFeature, "
3000 #[stable(feature = "rust1", since = "1.0.0")]
3001 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
3002 #[must_use = "this returns the result of the operation, \
3003 without modifying the original"]
3005 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
3006 let (a, b) = self.overflowing_add(rhs);
3007 if unlikely!(b) {None} else {Some(a)}
3012 concat!("Unchecked integer addition. Computes `self + rhs`, assuming overflow
3013 cannot occur. This results in undefined behavior when `self + rhs > ", stringify!($SelfT),
3014 "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`."),
3016 feature = "unchecked_math",
3017 reason = "niche optimization path",
3020 #[must_use = "this returns the result of the operation, \
3021 without modifying the original"]
3023 pub unsafe fn unchecked_add(self, rhs: Self) -> Self {
3024 // SAFETY: the caller must uphold the safety contract for
3026 unsafe { intrinsics::unchecked_add(self, rhs) }
3031 concat!("Checked integer subtraction. Computes `self - rhs`, returning
3032 `None` if overflow occurred.
3039 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
3040 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
3042 #[stable(feature = "rust1", since = "1.0.0")]
3043 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
3044 #[must_use = "this returns the result of the operation, \
3045 without modifying the original"]
3047 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
3048 let (a, b) = self.overflowing_sub(rhs);
3049 if unlikely!(b) {None} else {Some(a)}
3054 concat!("Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
3055 cannot occur. This results in undefined behavior when `self - rhs > ", stringify!($SelfT),
3056 "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`."),
3058 feature = "unchecked_math",
3059 reason = "niche optimization path",
3062 #[must_use = "this returns the result of the operation, \
3063 without modifying the original"]
3065 pub unsafe fn unchecked_sub(self, rhs: Self) -> Self {
3066 // SAFETY: the caller must uphold the safety contract for
3068 unsafe { intrinsics::unchecked_sub(self, rhs) }
3073 concat!("Checked integer multiplication. Computes `self * rhs`, returning
3074 `None` if overflow occurred.
3081 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
3082 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);", $EndFeature, "
3084 #[stable(feature = "rust1", since = "1.0.0")]
3085 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
3086 #[must_use = "this returns the result of the operation, \
3087 without modifying the original"]
3089 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
3090 let (a, b) = self.overflowing_mul(rhs);
3091 if unlikely!(b) {None} else {Some(a)}
3096 concat!("Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
3097 cannot occur. This results in undefined behavior when `self * rhs > ", stringify!($SelfT),
3098 "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`."),
3100 feature = "unchecked_math",
3101 reason = "niche optimization path",
3104 #[must_use = "this returns the result of the operation, \
3105 without modifying the original"]
3107 pub unsafe fn unchecked_mul(self, rhs: Self) -> Self {
3108 // SAFETY: the caller must uphold the safety contract for
3110 unsafe { intrinsics::unchecked_mul(self, rhs) }
3115 concat!("Checked integer division. Computes `self / rhs`, returning `None`
3123 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
3124 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
3126 #[stable(feature = "rust1", since = "1.0.0")]
3127 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3128 #[must_use = "this returns the result of the operation, \
3129 without modifying the original"]
3131 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
3132 if unlikely!(rhs == 0) {
3135 // SAFETY: div by zero has been checked above and unsigned types have no other
3136 // failure modes for division
3137 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
3143 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
3151 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
3152 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
3154 #[stable(feature = "euclidean_division", since = "1.38.0")]
3155 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3156 #[must_use = "this returns the result of the operation, \
3157 without modifying the original"]
3159 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
3160 if unlikely!(rhs == 0) {
3163 Some(self.div_euclid(rhs))
3170 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
3178 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
3179 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
3181 #[stable(feature = "wrapping", since = "1.7.0")]
3182 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3183 #[must_use = "this returns the result of the operation, \
3184 without modifying the original"]
3186 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
3187 if unlikely!(rhs == 0) {
3190 // SAFETY: div by zero has been checked above and unsigned types have no other
3191 // failure modes for division
3192 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3198 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3206 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3207 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3209 #[stable(feature = "euclidean_division", since = "1.38.0")]
3210 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3211 #[must_use = "this returns the result of the operation, \
3212 without modifying the original"]
3214 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3215 if unlikely!(rhs == 0) {
3218 Some(self.rem_euclid(rhs))
3224 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3227 Note that negating any positive integer will overflow.
3234 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3235 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3237 #[stable(feature = "wrapping", since = "1.7.0")]
3238 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
3240 pub const fn checked_neg(self) -> Option<Self> {
3241 let (a, b) = self.overflowing_neg();
3242 if unlikely!(b) {None} else {Some(a)}
3247 concat!("Checked shift left. Computes `self << rhs`, returning `None`
3248 if `rhs` is larger than or equal to the number of bits in `self`.
3255 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3256 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3258 #[stable(feature = "wrapping", since = "1.7.0")]
3259 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
3260 #[must_use = "this returns the result of the operation, \
3261 without modifying the original"]
3263 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
3264 let (a, b) = self.overflowing_shl(rhs);
3265 if unlikely!(b) {None} else {Some(a)}
3270 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3271 if `rhs` is larger than or equal to the number of bits in `self`.
3278 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3279 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3281 #[stable(feature = "wrapping", since = "1.7.0")]
3282 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
3283 #[must_use = "this returns the result of the operation, \
3284 without modifying the original"]
3286 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
3287 let (a, b) = self.overflowing_shr(rhs);
3288 if unlikely!(b) {None} else {Some(a)}
3293 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3301 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3302 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);", $EndFeature, "
3304 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3305 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3306 #[must_use = "this returns the result of the operation, \
3307 without modifying the original"]
3309 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
3313 let mut base = self;
3314 let mut acc: Self = 1;
3318 acc = try_opt!(acc.checked_mul(base));
3321 base = try_opt!(base.checked_mul(base));
3324 // since exp!=0, finally the exp must be 1.
3325 // Deal with the final bit of the exponent separately, since
3326 // squaring the base afterwards is not necessary and may cause a
3327 // needless overflow.
3329 Some(try_opt!(acc.checked_mul(base)))
3334 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3335 the numeric bounds instead of overflowing.
3342 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3343 assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);",
3347 #[stable(feature = "rust1", since = "1.0.0")]
3348 #[must_use = "this returns the result of the operation, \
3349 without modifying the original"]
3350 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
3352 pub const fn saturating_add(self, rhs: Self) -> Self {
3353 intrinsics::saturating_add(self, rhs)
3358 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3359 at the numeric bounds instead of overflowing.
3366 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3367 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3369 #[stable(feature = "rust1", since = "1.0.0")]
3370 #[must_use = "this returns the result of the operation, \
3371 without modifying the original"]
3372 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
3374 pub const fn saturating_sub(self, rhs: Self) -> Self {
3375 intrinsics::saturating_sub(self, rhs)
3380 concat!("Saturating integer multiplication. Computes `self * rhs`,
3381 saturating at the numeric bounds instead of overflowing.
3389 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3390 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3391 "::MAX);", $EndFeature, "
3393 #[stable(feature = "wrapping", since = "1.7.0")]
3394 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
3395 #[must_use = "this returns the result of the operation, \
3396 without modifying the original"]
3398 pub const fn saturating_mul(self, rhs: Self) -> Self {
3399 match self.checked_mul(rhs) {
3407 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3408 saturating at the numeric bounds instead of overflowing.
3416 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3417 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3420 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3421 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3422 #[must_use = "this returns the result of the operation, \
3423 without modifying the original"]
3425 pub const fn saturating_pow(self, exp: u32) -> Self {
3426 match self.checked_pow(exp) {
3434 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3435 wrapping around at the boundary of the type.
3442 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3443 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);",
3446 #[stable(feature = "rust1", since = "1.0.0")]
3447 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3448 #[must_use = "this returns the result of the operation, \
3449 without modifying the original"]
3451 pub const fn wrapping_add(self, rhs: Self) -> Self {
3452 intrinsics::wrapping_add(self, rhs)
3457 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3458 wrapping around at the boundary of the type.
3465 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3466 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);",
3469 #[stable(feature = "rust1", since = "1.0.0")]
3470 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3471 #[must_use = "this returns the result of the operation, \
3472 without modifying the original"]
3474 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3475 intrinsics::wrapping_sub(self, rhs)
3479 /// Wrapping (modular) multiplication. Computes `self *
3480 /// rhs`, wrapping around at the boundary of the type.
3486 /// Please note that this example is shared between integer types.
3487 /// Which explains why `u8` is used here.
3490 /// assert_eq!(10u8.wrapping_mul(12), 120);
3491 /// assert_eq!(25u8.wrapping_mul(12), 44);
3493 #[stable(feature = "rust1", since = "1.0.0")]
3494 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3495 #[must_use = "this returns the result of the operation, \
3496 without modifying the original"]
3498 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3499 intrinsics::wrapping_mul(self, rhs)
3503 concat!("Wrapping (modular) division. Computes `self / rhs`.
3504 Wrapped division on unsigned types is just normal division.
3505 There's no way wrapping could ever happen.
3506 This function exists, so that all operations
3507 are accounted for in the wrapping operations.
3514 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3516 #[stable(feature = "num_wrapping", since = "1.2.0")]
3517 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3518 #[must_use = "this returns the result of the operation, \
3519 without modifying the original"]
3521 pub const fn wrapping_div(self, rhs: Self) -> Self {
3527 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3528 Wrapped division on unsigned types is just normal division.
3529 There's no way wrapping could ever happen.
3530 This function exists, so that all operations
3531 are accounted for in the wrapping operations.
3532 Since, for the positive integers, all common
3533 definitions of division are equal, this
3534 is exactly equal to `self.wrapping_div(rhs)`.
3541 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3543 #[stable(feature = "euclidean_division", since = "1.38.0")]
3544 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3545 #[must_use = "this returns the result of the operation, \
3546 without modifying the original"]
3548 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
3554 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3555 Wrapped remainder calculation on unsigned types is
3556 just the regular remainder calculation.
3557 There's no way wrapping could ever happen.
3558 This function exists, so that all operations
3559 are accounted for in the wrapping operations.
3566 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3568 #[stable(feature = "num_wrapping", since = "1.2.0")]
3569 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3570 #[must_use = "this returns the result of the operation, \
3571 without modifying the original"]
3573 pub const fn wrapping_rem(self, rhs: Self) -> Self {
3579 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3580 Wrapped modulo calculation on unsigned types is
3581 just the regular remainder calculation.
3582 There's no way wrapping could ever happen.
3583 This function exists, so that all operations
3584 are accounted for in the wrapping operations.
3585 Since, for the positive integers, all common
3586 definitions of division are equal, this
3587 is exactly equal to `self.wrapping_rem(rhs)`.
3594 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3596 #[stable(feature = "euclidean_division", since = "1.38.0")]
3597 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3598 #[must_use = "this returns the result of the operation, \
3599 without modifying the original"]
3601 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3606 /// Wrapping (modular) negation. Computes `-self`,
3607 /// wrapping around at the boundary of the type.
3609 /// Since unsigned types do not have negative equivalents
3610 /// all applications of this function will wrap (except for `-0`).
3611 /// For values smaller than the corresponding signed type's maximum
3612 /// the result is the same as casting the corresponding signed value.
3613 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3614 /// `MAX` is the corresponding signed type's maximum.
3620 /// Please note that this example is shared between integer types.
3621 /// Which explains why `i8` is used here.
3624 /// assert_eq!(100i8.wrapping_neg(), -100);
3625 /// assert_eq!((-128i8).wrapping_neg(), -128);
3627 #[stable(feature = "num_wrapping", since = "1.2.0")]
3628 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3630 pub const fn wrapping_neg(self) -> Self {
3631 self.overflowing_neg().0
3635 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3636 where `mask` removes any high-order bits of `rhs` that
3637 would cause the shift to exceed the bitwidth of the type.
3639 Note that this is *not* the same as a rotate-left; the
3640 RHS of a wrapping shift-left is restricted to the range
3641 of the type, rather than the bits shifted out of the LHS
3642 being returned to the other end. The primitive integer
3643 types all implement a [`rotate_left`](#method.rotate_left) function,
3644 which may be what you want instead.
3651 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3652 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3654 #[stable(feature = "num_wrapping", since = "1.2.0")]
3655 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3656 #[must_use = "this returns the result of the operation, \
3657 without modifying the original"]
3659 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3660 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3663 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3669 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3670 where `mask` removes any high-order bits of `rhs` that
3671 would cause the shift to exceed the bitwidth of the type.
3673 Note that this is *not* the same as a rotate-right; the
3674 RHS of a wrapping shift-right is restricted to the range
3675 of the type, rather than the bits shifted out of the LHS
3676 being returned to the other end. The primitive integer
3677 types all implement a [`rotate_right`](#method.rotate_right) function,
3678 which may be what you want instead.
3685 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3686 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3688 #[stable(feature = "num_wrapping", since = "1.2.0")]
3689 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3690 #[must_use = "this returns the result of the operation, \
3691 without modifying the original"]
3693 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3694 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3697 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3703 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3704 wrapping around at the boundary of the type.
3711 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3712 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3714 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3715 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3716 #[must_use = "this returns the result of the operation, \
3717 without modifying the original"]
3719 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
3723 let mut base = self;
3724 let mut acc: Self = 1;
3728 acc = acc.wrapping_mul(base);
3731 base = base.wrapping_mul(base);
3734 // since exp!=0, finally the exp must be 1.
3735 // Deal with the final bit of the exponent separately, since
3736 // squaring the base afterwards is not necessary and may cause a
3737 // needless overflow.
3738 acc.wrapping_mul(base)
3743 concat!("Calculates `self` + `rhs`
3745 Returns a tuple of the addition along with a boolean indicating
3746 whether an arithmetic overflow would occur. If an overflow would
3747 have occurred then the wrapped value is returned.
3755 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3756 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3758 #[stable(feature = "wrapping", since = "1.7.0")]
3759 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3760 #[must_use = "this returns the result of the operation, \
3761 without modifying the original"]
3763 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3764 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3770 concat!("Calculates `self` - `rhs`
3772 Returns a tuple of the subtraction along with a boolean indicating
3773 whether an arithmetic overflow would occur. If an overflow would
3774 have occurred then the wrapped value is returned.
3782 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3783 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3786 #[stable(feature = "wrapping", since = "1.7.0")]
3787 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3788 #[must_use = "this returns the result of the operation, \
3789 without modifying the original"]
3791 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3792 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3797 /// Calculates the multiplication of `self` and `rhs`.
3799 /// Returns a tuple of the multiplication along with a boolean
3800 /// indicating whether an arithmetic overflow would occur. If an
3801 /// overflow would have occurred then the wrapped value is returned.
3807 /// Please note that this example is shared between integer types.
3808 /// Which explains why `u32` is used here.
3811 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3812 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3814 #[stable(feature = "wrapping", since = "1.7.0")]
3815 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3816 #[must_use = "this returns the result of the operation, \
3817 without modifying the original"]
3819 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3820 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3825 concat!("Calculates the divisor when `self` is divided by `rhs`.
3827 Returns a tuple of the divisor along with a boolean indicating
3828 whether an arithmetic overflow would occur. Note that for unsigned
3829 integers overflow never occurs, so the second value is always
3834 This function will panic if `rhs` is 0.
3841 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3844 #[stable(feature = "wrapping", since = "1.7.0")]
3845 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3846 #[must_use = "this returns the result of the operation, \
3847 without modifying the original"]
3848 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3854 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3856 Returns a tuple of the divisor along with a boolean indicating
3857 whether an arithmetic overflow would occur. Note that for unsigned
3858 integers overflow never occurs, so the second value is always
3860 Since, for the positive integers, all common
3861 definitions of division are equal, this
3862 is exactly equal to `self.overflowing_div(rhs)`.
3866 This function will panic if `rhs` is 0.
3873 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3876 #[stable(feature = "euclidean_division", since = "1.38.0")]
3877 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3878 #[must_use = "this returns the result of the operation, \
3879 without modifying the original"]
3880 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3886 concat!("Calculates the remainder when `self` is divided by `rhs`.
3888 Returns a tuple of the remainder after dividing along with a boolean
3889 indicating whether an arithmetic overflow would occur. Note that for
3890 unsigned integers overflow never occurs, so the second value is
3895 This function will panic if `rhs` is 0.
3902 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3905 #[stable(feature = "wrapping", since = "1.7.0")]
3906 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3907 #[must_use = "this returns the result of the operation, \
3908 without modifying the original"]
3909 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3915 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3917 Returns a tuple of the modulo after dividing along with a boolean
3918 indicating whether an arithmetic overflow would occur. Note that for
3919 unsigned integers overflow never occurs, so the second value is
3921 Since, for the positive integers, all common
3922 definitions of division are equal, this operation
3923 is exactly equal to `self.overflowing_rem(rhs)`.
3927 This function will panic if `rhs` is 0.
3934 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3937 #[stable(feature = "euclidean_division", since = "1.38.0")]
3938 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3939 #[must_use = "this returns the result of the operation, \
3940 without modifying the original"]
3941 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3947 concat!("Negates self in an overflowing fashion.
3949 Returns `!self + 1` using wrapping operations to return the value
3950 that represents the negation of this unsigned value. Note that for
3951 positive unsigned values overflow always occurs, but negating 0 does
3959 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3960 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3961 ", true));", $EndFeature, "
3964 #[stable(feature = "wrapping", since = "1.7.0")]
3965 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3966 pub const fn overflowing_neg(self) -> (Self, bool) {
3967 ((!self).wrapping_add(1), self != 0)
3972 concat!("Shifts self left by `rhs` bits.
3974 Returns a tuple of the shifted version of self along with a boolean
3975 indicating whether the shift value was larger than or equal to the
3976 number of bits. If the shift value is too large, then value is
3977 masked (N-1) where N is the number of bits, and this value is then
3978 used to perform the shift.
3985 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3986 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3988 #[stable(feature = "wrapping", since = "1.7.0")]
3989 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3990 #[must_use = "this returns the result of the operation, \
3991 without modifying the original"]
3993 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3994 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3999 concat!("Shifts self right by `rhs` bits.
4001 Returns a tuple of the shifted version of self along with a boolean
4002 indicating whether the shift value was larger than or equal to the
4003 number of bits. If the shift value is too large, then value is
4004 masked (N-1) where N is the number of bits, and this value is then
4005 used to perform the shift.
4012 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
4013 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
4015 #[stable(feature = "wrapping", since = "1.7.0")]
4016 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
4017 #[must_use = "this returns the result of the operation, \
4018 without modifying the original"]
4020 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
4021 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
4026 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
4028 Returns a tuple of the exponentiation along with a bool indicating
4029 whether an overflow happened.
4036 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
4037 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
4039 #[stable(feature = "no_panic_pow", since = "1.34.0")]
4040 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4041 #[must_use = "this returns the result of the operation, \
4042 without modifying the original"]
4044 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
4048 let mut base = self;
4049 let mut acc: Self = 1;
4050 let mut overflown = false;
4051 // Scratch space for storing results of overflowing_mul.
4056 r = acc.overflowing_mul(base);
4061 r = base.overflowing_mul(base);
4066 // since exp!=0, finally the exp must be 1.
4067 // Deal with the final bit of the exponent separately, since
4068 // squaring the base afterwards is not necessary and may cause a
4069 // needless overflow.
4070 r = acc.overflowing_mul(base);
4078 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
4085 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
4087 #[stable(feature = "rust1", since = "1.0.0")]
4088 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4089 #[must_use = "this returns the result of the operation, \
4090 without modifying the original"]
4092 #[rustc_inherit_overflow_checks]
4093 pub const fn pow(self, mut exp: u32) -> Self {
4097 let mut base = self;
4108 // since exp!=0, finally the exp must be 1.
4109 // Deal with the final bit of the exponent separately, since
4110 // squaring the base afterwards is not necessary and may cause a
4111 // needless overflow.
4117 concat!("Performs Euclidean division.
4119 Since, for the positive integers, all common
4120 definitions of division are equal, this
4121 is exactly equal to `self / rhs`.
4125 This function will panic if `rhs` is 0.
4132 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
4134 #[stable(feature = "euclidean_division", since = "1.38.0")]
4135 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
4136 #[must_use = "this returns the result of the operation, \
4137 without modifying the original"]
4139 #[rustc_inherit_overflow_checks]
4140 pub const fn div_euclid(self, rhs: Self) -> Self {
4147 concat!("Calculates the least remainder of `self (mod rhs)`.
4149 Since, for the positive integers, all common
4150 definitions of division are equal, this
4151 is exactly equal to `self % rhs`.
4155 This function will panic if `rhs` is 0.
4162 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
4164 #[stable(feature = "euclidean_division", since = "1.38.0")]
4165 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
4166 #[must_use = "this returns the result of the operation, \
4167 without modifying the original"]
4169 #[rustc_inherit_overflow_checks]
4170 pub const fn rem_euclid(self, rhs: Self) -> Self {
4176 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
4183 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
4184 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
4186 #[stable(feature = "rust1", since = "1.0.0")]
4187 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
4189 pub const fn is_power_of_two(self) -> bool {
4190 self.count_ones() == 1
4194 // Returns one less than next power of two.
4195 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
4197 // 8u8.one_less_than_next_power_of_two() == 7
4198 // 6u8.one_less_than_next_power_of_two() == 7
4200 // This method cannot overflow, as in the `next_power_of_two`
4201 // overflow cases it instead ends up returning the maximum value
4202 // of the type, and can return 0 for 0.
4204 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4205 const fn one_less_than_next_power_of_two(self) -> Self {
4206 if self <= 1 { return 0; }
4209 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4210 // That means the shift is always in-bounds, and some processors
4211 // (such as intel pre-haswell) have more efficient ctlz
4212 // intrinsics when the argument is non-zero.
4213 let z = unsafe { intrinsics::ctlz_nonzero(p) };
4218 concat!("Returns the smallest power of two greater than or equal to `self`.
4220 When return value overflows (i.e., `self > (1 << (N-1))` for type
4221 `uN`), it panics in debug mode and return value is wrapped to 0 in
4222 release mode (the only situation in which method can return 0).
4229 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4230 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4232 #[stable(feature = "rust1", since = "1.0.0")]
4233 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4235 #[rustc_inherit_overflow_checks]
4236 pub const fn next_power_of_two(self) -> Self {
4237 self.one_less_than_next_power_of_two() + 1
4242 concat!("Returns the smallest power of two greater than or equal to `n`. If
4243 the next power of two is greater than the type's maximum value,
4244 `None` is returned, otherwise the power of two is wrapped in `Some`.
4251 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4252 ".checked_next_power_of_two(), Some(2));
4253 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4254 assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);",
4258 #[stable(feature = "rust1", since = "1.0.0")]
4259 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4260 pub const fn checked_next_power_of_two(self) -> Option<Self> {
4261 self.one_less_than_next_power_of_two().checked_add(1)
4266 concat!("Returns the smallest power of two greater than or equal to `n`. If
4267 the next power of two is greater than the type's maximum value,
4268 the return value is wrapped to `0`.
4275 #![feature(wrapping_next_power_of_two)]
4277 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4278 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4279 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);",
4282 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4283 reason = "needs decision on wrapping behaviour")]
4284 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4285 pub const fn wrapping_next_power_of_two(self) -> Self {
4286 self.one_less_than_next_power_of_two().wrapping_add(1)
4291 concat!("Return the memory representation of this integer as a byte array in
4292 big-endian (network) byte order.
4299 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4300 assert_eq!(bytes, ", $be_bytes, ");
4302 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4303 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4305 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4306 self.to_be().to_ne_bytes()
4311 concat!("Return the memory representation of this integer as a byte array in
4312 little-endian byte order.
4319 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4320 assert_eq!(bytes, ", $le_bytes, ");
4322 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4323 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4325 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4326 self.to_le().to_ne_bytes()
4332 Return the memory representation of this integer as a byte array in
4335 As the target platform's native endianness is used, portable code
4336 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4341 [`to_be_bytes`]: #method.to_be_bytes
4342 [`to_le_bytes`]: #method.to_le_bytes
4347 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4350 if cfg!(target_endian = \"big\") {
4357 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4358 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4359 // SAFETY: const sound because integers are plain old datatypes so we can always
4360 // transmute them to arrays of bytes
4361 #[allow_internal_unstable(const_fn_transmute)]
4363 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4364 // SAFETY: integers are plain old datatypes so we can always transmute them to
4366 unsafe { mem::transmute(self) }
4371 concat!("Create a native endian integer value from its representation
4372 as a byte array in big endian.
4379 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4380 assert_eq!(value, ", $swap_op, ");
4383 When starting from a slice rather than an array, fallible conversion APIs can be used:
4386 use std::convert::TryInto;
4388 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4389 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4391 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4394 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4395 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4397 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4398 Self::from_be(Self::from_ne_bytes(bytes))
4404 Create a native endian integer value from its representation
4405 as a byte array in little endian.
4412 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4413 assert_eq!(value, ", $swap_op, ");
4416 When starting from a slice rather than an array, fallible conversion APIs can be used:
4419 use std::convert::TryInto;
4421 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4422 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4424 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4427 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4428 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4430 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4431 Self::from_le(Self::from_ne_bytes(bytes))
4436 concat!("Create a native endian integer value from its memory representation
4437 as a byte array in native endianness.
4439 As the target platform's native endianness is used, portable code
4440 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4441 appropriate instead.
4443 [`from_be_bytes`]: #method.from_be_bytes
4444 [`from_le_bytes`]: #method.from_le_bytes
4451 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4456 assert_eq!(value, ", $swap_op, ");
4459 When starting from a slice rather than an array, fallible conversion APIs can be used:
4462 use std::convert::TryInto;
4464 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4465 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4467 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4470 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4471 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4472 // SAFETY: const sound because integers are plain old datatypes so we can always
4473 // transmute to them
4474 #[allow_internal_unstable(const_fn_transmute)]
4476 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4477 // SAFETY: integers are plain old datatypes so we can always transmute to them
4478 unsafe { mem::transmute(bytes) }
4483 concat!("**This method is soft-deprecated.**
4485 Although using it won’t cause compilation warning,
4486 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
4488 Returns the smallest value that can be represented by this integer type."),
4489 #[stable(feature = "rust1", since = "1.0.0")]
4492 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4493 pub const fn min_value() -> Self { Self::MIN }
4497 concat!("**This method is soft-deprecated.**
4499 Although using it won’t cause compilation warning,
4500 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
4502 Returns the largest value that can be represented by this integer type."),
4503 #[stable(feature = "rust1", since = "1.0.0")]
4506 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4507 pub const fn max_value() -> Self { Self::MAX }
4514 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4517 /// Checks if the value is within the ASCII range.
4522 /// let ascii = 97u8;
4523 /// let non_ascii = 150u8;
4525 /// assert!(ascii.is_ascii());
4526 /// assert!(!non_ascii.is_ascii());
4528 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4529 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.43.0")]
4531 pub const fn is_ascii(&self) -> bool {
4535 /// Makes a copy of the value in its ASCII upper case equivalent.
4537 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4538 /// but non-ASCII letters are unchanged.
4540 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4545 /// let lowercase_a = 97u8;
4547 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4550 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4551 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4553 pub fn to_ascii_uppercase(&self) -> u8 {
4554 // Unset the fifth bit if this is a lowercase letter
4555 *self & !((self.is_ascii_lowercase() as u8) << 5)
4558 /// Makes a copy of the value in its ASCII lower case equivalent.
4560 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4561 /// but non-ASCII letters are unchanged.
4563 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4568 /// let uppercase_a = 65u8;
4570 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4573 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4574 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4576 pub fn to_ascii_lowercase(&self) -> u8 {
4577 // Set the fifth bit if this is an uppercase letter
4578 *self | ((self.is_ascii_uppercase() as u8) << 5)
4581 /// Checks that two values are an ASCII case-insensitive match.
4583 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4588 /// let lowercase_a = 97u8;
4589 /// let uppercase_a = 65u8;
4591 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4593 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4595 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4596 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4599 /// Converts this value to its ASCII upper case equivalent in-place.
4601 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4602 /// but non-ASCII letters are unchanged.
4604 /// To return a new uppercased value without modifying the existing one, use
4605 /// [`to_ascii_uppercase`].
4610 /// let mut byte = b'a';
4612 /// byte.make_ascii_uppercase();
4614 /// assert_eq!(b'A', byte);
4617 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4618 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4620 pub fn make_ascii_uppercase(&mut self) {
4621 *self = self.to_ascii_uppercase();
4624 /// Converts this value to its ASCII lower case equivalent in-place.
4626 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4627 /// but non-ASCII letters are unchanged.
4629 /// To return a new lowercased value without modifying the existing one, use
4630 /// [`to_ascii_lowercase`].
4635 /// let mut byte = b'A';
4637 /// byte.make_ascii_lowercase();
4639 /// assert_eq!(b'a', byte);
4642 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4643 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4645 pub fn make_ascii_lowercase(&mut self) {
4646 *self = self.to_ascii_lowercase();
4649 /// Checks if the value is an ASCII alphabetic character:
4651 /// - U+0041 'A' ..= U+005A 'Z', or
4652 /// - U+0061 'a' ..= U+007A 'z'.
4657 /// let uppercase_a = b'A';
4658 /// let uppercase_g = b'G';
4661 /// let zero = b'0';
4662 /// let percent = b'%';
4663 /// let space = b' ';
4665 /// let esc = 0x1b_u8;
4667 /// assert!(uppercase_a.is_ascii_alphabetic());
4668 /// assert!(uppercase_g.is_ascii_alphabetic());
4669 /// assert!(a.is_ascii_alphabetic());
4670 /// assert!(g.is_ascii_alphabetic());
4671 /// assert!(!zero.is_ascii_alphabetic());
4672 /// assert!(!percent.is_ascii_alphabetic());
4673 /// assert!(!space.is_ascii_alphabetic());
4674 /// assert!(!lf.is_ascii_alphabetic());
4675 /// assert!(!esc.is_ascii_alphabetic());
4677 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4678 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4680 pub const fn is_ascii_alphabetic(&self) -> bool {
4681 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
4684 /// Checks if the value is an ASCII uppercase character:
4685 /// U+0041 'A' ..= U+005A 'Z'.
4690 /// let uppercase_a = b'A';
4691 /// let uppercase_g = b'G';
4694 /// let zero = b'0';
4695 /// let percent = b'%';
4696 /// let space = b' ';
4698 /// let esc = 0x1b_u8;
4700 /// assert!(uppercase_a.is_ascii_uppercase());
4701 /// assert!(uppercase_g.is_ascii_uppercase());
4702 /// assert!(!a.is_ascii_uppercase());
4703 /// assert!(!g.is_ascii_uppercase());
4704 /// assert!(!zero.is_ascii_uppercase());
4705 /// assert!(!percent.is_ascii_uppercase());
4706 /// assert!(!space.is_ascii_uppercase());
4707 /// assert!(!lf.is_ascii_uppercase());
4708 /// assert!(!esc.is_ascii_uppercase());
4710 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4711 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4713 pub const fn is_ascii_uppercase(&self) -> bool {
4714 matches!(*self, b'A'..=b'Z')
4717 /// Checks if the value is an ASCII lowercase character:
4718 /// U+0061 'a' ..= U+007A 'z'.
4723 /// let uppercase_a = b'A';
4724 /// let uppercase_g = b'G';
4727 /// let zero = b'0';
4728 /// let percent = b'%';
4729 /// let space = b' ';
4731 /// let esc = 0x1b_u8;
4733 /// assert!(!uppercase_a.is_ascii_lowercase());
4734 /// assert!(!uppercase_g.is_ascii_lowercase());
4735 /// assert!(a.is_ascii_lowercase());
4736 /// assert!(g.is_ascii_lowercase());
4737 /// assert!(!zero.is_ascii_lowercase());
4738 /// assert!(!percent.is_ascii_lowercase());
4739 /// assert!(!space.is_ascii_lowercase());
4740 /// assert!(!lf.is_ascii_lowercase());
4741 /// assert!(!esc.is_ascii_lowercase());
4743 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4744 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4746 pub const fn is_ascii_lowercase(&self) -> bool {
4747 matches!(*self, b'a'..=b'z')
4750 /// Checks if the value is an ASCII alphanumeric character:
4752 /// - U+0041 'A' ..= U+005A 'Z', or
4753 /// - U+0061 'a' ..= U+007A 'z', or
4754 /// - U+0030 '0' ..= U+0039 '9'.
4759 /// let uppercase_a = b'A';
4760 /// let uppercase_g = b'G';
4763 /// let zero = b'0';
4764 /// let percent = b'%';
4765 /// let space = b' ';
4767 /// let esc = 0x1b_u8;
4769 /// assert!(uppercase_a.is_ascii_alphanumeric());
4770 /// assert!(uppercase_g.is_ascii_alphanumeric());
4771 /// assert!(a.is_ascii_alphanumeric());
4772 /// assert!(g.is_ascii_alphanumeric());
4773 /// assert!(zero.is_ascii_alphanumeric());
4774 /// assert!(!percent.is_ascii_alphanumeric());
4775 /// assert!(!space.is_ascii_alphanumeric());
4776 /// assert!(!lf.is_ascii_alphanumeric());
4777 /// assert!(!esc.is_ascii_alphanumeric());
4779 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4780 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4782 pub const fn is_ascii_alphanumeric(&self) -> bool {
4783 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
4786 /// Checks if the value is an ASCII decimal digit:
4787 /// U+0030 '0' ..= U+0039 '9'.
4792 /// let uppercase_a = b'A';
4793 /// let uppercase_g = b'G';
4796 /// let zero = b'0';
4797 /// let percent = b'%';
4798 /// let space = b' ';
4800 /// let esc = 0x1b_u8;
4802 /// assert!(!uppercase_a.is_ascii_digit());
4803 /// assert!(!uppercase_g.is_ascii_digit());
4804 /// assert!(!a.is_ascii_digit());
4805 /// assert!(!g.is_ascii_digit());
4806 /// assert!(zero.is_ascii_digit());
4807 /// assert!(!percent.is_ascii_digit());
4808 /// assert!(!space.is_ascii_digit());
4809 /// assert!(!lf.is_ascii_digit());
4810 /// assert!(!esc.is_ascii_digit());
4812 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4813 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4815 pub const fn is_ascii_digit(&self) -> bool {
4816 matches!(*self, b'0'..=b'9')
4819 /// Checks if the value is an ASCII hexadecimal digit:
4821 /// - U+0030 '0' ..= U+0039 '9', or
4822 /// - U+0041 'A' ..= U+0046 'F', or
4823 /// - U+0061 'a' ..= U+0066 'f'.
4828 /// let uppercase_a = b'A';
4829 /// let uppercase_g = b'G';
4832 /// let zero = b'0';
4833 /// let percent = b'%';
4834 /// let space = b' ';
4836 /// let esc = 0x1b_u8;
4838 /// assert!(uppercase_a.is_ascii_hexdigit());
4839 /// assert!(!uppercase_g.is_ascii_hexdigit());
4840 /// assert!(a.is_ascii_hexdigit());
4841 /// assert!(!g.is_ascii_hexdigit());
4842 /// assert!(zero.is_ascii_hexdigit());
4843 /// assert!(!percent.is_ascii_hexdigit());
4844 /// assert!(!space.is_ascii_hexdigit());
4845 /// assert!(!lf.is_ascii_hexdigit());
4846 /// assert!(!esc.is_ascii_hexdigit());
4848 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4849 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4851 pub const fn is_ascii_hexdigit(&self) -> bool {
4852 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
4855 /// Checks if the value is an ASCII punctuation character:
4857 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4858 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4859 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4860 /// - U+007B ..= U+007E `{ | } ~`
4865 /// let uppercase_a = b'A';
4866 /// let uppercase_g = b'G';
4869 /// let zero = b'0';
4870 /// let percent = b'%';
4871 /// let space = b' ';
4873 /// let esc = 0x1b_u8;
4875 /// assert!(!uppercase_a.is_ascii_punctuation());
4876 /// assert!(!uppercase_g.is_ascii_punctuation());
4877 /// assert!(!a.is_ascii_punctuation());
4878 /// assert!(!g.is_ascii_punctuation());
4879 /// assert!(!zero.is_ascii_punctuation());
4880 /// assert!(percent.is_ascii_punctuation());
4881 /// assert!(!space.is_ascii_punctuation());
4882 /// assert!(!lf.is_ascii_punctuation());
4883 /// assert!(!esc.is_ascii_punctuation());
4885 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4886 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4888 pub const fn is_ascii_punctuation(&self) -> bool {
4889 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
4892 /// Checks if the value is an ASCII graphic character:
4893 /// U+0021 '!' ..= U+007E '~'.
4898 /// let uppercase_a = b'A';
4899 /// let uppercase_g = b'G';
4902 /// let zero = b'0';
4903 /// let percent = b'%';
4904 /// let space = b' ';
4906 /// let esc = 0x1b_u8;
4908 /// assert!(uppercase_a.is_ascii_graphic());
4909 /// assert!(uppercase_g.is_ascii_graphic());
4910 /// assert!(a.is_ascii_graphic());
4911 /// assert!(g.is_ascii_graphic());
4912 /// assert!(zero.is_ascii_graphic());
4913 /// assert!(percent.is_ascii_graphic());
4914 /// assert!(!space.is_ascii_graphic());
4915 /// assert!(!lf.is_ascii_graphic());
4916 /// assert!(!esc.is_ascii_graphic());
4918 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4919 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4921 pub const fn is_ascii_graphic(&self) -> bool {
4922 matches!(*self, b'!'..=b'~')
4925 /// Checks if the value is an ASCII whitespace character:
4926 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4927 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4929 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4930 /// whitespace][infra-aw]. There are several other definitions in
4931 /// wide use. For instance, [the POSIX locale][pct] includes
4932 /// U+000B VERTICAL TAB as well as all the above characters,
4933 /// but—from the very same specification—[the default rule for
4934 /// "field splitting" in the Bourne shell][bfs] considers *only*
4935 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4937 /// If you are writing a program that will process an existing
4938 /// file format, check what that format's definition of whitespace is
4939 /// before using this function.
4941 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4942 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4943 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4948 /// let uppercase_a = b'A';
4949 /// let uppercase_g = b'G';
4952 /// let zero = b'0';
4953 /// let percent = b'%';
4954 /// let space = b' ';
4956 /// let esc = 0x1b_u8;
4958 /// assert!(!uppercase_a.is_ascii_whitespace());
4959 /// assert!(!uppercase_g.is_ascii_whitespace());
4960 /// assert!(!a.is_ascii_whitespace());
4961 /// assert!(!g.is_ascii_whitespace());
4962 /// assert!(!zero.is_ascii_whitespace());
4963 /// assert!(!percent.is_ascii_whitespace());
4964 /// assert!(space.is_ascii_whitespace());
4965 /// assert!(lf.is_ascii_whitespace());
4966 /// assert!(!esc.is_ascii_whitespace());
4968 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4969 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4971 pub const fn is_ascii_whitespace(&self) -> bool {
4972 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
4975 /// Checks if the value is an ASCII control character:
4976 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4977 /// Note that most ASCII whitespace characters are control
4978 /// characters, but SPACE is not.
4983 /// let uppercase_a = b'A';
4984 /// let uppercase_g = b'G';
4987 /// let zero = b'0';
4988 /// let percent = b'%';
4989 /// let space = b' ';
4991 /// let esc = 0x1b_u8;
4993 /// assert!(!uppercase_a.is_ascii_control());
4994 /// assert!(!uppercase_g.is_ascii_control());
4995 /// assert!(!a.is_ascii_control());
4996 /// assert!(!g.is_ascii_control());
4997 /// assert!(!zero.is_ascii_control());
4998 /// assert!(!percent.is_ascii_control());
4999 /// assert!(!space.is_ascii_control());
5000 /// assert!(lf.is_ascii_control());
5001 /// assert!(esc.is_ascii_control());
5003 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
5004 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
5006 pub const fn is_ascii_control(&self) -> bool {
5007 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
5013 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
5014 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
5019 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
5020 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
5025 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
5026 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
5027 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
5028 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
5034 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
5035 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
5036 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
5037 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
5038 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
5039 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
5040 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
5044 #[cfg(target_pointer_width = "16")]
5047 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
5048 "[0x34, 0x12]", "[0x12, 0x34]",
5049 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
5051 #[cfg(target_pointer_width = "32")]
5054 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
5055 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
5056 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
5059 #[cfg(target_pointer_width = "64")]
5062 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
5063 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
5064 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
5065 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
5066 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
5069 /// A classification of floating point numbers.
5071 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
5072 /// their documentation for more.
5074 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
5075 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
5080 /// use std::num::FpCategory;
5082 /// let num = 12.4_f32;
5083 /// let inf = f32::INFINITY;
5084 /// let zero = 0f32;
5085 /// let sub: f32 = 1.1754942e-38;
5086 /// let nan = f32::NAN;
5088 /// assert_eq!(num.classify(), FpCategory::Normal);
5089 /// assert_eq!(inf.classify(), FpCategory::Infinite);
5090 /// assert_eq!(zero.classify(), FpCategory::Zero);
5091 /// assert_eq!(nan.classify(), FpCategory::Nan);
5092 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
5094 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
5095 #[stable(feature = "rust1", since = "1.0.0")]
5096 pub enum FpCategory {
5097 /// "Not a Number", often obtained by dividing by zero.
5098 #[stable(feature = "rust1", since = "1.0.0")]
5101 /// Positive or negative infinity.
5102 #[stable(feature = "rust1", since = "1.0.0")]
5105 /// Positive or negative zero.
5106 #[stable(feature = "rust1", since = "1.0.0")]
5109 /// De-normalized floating point representation (less precise than `Normal`).
5110 #[stable(feature = "rust1", since = "1.0.0")]
5113 /// A regular floating point number.
5114 #[stable(feature = "rust1", since = "1.0.0")]
5118 macro_rules! from_str_radix_int_impl {
5120 #[stable(feature = "rust1", since = "1.0.0")]
5121 impl FromStr for $t {
5122 type Err = ParseIntError;
5123 fn from_str(src: &str) -> Result<Self, ParseIntError> {
5124 from_str_radix(src, 10)
5129 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
5131 /// The error type returned when a checked integral type conversion fails.
5132 #[stable(feature = "try_from", since = "1.34.0")]
5133 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
5134 pub struct TryFromIntError(pub(crate) ());
5136 impl TryFromIntError {
5138 feature = "int_error_internals",
5139 reason = "available through Error trait and this method should \
5140 not be exposed publicly",
5144 pub fn __description(&self) -> &str {
5145 "out of range integral type conversion attempted"
5149 #[stable(feature = "try_from", since = "1.34.0")]
5150 impl fmt::Display for TryFromIntError {
5151 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
5152 self.__description().fmt(fmt)
5156 #[stable(feature = "try_from", since = "1.34.0")]
5157 impl From<Infallible> for TryFromIntError {
5158 fn from(x: Infallible) -> TryFromIntError {
5163 #[unstable(feature = "never_type", issue = "35121")]
5164 impl From<!> for TryFromIntError {
5165 fn from(never: !) -> TryFromIntError {
5166 // Match rather than coerce to make sure that code like
5167 // `From<Infallible> for TryFromIntError` above will keep working
5168 // when `Infallible` becomes an alias to `!`.
5174 trait FromStrRadixHelper: PartialOrd + Copy {
5175 fn min_value() -> Self;
5176 fn max_value() -> Self;
5177 fn from_u32(u: u32) -> Self;
5178 fn checked_mul(&self, other: u32) -> Option<Self>;
5179 fn checked_sub(&self, other: u32) -> Option<Self>;
5180 fn checked_add(&self, other: u32) -> Option<Self>;
5184 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
5186 fn min_value() -> Self { Self::MIN }
5188 fn max_value() -> Self { Self::MAX }
5190 fn from_u32(u: u32) -> Self { u as Self }
5192 fn checked_mul(&self, other: u32) -> Option<Self> {
5193 Self::checked_mul(*self, other as Self)
5196 fn checked_sub(&self, other: u32) -> Option<Self> {
5197 Self::checked_sub(*self, other as Self)
5200 fn checked_add(&self, other: u32) -> Option<Self> {
5201 Self::checked_add(*self, other as Self)
5205 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5207 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5208 use self::IntErrorKind::*;
5209 use self::ParseIntError as PIE;
5212 radix >= 2 && radix <= 36,
5213 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5218 return Err(PIE { kind: Empty });
5221 let is_signed_ty = T::from_u32(0) > T::min_value();
5223 // all valid digits are ascii, so we will just iterate over the utf8 bytes
5224 // and cast them to chars. .to_digit() will safely return None for anything
5225 // other than a valid ascii digit for the given radix, including the first-byte
5226 // of multi-byte sequences
5227 let src = src.as_bytes();
5229 let (is_positive, digits) = match src[0] {
5230 b'+' => (true, &src[1..]),
5231 b'-' if is_signed_ty => (false, &src[1..]),
5235 if digits.is_empty() {
5236 return Err(PIE { kind: Empty });
5239 let mut result = T::from_u32(0);
5241 // The number is positive
5243 let x = match (c as char).to_digit(radix) {
5245 None => return Err(PIE { kind: InvalidDigit }),
5247 result = match result.checked_mul(radix) {
5248 Some(result) => result,
5249 None => return Err(PIE { kind: Overflow }),
5251 result = match result.checked_add(x) {
5252 Some(result) => result,
5253 None => return Err(PIE { kind: Overflow }),
5257 // The number is negative
5259 let x = match (c as char).to_digit(radix) {
5261 None => return Err(PIE { kind: InvalidDigit }),
5263 result = match result.checked_mul(radix) {
5264 Some(result) => result,
5265 None => return Err(PIE { kind: Underflow }),
5267 result = match result.checked_sub(x) {
5268 Some(result) => result,
5269 None => return Err(PIE { kind: Underflow }),
5276 /// An error which can be returned when parsing an integer.
5278 /// This error is used as the error type for the `from_str_radix()` functions
5279 /// on the primitive integer types, such as [`i8::from_str_radix`].
5281 /// # Potential causes
5283 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5284 /// in the string e.g., when it is obtained from the standard input.
5285 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5287 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5288 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5289 #[derive(Debug, Clone, PartialEq, Eq)]
5290 #[stable(feature = "rust1", since = "1.0.0")]
5291 pub struct ParseIntError {
5295 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5297 feature = "int_error_matching",
5298 reason = "it can be useful to match errors when making error messages \
5299 for integer parsing",
5302 #[derive(Debug, Clone, PartialEq, Eq)]
5304 pub enum IntErrorKind {
5305 /// Value being parsed is empty.
5307 /// Among other causes, this variant will be constructed when parsing an empty string.
5309 /// Contains an invalid digit.
5311 /// Among other causes, this variant will be constructed when parsing a string that
5312 /// contains a letter.
5314 /// Integer is too large to store in target integer type.
5316 /// Integer is too small to store in target integer type.
5320 /// This variant will be emitted when the parsing string has a value of zero, which
5321 /// would be illegal for non-zero types.
5325 impl ParseIntError {
5326 /// Outputs the detailed cause of parsing an integer failing.
5328 feature = "int_error_matching",
5329 reason = "it can be useful to match errors when making error messages \
5330 for integer parsing",
5333 pub fn kind(&self) -> &IntErrorKind {
5337 feature = "int_error_internals",
5338 reason = "available through Error trait and this method should \
5339 not be exposed publicly",
5343 pub fn __description(&self) -> &str {
5345 IntErrorKind::Empty => "cannot parse integer from empty string",
5346 IntErrorKind::InvalidDigit => "invalid digit found in string",
5347 IntErrorKind::Overflow => "number too large to fit in target type",
5348 IntErrorKind::Underflow => "number too small to fit in target type",
5349 IntErrorKind::Zero => "number would be zero for non-zero type",
5354 #[stable(feature = "rust1", since = "1.0.0")]
5355 impl fmt::Display for ParseIntError {
5356 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5357 self.__description().fmt(f)
5361 #[stable(feature = "rust1", since = "1.0.0")]
5362 pub use crate::num::dec2flt::ParseFloatError;