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;
12 use crate::str::FromStr;
14 macro_rules! impl_nonzero_fmt {
15 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
18 impl fmt::$Trait for $Ty {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28 macro_rules! doc_comment {
29 ($x:expr, $($tt:tt)*) => {
35 macro_rules! nonzero_integers {
36 ( $( #[$stability: meta] $Ty: ident($Int: ty); )+ ) => {
39 concat!("An integer that is known not to equal zero.
41 This enables some memory layout optimization.
42 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
45 use std::mem::size_of;
46 assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
50 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
52 #[rustc_layout_scalar_valid_range_start(1)]
53 #[rustc_nonnull_optimization_guaranteed]
58 /// Creates a non-zero without checking the value.
62 /// The value must not be zero.
66 rustc_const_stable(feature = "nonzero", since = "1.34.0"),
69 pub const unsafe fn new_unchecked(n: $Int) -> Self {
73 /// Creates a non-zero if the given value is not zero.
76 pub fn new(n: $Int) -> Option<Self> {
78 // SAFETY: we just checked that there's no `0`
79 Some(unsafe { $Ty(n) })
85 /// Returns the value as a primitive type.
90 rustc_const_stable(feature = "nonzero", since = "1.34.0"),
92 pub const fn get(self) -> $Int {
98 #[stable(feature = "from_nonzero", since = "1.31.0")]
99 impl From<$Ty> for $Int {
100 fn from(nonzero: $Ty) -> Self {
106 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
113 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
114 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
115 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
116 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
117 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
118 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
119 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
120 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
121 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
122 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
123 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
124 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
127 macro_rules! from_str_radix_nzint_impl {
129 #[stable(feature = "nonzero_parse", since = "1.35.0")]
130 impl FromStr for $t {
131 type Err = ParseIntError;
132 fn from_str(src: &str) -> Result<Self, Self::Err> {
133 Self::new(from_str_radix(src, 10)?)
134 .ok_or(ParseIntError {
135 kind: IntErrorKind::Zero
142 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
143 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
145 /// Provides intentionally-wrapped arithmetic on `T`.
147 /// Operations like `+` on `u32` values are intended to never overflow,
148 /// and in some debug configurations overflow is detected and results
149 /// in a panic. While most arithmetic falls into this category, some
150 /// code explicitly expects and relies upon modular arithmetic (e.g.,
153 /// Wrapping arithmetic can be achieved either through methods like
154 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
155 /// all standard arithmetic operations on the underlying value are
156 /// intended to have wrapping semantics.
158 /// The underlying value can be retrieved through the `.0` index of the
159 /// `Wrapping` tuple.
164 /// use std::num::Wrapping;
166 /// let zero = Wrapping(0u32);
167 /// let one = Wrapping(1u32);
169 /// assert_eq!(std::u32::MAX, (zero - one).0);
171 #[stable(feature = "rust1", since = "1.0.0")]
172 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
174 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
176 #[stable(feature = "rust1", since = "1.0.0")]
177 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 #[stable(feature = "wrapping_display", since = "1.10.0")]
184 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
191 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
198 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
199 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
205 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
206 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
212 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218 // All these modules are technically private and only exposed for coretests:
226 macro_rules! usize_isize_to_xe_bytes_doc {
230 **Note**: This function returns an array of length 2, 4 or 8 bytes
231 depending on the target pointer size.
237 macro_rules! usize_isize_from_xe_bytes_doc {
241 **Note**: This function takes an array of length 2, 4 or 8 bytes
242 depending on the target pointer size.
248 macro_rules! int_impl {
249 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
250 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
251 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
252 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
254 concat!("Returns the smallest value that can be represented by this integer type.
261 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
264 #[stable(feature = "rust1", since = "1.0.0")]
269 rustc_const_stable(feature = "const_min_value", since = "1.32.0"),
271 pub const fn min_value() -> Self {
272 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
277 concat!("Returns the largest value that can be represented by this integer type.
284 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
287 #[stable(feature = "rust1", since = "1.0.0")]
292 rustc_const_stable(feature = "const_max_value", since = "1.32.0"),
294 pub const fn max_value() -> Self {
300 concat!("Converts a string slice in a given base to an integer.
302 The string is expected to be an optional `+` or `-` sign followed by digits.
303 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
304 depending on `radix`:
312 This function panics if `radix` is not in the range from 2 to 36.
319 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
324 from_str_radix(src, radix)
329 concat!("Returns the number of ones in the binary representation of `self`.
336 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
338 assert_eq!(n.count_ones(), 1);",
342 #[stable(feature = "rust1", since = "1.0.0")]
345 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
348 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
352 concat!("Returns the number of zeros in the binary representation of `self`.
359 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
361 #[stable(feature = "rust1", since = "1.0.0")]
364 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
367 pub const fn count_zeros(self) -> u32 {
373 concat!("Returns the number of leading zeros in the binary representation of `self`.
380 ", $Feature, "let n = -1", stringify!($SelfT), ";
382 assert_eq!(n.leading_zeros(), 0);",
385 #[stable(feature = "rust1", since = "1.0.0")]
388 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
391 pub const fn leading_zeros(self) -> u32 {
392 (self as $UnsignedT).leading_zeros()
397 concat!("Returns the number of trailing zeros in the binary representation of `self`.
404 ", $Feature, "let n = -4", stringify!($SelfT), ";
406 assert_eq!(n.trailing_zeros(), 2);",
409 #[stable(feature = "rust1", since = "1.0.0")]
412 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
415 pub const fn trailing_zeros(self) -> u32 {
416 (self as $UnsignedT).trailing_zeros()
421 concat!("Shifts the bits to the left by a specified amount, `n`,
422 wrapping the truncated bits to the end of the resulting integer.
424 Please note this isn't the same operation as the `<<` shifting operator!
431 let n = ", $rot_op, stringify!($SelfT), ";
432 let m = ", $rot_result, ";
434 assert_eq!(n.rotate_left(", $rot, "), m);
436 #[stable(feature = "rust1", since = "1.0.0")]
439 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
441 #[must_use = "this returns the result of the operation, \
442 without modifying the original"]
444 pub const fn rotate_left(self, n: u32) -> Self {
445 (self as $UnsignedT).rotate_left(n) as Self
450 concat!("Shifts the bits to the right by a specified amount, `n`,
451 wrapping the truncated bits to the beginning of the resulting
454 Please note this isn't the same operation as the `>>` shifting operator!
461 let n = ", $rot_result, stringify!($SelfT), ";
462 let m = ", $rot_op, ";
464 assert_eq!(n.rotate_right(", $rot, "), m);
466 #[stable(feature = "rust1", since = "1.0.0")]
469 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
471 #[must_use = "this returns the result of the operation, \
472 without modifying the original"]
474 pub const fn rotate_right(self, n: u32) -> Self {
475 (self as $UnsignedT).rotate_right(n) as Self
480 concat!("Reverses the byte order of the integer.
487 let n = ", $swap_op, stringify!($SelfT), ";
489 let m = n.swap_bytes();
491 assert_eq!(m, ", $swapped, ");
493 #[stable(feature = "rust1", since = "1.0.0")]
496 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
499 pub const fn swap_bytes(self) -> Self {
500 (self as $UnsignedT).swap_bytes() as Self
505 concat!("Reverses the bit pattern of the integer.
512 let n = ", $swap_op, stringify!($SelfT), ";
513 let m = n.reverse_bits();
515 assert_eq!(m, ", $reversed, ");
517 #[stable(feature = "reverse_bits", since = "1.37.0")]
520 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
524 pub const fn reverse_bits(self) -> Self {
525 (self as $UnsignedT).reverse_bits() as Self
530 concat!("Converts an integer from big endian to the target's endianness.
532 On big endian this is a no-op. On little endian the bytes are swapped.
539 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
541 if cfg!(target_endian = \"big\") {
542 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
544 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
548 #[stable(feature = "rust1", since = "1.0.0")]
551 rustc_const_stable(feature = "const_int_conversions", since = "1.32.0"),
554 pub const fn from_be(x: Self) -> Self {
555 #[cfg(target_endian = "big")]
559 #[cfg(not(target_endian = "big"))]
567 concat!("Converts an integer from little endian to the target's endianness.
569 On little endian this is a no-op. On big endian the bytes are swapped.
576 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
578 if cfg!(target_endian = \"little\") {
579 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
581 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
585 #[stable(feature = "rust1", since = "1.0.0")]
588 rustc_const_stable(feature = "const_int_conversions", since = "1.32.0"),
591 pub const fn from_le(x: Self) -> Self {
592 #[cfg(target_endian = "little")]
596 #[cfg(not(target_endian = "little"))]
604 concat!("Converts `self` to big endian from the target's endianness.
606 On big endian this is a no-op. On little endian the bytes are swapped.
613 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
615 if cfg!(target_endian = \"big\") {
616 assert_eq!(n.to_be(), n)
618 assert_eq!(n.to_be(), n.swap_bytes())
622 #[stable(feature = "rust1", since = "1.0.0")]
625 rustc_const_stable(feature = "const_int_conversions", since = "1.32.0"),
628 pub const fn to_be(self) -> Self { // or not to be?
629 #[cfg(target_endian = "big")]
633 #[cfg(not(target_endian = "big"))]
641 concat!("Converts `self` to little endian from the target's endianness.
643 On little endian this is a no-op. On big endian the bytes are swapped.
650 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
652 if cfg!(target_endian = \"little\") {
653 assert_eq!(n.to_le(), n)
655 assert_eq!(n.to_le(), n.swap_bytes())
659 #[stable(feature = "rust1", since = "1.0.0")]
662 rustc_const_stable(feature = "const_int_conversions", since = "1.32.0"),
665 pub const fn to_le(self) -> Self {
666 #[cfg(target_endian = "little")]
670 #[cfg(not(target_endian = "little"))]
678 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
679 if overflow occurred.
686 ", $Feature, "assert_eq!((", stringify!($SelfT),
687 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
688 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
691 #[stable(feature = "rust1", since = "1.0.0")]
692 #[must_use = "this returns the result of the operation, \
693 without modifying the original"]
695 pub fn checked_add(self, rhs: Self) -> Option<Self> {
696 let (a, b) = self.overflowing_add(rhs);
697 if b {None} else {Some(a)}
702 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
710 ", $Feature, "assert_eq!((", stringify!($SelfT),
711 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
712 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
715 #[stable(feature = "rust1", since = "1.0.0")]
716 #[must_use = "this returns the result of the operation, \
717 without modifying the original"]
719 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
720 let (a, b) = self.overflowing_sub(rhs);
721 if b {None} else {Some(a)}
726 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
734 ", $Feature, "assert_eq!(", stringify!($SelfT),
735 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
736 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
739 #[stable(feature = "rust1", since = "1.0.0")]
740 #[must_use = "this returns the result of the operation, \
741 without modifying the original"]
743 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
744 let (a, b) = self.overflowing_mul(rhs);
745 if b {None} else {Some(a)}
750 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
751 or the division results in overflow.
758 ", $Feature, "assert_eq!((", stringify!($SelfT),
759 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
760 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
761 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
764 #[stable(feature = "rust1", since = "1.0.0")]
765 #[must_use = "this returns the result of the operation, \
766 without modifying the original"]
768 pub fn checked_div(self, rhs: Self) -> Option<Self> {
769 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
772 // SAFETY: div by zero and by INT_MIN have been checked above
773 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
779 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
780 returning `None` if `rhs == 0` or the division results in overflow.
787 assert_eq!((", stringify!($SelfT),
788 "::min_value() + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
789 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euclid(-1), None);
790 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
792 #[stable(feature = "euclidean_division", since = "1.38.0")]
793 #[must_use = "this returns the result of the operation, \
794 without modifying the original"]
796 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
797 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
800 Some(self.div_euclid(rhs))
806 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
807 `rhs == 0` or the division results in overflow.
814 ", $Feature, "use std::", stringify!($SelfT), ";
816 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
817 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
818 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
821 #[stable(feature = "wrapping", since = "1.7.0")]
822 #[must_use = "this returns the result of the operation, \
823 without modifying the original"]
825 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
826 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
829 // SAFETY: div by zero and by INT_MIN have been checked above
830 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
836 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
837 if `rhs == 0` or the division results in overflow.
844 use std::", stringify!($SelfT), ";
846 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
847 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
848 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
850 #[stable(feature = "euclidean_division", since = "1.38.0")]
851 #[must_use = "this returns the result of the operation, \
852 without modifying the original"]
854 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
855 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
858 Some(self.rem_euclid(rhs))
864 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
871 ", $Feature, "use std::", stringify!($SelfT), ";
873 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
874 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
877 #[stable(feature = "wrapping", since = "1.7.0")]
879 pub fn checked_neg(self) -> Option<Self> {
880 let (a, b) = self.overflowing_neg();
881 if b {None} else {Some(a)}
886 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
887 than or equal to the number of bits in `self`.
894 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
895 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
898 #[stable(feature = "wrapping", since = "1.7.0")]
899 #[must_use = "this returns the result of the operation, \
900 without modifying the original"]
902 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
903 let (a, b) = self.overflowing_shl(rhs);
904 if b {None} else {Some(a)}
909 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
910 larger than or equal to the number of bits in `self`.
917 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
918 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
921 #[stable(feature = "wrapping", since = "1.7.0")]
922 #[must_use = "this returns the result of the operation, \
923 without modifying the original"]
925 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
926 let (a, b) = self.overflowing_shr(rhs);
927 if b {None} else {Some(a)}
932 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
940 ", $Feature, "use std::", stringify!($SelfT), ";
942 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
943 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
946 #[stable(feature = "no_panic_abs", since = "1.13.0")]
948 pub fn checked_abs(self) -> Option<Self> {
949 if self.is_negative() {
958 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
966 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
967 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
971 #[stable(feature = "no_panic_pow", since = "1.34.0")]
972 #[must_use = "this returns the result of the operation, \
973 without modifying the original"]
975 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
977 let mut acc: Self = 1;
981 acc = acc.checked_mul(base)?;
984 base = base.checked_mul(base)?;
987 // Deal with the final bit of the exponent separately, since
988 // squaring the base afterwards is not necessary and may cause a
989 // needless overflow.
991 acc = acc.checked_mul(base)?;
999 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
1000 bounds instead of overflowing.
1007 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
1008 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
1010 assert_eq!(", stringify!($SelfT), "::min_value().saturating_add(-1), ", stringify!($SelfT),
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_saturating_int_methods"))]
1019 rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718"),
1021 #[must_use = "this returns the result of the operation, \
1022 without modifying the original"]
1024 pub const fn saturating_add(self, rhs: Self) -> Self {
1025 intrinsics::saturating_add(self, rhs)
1030 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
1031 numeric bounds instead of overflowing.
1038 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
1039 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
1041 assert_eq!(", stringify!($SelfT), "::max_value().saturating_sub(-1), ", stringify!($SelfT),
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_saturating_int_methods"))]
1049 rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718"),
1051 #[must_use = "this returns the result of the operation, \
1052 without modifying the original"]
1054 pub const fn saturating_sub(self, rhs: Self) -> Self {
1055 intrinsics::saturating_sub(self, rhs)
1060 concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
1061 instead of overflowing.
1068 ", $Feature, "#![feature(saturating_neg)]
1069 assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
1070 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
1071 assert_eq!(", stringify!($SelfT), "::min_value().saturating_neg(), ", stringify!($SelfT),
1073 assert_eq!(", stringify!($SelfT), "::max_value().saturating_neg(), ", stringify!($SelfT),
1074 "::min_value() + 1);",
1078 #[unstable(feature = "saturating_neg", issue = "59983")]
1080 pub fn saturating_neg(self) -> Self {
1081 intrinsics::saturating_sub(0, self)
1086 concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1087 MIN` instead of overflowing.
1094 ", $Feature, "#![feature(saturating_neg)]
1095 assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
1096 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
1097 assert_eq!(", stringify!($SelfT), "::min_value().saturating_abs(), ", stringify!($SelfT),
1099 assert_eq!((", stringify!($SelfT), "::min_value() + 1).saturating_abs(), ", stringify!($SelfT),
1104 #[unstable(feature = "saturating_neg", issue = "59983")]
1106 pub fn saturating_abs(self) -> Self {
1107 if self.is_negative() {
1108 self.saturating_neg()
1116 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1117 numeric bounds instead of overflowing.
1124 ", $Feature, "use std::", stringify!($SelfT), ";
1126 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1127 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1128 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1131 #[stable(feature = "wrapping", since = "1.7.0")]
1132 #[must_use = "this returns the result of the operation, \
1133 without modifying the original"]
1135 pub fn saturating_mul(self, rhs: Self) -> Self {
1136 self.checked_mul(rhs).unwrap_or_else(|| {
1137 if (self < 0) == (rhs < 0) {
1147 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1148 saturating at the numeric bounds instead of overflowing.
1155 ", $Feature, "use std::", stringify!($SelfT), ";
1157 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1158 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1159 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1162 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1163 #[must_use = "this returns the result of the operation, \
1164 without modifying the original"]
1166 pub fn saturating_pow(self, exp: u32) -> Self {
1167 match self.checked_pow(exp) {
1169 None if self < 0 && exp % 2 == 1 => Self::min_value(),
1170 None => Self::max_value(),
1176 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1177 boundary of the type.
1184 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1185 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
1186 "::min_value() + 1);",
1189 #[stable(feature = "rust1", since = "1.0.0")]
1192 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1194 #[must_use = "this returns the result of the operation, \
1195 without modifying the original"]
1197 pub const fn wrapping_add(self, rhs: Self) -> Self {
1198 intrinsics::wrapping_add(self, rhs)
1203 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1204 boundary of the type.
1211 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1212 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1213 stringify!($SelfT), "::max_value());",
1216 #[stable(feature = "rust1", since = "1.0.0")]
1219 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1221 #[must_use = "this returns the result of the operation, \
1222 without modifying the original"]
1224 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1225 intrinsics::wrapping_sub(self, rhs)
1230 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1231 the boundary of the type.
1238 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1239 assert_eq!(11i8.wrapping_mul(12), -124);",
1242 #[stable(feature = "rust1", since = "1.0.0")]
1245 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1247 #[must_use = "this returns the result of the operation, \
1248 without modifying the original"]
1250 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1251 intrinsics::wrapping_mul(self, rhs)
1256 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1257 boundary of the type.
1259 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1260 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1261 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1265 This function will panic if `rhs` is 0.
1272 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1273 assert_eq!((-128i8).wrapping_div(-1), -128);",
1276 #[stable(feature = "num_wrapping", since = "1.2.0")]
1277 #[must_use = "this returns the result of the operation, \
1278 without modifying the original"]
1280 pub fn wrapping_div(self, rhs: Self) -> Self {
1281 self.overflowing_div(rhs).0
1286 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1287 wrapping around at the boundary of the type.
1289 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1290 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1291 type. In this case, this method returns `MIN` itself.
1295 This function will panic if `rhs` is 0.
1302 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1303 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1305 #[stable(feature = "euclidean_division", since = "1.38.0")]
1306 #[must_use = "this returns the result of the operation, \
1307 without modifying the original"]
1309 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
1310 self.overflowing_div_euclid(rhs).0
1315 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1316 boundary of the type.
1318 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1319 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1320 this function returns `0`.
1324 This function will panic if `rhs` is 0.
1331 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1332 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1335 #[stable(feature = "num_wrapping", since = "1.2.0")]
1336 #[must_use = "this returns the result of the operation, \
1337 without modifying the original"]
1339 pub fn wrapping_rem(self, rhs: Self) -> Self {
1340 self.overflowing_rem(rhs).0
1345 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1346 at the boundary of the type.
1348 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1349 for the type). In this case, this method returns 0.
1353 This function will panic if `rhs` is 0.
1360 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1361 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1363 #[stable(feature = "euclidean_division", since = "1.38.0")]
1364 #[must_use = "this returns the result of the operation, \
1365 without modifying the original"]
1367 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1368 self.overflowing_rem_euclid(rhs).0
1373 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1376 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1377 is the negative minimal value for the type); this is a positive value that is too large to represent
1378 in the type. In such a case, this function returns `MIN` itself.
1385 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1386 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1390 #[stable(feature = "num_wrapping", since = "1.2.0")]
1393 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1396 pub const fn wrapping_neg(self) -> Self {
1397 self.overflowing_neg().0
1402 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1403 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1405 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1406 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1407 The primitive integer types all implement a `rotate_left` function, which may be what you want
1415 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1416 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1419 #[stable(feature = "num_wrapping", since = "1.2.0")]
1422 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1424 #[must_use = "this returns the result of the operation, \
1425 without modifying the original"]
1427 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1428 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1431 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1437 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1438 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1440 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1441 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1442 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1450 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1451 assert_eq!((-128i16).wrapping_shr(64), -128);",
1454 #[stable(feature = "num_wrapping", since = "1.2.0")]
1457 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1459 #[must_use = "this returns the result of the operation, \
1460 without modifying the original"]
1462 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1463 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1466 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1472 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1473 the boundary of the type.
1475 The only case where such wrapping can occur is when one takes the absolute value of the negative
1476 minimal value for the type this is a positive value that is too large to represent in the type. In
1477 such a case, this function returns `MIN` itself.
1484 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1485 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1486 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1488 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1491 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1494 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1497 pub const fn wrapping_abs(self) -> Self {
1498 // sign is -1 (all ones) for negative numbers, 0 otherwise.
1499 let sign = self >> ($BITS - 1);
1500 // For positive self, sign == 0 so the expression is simply
1501 // (self ^ 0).wrapping_sub(0) == self == abs(self).
1503 // For negative self, self ^ sign == self ^ all_ones.
1504 // But all_ones ^ self == all_ones - self == -1 - self.
1505 // So for negative numbers, (self ^ sign).wrapping_sub(sign) is
1506 // (-1 - self).wrapping_sub(-1) == -self == abs(self).
1507 (self ^ sign).wrapping_sub(sign)
1512 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1513 wrapping around at the boundary of the type.
1520 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1521 assert_eq!(3i8.wrapping_pow(5), -13);
1522 assert_eq!(3i8.wrapping_pow(6), -39);",
1525 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1526 #[must_use = "this returns the result of the operation, \
1527 without modifying the original"]
1529 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1530 let mut base = self;
1531 let mut acc: Self = 1;
1535 acc = acc.wrapping_mul(base);
1538 base = base.wrapping_mul(base);
1541 // Deal with the final bit of the exponent separately, since
1542 // squaring the base afterwards is not necessary and may cause a
1543 // needless overflow.
1545 acc = acc.wrapping_mul(base);
1553 concat!("Calculates `self` + `rhs`
1555 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1556 occur. If an overflow would have occurred then the wrapped value is returned.
1563 ", $Feature, "use std::", stringify!($SelfT), ";
1565 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1566 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1567 "::MIN, true));", $EndFeature, "
1569 #[stable(feature = "wrapping", since = "1.7.0")]
1572 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1574 #[must_use = "this returns the result of the operation, \
1575 without modifying the original"]
1577 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1578 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1584 concat!("Calculates `self` - `rhs`
1586 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1587 would occur. If an overflow would have occurred then the wrapped value is returned.
1594 ", $Feature, "use std::", stringify!($SelfT), ";
1596 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1597 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1598 "::MAX, true));", $EndFeature, "
1600 #[stable(feature = "wrapping", since = "1.7.0")]
1603 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1605 #[must_use = "this returns the result of the operation, \
1606 without modifying the original"]
1608 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1609 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1615 concat!("Calculates the multiplication of `self` and `rhs`.
1617 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1618 would occur. If an overflow would have occurred then the wrapped value is returned.
1625 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1626 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1629 #[stable(feature = "wrapping", since = "1.7.0")]
1632 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1634 #[must_use = "this returns the result of the operation, \
1635 without modifying the original"]
1637 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1638 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1644 concat!("Calculates the divisor when `self` is divided by `rhs`.
1646 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1647 occur. If an overflow would occur then self is returned.
1651 This function will panic if `rhs` is 0.
1658 ", $Feature, "use std::", stringify!($SelfT), ";
1660 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1661 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1666 #[stable(feature = "wrapping", since = "1.7.0")]
1667 #[must_use = "this returns the result of the operation, \
1668 without modifying the original"]
1669 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1670 if self == Self::min_value() && rhs == -1 {
1679 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1681 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1682 occur. If an overflow would occur then `self` is returned.
1686 This function will panic if `rhs` is 0.
1693 use std::", stringify!($SelfT), ";
1695 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1696 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1700 #[stable(feature = "euclidean_division", since = "1.38.0")]
1701 #[must_use = "this returns the result of the operation, \
1702 without modifying the original"]
1703 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1704 if self == Self::min_value() && rhs == -1 {
1707 (self.div_euclid(rhs), false)
1713 concat!("Calculates the remainder when `self` is divided by `rhs`.
1715 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1716 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1720 This function will panic if `rhs` is 0.
1727 ", $Feature, "use std::", stringify!($SelfT), ";
1729 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1730 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1734 #[stable(feature = "wrapping", since = "1.7.0")]
1735 #[must_use = "this returns the result of the operation, \
1736 without modifying the original"]
1737 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1738 if self == Self::min_value() && rhs == -1 {
1748 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1750 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1751 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1755 This function will panic if `rhs` is 0.
1762 use std::", stringify!($SelfT), ";
1764 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1765 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1767 #[stable(feature = "euclidean_division", since = "1.38.0")]
1768 #[must_use = "this returns the result of the operation, \
1769 without modifying the original"]
1771 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1772 if self == Self::min_value() && rhs == -1 {
1775 (self.rem_euclid(rhs), false)
1782 concat!("Negates self, overflowing if this is equal to the minimum value.
1784 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1785 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1786 minimum value will be returned again and `true` will be returned for an overflow happening.
1793 ", $Feature, "use std::", stringify!($SelfT), ";
1795 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1796 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1797 "::MIN, true));", $EndFeature, "
1800 #[stable(feature = "wrapping", since = "1.7.0")]
1803 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1805 pub const fn overflowing_neg(self) -> (Self, bool) {
1806 ((!self).wrapping_add(1), self == Self::min_value())
1811 concat!("Shifts self left by `rhs` bits.
1813 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1814 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1815 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1822 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1823 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1826 #[stable(feature = "wrapping", since = "1.7.0")]
1829 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1831 #[must_use = "this returns the result of the operation, \
1832 without modifying the original"]
1834 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1835 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1840 concat!("Shifts self right by `rhs` bits.
1842 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1843 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1844 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1851 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1852 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1855 #[stable(feature = "wrapping", since = "1.7.0")]
1858 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1860 #[must_use = "this returns the result of the operation, \
1861 without modifying the original"]
1863 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1864 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1869 concat!("Computes the absolute value of `self`.
1871 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1872 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1873 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1874 for an overflow happening.
1881 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1882 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1883 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1884 "::min_value(), true));",
1887 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1890 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
1893 pub const fn overflowing_abs(self) -> (Self, bool) {
1894 (self.wrapping_abs(), self == Self::min_value())
1899 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1901 Returns a tuple of the exponentiation along with a bool indicating
1902 whether an overflow happened.
1909 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1910 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1913 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1914 #[must_use = "this returns the result of the operation, \
1915 without modifying the original"]
1917 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1918 let mut base = self;
1919 let mut acc: Self = 1;
1920 let mut overflown = false;
1921 // Scratch space for storing results of overflowing_mul.
1926 r = acc.overflowing_mul(base);
1931 r = base.overflowing_mul(base);
1936 // Deal with the final bit of the exponent separately, since
1937 // squaring the base afterwards is not necessary and may cause a
1938 // needless overflow.
1940 r = acc.overflowing_mul(base);
1950 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1957 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1959 assert_eq!(x.pow(5), 32);",
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 #[must_use = "this returns the result of the operation, \
1964 without modifying the original"]
1966 #[rustc_inherit_overflow_checks]
1967 pub fn pow(self, mut exp: u32) -> Self {
1968 let mut base = self;
1979 // Deal with the final bit of the exponent separately, since
1980 // squaring the base afterwards is not necessary and may cause a
1981 // needless overflow.
1991 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1993 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
1994 with `0 <= self.rem_euclid(rhs) < rhs`.
1996 In other words, the result is `self / rhs` rounded to the integer `n`
1997 such that `self >= n * rhs`.
1998 If `self > 0`, this is equal to round towards zero (the default in Rust);
1999 if `self < 0`, this is equal to round towards +/- infinity.
2003 This function will panic if `rhs` is 0 or the division results in overflow.
2010 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2013 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
2014 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
2015 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
2016 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
2018 #[stable(feature = "euclidean_division", since = "1.38.0")]
2019 #[must_use = "this returns the result of the operation, \
2020 without modifying the original"]
2022 #[rustc_inherit_overflow_checks]
2023 pub fn div_euclid(self, rhs: Self) -> Self {
2026 return if rhs > 0 { q - 1 } else { q + 1 }
2034 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
2036 This is done as if by the Euclidean division algorithm -- given
2037 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
2038 `0 <= r < abs(rhs)`.
2042 This function will panic if `rhs` is 0 or the division results in overflow.
2049 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2052 assert_eq!(a.rem_euclid(b), 3);
2053 assert_eq!((-a).rem_euclid(b), 1);
2054 assert_eq!(a.rem_euclid(-b), 3);
2055 assert_eq!((-a).rem_euclid(-b), 1);
2057 #[stable(feature = "euclidean_division", since = "1.38.0")]
2058 #[must_use = "this returns the result of the operation, \
2059 without modifying the original"]
2061 #[rustc_inherit_overflow_checks]
2062 pub fn rem_euclid(self, rhs: Self) -> Self {
2077 concat!("Computes the absolute value of `self`.
2081 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
2082 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
2083 code in debug mode will trigger a panic on this case and optimized code will return `",
2084 stringify!($SelfT), "::min_value()` without a panic.
2091 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
2092 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
2095 #[stable(feature = "rust1", since = "1.0.0")]
2098 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
2101 #[rustc_inherit_overflow_checks]
2102 pub const fn abs(self) -> Self {
2103 // Note that the #[inline] above means that the overflow
2104 // semantics of the subtraction depend on the crate we're being
2107 // sign is -1 (all ones) for negative numbers, 0 otherwise.
2108 let sign = self >> ($BITS - 1);
2109 // For positive self, sign == 0 so the expression is simply
2110 // (self ^ 0) - 0 == self == abs(self).
2112 // For negative self, self ^ sign == self ^ all_ones.
2113 // But all_ones ^ self == all_ones - self == -1 - self.
2114 // So for negative numbers, (self ^ sign) - sign is
2115 // (-1 - self) - -1 == -self == abs(self).
2117 // The subtraction overflows when self is min_value(), because
2118 // (-1 - min_value()) - -1 is max_value() - -1 which overflows.
2119 // This is exactly when we want self.abs() to overflow.
2120 (self ^ sign) - sign
2125 concat!("Returns a number representing sign of `self`.
2127 - `0` if the number is zero
2128 - `1` if the number is positive
2129 - `-1` if the number is negative
2136 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
2137 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
2138 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
2141 #[stable(feature = "rust1", since = "1.0.0")]
2142 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_sign"))]
2145 rustc_const_unstable(feature = "const_int_sign", issue = "53718"),
2148 pub const fn signum(self) -> Self {
2149 (self > 0) as Self - (self < 0) as Self
2154 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2162 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2163 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2166 #[stable(feature = "rust1", since = "1.0.0")]
2169 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
2172 pub const fn is_positive(self) -> bool { self > 0 }
2176 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2184 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2185 assert!(!10", stringify!($SelfT), ".is_negative());",
2188 #[stable(feature = "rust1", since = "1.0.0")]
2191 rustc_const_stable(feature = "const_int_methods", since = "1.32.0"),
2194 pub const fn is_negative(self) -> bool { self < 0 }
2198 concat!("Return the memory representation of this integer as a byte array in
2199 big-endian (network) byte order.
2206 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2207 assert_eq!(bytes, ", $be_bytes, ");
2209 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2210 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
2213 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
2216 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2217 self.to_be().to_ne_bytes()
2222 concat!("Return the memory representation of this integer as a byte array in
2223 little-endian byte order.
2230 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2231 assert_eq!(bytes, ", $le_bytes, ");
2233 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2234 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
2237 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
2240 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2241 self.to_le().to_ne_bytes()
2247 Return the memory representation of this integer as a byte array in
2250 As the target platform's native endianness is used, portable code
2251 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2256 [`to_be_bytes`]: #method.to_be_bytes
2257 [`to_le_bytes`]: #method.to_le_bytes
2262 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2265 if cfg!(target_endian = \"big\") {
2272 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2273 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
2276 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
2279 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2280 // SAFETY: integers are plain old datatypes so we can always transmute them to
2282 unsafe { mem::transmute(self) }
2287 concat!("Create an integer value from its representation as a byte array in
2295 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2296 assert_eq!(value, ", $swap_op, ");
2299 When starting from a slice rather than an array, fallible conversion APIs can be used:
2302 use std::convert::TryInto;
2304 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2305 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2307 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2310 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2311 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
2314 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
2317 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2318 Self::from_be(Self::from_ne_bytes(bytes))
2324 Create an integer value from its representation as a byte array in
2332 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2333 assert_eq!(value, ", $swap_op, ");
2336 When starting from a slice rather than an array, fallible conversion APIs can be used:
2339 use std::convert::TryInto;
2341 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2342 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2344 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2347 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2348 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
2351 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
2354 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2355 Self::from_le(Self::from_ne_bytes(bytes))
2360 concat!("Create an integer value from its memory representation as a byte
2361 array in native endianness.
2363 As the target platform's native endianness is used, portable code
2364 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2365 appropriate instead.
2367 [`from_be_bytes`]: #method.from_be_bytes
2368 [`from_le_bytes`]: #method.from_le_bytes
2375 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2380 assert_eq!(value, ", $swap_op, ");
2383 When starting from a slice rather than an array, fallible conversion APIs can be used:
2386 use std::convert::TryInto;
2388 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2389 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2391 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2394 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2395 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
2398 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
2401 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2402 // SAFETY: integers are plain old datatypes so we can always transmute to them
2403 unsafe { mem::transmute(bytes) }
2411 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2412 "[0x12]", "[0x12]", "", "" }
2417 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2418 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2423 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2424 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2425 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2430 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2431 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2432 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2433 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2438 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2439 170141183460469231731687303715884105727, "", "", 16,
2440 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2441 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2442 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2443 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2444 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2445 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2448 #[cfg(target_pointer_width = "16")]
2451 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2452 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2453 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2456 #[cfg(target_pointer_width = "32")]
2459 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2460 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2461 "[0x12, 0x34, 0x56, 0x78]",
2462 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2465 #[cfg(target_pointer_width = "64")]
2468 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2469 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2470 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2471 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2472 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2475 macro_rules! uint_impl {
2476 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2477 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2478 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2479 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2481 concat!("Returns the smallest value that can be represented by this integer type.
2488 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2490 #[stable(feature = "rust1", since = "1.0.0")]
2495 rustc_const_stable(feature = "const_min_value", since = "1.32.0"),
2497 pub const fn min_value() -> Self { 0 }
2501 concat!("Returns the largest value that can be represented by this integer type.
2508 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2509 stringify!($MaxV), ");", $EndFeature, "
2511 #[stable(feature = "rust1", since = "1.0.0")]
2516 rustc_const_stable(feature = "const_max_value", since = "1.32.0"),
2518 pub const fn max_value() -> Self { !0 }
2522 concat!("Converts a string slice in a given base to an integer.
2524 The string is expected to be an optional `+` sign
2526 Leading and trailing whitespace represent an error.
2527 Digits are a subset of these characters, depending on `radix`:
2535 This function panics if `radix` is not in the range from 2 to 36.
2542 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2545 #[stable(feature = "rust1", since = "1.0.0")]
2546 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2547 from_str_radix(src, radix)
2552 concat!("Returns the number of ones in the binary representation of `self`.
2559 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2561 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2563 #[stable(feature = "rust1", since = "1.0.0")]
2566 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2569 pub const fn count_ones(self) -> u32 {
2570 intrinsics::ctpop(self as $ActualT) as u32
2575 concat!("Returns the number of zeros in the binary representation of `self`.
2582 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2584 #[stable(feature = "rust1", since = "1.0.0")]
2587 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2590 pub const fn count_zeros(self) -> u32 {
2591 (!self).count_ones()
2596 concat!("Returns the number of leading zeros in the binary representation of `self`.
2603 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2605 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2607 #[stable(feature = "rust1", since = "1.0.0")]
2610 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2613 pub const fn leading_zeros(self) -> u32 {
2614 intrinsics::ctlz(self as $ActualT) as u32
2619 concat!("Returns the number of trailing zeros in the binary representation
2627 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2629 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2631 #[stable(feature = "rust1", since = "1.0.0")]
2634 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2637 pub const fn trailing_zeros(self) -> u32 {
2638 intrinsics::cttz(self) as u32
2643 concat!("Shifts the bits to the left by a specified amount, `n`,
2644 wrapping the truncated bits to the end of the resulting integer.
2646 Please note this isn't the same operation as the `<<` shifting operator!
2653 let n = ", $rot_op, stringify!($SelfT), ";
2654 let m = ", $rot_result, ";
2656 assert_eq!(n.rotate_left(", $rot, "), m);
2658 #[stable(feature = "rust1", since = "1.0.0")]
2661 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2663 #[must_use = "this returns the result of the operation, \
2664 without modifying the original"]
2666 pub const fn rotate_left(self, n: u32) -> Self {
2667 intrinsics::rotate_left(self, n as $SelfT)
2672 concat!("Shifts the bits to the right by a specified amount, `n`,
2673 wrapping the truncated bits to the beginning of the resulting
2676 Please note this isn't the same operation as the `>>` shifting operator!
2683 let n = ", $rot_result, stringify!($SelfT), ";
2684 let m = ", $rot_op, ";
2686 assert_eq!(n.rotate_right(", $rot, "), m);
2688 #[stable(feature = "rust1", since = "1.0.0")]
2691 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2693 #[must_use = "this returns the result of the operation, \
2694 without modifying the original"]
2696 pub const fn rotate_right(self, n: u32) -> Self {
2697 intrinsics::rotate_right(self, n as $SelfT)
2703 Reverses the byte order of the integer.
2710 let n = ", $swap_op, stringify!($SelfT), ";
2711 let m = n.swap_bytes();
2713 assert_eq!(m, ", $swapped, ");
2715 #[stable(feature = "rust1", since = "1.0.0")]
2718 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2721 pub const fn swap_bytes(self) -> Self {
2722 intrinsics::bswap(self as $ActualT) as Self
2727 concat!("Reverses the bit pattern of the integer.
2734 let n = ", $swap_op, stringify!($SelfT), ";
2735 let m = n.reverse_bits();
2737 assert_eq!(m, ", $reversed, ");
2739 #[stable(feature = "reverse_bits", since = "1.37.0")]
2742 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2746 pub const fn reverse_bits(self) -> Self {
2747 intrinsics::bitreverse(self as $ActualT) as Self
2752 concat!("Converts an integer from big endian to the target's endianness.
2754 On big endian this is a no-op. On little endian the bytes are
2762 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2764 if cfg!(target_endian = \"big\") {
2765 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2767 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2770 #[stable(feature = "rust1", since = "1.0.0")]
2773 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2776 pub const fn from_be(x: Self) -> Self {
2777 #[cfg(target_endian = "big")]
2781 #[cfg(not(target_endian = "big"))]
2789 concat!("Converts an integer from little endian to the target's endianness.
2791 On little endian this is a no-op. On big endian the bytes are
2799 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2801 if cfg!(target_endian = \"little\") {
2802 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2804 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2807 #[stable(feature = "rust1", since = "1.0.0")]
2810 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2813 pub const fn from_le(x: Self) -> Self {
2814 #[cfg(target_endian = "little")]
2818 #[cfg(not(target_endian = "little"))]
2826 concat!("Converts `self` to big endian from the target's endianness.
2828 On big endian this is a no-op. On little endian the bytes are
2836 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2838 if cfg!(target_endian = \"big\") {
2839 assert_eq!(n.to_be(), n)
2841 assert_eq!(n.to_be(), n.swap_bytes())
2844 #[stable(feature = "rust1", since = "1.0.0")]
2847 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2850 pub const fn to_be(self) -> Self { // or not to be?
2851 #[cfg(target_endian = "big")]
2855 #[cfg(not(target_endian = "big"))]
2863 concat!("Converts `self` to little endian from the target's endianness.
2865 On little endian this is a no-op. On big endian the bytes are
2873 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2875 if cfg!(target_endian = \"little\") {
2876 assert_eq!(n.to_le(), n)
2878 assert_eq!(n.to_le(), n.swap_bytes())
2881 #[stable(feature = "rust1", since = "1.0.0")]
2884 rustc_const_stable(feature = "const_math", since = "1.32.0"),
2887 pub const fn to_le(self) -> Self {
2888 #[cfg(target_endian = "little")]
2892 #[cfg(not(target_endian = "little"))]
2900 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2901 if overflow occurred.
2908 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2909 "Some(", stringify!($SelfT), "::max_value() - 1));
2910 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2912 #[stable(feature = "rust1", since = "1.0.0")]
2913 #[must_use = "this returns the result of the operation, \
2914 without modifying the original"]
2916 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2917 let (a, b) = self.overflowing_add(rhs);
2918 if b {None} else {Some(a)}
2923 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2924 `None` if overflow occurred.
2931 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2932 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2934 #[stable(feature = "rust1", since = "1.0.0")]
2935 #[must_use = "this returns the result of the operation, \
2936 without modifying the original"]
2938 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2939 let (a, b) = self.overflowing_sub(rhs);
2940 if b {None} else {Some(a)}
2945 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2946 `None` if overflow occurred.
2953 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2954 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2956 #[stable(feature = "rust1", since = "1.0.0")]
2957 #[must_use = "this returns the result of the operation, \
2958 without modifying the original"]
2960 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2961 let (a, b) = self.overflowing_mul(rhs);
2962 if b {None} else {Some(a)}
2967 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2975 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2976 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2978 #[stable(feature = "rust1", since = "1.0.0")]
2979 #[must_use = "this returns the result of the operation, \
2980 without modifying the original"]
2982 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2985 // SAFETY: div by zero has been checked above and unsigned types have no other
2986 // failure modes for division
2987 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2993 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
3001 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
3002 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
3004 #[stable(feature = "euclidean_division", since = "1.38.0")]
3005 #[must_use = "this returns the result of the operation, \
3006 without modifying the original"]
3008 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
3012 Some(self.div_euclid(rhs))
3019 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
3027 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
3028 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
3030 #[stable(feature = "wrapping", since = "1.7.0")]
3031 #[must_use = "this returns the result of the operation, \
3032 without modifying the original"]
3034 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
3038 // SAFETY: div by zero has been checked above and unsigned types have no other
3039 // failure modes for division
3040 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3046 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3054 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3055 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3057 #[stable(feature = "euclidean_division", since = "1.38.0")]
3058 #[must_use = "this returns the result of the operation, \
3059 without modifying the original"]
3061 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3065 Some(self.rem_euclid(rhs))
3071 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3074 Note that negating any positive integer will overflow.
3081 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3082 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3084 #[stable(feature = "wrapping", since = "1.7.0")]
3086 pub fn checked_neg(self) -> Option<Self> {
3087 let (a, b) = self.overflowing_neg();
3088 if b {None} else {Some(a)}
3093 concat!("Checked shift left. Computes `self << rhs`, returning `None`
3094 if `rhs` is larger than or equal to the number of bits in `self`.
3101 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3102 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3104 #[stable(feature = "wrapping", since = "1.7.0")]
3105 #[must_use = "this returns the result of the operation, \
3106 without modifying the original"]
3108 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
3109 let (a, b) = self.overflowing_shl(rhs);
3110 if b {None} else {Some(a)}
3115 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3116 if `rhs` is larger than or equal to the number of bits in `self`.
3123 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3124 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3126 #[stable(feature = "wrapping", since = "1.7.0")]
3127 #[must_use = "this returns the result of the operation, \
3128 without modifying the original"]
3130 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
3131 let (a, b) = self.overflowing_shr(rhs);
3132 if b {None} else {Some(a)}
3137 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3145 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3146 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
3148 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3149 #[must_use = "this returns the result of the operation, \
3150 without modifying the original"]
3152 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
3153 let mut base = self;
3154 let mut acc: Self = 1;
3158 acc = acc.checked_mul(base)?;
3161 base = base.checked_mul(base)?;
3164 // Deal with the final bit of the exponent separately, since
3165 // squaring the base afterwards is not necessary and may cause a
3166 // needless overflow.
3168 acc = acc.checked_mul(base)?;
3176 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3177 the numeric bounds instead of overflowing.
3184 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3185 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
3188 #[stable(feature = "rust1", since = "1.0.0")]
3189 #[must_use = "this returns the result of the operation, \
3190 without modifying the original"]
3191 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_saturating_int_methods"))]
3194 rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718"),
3197 pub const fn saturating_add(self, rhs: Self) -> Self {
3198 intrinsics::saturating_add(self, rhs)
3203 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3204 at the numeric bounds instead of overflowing.
3211 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3212 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3214 #[stable(feature = "rust1", since = "1.0.0")]
3215 #[must_use = "this returns the result of the operation, \
3216 without modifying the original"]
3217 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_saturating_int_methods"))]
3220 rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718"),
3223 pub const fn saturating_sub(self, rhs: Self) -> Self {
3224 intrinsics::saturating_sub(self, rhs)
3229 concat!("Saturating integer multiplication. Computes `self * rhs`,
3230 saturating at the numeric bounds instead of overflowing.
3237 ", $Feature, "use std::", stringify!($SelfT), ";
3239 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3240 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3241 "::MAX);", $EndFeature, "
3243 #[stable(feature = "wrapping", since = "1.7.0")]
3244 #[must_use = "this returns the result of the operation, \
3245 without modifying the original"]
3247 pub fn saturating_mul(self, rhs: Self) -> Self {
3248 self.checked_mul(rhs).unwrap_or(Self::max_value())
3253 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3254 saturating at the numeric bounds instead of overflowing.
3261 ", $Feature, "use std::", stringify!($SelfT), ";
3263 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3264 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3267 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3268 #[must_use = "this returns the result of the operation, \
3269 without modifying the original"]
3271 pub fn saturating_pow(self, exp: u32) -> Self {
3272 match self.checked_pow(exp) {
3274 None => Self::max_value(),
3280 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3281 wrapping around at the boundary of the type.
3288 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3289 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
3292 #[stable(feature = "rust1", since = "1.0.0")]
3295 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3297 #[must_use = "this returns the result of the operation, \
3298 without modifying the original"]
3300 pub const fn wrapping_add(self, rhs: Self) -> Self {
3301 intrinsics::wrapping_add(self, rhs)
3306 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3307 wrapping around at the boundary of the type.
3314 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3315 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
3318 #[stable(feature = "rust1", since = "1.0.0")]
3321 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3323 #[must_use = "this returns the result of the operation, \
3324 without modifying the original"]
3326 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3327 intrinsics::wrapping_sub(self, rhs)
3331 /// Wrapping (modular) multiplication. Computes `self *
3332 /// rhs`, wrapping around at the boundary of the type.
3338 /// Please note that this example is shared between integer types.
3339 /// Which explains why `u8` is used here.
3342 /// assert_eq!(10u8.wrapping_mul(12), 120);
3343 /// assert_eq!(25u8.wrapping_mul(12), 44);
3345 #[stable(feature = "rust1", since = "1.0.0")]
3348 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3350 #[must_use = "this returns the result of the operation, \
3351 without modifying the original"]
3353 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3354 intrinsics::wrapping_mul(self, rhs)
3358 concat!("Wrapping (modular) division. Computes `self / rhs`.
3359 Wrapped division on unsigned types is just normal division.
3360 There's no way wrapping could ever happen.
3361 This function exists, so that all operations
3362 are accounted for in the wrapping operations.
3369 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3371 #[stable(feature = "num_wrapping", since = "1.2.0")]
3372 #[must_use = "this returns the result of the operation, \
3373 without modifying the original"]
3375 pub fn wrapping_div(self, rhs: Self) -> Self {
3381 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3382 Wrapped division on unsigned types is just normal division.
3383 There's no way wrapping could ever happen.
3384 This function exists, so that all operations
3385 are accounted for in the wrapping operations.
3386 Since, for the positive integers, all common
3387 definitions of division are equal, this
3388 is exactly equal to `self.wrapping_div(rhs)`.
3395 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3397 #[stable(feature = "euclidean_division", since = "1.38.0")]
3398 #[must_use = "this returns the result of the operation, \
3399 without modifying the original"]
3401 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
3407 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3408 Wrapped remainder calculation on unsigned types is
3409 just the regular remainder calculation.
3410 There's no way wrapping could ever happen.
3411 This function exists, so that all operations
3412 are accounted for in the wrapping operations.
3419 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3421 #[stable(feature = "num_wrapping", since = "1.2.0")]
3422 #[must_use = "this returns the result of the operation, \
3423 without modifying the original"]
3425 pub fn wrapping_rem(self, rhs: Self) -> Self {
3431 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3432 Wrapped modulo calculation on unsigned types is
3433 just the regular remainder calculation.
3434 There's no way wrapping could ever happen.
3435 This function exists, so that all operations
3436 are accounted for in the wrapping operations.
3437 Since, for the positive integers, all common
3438 definitions of division are equal, this
3439 is exactly equal to `self.wrapping_rem(rhs)`.
3446 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3448 #[stable(feature = "euclidean_division", since = "1.38.0")]
3449 #[must_use = "this returns the result of the operation, \
3450 without modifying the original"]
3452 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3457 /// Wrapping (modular) negation. Computes `-self`,
3458 /// wrapping around at the boundary of the type.
3460 /// Since unsigned types do not have negative equivalents
3461 /// all applications of this function will wrap (except for `-0`).
3462 /// For values smaller than the corresponding signed type's maximum
3463 /// the result is the same as casting the corresponding signed value.
3464 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3465 /// `MAX` is the corresponding signed type's maximum.
3471 /// Please note that this example is shared between integer types.
3472 /// Which explains why `i8` is used here.
3475 /// assert_eq!(100i8.wrapping_neg(), -100);
3476 /// assert_eq!((-128i8).wrapping_neg(), -128);
3478 #[stable(feature = "num_wrapping", since = "1.2.0")]
3481 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3484 pub const fn wrapping_neg(self) -> Self {
3485 self.overflowing_neg().0
3489 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3490 where `mask` removes any high-order bits of `rhs` that
3491 would cause the shift to exceed the bitwidth of the type.
3493 Note that this is *not* the same as a rotate-left; the
3494 RHS of a wrapping shift-left is restricted to the range
3495 of the type, rather than the bits shifted out of the LHS
3496 being returned to the other end. The primitive integer
3497 types all implement a `rotate_left` function, which may
3498 be what you want instead.
3505 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3506 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3508 #[stable(feature = "num_wrapping", since = "1.2.0")]
3511 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3513 #[must_use = "this returns the result of the operation, \
3514 without modifying the original"]
3516 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3517 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3520 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3526 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3527 where `mask` removes any high-order bits of `rhs` that
3528 would cause the shift to exceed the bitwidth of the type.
3530 Note that this is *not* the same as a rotate-right; the
3531 RHS of a wrapping shift-right is restricted to the range
3532 of the type, rather than the bits shifted out of the LHS
3533 being returned to the other end. The primitive integer
3534 types all implement a `rotate_right` function, which may
3535 be what you want instead.
3542 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3543 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3545 #[stable(feature = "num_wrapping", since = "1.2.0")]
3548 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3550 #[must_use = "this returns the result of the operation, \
3551 without modifying the original"]
3553 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3554 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3557 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3563 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3564 wrapping around at the boundary of the type.
3571 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3572 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3574 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3575 #[must_use = "this returns the result of the operation, \
3576 without modifying the original"]
3578 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3579 let mut base = self;
3580 let mut acc: Self = 1;
3584 acc = acc.wrapping_mul(base);
3587 base = base.wrapping_mul(base);
3590 // Deal with the final bit of the exponent separately, since
3591 // squaring the base afterwards is not necessary and may cause a
3592 // needless overflow.
3594 acc = acc.wrapping_mul(base);
3602 concat!("Calculates `self` + `rhs`
3604 Returns a tuple of the addition along with a boolean indicating
3605 whether an arithmetic overflow would occur. If an overflow would
3606 have occurred then the wrapped value is returned.
3613 ", $Feature, "use std::", stringify!($SelfT), ";
3615 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3616 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3618 #[stable(feature = "wrapping", since = "1.7.0")]
3621 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3623 #[must_use = "this returns the result of the operation, \
3624 without modifying the original"]
3626 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3627 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3633 concat!("Calculates `self` - `rhs`
3635 Returns a tuple of the subtraction along with a boolean indicating
3636 whether an arithmetic overflow would occur. If an overflow would
3637 have occurred then the wrapped value is returned.
3644 ", $Feature, "use std::", stringify!($SelfT), ";
3646 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3647 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3650 #[stable(feature = "wrapping", since = "1.7.0")]
3653 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3655 #[must_use = "this returns the result of the operation, \
3656 without modifying the original"]
3658 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3659 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3664 /// Calculates the multiplication of `self` and `rhs`.
3666 /// Returns a tuple of the multiplication along with a boolean
3667 /// indicating whether an arithmetic overflow would occur. If an
3668 /// overflow would have occurred then the wrapped value is returned.
3674 /// Please note that this example is shared between integer types.
3675 /// Which explains why `u32` is used here.
3678 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3679 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3681 #[stable(feature = "wrapping", since = "1.7.0")]
3684 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3686 #[must_use = "this returns the result of the operation, \
3687 without modifying the original"]
3689 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3690 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3695 concat!("Calculates the divisor when `self` is divided by `rhs`.
3697 Returns a tuple of the divisor along with a boolean indicating
3698 whether an arithmetic overflow would occur. Note that for unsigned
3699 integers overflow never occurs, so the second value is always
3704 This function will panic if `rhs` is 0.
3711 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3714 #[stable(feature = "wrapping", since = "1.7.0")]
3715 #[must_use = "this returns the result of the operation, \
3716 without modifying the original"]
3717 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3723 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3725 Returns a tuple of the divisor along with a boolean indicating
3726 whether an arithmetic overflow would occur. Note that for unsigned
3727 integers overflow never occurs, so the second value is always
3729 Since, for the positive integers, all common
3730 definitions of division are equal, this
3731 is exactly equal to `self.overflowing_div(rhs)`.
3735 This function will panic if `rhs` is 0.
3742 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3745 #[stable(feature = "euclidean_division", since = "1.38.0")]
3746 #[must_use = "this returns the result of the operation, \
3747 without modifying the original"]
3748 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3754 concat!("Calculates the remainder when `self` is divided by `rhs`.
3756 Returns a tuple of the remainder after dividing along with a boolean
3757 indicating whether an arithmetic overflow would occur. Note that for
3758 unsigned integers overflow never occurs, so the second value is
3763 This function will panic if `rhs` is 0.
3770 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3773 #[stable(feature = "wrapping", since = "1.7.0")]
3774 #[must_use = "this returns the result of the operation, \
3775 without modifying the original"]
3776 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3782 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3784 Returns a tuple of the modulo after dividing along with a boolean
3785 indicating whether an arithmetic overflow would occur. Note that for
3786 unsigned integers overflow never occurs, so the second value is
3788 Since, for the positive integers, all common
3789 definitions of division are equal, this operation
3790 is exactly equal to `self.overflowing_rem(rhs)`.
3794 This function will panic if `rhs` is 0.
3801 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3804 #[stable(feature = "euclidean_division", since = "1.38.0")]
3805 #[must_use = "this returns the result of the operation, \
3806 without modifying the original"]
3807 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3813 concat!("Negates self in an overflowing fashion.
3815 Returns `!self + 1` using wrapping operations to return the value
3816 that represents the negation of this unsigned value. Note that for
3817 positive unsigned values overflow always occurs, but negating 0 does
3825 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3826 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3827 ", true));", $EndFeature, "
3830 #[stable(feature = "wrapping", since = "1.7.0")]
3833 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3835 pub const fn overflowing_neg(self) -> (Self, bool) {
3836 ((!self).wrapping_add(1), self != 0)
3841 concat!("Shifts self left by `rhs` bits.
3843 Returns a tuple of the shifted version of self along with a boolean
3844 indicating whether the shift value was larger than or equal to the
3845 number of bits. If the shift value is too large, then value is
3846 masked (N-1) where N is the number of bits, and this value is then
3847 used to perform the shift.
3854 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3855 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3857 #[stable(feature = "wrapping", since = "1.7.0")]
3860 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3862 #[must_use = "this returns the result of the operation, \
3863 without modifying the original"]
3865 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3866 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3871 concat!("Shifts self right by `rhs` bits.
3873 Returns a tuple of the shifted version of self along with a boolean
3874 indicating whether the shift value was larger than or equal to the
3875 number of bits. If the shift value is too large, then value is
3876 masked (N-1) where N is the number of bits, and this value is then
3877 used to perform the shift.
3884 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3885 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3887 #[stable(feature = "wrapping", since = "1.7.0")]
3890 rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0"),
3892 #[must_use = "this returns the result of the operation, \
3893 without modifying the original"]
3895 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3896 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3901 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3903 Returns a tuple of the exponentiation along with a bool indicating
3904 whether an overflow happened.
3911 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3912 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3914 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3915 #[must_use = "this returns the result of the operation, \
3916 without modifying the original"]
3918 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3919 let mut base = self;
3920 let mut acc: Self = 1;
3921 let mut overflown = false;
3922 // Scratch space for storing results of overflowing_mul.
3927 r = acc.overflowing_mul(base);
3932 r = base.overflowing_mul(base);
3937 // Deal with the final bit of the exponent separately, since
3938 // squaring the base afterwards is not necessary and may cause a
3939 // needless overflow.
3941 r = acc.overflowing_mul(base);
3951 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3958 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3960 #[stable(feature = "rust1", since = "1.0.0")]
3961 #[must_use = "this returns the result of the operation, \
3962 without modifying the original"]
3964 #[rustc_inherit_overflow_checks]
3965 pub fn pow(self, mut exp: u32) -> Self {
3966 let mut base = self;
3977 // Deal with the final bit of the exponent separately, since
3978 // squaring the base afterwards is not necessary and may cause a
3979 // needless overflow.
3989 concat!("Performs Euclidean division.
3991 Since, for the positive integers, all common
3992 definitions of division are equal, this
3993 is exactly equal to `self / rhs`.
3997 This function will panic if `rhs` is 0.
4004 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
4006 #[stable(feature = "euclidean_division", since = "1.38.0")]
4007 #[must_use = "this returns the result of the operation, \
4008 without modifying the original"]
4010 #[rustc_inherit_overflow_checks]
4011 pub fn div_euclid(self, rhs: Self) -> Self {
4018 concat!("Calculates the least remainder of `self (mod rhs)`.
4020 Since, for the positive integers, all common
4021 definitions of division are equal, this
4022 is exactly equal to `self % rhs`.
4026 This function will panic if `rhs` is 0.
4033 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
4035 #[stable(feature = "euclidean_division", since = "1.38.0")]
4036 #[must_use = "this returns the result of the operation, \
4037 without modifying the original"]
4039 #[rustc_inherit_overflow_checks]
4040 pub fn rem_euclid(self, rhs: Self) -> Self {
4046 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
4053 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
4054 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
4056 #[stable(feature = "rust1", since = "1.0.0")]
4059 rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0"),
4062 pub const fn is_power_of_two(self) -> bool {
4063 self.count_ones() == 1
4067 // Returns one less than next power of two.
4068 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
4070 // 8u8.one_less_than_next_power_of_two() == 7
4071 // 6u8.one_less_than_next_power_of_two() == 7
4073 // This method cannot overflow, as in the `next_power_of_two`
4074 // overflow cases it instead ends up returning the maximum value
4075 // of the type, and can return 0 for 0.
4077 fn one_less_than_next_power_of_two(self) -> Self {
4078 if self <= 1 { return 0; }
4081 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4082 // That means the shift is always in-bounds, and some processors
4083 // (such as intel pre-haswell) have more efficient ctlz
4084 // intrinsics when the argument is non-zero.
4085 let z = unsafe { intrinsics::ctlz_nonzero(p) };
4086 <$SelfT>::max_value() >> z
4090 concat!("Returns the smallest power of two greater than or equal to `self`.
4092 When return value overflows (i.e., `self > (1 << (N-1))` for type
4093 `uN`), it panics in debug mode and return value is wrapped to 0 in
4094 release mode (the only situation in which method can return 0).
4101 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4102 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4104 #[stable(feature = "rust1", since = "1.0.0")]
4106 pub fn next_power_of_two(self) -> Self {
4107 // Call the trait to get overflow checks
4108 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
4113 concat!("Returns the smallest power of two greater than or equal to `n`. If
4114 the next power of two is greater than the type's maximum value,
4115 `None` is returned, otherwise the power of two is wrapped in `Some`.
4122 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4123 ".checked_next_power_of_two(), Some(2));
4124 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4125 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
4129 #[stable(feature = "rust1", since = "1.0.0")]
4130 pub fn checked_next_power_of_two(self) -> Option<Self> {
4131 self.one_less_than_next_power_of_two().checked_add(1)
4136 concat!("Returns the smallest power of two greater than or equal to `n`. If
4137 the next power of two is greater than the type's maximum value,
4138 the return value is wrapped to `0`.
4145 #![feature(wrapping_next_power_of_two)]
4147 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4148 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4149 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
4152 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4153 reason = "needs decision on wrapping behaviour")]
4154 pub fn wrapping_next_power_of_two(self) -> Self {
4155 self.one_less_than_next_power_of_two().wrapping_add(1)
4160 concat!("Return the memory representation of this integer as a byte array in
4161 big-endian (network) byte order.
4168 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4169 assert_eq!(bytes, ", $be_bytes, ");
4171 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4172 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
4175 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
4178 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4179 self.to_be().to_ne_bytes()
4184 concat!("Return the memory representation of this integer as a byte array in
4185 little-endian byte order.
4192 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4193 assert_eq!(bytes, ", $le_bytes, ");
4195 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4196 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
4199 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
4202 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4203 self.to_le().to_ne_bytes()
4209 Return the memory representation of this integer as a byte array in
4212 As the target platform's native endianness is used, portable code
4213 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4218 [`to_be_bytes`]: #method.to_be_bytes
4219 [`to_le_bytes`]: #method.to_le_bytes
4224 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4227 if cfg!(target_endian = \"big\") {
4234 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4235 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
4238 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
4241 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4242 // SAFETY: integers are plain old datatypes so we can always transmute them to
4244 unsafe { mem::transmute(self) }
4249 concat!("Create an integer value from its representation as a byte array in
4257 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4258 assert_eq!(value, ", $swap_op, ");
4261 When starting from a slice rather than an array, fallible conversion APIs can be used:
4264 use std::convert::TryInto;
4266 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4267 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4269 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4272 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4273 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
4276 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
4279 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4280 Self::from_be(Self::from_ne_bytes(bytes))
4286 Create an integer value from its representation as a byte array in
4294 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4295 assert_eq!(value, ", $swap_op, ");
4298 When starting from a slice rather than an array, fallible conversion APIs can be used:
4301 use std::convert::TryInto;
4303 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4304 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4306 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4309 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4310 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
4313 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
4316 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4317 Self::from_le(Self::from_ne_bytes(bytes))
4322 concat!("Create an integer value from its memory representation as a byte
4323 array in native endianness.
4325 As the target platform's native endianness is used, portable code
4326 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4327 appropriate instead.
4329 [`from_be_bytes`]: #method.from_be_bytes
4330 [`from_le_bytes`]: #method.from_le_bytes
4337 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4342 assert_eq!(value, ", $swap_op, ");
4345 When starting from a slice rather than an array, fallible conversion APIs can be used:
4348 use std::convert::TryInto;
4350 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4351 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4353 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4356 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4357 #[cfg_attr(bootstrap, rustc_const_unstable(feature = "const_int_conversion"))]
4360 rustc_const_unstable(feature = "const_int_conversion", issue = "53718"),
4363 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4364 // SAFETY: integers are plain old datatypes so we can always transmute to them
4365 unsafe { mem::transmute(bytes) }
4373 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4376 /// Checks if the value is within the ASCII range.
4381 /// let ascii = 97u8;
4382 /// let non_ascii = 150u8;
4384 /// assert!(ascii.is_ascii());
4385 /// assert!(!non_ascii.is_ascii());
4387 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4389 pub fn is_ascii(&self) -> bool {
4393 /// Makes a copy of the value in its ASCII upper case equivalent.
4395 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4396 /// but non-ASCII letters are unchanged.
4398 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4403 /// let lowercase_a = 97u8;
4405 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4408 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4409 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4411 pub fn to_ascii_uppercase(&self) -> u8 {
4412 // Unset the fith bit if this is a lowercase letter
4413 *self & !((self.is_ascii_lowercase() as u8) << 5)
4416 /// Makes a copy of the value in its ASCII lower case equivalent.
4418 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4419 /// but non-ASCII letters are unchanged.
4421 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4426 /// let uppercase_a = 65u8;
4428 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4431 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4432 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4434 pub fn to_ascii_lowercase(&self) -> u8 {
4435 // Set the fith bit if this is an uppercase letter
4436 *self | ((self.is_ascii_uppercase() as u8) << 5)
4439 /// Checks that two values are an ASCII case-insensitive match.
4441 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4446 /// let lowercase_a = 97u8;
4447 /// let uppercase_a = 65u8;
4449 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4451 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4453 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4454 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4457 /// Converts this value to its ASCII upper case equivalent in-place.
4459 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4460 /// but non-ASCII letters are unchanged.
4462 /// To return a new uppercased value without modifying the existing one, use
4463 /// [`to_ascii_uppercase`].
4468 /// let mut byte = b'a';
4470 /// byte.make_ascii_uppercase();
4472 /// assert_eq!(b'A', byte);
4475 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4476 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4478 pub fn make_ascii_uppercase(&mut self) {
4479 *self = self.to_ascii_uppercase();
4482 /// Converts this value to its ASCII lower case equivalent in-place.
4484 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4485 /// but non-ASCII letters are unchanged.
4487 /// To return a new lowercased value without modifying the existing one, use
4488 /// [`to_ascii_lowercase`].
4493 /// let mut byte = b'A';
4495 /// byte.make_ascii_lowercase();
4497 /// assert_eq!(b'a', byte);
4500 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4501 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4503 pub fn make_ascii_lowercase(&mut self) {
4504 *self = self.to_ascii_lowercase();
4507 /// Checks if the value is an ASCII alphabetic character:
4509 /// - U+0041 'A' ..= U+005A 'Z', or
4510 /// - U+0061 'a' ..= U+007A 'z'.
4515 /// let uppercase_a = b'A';
4516 /// let uppercase_g = b'G';
4519 /// let zero = b'0';
4520 /// let percent = b'%';
4521 /// let space = b' ';
4523 /// let esc = 0x1b_u8;
4525 /// assert!(uppercase_a.is_ascii_alphabetic());
4526 /// assert!(uppercase_g.is_ascii_alphabetic());
4527 /// assert!(a.is_ascii_alphabetic());
4528 /// assert!(g.is_ascii_alphabetic());
4529 /// assert!(!zero.is_ascii_alphabetic());
4530 /// assert!(!percent.is_ascii_alphabetic());
4531 /// assert!(!space.is_ascii_alphabetic());
4532 /// assert!(!lf.is_ascii_alphabetic());
4533 /// assert!(!esc.is_ascii_alphabetic());
4535 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4537 pub fn is_ascii_alphabetic(&self) -> bool {
4539 b'A'..=b'Z' | b'a'..=b'z' => true,
4544 /// Checks if the value is an ASCII uppercase character:
4545 /// U+0041 'A' ..= U+005A 'Z'.
4550 /// let uppercase_a = b'A';
4551 /// let uppercase_g = b'G';
4554 /// let zero = b'0';
4555 /// let percent = b'%';
4556 /// let space = b' ';
4558 /// let esc = 0x1b_u8;
4560 /// assert!(uppercase_a.is_ascii_uppercase());
4561 /// assert!(uppercase_g.is_ascii_uppercase());
4562 /// assert!(!a.is_ascii_uppercase());
4563 /// assert!(!g.is_ascii_uppercase());
4564 /// assert!(!zero.is_ascii_uppercase());
4565 /// assert!(!percent.is_ascii_uppercase());
4566 /// assert!(!space.is_ascii_uppercase());
4567 /// assert!(!lf.is_ascii_uppercase());
4568 /// assert!(!esc.is_ascii_uppercase());
4570 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4572 pub fn is_ascii_uppercase(&self) -> bool {
4574 b'A'..=b'Z' => true,
4579 /// Checks if the value is an ASCII lowercase character:
4580 /// U+0061 'a' ..= U+007A 'z'.
4585 /// let uppercase_a = b'A';
4586 /// let uppercase_g = b'G';
4589 /// let zero = b'0';
4590 /// let percent = b'%';
4591 /// let space = b' ';
4593 /// let esc = 0x1b_u8;
4595 /// assert!(!uppercase_a.is_ascii_lowercase());
4596 /// assert!(!uppercase_g.is_ascii_lowercase());
4597 /// assert!(a.is_ascii_lowercase());
4598 /// assert!(g.is_ascii_lowercase());
4599 /// assert!(!zero.is_ascii_lowercase());
4600 /// assert!(!percent.is_ascii_lowercase());
4601 /// assert!(!space.is_ascii_lowercase());
4602 /// assert!(!lf.is_ascii_lowercase());
4603 /// assert!(!esc.is_ascii_lowercase());
4605 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4607 pub fn is_ascii_lowercase(&self) -> bool {
4609 b'a'..=b'z' => true,
4614 /// Checks if the value is an ASCII alphanumeric character:
4616 /// - U+0041 'A' ..= U+005A 'Z', or
4617 /// - U+0061 'a' ..= U+007A 'z', or
4618 /// - U+0030 '0' ..= U+0039 '9'.
4623 /// let uppercase_a = b'A';
4624 /// let uppercase_g = b'G';
4627 /// let zero = b'0';
4628 /// let percent = b'%';
4629 /// let space = b' ';
4631 /// let esc = 0x1b_u8;
4633 /// assert!(uppercase_a.is_ascii_alphanumeric());
4634 /// assert!(uppercase_g.is_ascii_alphanumeric());
4635 /// assert!(a.is_ascii_alphanumeric());
4636 /// assert!(g.is_ascii_alphanumeric());
4637 /// assert!(zero.is_ascii_alphanumeric());
4638 /// assert!(!percent.is_ascii_alphanumeric());
4639 /// assert!(!space.is_ascii_alphanumeric());
4640 /// assert!(!lf.is_ascii_alphanumeric());
4641 /// assert!(!esc.is_ascii_alphanumeric());
4643 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4645 pub fn is_ascii_alphanumeric(&self) -> bool {
4647 b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' => true,
4652 /// Checks if the value is an ASCII decimal digit:
4653 /// U+0030 '0' ..= U+0039 '9'.
4658 /// let uppercase_a = b'A';
4659 /// let uppercase_g = b'G';
4662 /// let zero = b'0';
4663 /// let percent = b'%';
4664 /// let space = b' ';
4666 /// let esc = 0x1b_u8;
4668 /// assert!(!uppercase_a.is_ascii_digit());
4669 /// assert!(!uppercase_g.is_ascii_digit());
4670 /// assert!(!a.is_ascii_digit());
4671 /// assert!(!g.is_ascii_digit());
4672 /// assert!(zero.is_ascii_digit());
4673 /// assert!(!percent.is_ascii_digit());
4674 /// assert!(!space.is_ascii_digit());
4675 /// assert!(!lf.is_ascii_digit());
4676 /// assert!(!esc.is_ascii_digit());
4678 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4680 pub fn is_ascii_digit(&self) -> bool {
4682 b'0'..=b'9' => true,
4687 /// Checks if the value is an ASCII hexadecimal digit:
4689 /// - U+0030 '0' ..= U+0039 '9', or
4690 /// - U+0041 'A' ..= U+0046 'F', or
4691 /// - U+0061 'a' ..= U+0066 'f'.
4696 /// let uppercase_a = b'A';
4697 /// let uppercase_g = b'G';
4700 /// let zero = b'0';
4701 /// let percent = b'%';
4702 /// let space = b' ';
4704 /// let esc = 0x1b_u8;
4706 /// assert!(uppercase_a.is_ascii_hexdigit());
4707 /// assert!(!uppercase_g.is_ascii_hexdigit());
4708 /// assert!(a.is_ascii_hexdigit());
4709 /// assert!(!g.is_ascii_hexdigit());
4710 /// assert!(zero.is_ascii_hexdigit());
4711 /// assert!(!percent.is_ascii_hexdigit());
4712 /// assert!(!space.is_ascii_hexdigit());
4713 /// assert!(!lf.is_ascii_hexdigit());
4714 /// assert!(!esc.is_ascii_hexdigit());
4716 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4718 pub fn is_ascii_hexdigit(&self) -> bool {
4720 b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f' => true,
4725 /// Checks if the value is an ASCII punctuation character:
4727 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4728 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4729 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4730 /// - U+007B ..= U+007E `{ | } ~`
4735 /// let uppercase_a = b'A';
4736 /// let uppercase_g = b'G';
4739 /// let zero = b'0';
4740 /// let percent = b'%';
4741 /// let space = b' ';
4743 /// let esc = 0x1b_u8;
4745 /// assert!(!uppercase_a.is_ascii_punctuation());
4746 /// assert!(!uppercase_g.is_ascii_punctuation());
4747 /// assert!(!a.is_ascii_punctuation());
4748 /// assert!(!g.is_ascii_punctuation());
4749 /// assert!(!zero.is_ascii_punctuation());
4750 /// assert!(percent.is_ascii_punctuation());
4751 /// assert!(!space.is_ascii_punctuation());
4752 /// assert!(!lf.is_ascii_punctuation());
4753 /// assert!(!esc.is_ascii_punctuation());
4755 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4757 pub fn is_ascii_punctuation(&self) -> bool {
4759 b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~' => true,
4764 /// Checks if the value is an ASCII graphic character:
4765 /// U+0021 '!' ..= U+007E '~'.
4770 /// let uppercase_a = b'A';
4771 /// let uppercase_g = b'G';
4774 /// let zero = b'0';
4775 /// let percent = b'%';
4776 /// let space = b' ';
4778 /// let esc = 0x1b_u8;
4780 /// assert!(uppercase_a.is_ascii_graphic());
4781 /// assert!(uppercase_g.is_ascii_graphic());
4782 /// assert!(a.is_ascii_graphic());
4783 /// assert!(g.is_ascii_graphic());
4784 /// assert!(zero.is_ascii_graphic());
4785 /// assert!(percent.is_ascii_graphic());
4786 /// assert!(!space.is_ascii_graphic());
4787 /// assert!(!lf.is_ascii_graphic());
4788 /// assert!(!esc.is_ascii_graphic());
4790 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4792 pub fn is_ascii_graphic(&self) -> bool {
4794 b'!'..=b'~' => true,
4799 /// Checks if the value is an ASCII whitespace character:
4800 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4801 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4803 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4804 /// whitespace][infra-aw]. There are several other definitions in
4805 /// wide use. For instance, [the POSIX locale][pct] includes
4806 /// U+000B VERTICAL TAB as well as all the above characters,
4807 /// but—from the very same specification—[the default rule for
4808 /// "field splitting" in the Bourne shell][bfs] considers *only*
4809 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4811 /// If you are writing a program that will process an existing
4812 /// file format, check what that format's definition of whitespace is
4813 /// before using this function.
4815 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4816 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4817 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4822 /// let uppercase_a = b'A';
4823 /// let uppercase_g = b'G';
4826 /// let zero = b'0';
4827 /// let percent = b'%';
4828 /// let space = b' ';
4830 /// let esc = 0x1b_u8;
4832 /// assert!(!uppercase_a.is_ascii_whitespace());
4833 /// assert!(!uppercase_g.is_ascii_whitespace());
4834 /// assert!(!a.is_ascii_whitespace());
4835 /// assert!(!g.is_ascii_whitespace());
4836 /// assert!(!zero.is_ascii_whitespace());
4837 /// assert!(!percent.is_ascii_whitespace());
4838 /// assert!(space.is_ascii_whitespace());
4839 /// assert!(lf.is_ascii_whitespace());
4840 /// assert!(!esc.is_ascii_whitespace());
4842 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4844 pub fn is_ascii_whitespace(&self) -> bool {
4846 b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' => true,
4851 /// Checks if the value is an ASCII control character:
4852 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4853 /// Note that most ASCII whitespace characters are control
4854 /// characters, but SPACE is not.
4859 /// let uppercase_a = b'A';
4860 /// let uppercase_g = b'G';
4863 /// let zero = b'0';
4864 /// let percent = b'%';
4865 /// let space = b' ';
4867 /// let esc = 0x1b_u8;
4869 /// assert!(!uppercase_a.is_ascii_control());
4870 /// assert!(!uppercase_g.is_ascii_control());
4871 /// assert!(!a.is_ascii_control());
4872 /// assert!(!g.is_ascii_control());
4873 /// assert!(!zero.is_ascii_control());
4874 /// assert!(!percent.is_ascii_control());
4875 /// assert!(!space.is_ascii_control());
4876 /// assert!(lf.is_ascii_control());
4877 /// assert!(esc.is_ascii_control());
4879 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4881 pub fn is_ascii_control(&self) -> bool {
4883 b'\0'..=b'\x1F' | b'\x7F' => true,
4891 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4892 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4897 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4898 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4903 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4904 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4905 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4906 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4912 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4913 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4914 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4915 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4916 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4917 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4918 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4922 #[cfg(target_pointer_width = "16")]
4925 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4926 "[0x34, 0x12]", "[0x12, 0x34]",
4927 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4929 #[cfg(target_pointer_width = "32")]
4932 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4933 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4934 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4937 #[cfg(target_pointer_width = "64")]
4940 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4941 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4942 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4943 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4944 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4947 /// A classification of floating point numbers.
4949 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4950 /// their documentation for more.
4952 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4953 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4958 /// use std::num::FpCategory;
4961 /// let num = 12.4_f32;
4962 /// let inf = f32::INFINITY;
4963 /// let zero = 0f32;
4964 /// let sub: f32 = 1.1754942e-38;
4965 /// let nan = f32::NAN;
4967 /// assert_eq!(num.classify(), FpCategory::Normal);
4968 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4969 /// assert_eq!(zero.classify(), FpCategory::Zero);
4970 /// assert_eq!(nan.classify(), FpCategory::Nan);
4971 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4973 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4974 #[stable(feature = "rust1", since = "1.0.0")]
4975 pub enum FpCategory {
4976 /// "Not a Number", often obtained by dividing by zero.
4977 #[stable(feature = "rust1", since = "1.0.0")]
4980 /// Positive or negative infinity.
4981 #[stable(feature = "rust1", since = "1.0.0")]
4984 /// Positive or negative zero.
4985 #[stable(feature = "rust1", since = "1.0.0")]
4988 /// De-normalized floating point representation (less precise than `Normal`).
4989 #[stable(feature = "rust1", since = "1.0.0")]
4992 /// A regular floating point number.
4993 #[stable(feature = "rust1", since = "1.0.0")]
4997 macro_rules! from_str_radix_int_impl {
4999 #[stable(feature = "rust1", since = "1.0.0")]
5000 impl FromStr for $t {
5001 type Err = ParseIntError;
5002 fn from_str(src: &str) -> Result<Self, ParseIntError> {
5003 from_str_radix(src, 10)
5008 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
5010 /// The error type returned when a checked integral type conversion fails.
5011 #[stable(feature = "try_from", since = "1.34.0")]
5012 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
5013 pub struct TryFromIntError(pub(crate) ());
5015 impl TryFromIntError {
5017 feature = "int_error_internals",
5018 reason = "available through Error trait and this method should \
5019 not be exposed publicly",
5023 pub fn __description(&self) -> &str {
5024 "out of range integral type conversion attempted"
5028 #[stable(feature = "try_from", since = "1.34.0")]
5029 impl fmt::Display for TryFromIntError {
5030 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
5031 self.__description().fmt(fmt)
5035 #[stable(feature = "try_from", since = "1.34.0")]
5036 impl From<Infallible> for TryFromIntError {
5037 fn from(x: Infallible) -> TryFromIntError {
5042 #[unstable(feature = "never_type", issue = "35121")]
5043 impl From<!> for TryFromIntError {
5044 fn from(never: !) -> TryFromIntError {
5045 // Match rather than coerce to make sure that code like
5046 // `From<Infallible> for TryFromIntError` above will keep working
5047 // when `Infallible` becomes an alias to `!`.
5053 trait FromStrRadixHelper: PartialOrd + Copy {
5054 fn min_value() -> Self;
5055 fn max_value() -> Self;
5056 fn from_u32(u: u32) -> Self;
5057 fn checked_mul(&self, other: u32) -> Option<Self>;
5058 fn checked_sub(&self, other: u32) -> Option<Self>;
5059 fn checked_add(&self, other: u32) -> Option<Self>;
5063 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
5065 fn min_value() -> Self { Self::min_value() }
5067 fn max_value() -> Self { Self::max_value() }
5069 fn from_u32(u: u32) -> Self { u as Self }
5071 fn checked_mul(&self, other: u32) -> Option<Self> {
5072 Self::checked_mul(*self, other as Self)
5075 fn checked_sub(&self, other: u32) -> Option<Self> {
5076 Self::checked_sub(*self, other as Self)
5079 fn checked_add(&self, other: u32) -> Option<Self> {
5080 Self::checked_add(*self, other as Self)
5084 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5086 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5087 use self::IntErrorKind::*;
5088 use self::ParseIntError as PIE;
5091 radix >= 2 && radix <= 36,
5092 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5097 return Err(PIE { kind: Empty });
5100 let is_signed_ty = T::from_u32(0) > T::min_value();
5102 // all valid digits are ascii, so we will just iterate over the utf8 bytes
5103 // and cast them to chars. .to_digit() will safely return None for anything
5104 // other than a valid ascii digit for the given radix, including the first-byte
5105 // of multi-byte sequences
5106 let src = src.as_bytes();
5108 let (is_positive, digits) = match src[0] {
5109 b'+' => (true, &src[1..]),
5110 b'-' if is_signed_ty => (false, &src[1..]),
5114 if digits.is_empty() {
5115 return Err(PIE { kind: Empty });
5118 let mut result = T::from_u32(0);
5120 // The number is positive
5122 let x = match (c as char).to_digit(radix) {
5124 None => return Err(PIE { kind: InvalidDigit }),
5126 result = match result.checked_mul(radix) {
5127 Some(result) => result,
5128 None => return Err(PIE { kind: Overflow }),
5130 result = match result.checked_add(x) {
5131 Some(result) => result,
5132 None => return Err(PIE { kind: Overflow }),
5136 // The number is negative
5138 let x = match (c as char).to_digit(radix) {
5140 None => return Err(PIE { kind: InvalidDigit }),
5142 result = match result.checked_mul(radix) {
5143 Some(result) => result,
5144 None => return Err(PIE { kind: Underflow }),
5146 result = match result.checked_sub(x) {
5147 Some(result) => result,
5148 None => return Err(PIE { kind: Underflow }),
5155 /// An error which can be returned when parsing an integer.
5157 /// This error is used as the error type for the `from_str_radix()` functions
5158 /// on the primitive integer types, such as [`i8::from_str_radix`].
5160 /// # Potential causes
5162 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5163 /// in the string e.g., when it is obtained from the standard input.
5164 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5166 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5167 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5168 #[derive(Debug, Clone, PartialEq, Eq)]
5169 #[stable(feature = "rust1", since = "1.0.0")]
5170 pub struct ParseIntError {
5174 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5176 feature = "int_error_matching",
5177 reason = "it can be useful to match errors when making error messages \
5178 for integer parsing",
5181 #[derive(Debug, Clone, PartialEq, Eq)]
5183 pub enum IntErrorKind {
5184 /// Value being parsed is empty.
5186 /// Among other causes, this variant will be constructed when parsing an empty string.
5188 /// Contains an invalid digit.
5190 /// Among other causes, this variant will be constructed when parsing a string that
5191 /// contains a letter.
5193 /// Integer is too large to store in target integer type.
5195 /// Integer is too small to store in target integer type.
5199 /// This variant will be emitted when the parsing string has a value of zero, which
5200 /// would be illegal for non-zero types.
5204 impl ParseIntError {
5205 /// Outputs the detailed cause of parsing an integer failing.
5207 feature = "int_error_matching",
5208 reason = "it can be useful to match errors when making error messages \
5209 for integer parsing",
5212 pub fn kind(&self) -> &IntErrorKind {
5216 feature = "int_error_internals",
5217 reason = "available through Error trait and this method should \
5218 not be exposed publicly",
5222 pub fn __description(&self) -> &str {
5224 IntErrorKind::Empty => "cannot parse integer from empty string",
5225 IntErrorKind::InvalidDigit => "invalid digit found in string",
5226 IntErrorKind::Overflow => "number too large to fit in target type",
5227 IntErrorKind::Underflow => "number too small to fit in target type",
5228 IntErrorKind::Zero => "number would be zero for non-zero type",
5233 #[stable(feature = "rust1", since = "1.0.0")]
5234 impl fmt::Display for ParseIntError {
5235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5236 self.__description().fmt(f)
5240 #[stable(feature = "rust1", since = "1.0.0")]
5241 pub use crate::num::dec2flt::ParseFloatError;