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_union)]
2351 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2355 bytes: [u8; mem::size_of::<$SelfT>()],
2357 // SAFETY: integers are plain old datatypes so we can always transmute them to
2359 unsafe { Bytes { val: self }.bytes }
2364 concat!("Create an integer value from its representation as a byte array in
2372 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2373 assert_eq!(value, ", $swap_op, ");
2376 When starting from a slice rather than an array, fallible conversion APIs can be used:
2379 use std::convert::TryInto;
2381 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2382 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2384 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2387 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2388 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2390 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2391 Self::from_be(Self::from_ne_bytes(bytes))
2397 Create an integer value from its representation as a byte array in
2405 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2406 assert_eq!(value, ", $swap_op, ");
2409 When starting from a slice rather than an array, fallible conversion APIs can be used:
2412 use std::convert::TryInto;
2414 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2415 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2417 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2420 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2421 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2423 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2424 Self::from_le(Self::from_ne_bytes(bytes))
2429 concat!("Create an integer value from its memory representation as a byte
2430 array in native endianness.
2432 As the target platform's native endianness is used, portable code
2433 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2434 appropriate instead.
2436 [`from_be_bytes`]: #method.from_be_bytes
2437 [`from_le_bytes`]: #method.from_le_bytes
2444 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2449 assert_eq!(value, ", $swap_op, ");
2452 When starting from a slice rather than an array, fallible conversion APIs can be used:
2455 use std::convert::TryInto;
2457 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2458 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2460 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2463 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2464 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2465 // SAFETY: const sound because integers are plain old datatypes so we can always
2466 // transmute to them
2467 #[allow_internal_unstable(const_fn_union)]
2469 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2473 bytes: [u8; mem::size_of::<$SelfT>()],
2475 // SAFETY: integers are plain old datatypes so we can always transmute to them
2476 unsafe { Bytes { bytes }.val }
2481 concat!("**This method is soft-deprecated.**
2483 Although using it won’t cause compilation warning,
2484 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
2486 Returns the smallest value that can be represented by this integer type."),
2487 #[stable(feature = "rust1", since = "1.0.0")]
2490 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2491 pub const fn min_value() -> Self {
2497 concat!("**This method is soft-deprecated.**
2499 Although using it won’t cause compilation warning,
2500 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
2502 Returns the largest value that can be represented by this integer type."),
2503 #[stable(feature = "rust1", since = "1.0.0")]
2506 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2507 pub const fn max_value() -> Self {
2516 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2517 "[0x12]", "[0x12]", "", "" }
2522 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2523 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2528 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2529 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2530 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2535 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2536 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2537 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2538 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2543 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2544 170141183460469231731687303715884105727, "", "", 16,
2545 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2546 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2547 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2548 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2549 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2550 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2553 #[cfg(target_pointer_width = "16")]
2556 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2557 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2558 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2561 #[cfg(target_pointer_width = "32")]
2564 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2565 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2566 "[0x12, 0x34, 0x56, 0x78]",
2567 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2570 #[cfg(target_pointer_width = "64")]
2573 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2574 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2575 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2576 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2577 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2580 macro_rules! uint_impl {
2581 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2582 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2583 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2584 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2586 concat!("The smallest value that can be represented by this integer type.
2593 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, 0);", $EndFeature, "
2595 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2596 pub const MIN: Self = 0;
2600 concat!("The largest value that can be represented by this integer type.
2607 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");",
2610 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2611 pub const MAX: Self = !0;
2615 concat!("Converts a string slice in a given base to an integer.
2617 The string is expected to be an optional `+` sign
2619 Leading and trailing whitespace represent an error.
2620 Digits are a subset of these characters, depending on `radix`:
2628 This function panics if `radix` is not in the range from 2 to 36.
2635 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2638 #[stable(feature = "rust1", since = "1.0.0")]
2639 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2640 from_str_radix(src, radix)
2645 concat!("Returns the number of ones in the binary representation of `self`.
2652 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2654 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2656 #[stable(feature = "rust1", since = "1.0.0")]
2657 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2659 pub const fn count_ones(self) -> u32 {
2660 intrinsics::ctpop(self as $ActualT) as u32
2665 concat!("Returns the number of zeros in the binary representation of `self`.
2672 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);", $EndFeature, "
2674 #[stable(feature = "rust1", since = "1.0.0")]
2675 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2677 pub const fn count_zeros(self) -> u32 {
2678 (!self).count_ones()
2683 concat!("Returns the number of leading zeros in the binary representation of `self`.
2690 ", $Feature, "let n = ", stringify!($SelfT), "::MAX >> 2;
2692 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2694 #[stable(feature = "rust1", since = "1.0.0")]
2695 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2697 pub const fn leading_zeros(self) -> u32 {
2698 intrinsics::ctlz(self as $ActualT) as u32
2703 concat!("Returns the number of trailing zeros in the binary representation
2711 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2713 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2715 #[stable(feature = "rust1", since = "1.0.0")]
2716 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2718 pub const fn trailing_zeros(self) -> u32 {
2719 intrinsics::cttz(self) as u32
2724 concat!("Returns the number of leading ones in the binary representation of `self`.
2731 ", $Feature, "let n = !(", stringify!($SelfT), "::MAX >> 2);
2733 assert_eq!(n.leading_ones(), 2);", $EndFeature, "
2735 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
2736 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
2738 pub const fn leading_ones(self) -> u32 {
2739 (!self).leading_zeros()
2744 concat!("Returns the number of trailing ones in the binary representation
2752 ", $Feature, "let n = 0b1010111", stringify!($SelfT), ";
2754 assert_eq!(n.trailing_ones(), 3);", $EndFeature, "
2756 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
2757 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
2759 pub const fn trailing_ones(self) -> u32 {
2760 (!self).trailing_zeros()
2765 concat!("Shifts the bits to the left by a specified amount, `n`,
2766 wrapping the truncated bits to the end of the resulting integer.
2768 Please note this isn't the same operation as the `<<` shifting operator!
2775 let n = ", $rot_op, stringify!($SelfT), ";
2776 let m = ", $rot_result, ";
2778 assert_eq!(n.rotate_left(", $rot, "), m);
2780 #[stable(feature = "rust1", since = "1.0.0")]
2781 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2782 #[must_use = "this returns the result of the operation, \
2783 without modifying the original"]
2785 pub const fn rotate_left(self, n: u32) -> Self {
2786 intrinsics::rotate_left(self, n as $SelfT)
2791 concat!("Shifts the bits to the right by a specified amount, `n`,
2792 wrapping the truncated bits to the beginning of the resulting
2795 Please note this isn't the same operation as the `>>` shifting operator!
2802 let n = ", $rot_result, stringify!($SelfT), ";
2803 let m = ", $rot_op, ";
2805 assert_eq!(n.rotate_right(", $rot, "), m);
2807 #[stable(feature = "rust1", since = "1.0.0")]
2808 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2809 #[must_use = "this returns the result of the operation, \
2810 without modifying the original"]
2812 pub const fn rotate_right(self, n: u32) -> Self {
2813 intrinsics::rotate_right(self, n as $SelfT)
2819 Reverses the byte order of the integer.
2826 let n = ", $swap_op, stringify!($SelfT), ";
2827 let m = n.swap_bytes();
2829 assert_eq!(m, ", $swapped, ");
2831 #[stable(feature = "rust1", since = "1.0.0")]
2832 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2834 pub const fn swap_bytes(self) -> Self {
2835 intrinsics::bswap(self as $ActualT) as Self
2840 concat!("Reverses the bit pattern of the integer.
2847 let n = ", $swap_op, stringify!($SelfT), ";
2848 let m = n.reverse_bits();
2850 assert_eq!(m, ", $reversed, ");
2852 #[stable(feature = "reverse_bits", since = "1.37.0")]
2853 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2856 pub const fn reverse_bits(self) -> Self {
2857 intrinsics::bitreverse(self as $ActualT) as Self
2862 concat!("Converts an integer from big endian to the target's endianness.
2864 On big endian this is a no-op. On little endian the bytes are
2872 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2874 if cfg!(target_endian = \"big\") {
2875 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2877 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2880 #[stable(feature = "rust1", since = "1.0.0")]
2881 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2883 pub const fn from_be(x: Self) -> Self {
2884 #[cfg(target_endian = "big")]
2888 #[cfg(not(target_endian = "big"))]
2896 concat!("Converts an integer from little endian to the target's endianness.
2898 On little endian this is a no-op. On big endian the bytes are
2906 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2908 if cfg!(target_endian = \"little\") {
2909 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2911 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2914 #[stable(feature = "rust1", since = "1.0.0")]
2915 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2917 pub const fn from_le(x: Self) -> Self {
2918 #[cfg(target_endian = "little")]
2922 #[cfg(not(target_endian = "little"))]
2930 concat!("Converts `self` to big endian from the target's endianness.
2932 On big endian this is a no-op. On little endian the bytes are
2940 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2942 if cfg!(target_endian = \"big\") {
2943 assert_eq!(n.to_be(), n)
2945 assert_eq!(n.to_be(), n.swap_bytes())
2948 #[stable(feature = "rust1", since = "1.0.0")]
2949 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2951 pub const fn to_be(self) -> Self { // or not to be?
2952 #[cfg(target_endian = "big")]
2956 #[cfg(not(target_endian = "big"))]
2964 concat!("Converts `self` to little endian from the target's endianness.
2966 On little endian this is a no-op. On big endian the bytes are
2974 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2976 if cfg!(target_endian = \"little\") {
2977 assert_eq!(n.to_le(), n)
2979 assert_eq!(n.to_le(), n.swap_bytes())
2982 #[stable(feature = "rust1", since = "1.0.0")]
2983 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2985 pub const fn to_le(self) -> Self {
2986 #[cfg(target_endian = "little")]
2990 #[cfg(not(target_endian = "little"))]
2998 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2999 if overflow occurred.
3006 ", $Feature, "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
3007 "Some(", stringify!($SelfT), "::MAX - 1));
3008 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);", $EndFeature, "
3010 #[stable(feature = "rust1", since = "1.0.0")]
3011 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
3012 #[must_use = "this returns the result of the operation, \
3013 without modifying the original"]
3015 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
3016 let (a, b) = self.overflowing_add(rhs);
3017 if unlikely!(b) {None} else {Some(a)}
3022 concat!("Unchecked integer addition. Computes `self + rhs`, assuming overflow
3023 cannot occur. This results in undefined behavior when `self + rhs > ", stringify!($SelfT),
3024 "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`."),
3026 feature = "unchecked_math",
3027 reason = "niche optimization path",
3030 #[must_use = "this returns the result of the operation, \
3031 without modifying the original"]
3033 pub unsafe fn unchecked_add(self, rhs: Self) -> Self {
3034 // SAFETY: the caller must uphold the safety contract for
3036 unsafe { intrinsics::unchecked_add(self, rhs) }
3041 concat!("Checked integer subtraction. Computes `self - rhs`, returning
3042 `None` if overflow occurred.
3049 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
3050 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
3052 #[stable(feature = "rust1", since = "1.0.0")]
3053 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
3054 #[must_use = "this returns the result of the operation, \
3055 without modifying the original"]
3057 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
3058 let (a, b) = self.overflowing_sub(rhs);
3059 if unlikely!(b) {None} else {Some(a)}
3064 concat!("Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
3065 cannot occur. This results in undefined behavior when `self - rhs > ", stringify!($SelfT),
3066 "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`."),
3068 feature = "unchecked_math",
3069 reason = "niche optimization path",
3072 #[must_use = "this returns the result of the operation, \
3073 without modifying the original"]
3075 pub unsafe fn unchecked_sub(self, rhs: Self) -> Self {
3076 // SAFETY: the caller must uphold the safety contract for
3078 unsafe { intrinsics::unchecked_sub(self, rhs) }
3083 concat!("Checked integer multiplication. Computes `self * rhs`, returning
3084 `None` if overflow occurred.
3091 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
3092 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);", $EndFeature, "
3094 #[stable(feature = "rust1", since = "1.0.0")]
3095 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
3096 #[must_use = "this returns the result of the operation, \
3097 without modifying the original"]
3099 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
3100 let (a, b) = self.overflowing_mul(rhs);
3101 if unlikely!(b) {None} else {Some(a)}
3106 concat!("Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
3107 cannot occur. This results in undefined behavior when `self * rhs > ", stringify!($SelfT),
3108 "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`."),
3110 feature = "unchecked_math",
3111 reason = "niche optimization path",
3114 #[must_use = "this returns the result of the operation, \
3115 without modifying the original"]
3117 pub unsafe fn unchecked_mul(self, rhs: Self) -> Self {
3118 // SAFETY: the caller must uphold the safety contract for
3120 unsafe { intrinsics::unchecked_mul(self, rhs) }
3125 concat!("Checked integer division. Computes `self / rhs`, returning `None`
3133 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
3134 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
3136 #[stable(feature = "rust1", since = "1.0.0")]
3137 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3138 #[must_use = "this returns the result of the operation, \
3139 without modifying the original"]
3141 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
3142 if unlikely!(rhs == 0) {
3145 // SAFETY: div by zero has been checked above and unsigned types have no other
3146 // failure modes for division
3147 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
3153 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
3161 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
3162 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
3164 #[stable(feature = "euclidean_division", since = "1.38.0")]
3165 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3166 #[must_use = "this returns the result of the operation, \
3167 without modifying the original"]
3169 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
3170 if unlikely!(rhs == 0) {
3173 Some(self.div_euclid(rhs))
3180 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
3188 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
3189 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
3191 #[stable(feature = "wrapping", since = "1.7.0")]
3192 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3193 #[must_use = "this returns the result of the operation, \
3194 without modifying the original"]
3196 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
3197 if unlikely!(rhs == 0) {
3200 // SAFETY: div by zero has been checked above and unsigned types have no other
3201 // failure modes for division
3202 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3208 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3216 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3217 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3219 #[stable(feature = "euclidean_division", since = "1.38.0")]
3220 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3221 #[must_use = "this returns the result of the operation, \
3222 without modifying the original"]
3224 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3225 if unlikely!(rhs == 0) {
3228 Some(self.rem_euclid(rhs))
3234 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3237 Note that negating any positive integer will overflow.
3244 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3245 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3247 #[stable(feature = "wrapping", since = "1.7.0")]
3248 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
3250 pub const fn checked_neg(self) -> Option<Self> {
3251 let (a, b) = self.overflowing_neg();
3252 if unlikely!(b) {None} else {Some(a)}
3257 concat!("Checked shift left. Computes `self << rhs`, returning `None`
3258 if `rhs` is larger than or equal to the number of bits in `self`.
3265 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3266 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3268 #[stable(feature = "wrapping", since = "1.7.0")]
3269 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
3270 #[must_use = "this returns the result of the operation, \
3271 without modifying the original"]
3273 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
3274 let (a, b) = self.overflowing_shl(rhs);
3275 if unlikely!(b) {None} else {Some(a)}
3280 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3281 if `rhs` is larger than or equal to the number of bits in `self`.
3288 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3289 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3291 #[stable(feature = "wrapping", since = "1.7.0")]
3292 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
3293 #[must_use = "this returns the result of the operation, \
3294 without modifying the original"]
3296 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
3297 let (a, b) = self.overflowing_shr(rhs);
3298 if unlikely!(b) {None} else {Some(a)}
3303 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3311 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3312 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);", $EndFeature, "
3314 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3315 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3316 #[must_use = "this returns the result of the operation, \
3317 without modifying the original"]
3319 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
3323 let mut base = self;
3324 let mut acc: Self = 1;
3328 acc = try_opt!(acc.checked_mul(base));
3331 base = try_opt!(base.checked_mul(base));
3334 // since exp!=0, finally the exp must be 1.
3335 // Deal with the final bit of the exponent separately, since
3336 // squaring the base afterwards is not necessary and may cause a
3337 // needless overflow.
3339 Some(try_opt!(acc.checked_mul(base)))
3344 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3345 the numeric bounds instead of overflowing.
3352 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3353 assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);",
3357 #[stable(feature = "rust1", since = "1.0.0")]
3358 #[must_use = "this returns the result of the operation, \
3359 without modifying the original"]
3360 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
3362 pub const fn saturating_add(self, rhs: Self) -> Self {
3363 intrinsics::saturating_add(self, rhs)
3368 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3369 at the numeric bounds instead of overflowing.
3376 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3377 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3379 #[stable(feature = "rust1", since = "1.0.0")]
3380 #[must_use = "this returns the result of the operation, \
3381 without modifying the original"]
3382 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
3384 pub const fn saturating_sub(self, rhs: Self) -> Self {
3385 intrinsics::saturating_sub(self, rhs)
3390 concat!("Saturating integer multiplication. Computes `self * rhs`,
3391 saturating at the numeric bounds instead of overflowing.
3399 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3400 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3401 "::MAX);", $EndFeature, "
3403 #[stable(feature = "wrapping", since = "1.7.0")]
3404 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
3405 #[must_use = "this returns the result of the operation, \
3406 without modifying the original"]
3408 pub const fn saturating_mul(self, rhs: Self) -> Self {
3409 match self.checked_mul(rhs) {
3417 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3418 saturating at the numeric bounds instead of overflowing.
3426 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3427 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3430 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3431 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3432 #[must_use = "this returns the result of the operation, \
3433 without modifying the original"]
3435 pub const fn saturating_pow(self, exp: u32) -> Self {
3436 match self.checked_pow(exp) {
3444 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3445 wrapping around at the boundary of the type.
3452 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3453 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);",
3456 #[stable(feature = "rust1", since = "1.0.0")]
3457 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3458 #[must_use = "this returns the result of the operation, \
3459 without modifying the original"]
3461 pub const fn wrapping_add(self, rhs: Self) -> Self {
3462 intrinsics::wrapping_add(self, rhs)
3467 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3468 wrapping around at the boundary of the type.
3475 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3476 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);",
3479 #[stable(feature = "rust1", since = "1.0.0")]
3480 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3481 #[must_use = "this returns the result of the operation, \
3482 without modifying the original"]
3484 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3485 intrinsics::wrapping_sub(self, rhs)
3489 /// Wrapping (modular) multiplication. Computes `self *
3490 /// rhs`, wrapping around at the boundary of the type.
3496 /// Please note that this example is shared between integer types.
3497 /// Which explains why `u8` is used here.
3500 /// assert_eq!(10u8.wrapping_mul(12), 120);
3501 /// assert_eq!(25u8.wrapping_mul(12), 44);
3503 #[stable(feature = "rust1", since = "1.0.0")]
3504 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3505 #[must_use = "this returns the result of the operation, \
3506 without modifying the original"]
3508 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3509 intrinsics::wrapping_mul(self, rhs)
3513 concat!("Wrapping (modular) division. Computes `self / rhs`.
3514 Wrapped division on unsigned types is just normal division.
3515 There's no way wrapping could ever happen.
3516 This function exists, so that all operations
3517 are accounted for in the wrapping operations.
3524 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3526 #[stable(feature = "num_wrapping", since = "1.2.0")]
3527 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3528 #[must_use = "this returns the result of the operation, \
3529 without modifying the original"]
3531 pub const fn wrapping_div(self, rhs: Self) -> Self {
3537 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3538 Wrapped division on unsigned types is just normal division.
3539 There's no way wrapping could ever happen.
3540 This function exists, so that all operations
3541 are accounted for in the wrapping operations.
3542 Since, for the positive integers, all common
3543 definitions of division are equal, this
3544 is exactly equal to `self.wrapping_div(rhs)`.
3551 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3553 #[stable(feature = "euclidean_division", since = "1.38.0")]
3554 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3555 #[must_use = "this returns the result of the operation, \
3556 without modifying the original"]
3558 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
3564 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3565 Wrapped remainder calculation on unsigned types is
3566 just the regular remainder calculation.
3567 There's no way wrapping could ever happen.
3568 This function exists, so that all operations
3569 are accounted for in the wrapping operations.
3576 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3578 #[stable(feature = "num_wrapping", since = "1.2.0")]
3579 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3580 #[must_use = "this returns the result of the operation, \
3581 without modifying the original"]
3583 pub const fn wrapping_rem(self, rhs: Self) -> Self {
3589 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3590 Wrapped modulo calculation on unsigned types is
3591 just the regular remainder calculation.
3592 There's no way wrapping could ever happen.
3593 This function exists, so that all operations
3594 are accounted for in the wrapping operations.
3595 Since, for the positive integers, all common
3596 definitions of division are equal, this
3597 is exactly equal to `self.wrapping_rem(rhs)`.
3604 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3606 #[stable(feature = "euclidean_division", since = "1.38.0")]
3607 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3608 #[must_use = "this returns the result of the operation, \
3609 without modifying the original"]
3611 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3616 /// Wrapping (modular) negation. Computes `-self`,
3617 /// wrapping around at the boundary of the type.
3619 /// Since unsigned types do not have negative equivalents
3620 /// all applications of this function will wrap (except for `-0`).
3621 /// For values smaller than the corresponding signed type's maximum
3622 /// the result is the same as casting the corresponding signed value.
3623 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3624 /// `MAX` is the corresponding signed type's maximum.
3630 /// Please note that this example is shared between integer types.
3631 /// Which explains why `i8` is used here.
3634 /// assert_eq!(100i8.wrapping_neg(), -100);
3635 /// assert_eq!((-128i8).wrapping_neg(), -128);
3637 #[stable(feature = "num_wrapping", since = "1.2.0")]
3638 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3640 pub const fn wrapping_neg(self) -> Self {
3641 self.overflowing_neg().0
3645 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3646 where `mask` removes any high-order bits of `rhs` that
3647 would cause the shift to exceed the bitwidth of the type.
3649 Note that this is *not* the same as a rotate-left; the
3650 RHS of a wrapping shift-left is restricted to the range
3651 of the type, rather than the bits shifted out of the LHS
3652 being returned to the other end. The primitive integer
3653 types all implement a [`rotate_left`](#method.rotate_left) function,
3654 which may be what you want instead.
3661 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3662 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3664 #[stable(feature = "num_wrapping", since = "1.2.0")]
3665 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3666 #[must_use = "this returns the result of the operation, \
3667 without modifying the original"]
3669 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3670 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3673 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3679 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3680 where `mask` removes any high-order bits of `rhs` that
3681 would cause the shift to exceed the bitwidth of the type.
3683 Note that this is *not* the same as a rotate-right; the
3684 RHS of a wrapping shift-right is restricted to the range
3685 of the type, rather than the bits shifted out of the LHS
3686 being returned to the other end. The primitive integer
3687 types all implement a [`rotate_right`](#method.rotate_right) function,
3688 which may be what you want instead.
3695 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3696 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3698 #[stable(feature = "num_wrapping", since = "1.2.0")]
3699 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3700 #[must_use = "this returns the result of the operation, \
3701 without modifying the original"]
3703 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3704 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3707 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3713 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3714 wrapping around at the boundary of the type.
3721 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3722 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3724 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3725 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3726 #[must_use = "this returns the result of the operation, \
3727 without modifying the original"]
3729 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
3733 let mut base = self;
3734 let mut acc: Self = 1;
3738 acc = acc.wrapping_mul(base);
3741 base = base.wrapping_mul(base);
3744 // since exp!=0, finally the exp must be 1.
3745 // Deal with the final bit of the exponent separately, since
3746 // squaring the base afterwards is not necessary and may cause a
3747 // needless overflow.
3748 acc.wrapping_mul(base)
3753 concat!("Calculates `self` + `rhs`
3755 Returns a tuple of the addition along with a boolean indicating
3756 whether an arithmetic overflow would occur. If an overflow would
3757 have occurred then the wrapped value is returned.
3765 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3766 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3768 #[stable(feature = "wrapping", since = "1.7.0")]
3769 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3770 #[must_use = "this returns the result of the operation, \
3771 without modifying the original"]
3773 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3774 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3780 concat!("Calculates `self` - `rhs`
3782 Returns a tuple of the subtraction along with a boolean indicating
3783 whether an arithmetic overflow would occur. If an overflow would
3784 have occurred then the wrapped value is returned.
3792 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3793 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3796 #[stable(feature = "wrapping", since = "1.7.0")]
3797 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3798 #[must_use = "this returns the result of the operation, \
3799 without modifying the original"]
3801 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3802 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3807 /// Calculates the multiplication of `self` and `rhs`.
3809 /// Returns a tuple of the multiplication along with a boolean
3810 /// indicating whether an arithmetic overflow would occur. If an
3811 /// overflow would have occurred then the wrapped value is returned.
3817 /// Please note that this example is shared between integer types.
3818 /// Which explains why `u32` is used here.
3821 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3822 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3824 #[stable(feature = "wrapping", since = "1.7.0")]
3825 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3826 #[must_use = "this returns the result of the operation, \
3827 without modifying the original"]
3829 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3830 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3835 concat!("Calculates the divisor when `self` is divided by `rhs`.
3837 Returns a tuple of the divisor along with a boolean indicating
3838 whether an arithmetic overflow would occur. Note that for unsigned
3839 integers overflow never occurs, so the second value is always
3844 This function will panic if `rhs` is 0.
3851 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3854 #[stable(feature = "wrapping", since = "1.7.0")]
3855 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3856 #[must_use = "this returns the result of the operation, \
3857 without modifying the original"]
3858 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3864 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3866 Returns a tuple of the divisor along with a boolean indicating
3867 whether an arithmetic overflow would occur. Note that for unsigned
3868 integers overflow never occurs, so the second value is always
3870 Since, for the positive integers, all common
3871 definitions of division are equal, this
3872 is exactly equal to `self.overflowing_div(rhs)`.
3876 This function will panic if `rhs` is 0.
3883 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3886 #[stable(feature = "euclidean_division", since = "1.38.0")]
3887 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3888 #[must_use = "this returns the result of the operation, \
3889 without modifying the original"]
3890 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3896 concat!("Calculates the remainder when `self` is divided by `rhs`.
3898 Returns a tuple of the remainder after dividing along with a boolean
3899 indicating whether an arithmetic overflow would occur. Note that for
3900 unsigned integers overflow never occurs, so the second value is
3905 This function will panic if `rhs` is 0.
3912 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3915 #[stable(feature = "wrapping", since = "1.7.0")]
3916 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3917 #[must_use = "this returns the result of the operation, \
3918 without modifying the original"]
3919 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3925 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3927 Returns a tuple of the modulo after dividing along with a boolean
3928 indicating whether an arithmetic overflow would occur. Note that for
3929 unsigned integers overflow never occurs, so the second value is
3931 Since, for the positive integers, all common
3932 definitions of division are equal, this operation
3933 is exactly equal to `self.overflowing_rem(rhs)`.
3937 This function will panic if `rhs` is 0.
3944 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3947 #[stable(feature = "euclidean_division", since = "1.38.0")]
3948 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3949 #[must_use = "this returns the result of the operation, \
3950 without modifying the original"]
3951 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3957 concat!("Negates self in an overflowing fashion.
3959 Returns `!self + 1` using wrapping operations to return the value
3960 that represents the negation of this unsigned value. Note that for
3961 positive unsigned values overflow always occurs, but negating 0 does
3969 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3970 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3971 ", true));", $EndFeature, "
3974 #[stable(feature = "wrapping", since = "1.7.0")]
3975 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3976 pub const fn overflowing_neg(self) -> (Self, bool) {
3977 ((!self).wrapping_add(1), self != 0)
3982 concat!("Shifts self left by `rhs` bits.
3984 Returns a tuple of the shifted version of self along with a boolean
3985 indicating whether the shift value was larger than or equal to the
3986 number of bits. If the shift value is too large, then value is
3987 masked (N-1) where N is the number of bits, and this value is then
3988 used to perform the shift.
3995 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3996 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3998 #[stable(feature = "wrapping", since = "1.7.0")]
3999 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
4000 #[must_use = "this returns the result of the operation, \
4001 without modifying the original"]
4003 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
4004 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
4009 concat!("Shifts self right by `rhs` bits.
4011 Returns a tuple of the shifted version of self along with a boolean
4012 indicating whether the shift value was larger than or equal to the
4013 number of bits. If the shift value is too large, then value is
4014 masked (N-1) where N is the number of bits, and this value is then
4015 used to perform the shift.
4022 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
4023 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
4025 #[stable(feature = "wrapping", since = "1.7.0")]
4026 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
4027 #[must_use = "this returns the result of the operation, \
4028 without modifying the original"]
4030 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
4031 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
4036 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
4038 Returns a tuple of the exponentiation along with a bool indicating
4039 whether an overflow happened.
4046 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
4047 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
4049 #[stable(feature = "no_panic_pow", since = "1.34.0")]
4050 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4051 #[must_use = "this returns the result of the operation, \
4052 without modifying the original"]
4054 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
4058 let mut base = self;
4059 let mut acc: Self = 1;
4060 let mut overflown = false;
4061 // Scratch space for storing results of overflowing_mul.
4066 r = acc.overflowing_mul(base);
4071 r = base.overflowing_mul(base);
4076 // since exp!=0, finally the exp must be 1.
4077 // Deal with the final bit of the exponent separately, since
4078 // squaring the base afterwards is not necessary and may cause a
4079 // needless overflow.
4080 r = acc.overflowing_mul(base);
4088 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
4095 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
4097 #[stable(feature = "rust1", since = "1.0.0")]
4098 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4099 #[must_use = "this returns the result of the operation, \
4100 without modifying the original"]
4102 #[rustc_inherit_overflow_checks]
4103 pub const fn pow(self, mut exp: u32) -> Self {
4107 let mut base = self;
4118 // since exp!=0, finally the exp must be 1.
4119 // Deal with the final bit of the exponent separately, since
4120 // squaring the base afterwards is not necessary and may cause a
4121 // needless overflow.
4127 concat!("Performs Euclidean division.
4129 Since, for the positive integers, all common
4130 definitions of division are equal, this
4131 is exactly equal to `self / rhs`.
4135 This function will panic if `rhs` is 0.
4142 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
4144 #[stable(feature = "euclidean_division", since = "1.38.0")]
4145 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
4146 #[must_use = "this returns the result of the operation, \
4147 without modifying the original"]
4149 #[rustc_inherit_overflow_checks]
4150 pub const fn div_euclid(self, rhs: Self) -> Self {
4157 concat!("Calculates the least remainder of `self (mod rhs)`.
4159 Since, for the positive integers, all common
4160 definitions of division are equal, this
4161 is exactly equal to `self % rhs`.
4165 This function will panic if `rhs` is 0.
4172 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
4174 #[stable(feature = "euclidean_division", since = "1.38.0")]
4175 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
4176 #[must_use = "this returns the result of the operation, \
4177 without modifying the original"]
4179 #[rustc_inherit_overflow_checks]
4180 pub const fn rem_euclid(self, rhs: Self) -> Self {
4186 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
4193 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
4194 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
4196 #[stable(feature = "rust1", since = "1.0.0")]
4197 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
4199 pub const fn is_power_of_two(self) -> bool {
4200 self.count_ones() == 1
4204 // Returns one less than next power of two.
4205 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
4207 // 8u8.one_less_than_next_power_of_two() == 7
4208 // 6u8.one_less_than_next_power_of_two() == 7
4210 // This method cannot overflow, as in the `next_power_of_two`
4211 // overflow cases it instead ends up returning the maximum value
4212 // of the type, and can return 0 for 0.
4214 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4215 const fn one_less_than_next_power_of_two(self) -> Self {
4216 if self <= 1 { return 0; }
4219 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4220 // That means the shift is always in-bounds, and some processors
4221 // (such as intel pre-haswell) have more efficient ctlz
4222 // intrinsics when the argument is non-zero.
4223 let z = unsafe { intrinsics::ctlz_nonzero(p) };
4228 concat!("Returns the smallest power of two greater than or equal to `self`.
4230 When return value overflows (i.e., `self > (1 << (N-1))` for type
4231 `uN`), it panics in debug mode and return value is wrapped to 0 in
4232 release mode (the only situation in which method can return 0).
4239 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4240 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4242 #[stable(feature = "rust1", since = "1.0.0")]
4243 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4245 #[rustc_inherit_overflow_checks]
4246 pub const fn next_power_of_two(self) -> Self {
4247 self.one_less_than_next_power_of_two() + 1
4252 concat!("Returns the smallest power of two greater than or equal to `n`. If
4253 the next power of two is greater than the type's maximum value,
4254 `None` is returned, otherwise the power of two is wrapped in `Some`.
4261 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4262 ".checked_next_power_of_two(), Some(2));
4263 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4264 assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);",
4268 #[stable(feature = "rust1", since = "1.0.0")]
4269 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4270 pub const fn checked_next_power_of_two(self) -> Option<Self> {
4271 self.one_less_than_next_power_of_two().checked_add(1)
4276 concat!("Returns the smallest power of two greater than or equal to `n`. If
4277 the next power of two is greater than the type's maximum value,
4278 the return value is wrapped to `0`.
4285 #![feature(wrapping_next_power_of_two)]
4287 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4288 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4289 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);",
4292 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4293 reason = "needs decision on wrapping behaviour")]
4294 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4295 pub const fn wrapping_next_power_of_two(self) -> Self {
4296 self.one_less_than_next_power_of_two().wrapping_add(1)
4301 concat!("Return the memory representation of this integer as a byte array in
4302 big-endian (network) byte order.
4309 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4310 assert_eq!(bytes, ", $be_bytes, ");
4312 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4313 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4315 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4316 self.to_be().to_ne_bytes()
4321 concat!("Return the memory representation of this integer as a byte array in
4322 little-endian byte order.
4329 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4330 assert_eq!(bytes, ", $le_bytes, ");
4332 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4333 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4335 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4336 self.to_le().to_ne_bytes()
4342 Return the memory representation of this integer as a byte array in
4345 As the target platform's native endianness is used, portable code
4346 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4351 [`to_be_bytes`]: #method.to_be_bytes
4352 [`to_le_bytes`]: #method.to_le_bytes
4357 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4360 if cfg!(target_endian = \"big\") {
4367 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4368 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4369 // SAFETY: const sound because integers are plain old datatypes so we can always
4370 // transmute them to arrays of bytes
4371 #[allow_internal_unstable(const_fn_union)]
4373 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4377 bytes: [u8; mem::size_of::<$SelfT>()],
4379 // SAFETY: integers are plain old datatypes so we can always transmute them to
4381 unsafe { Bytes { val: self }.bytes }
4386 concat!("Create an integer value from its representation as a byte array in
4394 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4395 assert_eq!(value, ", $swap_op, ");
4398 When starting from a slice rather than an array, fallible conversion APIs can be used:
4401 use std::convert::TryInto;
4403 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4404 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4406 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4409 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4410 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4412 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4413 Self::from_be(Self::from_ne_bytes(bytes))
4419 Create an integer value from its representation as a byte array in
4427 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4428 assert_eq!(value, ", $swap_op, ");
4431 When starting from a slice rather than an array, fallible conversion APIs can be used:
4434 use std::convert::TryInto;
4436 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4437 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4439 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4442 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4443 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4445 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4446 Self::from_le(Self::from_ne_bytes(bytes))
4451 concat!("Create an integer value from its memory representation as a byte
4452 array in native endianness.
4454 As the target platform's native endianness is used, portable code
4455 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4456 appropriate instead.
4458 [`from_be_bytes`]: #method.from_be_bytes
4459 [`from_le_bytes`]: #method.from_le_bytes
4466 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4471 assert_eq!(value, ", $swap_op, ");
4474 When starting from a slice rather than an array, fallible conversion APIs can be used:
4477 use std::convert::TryInto;
4479 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4480 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4482 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4485 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4486 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4487 // SAFETY: const sound because integers are plain old datatypes so we can always
4488 // transmute to them
4489 #[allow_internal_unstable(const_fn_union)]
4491 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4495 bytes: [u8; mem::size_of::<$SelfT>()],
4497 // SAFETY: integers are plain old datatypes so we can always transmute to them
4498 unsafe { Bytes { bytes }.val }
4503 concat!("**This method is soft-deprecated.**
4505 Although using it won’t cause compilation warning,
4506 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
4508 Returns the smallest value that can be represented by this integer type."),
4509 #[stable(feature = "rust1", since = "1.0.0")]
4512 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4513 pub const fn min_value() -> Self { Self::MIN }
4517 concat!("**This method is soft-deprecated.**
4519 Although using it won’t cause compilation warning,
4520 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
4522 Returns the largest value that can be represented by this integer type."),
4523 #[stable(feature = "rust1", since = "1.0.0")]
4526 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4527 pub const fn max_value() -> Self { Self::MAX }
4534 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4537 /// Checks if the value is within the ASCII range.
4542 /// let ascii = 97u8;
4543 /// let non_ascii = 150u8;
4545 /// assert!(ascii.is_ascii());
4546 /// assert!(!non_ascii.is_ascii());
4548 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4549 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.43.0")]
4551 pub const fn is_ascii(&self) -> bool {
4555 /// Makes a copy of the value in its ASCII upper case equivalent.
4557 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4558 /// but non-ASCII letters are unchanged.
4560 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4565 /// let lowercase_a = 97u8;
4567 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4570 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4571 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4573 pub fn to_ascii_uppercase(&self) -> u8 {
4574 // Unset the fifth bit if this is a lowercase letter
4575 *self & !((self.is_ascii_lowercase() as u8) << 5)
4578 /// Makes a copy of the value in its ASCII lower case equivalent.
4580 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4581 /// but non-ASCII letters are unchanged.
4583 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4588 /// let uppercase_a = 65u8;
4590 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4593 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4594 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4596 pub fn to_ascii_lowercase(&self) -> u8 {
4597 // Set the fifth bit if this is an uppercase letter
4598 *self | ((self.is_ascii_uppercase() as u8) << 5)
4601 /// Checks that two values are an ASCII case-insensitive match.
4603 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4608 /// let lowercase_a = 97u8;
4609 /// let uppercase_a = 65u8;
4611 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4613 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4615 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4616 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4619 /// Converts this value to its ASCII upper case equivalent in-place.
4621 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4622 /// but non-ASCII letters are unchanged.
4624 /// To return a new uppercased value without modifying the existing one, use
4625 /// [`to_ascii_uppercase`].
4630 /// let mut byte = b'a';
4632 /// byte.make_ascii_uppercase();
4634 /// assert_eq!(b'A', byte);
4637 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4638 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4640 pub fn make_ascii_uppercase(&mut self) {
4641 *self = self.to_ascii_uppercase();
4644 /// Converts this value to its ASCII lower case equivalent in-place.
4646 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4647 /// but non-ASCII letters are unchanged.
4649 /// To return a new lowercased value without modifying the existing one, use
4650 /// [`to_ascii_lowercase`].
4655 /// let mut byte = b'A';
4657 /// byte.make_ascii_lowercase();
4659 /// assert_eq!(b'a', byte);
4662 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4663 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4665 pub fn make_ascii_lowercase(&mut self) {
4666 *self = self.to_ascii_lowercase();
4669 /// Checks if the value is an ASCII alphabetic character:
4671 /// - U+0041 'A' ..= U+005A 'Z', or
4672 /// - U+0061 'a' ..= U+007A 'z'.
4677 /// let uppercase_a = b'A';
4678 /// let uppercase_g = b'G';
4681 /// let zero = b'0';
4682 /// let percent = b'%';
4683 /// let space = b' ';
4685 /// let esc = 0x1b_u8;
4687 /// assert!(uppercase_a.is_ascii_alphabetic());
4688 /// assert!(uppercase_g.is_ascii_alphabetic());
4689 /// assert!(a.is_ascii_alphabetic());
4690 /// assert!(g.is_ascii_alphabetic());
4691 /// assert!(!zero.is_ascii_alphabetic());
4692 /// assert!(!percent.is_ascii_alphabetic());
4693 /// assert!(!space.is_ascii_alphabetic());
4694 /// assert!(!lf.is_ascii_alphabetic());
4695 /// assert!(!esc.is_ascii_alphabetic());
4697 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4698 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4700 pub const fn is_ascii_alphabetic(&self) -> bool {
4701 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
4704 /// Checks if the value is an ASCII uppercase character:
4705 /// U+0041 'A' ..= U+005A 'Z'.
4710 /// let uppercase_a = b'A';
4711 /// let uppercase_g = b'G';
4714 /// let zero = b'0';
4715 /// let percent = b'%';
4716 /// let space = b' ';
4718 /// let esc = 0x1b_u8;
4720 /// assert!(uppercase_a.is_ascii_uppercase());
4721 /// assert!(uppercase_g.is_ascii_uppercase());
4722 /// assert!(!a.is_ascii_uppercase());
4723 /// assert!(!g.is_ascii_uppercase());
4724 /// assert!(!zero.is_ascii_uppercase());
4725 /// assert!(!percent.is_ascii_uppercase());
4726 /// assert!(!space.is_ascii_uppercase());
4727 /// assert!(!lf.is_ascii_uppercase());
4728 /// assert!(!esc.is_ascii_uppercase());
4730 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4731 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4733 pub const fn is_ascii_uppercase(&self) -> bool {
4734 matches!(*self, b'A'..=b'Z')
4737 /// Checks if the value is an ASCII lowercase character:
4738 /// U+0061 'a' ..= U+007A 'z'.
4743 /// let uppercase_a = b'A';
4744 /// let uppercase_g = b'G';
4747 /// let zero = b'0';
4748 /// let percent = b'%';
4749 /// let space = b' ';
4751 /// let esc = 0x1b_u8;
4753 /// assert!(!uppercase_a.is_ascii_lowercase());
4754 /// assert!(!uppercase_g.is_ascii_lowercase());
4755 /// assert!(a.is_ascii_lowercase());
4756 /// assert!(g.is_ascii_lowercase());
4757 /// assert!(!zero.is_ascii_lowercase());
4758 /// assert!(!percent.is_ascii_lowercase());
4759 /// assert!(!space.is_ascii_lowercase());
4760 /// assert!(!lf.is_ascii_lowercase());
4761 /// assert!(!esc.is_ascii_lowercase());
4763 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4764 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4766 pub const fn is_ascii_lowercase(&self) -> bool {
4767 matches!(*self, b'a'..=b'z')
4770 /// Checks if the value is an ASCII alphanumeric character:
4772 /// - U+0041 'A' ..= U+005A 'Z', or
4773 /// - U+0061 'a' ..= U+007A 'z', or
4774 /// - U+0030 '0' ..= U+0039 '9'.
4779 /// let uppercase_a = b'A';
4780 /// let uppercase_g = b'G';
4783 /// let zero = b'0';
4784 /// let percent = b'%';
4785 /// let space = b' ';
4787 /// let esc = 0x1b_u8;
4789 /// assert!(uppercase_a.is_ascii_alphanumeric());
4790 /// assert!(uppercase_g.is_ascii_alphanumeric());
4791 /// assert!(a.is_ascii_alphanumeric());
4792 /// assert!(g.is_ascii_alphanumeric());
4793 /// assert!(zero.is_ascii_alphanumeric());
4794 /// assert!(!percent.is_ascii_alphanumeric());
4795 /// assert!(!space.is_ascii_alphanumeric());
4796 /// assert!(!lf.is_ascii_alphanumeric());
4797 /// assert!(!esc.is_ascii_alphanumeric());
4799 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4800 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4802 pub const fn is_ascii_alphanumeric(&self) -> bool {
4803 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
4806 /// Checks if the value is an ASCII decimal digit:
4807 /// U+0030 '0' ..= U+0039 '9'.
4812 /// let uppercase_a = b'A';
4813 /// let uppercase_g = b'G';
4816 /// let zero = b'0';
4817 /// let percent = b'%';
4818 /// let space = b' ';
4820 /// let esc = 0x1b_u8;
4822 /// assert!(!uppercase_a.is_ascii_digit());
4823 /// assert!(!uppercase_g.is_ascii_digit());
4824 /// assert!(!a.is_ascii_digit());
4825 /// assert!(!g.is_ascii_digit());
4826 /// assert!(zero.is_ascii_digit());
4827 /// assert!(!percent.is_ascii_digit());
4828 /// assert!(!space.is_ascii_digit());
4829 /// assert!(!lf.is_ascii_digit());
4830 /// assert!(!esc.is_ascii_digit());
4832 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4833 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4835 pub const fn is_ascii_digit(&self) -> bool {
4836 matches!(*self, b'0'..=b'9')
4839 /// Checks if the value is an ASCII hexadecimal digit:
4841 /// - U+0030 '0' ..= U+0039 '9', or
4842 /// - U+0041 'A' ..= U+0046 'F', or
4843 /// - U+0061 'a' ..= U+0066 'f'.
4848 /// let uppercase_a = b'A';
4849 /// let uppercase_g = b'G';
4852 /// let zero = b'0';
4853 /// let percent = b'%';
4854 /// let space = b' ';
4856 /// let esc = 0x1b_u8;
4858 /// assert!(uppercase_a.is_ascii_hexdigit());
4859 /// assert!(!uppercase_g.is_ascii_hexdigit());
4860 /// assert!(a.is_ascii_hexdigit());
4861 /// assert!(!g.is_ascii_hexdigit());
4862 /// assert!(zero.is_ascii_hexdigit());
4863 /// assert!(!percent.is_ascii_hexdigit());
4864 /// assert!(!space.is_ascii_hexdigit());
4865 /// assert!(!lf.is_ascii_hexdigit());
4866 /// assert!(!esc.is_ascii_hexdigit());
4868 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4869 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4871 pub const fn is_ascii_hexdigit(&self) -> bool {
4872 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
4875 /// Checks if the value is an ASCII punctuation character:
4877 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4878 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4879 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4880 /// - U+007B ..= U+007E `{ | } ~`
4885 /// let uppercase_a = b'A';
4886 /// let uppercase_g = b'G';
4889 /// let zero = b'0';
4890 /// let percent = b'%';
4891 /// let space = b' ';
4893 /// let esc = 0x1b_u8;
4895 /// assert!(!uppercase_a.is_ascii_punctuation());
4896 /// assert!(!uppercase_g.is_ascii_punctuation());
4897 /// assert!(!a.is_ascii_punctuation());
4898 /// assert!(!g.is_ascii_punctuation());
4899 /// assert!(!zero.is_ascii_punctuation());
4900 /// assert!(percent.is_ascii_punctuation());
4901 /// assert!(!space.is_ascii_punctuation());
4902 /// assert!(!lf.is_ascii_punctuation());
4903 /// assert!(!esc.is_ascii_punctuation());
4905 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4906 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4908 pub const fn is_ascii_punctuation(&self) -> bool {
4909 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
4912 /// Checks if the value is an ASCII graphic character:
4913 /// U+0021 '!' ..= U+007E '~'.
4918 /// let uppercase_a = b'A';
4919 /// let uppercase_g = b'G';
4922 /// let zero = b'0';
4923 /// let percent = b'%';
4924 /// let space = b' ';
4926 /// let esc = 0x1b_u8;
4928 /// assert!(uppercase_a.is_ascii_graphic());
4929 /// assert!(uppercase_g.is_ascii_graphic());
4930 /// assert!(a.is_ascii_graphic());
4931 /// assert!(g.is_ascii_graphic());
4932 /// assert!(zero.is_ascii_graphic());
4933 /// assert!(percent.is_ascii_graphic());
4934 /// assert!(!space.is_ascii_graphic());
4935 /// assert!(!lf.is_ascii_graphic());
4936 /// assert!(!esc.is_ascii_graphic());
4938 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4939 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4941 pub const fn is_ascii_graphic(&self) -> bool {
4942 matches!(*self, b'!'..=b'~')
4945 /// Checks if the value is an ASCII whitespace character:
4946 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4947 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4949 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4950 /// whitespace][infra-aw]. There are several other definitions in
4951 /// wide use. For instance, [the POSIX locale][pct] includes
4952 /// U+000B VERTICAL TAB as well as all the above characters,
4953 /// but—from the very same specification—[the default rule for
4954 /// "field splitting" in the Bourne shell][bfs] considers *only*
4955 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4957 /// If you are writing a program that will process an existing
4958 /// file format, check what that format's definition of whitespace is
4959 /// before using this function.
4961 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4962 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4963 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4968 /// let uppercase_a = b'A';
4969 /// let uppercase_g = b'G';
4972 /// let zero = b'0';
4973 /// let percent = b'%';
4974 /// let space = b' ';
4976 /// let esc = 0x1b_u8;
4978 /// assert!(!uppercase_a.is_ascii_whitespace());
4979 /// assert!(!uppercase_g.is_ascii_whitespace());
4980 /// assert!(!a.is_ascii_whitespace());
4981 /// assert!(!g.is_ascii_whitespace());
4982 /// assert!(!zero.is_ascii_whitespace());
4983 /// assert!(!percent.is_ascii_whitespace());
4984 /// assert!(space.is_ascii_whitespace());
4985 /// assert!(lf.is_ascii_whitespace());
4986 /// assert!(!esc.is_ascii_whitespace());
4988 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4989 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
4991 pub const fn is_ascii_whitespace(&self) -> bool {
4992 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
4995 /// Checks if the value is an ASCII control character:
4996 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4997 /// Note that most ASCII whitespace characters are control
4998 /// characters, but SPACE is not.
5003 /// let uppercase_a = b'A';
5004 /// let uppercase_g = b'G';
5007 /// let zero = b'0';
5008 /// let percent = b'%';
5009 /// let space = b' ';
5011 /// let esc = 0x1b_u8;
5013 /// assert!(!uppercase_a.is_ascii_control());
5014 /// assert!(!uppercase_g.is_ascii_control());
5015 /// assert!(!a.is_ascii_control());
5016 /// assert!(!g.is_ascii_control());
5017 /// assert!(!zero.is_ascii_control());
5018 /// assert!(!percent.is_ascii_control());
5019 /// assert!(!space.is_ascii_control());
5020 /// assert!(lf.is_ascii_control());
5021 /// assert!(esc.is_ascii_control());
5023 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
5024 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
5026 pub const fn is_ascii_control(&self) -> bool {
5027 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
5033 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
5034 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
5039 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
5040 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
5045 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
5046 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
5047 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
5048 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
5054 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
5055 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
5056 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
5057 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
5058 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
5059 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
5060 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
5064 #[cfg(target_pointer_width = "16")]
5067 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
5068 "[0x34, 0x12]", "[0x12, 0x34]",
5069 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
5071 #[cfg(target_pointer_width = "32")]
5074 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
5075 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
5076 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
5079 #[cfg(target_pointer_width = "64")]
5082 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
5083 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
5084 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
5085 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
5086 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
5089 /// A classification of floating point numbers.
5091 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
5092 /// their documentation for more.
5094 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
5095 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
5100 /// use std::num::FpCategory;
5102 /// let num = 12.4_f32;
5103 /// let inf = f32::INFINITY;
5104 /// let zero = 0f32;
5105 /// let sub: f32 = 1.1754942e-38;
5106 /// let nan = f32::NAN;
5108 /// assert_eq!(num.classify(), FpCategory::Normal);
5109 /// assert_eq!(inf.classify(), FpCategory::Infinite);
5110 /// assert_eq!(zero.classify(), FpCategory::Zero);
5111 /// assert_eq!(nan.classify(), FpCategory::Nan);
5112 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
5114 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
5115 #[stable(feature = "rust1", since = "1.0.0")]
5116 pub enum FpCategory {
5117 /// "Not a Number", often obtained by dividing by zero.
5118 #[stable(feature = "rust1", since = "1.0.0")]
5121 /// Positive or negative infinity.
5122 #[stable(feature = "rust1", since = "1.0.0")]
5125 /// Positive or negative zero.
5126 #[stable(feature = "rust1", since = "1.0.0")]
5129 /// De-normalized floating point representation (less precise than `Normal`).
5130 #[stable(feature = "rust1", since = "1.0.0")]
5133 /// A regular floating point number.
5134 #[stable(feature = "rust1", since = "1.0.0")]
5138 macro_rules! from_str_radix_int_impl {
5140 #[stable(feature = "rust1", since = "1.0.0")]
5141 impl FromStr for $t {
5142 type Err = ParseIntError;
5143 fn from_str(src: &str) -> Result<Self, ParseIntError> {
5144 from_str_radix(src, 10)
5149 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
5151 /// The error type returned when a checked integral type conversion fails.
5152 #[stable(feature = "try_from", since = "1.34.0")]
5153 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
5154 pub struct TryFromIntError(pub(crate) ());
5156 impl TryFromIntError {
5158 feature = "int_error_internals",
5159 reason = "available through Error trait and this method should \
5160 not be exposed publicly",
5164 pub fn __description(&self) -> &str {
5165 "out of range integral type conversion attempted"
5169 #[stable(feature = "try_from", since = "1.34.0")]
5170 impl fmt::Display for TryFromIntError {
5171 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
5172 self.__description().fmt(fmt)
5176 #[stable(feature = "try_from", since = "1.34.0")]
5177 impl From<Infallible> for TryFromIntError {
5178 fn from(x: Infallible) -> TryFromIntError {
5183 #[unstable(feature = "never_type", issue = "35121")]
5184 impl From<!> for TryFromIntError {
5185 fn from(never: !) -> TryFromIntError {
5186 // Match rather than coerce to make sure that code like
5187 // `From<Infallible> for TryFromIntError` above will keep working
5188 // when `Infallible` becomes an alias to `!`.
5194 trait FromStrRadixHelper: PartialOrd + Copy {
5195 fn min_value() -> Self;
5196 fn max_value() -> Self;
5197 fn from_u32(u: u32) -> Self;
5198 fn checked_mul(&self, other: u32) -> Option<Self>;
5199 fn checked_sub(&self, other: u32) -> Option<Self>;
5200 fn checked_add(&self, other: u32) -> Option<Self>;
5204 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
5206 fn min_value() -> Self { Self::MIN }
5208 fn max_value() -> Self { Self::MAX }
5210 fn from_u32(u: u32) -> Self { u as Self }
5212 fn checked_mul(&self, other: u32) -> Option<Self> {
5213 Self::checked_mul(*self, other as Self)
5216 fn checked_sub(&self, other: u32) -> Option<Self> {
5217 Self::checked_sub(*self, other as Self)
5220 fn checked_add(&self, other: u32) -> Option<Self> {
5221 Self::checked_add(*self, other as Self)
5225 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5227 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5228 use self::IntErrorKind::*;
5229 use self::ParseIntError as PIE;
5232 radix >= 2 && radix <= 36,
5233 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5238 return Err(PIE { kind: Empty });
5241 let is_signed_ty = T::from_u32(0) > T::min_value();
5243 // all valid digits are ascii, so we will just iterate over the utf8 bytes
5244 // and cast them to chars. .to_digit() will safely return None for anything
5245 // other than a valid ascii digit for the given radix, including the first-byte
5246 // of multi-byte sequences
5247 let src = src.as_bytes();
5249 let (is_positive, digits) = match src[0] {
5250 b'+' => (true, &src[1..]),
5251 b'-' if is_signed_ty => (false, &src[1..]),
5255 if digits.is_empty() {
5256 return Err(PIE { kind: Empty });
5259 let mut result = T::from_u32(0);
5261 // The number is positive
5263 let x = match (c as char).to_digit(radix) {
5265 None => return Err(PIE { kind: InvalidDigit }),
5267 result = match result.checked_mul(radix) {
5268 Some(result) => result,
5269 None => return Err(PIE { kind: Overflow }),
5271 result = match result.checked_add(x) {
5272 Some(result) => result,
5273 None => return Err(PIE { kind: Overflow }),
5277 // The number is negative
5279 let x = match (c as char).to_digit(radix) {
5281 None => return Err(PIE { kind: InvalidDigit }),
5283 result = match result.checked_mul(radix) {
5284 Some(result) => result,
5285 None => return Err(PIE { kind: Underflow }),
5287 result = match result.checked_sub(x) {
5288 Some(result) => result,
5289 None => return Err(PIE { kind: Underflow }),
5296 /// An error which can be returned when parsing an integer.
5298 /// This error is used as the error type for the `from_str_radix()` functions
5299 /// on the primitive integer types, such as [`i8::from_str_radix`].
5301 /// # Potential causes
5303 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5304 /// in the string e.g., when it is obtained from the standard input.
5305 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5307 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5308 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5309 #[derive(Debug, Clone, PartialEq, Eq)]
5310 #[stable(feature = "rust1", since = "1.0.0")]
5311 pub struct ParseIntError {
5315 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5317 feature = "int_error_matching",
5318 reason = "it can be useful to match errors when making error messages \
5319 for integer parsing",
5322 #[derive(Debug, Clone, PartialEq, Eq)]
5324 pub enum IntErrorKind {
5325 /// Value being parsed is empty.
5327 /// Among other causes, this variant will be constructed when parsing an empty string.
5329 /// Contains an invalid digit.
5331 /// Among other causes, this variant will be constructed when parsing a string that
5332 /// contains a letter.
5334 /// Integer is too large to store in target integer type.
5336 /// Integer is too small to store in target integer type.
5340 /// This variant will be emitted when the parsing string has a value of zero, which
5341 /// would be illegal for non-zero types.
5345 impl ParseIntError {
5346 /// Outputs the detailed cause of parsing an integer failing.
5348 feature = "int_error_matching",
5349 reason = "it can be useful to match errors when making error messages \
5350 for integer parsing",
5353 pub fn kind(&self) -> &IntErrorKind {
5357 feature = "int_error_internals",
5358 reason = "available through Error trait and this method should \
5359 not be exposed publicly",
5363 pub fn __description(&self) -> &str {
5365 IntErrorKind::Empty => "cannot parse integer from empty string",
5366 IntErrorKind::InvalidDigit => "invalid digit found in string",
5367 IntErrorKind::Overflow => "number too large to fit in target type",
5368 IntErrorKind::Underflow => "number too small to fit in target type",
5369 IntErrorKind::Zero => "number would be zero for non-zero type",
5374 #[stable(feature = "rust1", since = "1.0.0")]
5375 impl fmt::Display for ParseIntError {
5376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5377 self.__description().fmt(f)
5381 #[stable(feature = "rust1", since = "1.0.0")]
5382 pub use crate::num::dec2flt::ParseFloatError;