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::{TryFrom, 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.
65 pub const unsafe fn new_unchecked(n: $Int) -> Self {
69 /// Creates a non-zero if the given value is not zero.
72 pub fn new(n: $Int) -> Option<Self> {
74 Some(unsafe { $Ty(n) })
80 /// Returns the value as a primitive type.
83 pub const fn get(self) -> $Int {
89 #[stable(feature = "from_nonzero", since = "1.31.0")]
90 impl From<$Ty> for $Int {
91 fn from(nonzero: $Ty) -> Self {
97 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
104 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
105 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
106 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
107 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
108 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
109 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
110 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
111 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
112 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
113 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
114 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
115 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
118 macro_rules! from_str_radix_nzint_impl {
120 #[stable(feature = "nonzero_parse", since = "1.35.0")]
121 impl FromStr for $t {
122 type Err = ParseIntError;
123 fn from_str(src: &str) -> Result<Self, Self::Err> {
124 Self::new(from_str_radix(src, 10)?)
125 .ok_or(ParseIntError {
126 kind: IntErrorKind::Zero
133 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
134 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
136 /// Provides intentionally-wrapped arithmetic on `T`.
138 /// Operations like `+` on `u32` values is intended to never overflow,
139 /// and in some debug configurations overflow is detected and results
140 /// in a panic. While most arithmetic falls into this category, some
141 /// code explicitly expects and relies upon modular arithmetic (e.g.,
144 /// Wrapping arithmetic can be achieved either through methods like
145 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
146 /// all standard arithmetic operations on the underlying value are
147 /// intended to have wrapping semantics.
149 /// The underlying value can be retrieved through the `.0` index of the
150 /// `Wrapping` tuple.
155 /// use std::num::Wrapping;
157 /// let zero = Wrapping(0u32);
158 /// let one = Wrapping(1u32);
160 /// assert_eq!(std::u32::MAX, (zero - one).0);
162 #[stable(feature = "rust1", since = "1.0.0")]
163 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
165 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
168 #[stable(feature = "rust1", since = "1.0.0")]
169 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175 #[stable(feature = "wrapping_display", since = "1.10.0")]
176 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
183 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
190 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
197 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
204 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
205 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 // All these modules are technically private and only exposed for coretests:
218 macro_rules! usize_isize_to_xe_bytes_doc {
221 **Note**: This function returns an array of length 2, 4 or 8 bytes
222 depending on the target pointer size.
228 macro_rules! usize_isize_from_xe_bytes_doc {
231 **Note**: This function takes an array of length 2, 4 or 8 bytes
232 depending on the target pointer size.
237 // `Int` + `SignedInt` implemented for signed integers
238 macro_rules! int_impl {
239 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
240 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
241 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
242 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
244 concat!("Returns the smallest value that can be represented by this integer type.
251 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
254 #[stable(feature = "rust1", since = "1.0.0")]
257 pub const fn min_value() -> Self {
258 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
263 concat!("Returns the largest value that can be represented by this integer type.
270 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
273 #[stable(feature = "rust1", since = "1.0.0")]
276 pub const fn max_value() -> Self {
282 concat!("Converts a string slice in a given base to an integer.
284 The string is expected to be an optional `+` or `-` sign followed by digits.
285 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
286 depending on `radix`:
294 This function panics if `radix` is not in the range from 2 to 36.
301 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
304 #[stable(feature = "rust1", since = "1.0.0")]
305 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
306 from_str_radix(src, radix)
311 concat!("Returns the number of ones in the binary representation of `self`.
318 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
320 assert_eq!(n.count_ones(), 1);",
324 #[stable(feature = "rust1", since = "1.0.0")]
326 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
330 concat!("Returns the number of zeros in the binary representation of `self`.
337 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
339 #[stable(feature = "rust1", since = "1.0.0")]
341 pub const fn count_zeros(self) -> u32 {
347 concat!("Returns the number of leading zeros in the binary representation of `self`.
354 ", $Feature, "let n = -1", stringify!($SelfT), ";
356 assert_eq!(n.leading_zeros(), 0);",
359 #[stable(feature = "rust1", since = "1.0.0")]
361 pub const fn leading_zeros(self) -> u32 {
362 (self as $UnsignedT).leading_zeros()
367 concat!("Returns the number of trailing zeros in the binary representation of `self`.
374 ", $Feature, "let n = -4", stringify!($SelfT), ";
376 assert_eq!(n.trailing_zeros(), 2);",
379 #[stable(feature = "rust1", since = "1.0.0")]
381 pub const fn trailing_zeros(self) -> u32 {
382 (self as $UnsignedT).trailing_zeros()
387 concat!("Shifts the bits to the left by a specified amount, `n`,
388 wrapping the truncated bits to the end of the resulting integer.
390 Please note this isn't the same operation as the `<<` shifting operator!
397 let n = ", $rot_op, stringify!($SelfT), ";
398 let m = ", $rot_result, ";
400 assert_eq!(n.rotate_left(", $rot, "), m);
402 #[stable(feature = "rust1", since = "1.0.0")]
403 #[must_use = "this returns the result of the operation, \
404 without modifying the original"]
406 pub const fn rotate_left(self, n: u32) -> Self {
407 (self as $UnsignedT).rotate_left(n) as Self
412 concat!("Shifts the bits to the right by a specified amount, `n`,
413 wrapping the truncated bits to the beginning of the resulting
416 Please note this isn't the same operation as the `>>` shifting operator!
423 let n = ", $rot_result, stringify!($SelfT), ";
424 let m = ", $rot_op, ";
426 assert_eq!(n.rotate_right(", $rot, "), m);
428 #[stable(feature = "rust1", since = "1.0.0")]
429 #[must_use = "this returns the result of the operation, \
430 without modifying the original"]
432 pub const fn rotate_right(self, n: u32) -> Self {
433 (self as $UnsignedT).rotate_right(n) as Self
438 concat!("Reverses the byte order of the integer.
445 let n = ", $swap_op, stringify!($SelfT), ";
447 let m = n.swap_bytes();
449 assert_eq!(m, ", $swapped, ");
451 #[stable(feature = "rust1", since = "1.0.0")]
453 pub const fn swap_bytes(self) -> Self {
454 (self as $UnsignedT).swap_bytes() as Self
459 concat!("Reverses the bit pattern of the integer.
466 let n = ", $swap_op, stringify!($SelfT), ";
467 let m = n.reverse_bits();
469 assert_eq!(m, ", $reversed, ");
471 #[stable(feature = "reverse_bits", since = "1.37.0")]
474 pub const fn reverse_bits(self) -> Self {
475 (self as $UnsignedT).reverse_bits() as Self
480 concat!("Converts an integer from big endian to the target's endianness.
482 On big endian this is a no-op. On little endian the bytes are swapped.
489 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
491 if cfg!(target_endian = \"big\") {
492 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
494 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
498 #[stable(feature = "rust1", since = "1.0.0")]
500 pub const fn from_be(x: Self) -> Self {
501 #[cfg(target_endian = "big")]
505 #[cfg(not(target_endian = "big"))]
513 concat!("Converts an integer from little endian to the target's endianness.
515 On little endian this is a no-op. On big endian the bytes are swapped.
522 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
524 if cfg!(target_endian = \"little\") {
525 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
527 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
531 #[stable(feature = "rust1", since = "1.0.0")]
533 pub const fn from_le(x: Self) -> Self {
534 #[cfg(target_endian = "little")]
538 #[cfg(not(target_endian = "little"))]
546 concat!("Converts `self` to big endian from the target's endianness.
548 On big endian this is a no-op. On little endian the bytes are swapped.
555 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
557 if cfg!(target_endian = \"big\") {
558 assert_eq!(n.to_be(), n)
560 assert_eq!(n.to_be(), n.swap_bytes())
564 #[stable(feature = "rust1", since = "1.0.0")]
566 pub const fn to_be(self) -> Self { // or not to be?
567 #[cfg(target_endian = "big")]
571 #[cfg(not(target_endian = "big"))]
579 concat!("Converts `self` to little endian from the target's endianness.
581 On little endian this is a no-op. On big endian the bytes are swapped.
588 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
590 if cfg!(target_endian = \"little\") {
591 assert_eq!(n.to_le(), n)
593 assert_eq!(n.to_le(), n.swap_bytes())
597 #[stable(feature = "rust1", since = "1.0.0")]
599 pub const fn to_le(self) -> Self {
600 #[cfg(target_endian = "little")]
604 #[cfg(not(target_endian = "little"))]
612 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
613 if overflow occurred.
620 ", $Feature, "assert_eq!((", stringify!($SelfT),
621 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
622 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
625 #[stable(feature = "rust1", since = "1.0.0")]
626 #[must_use = "this returns the result of the operation, \
627 without modifying the original"]
629 pub fn checked_add(self, rhs: Self) -> Option<Self> {
630 let (a, b) = self.overflowing_add(rhs);
631 if b {None} else {Some(a)}
636 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
644 ", $Feature, "assert_eq!((", stringify!($SelfT),
645 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
646 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
649 #[stable(feature = "rust1", since = "1.0.0")]
650 #[must_use = "this returns the result of the operation, \
651 without modifying the original"]
653 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
654 let (a, b) = self.overflowing_sub(rhs);
655 if b {None} else {Some(a)}
660 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
668 ", $Feature, "assert_eq!(", stringify!($SelfT),
669 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
670 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
673 #[stable(feature = "rust1", since = "1.0.0")]
674 #[must_use = "this returns the result of the operation, \
675 without modifying the original"]
677 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
678 let (a, b) = self.overflowing_mul(rhs);
679 if b {None} else {Some(a)}
684 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
685 or the division results in overflow.
692 ", $Feature, "assert_eq!((", stringify!($SelfT),
693 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
694 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
695 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
698 #[stable(feature = "rust1", since = "1.0.0")]
699 #[must_use = "this returns the result of the operation, \
700 without modifying the original"]
702 pub fn checked_div(self, rhs: Self) -> Option<Self> {
703 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
706 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
712 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
713 returning `None` if `rhs == 0` or the division results in overflow.
720 assert_eq!((", stringify!($SelfT),
721 "::min_value() + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
722 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euclid(-1), None);
723 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
725 #[stable(feature = "euclidean_division", since = "1.38.0")]
726 #[must_use = "this returns the result of the operation, \
727 without modifying the original"]
729 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
730 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
733 Some(self.div_euclid(rhs))
739 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
740 `rhs == 0` or the division results in overflow.
747 ", $Feature, "use std::", stringify!($SelfT), ";
749 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
750 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
751 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
754 #[stable(feature = "wrapping", since = "1.7.0")]
755 #[must_use = "this returns the result of the operation, \
756 without modifying the original"]
758 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
759 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
762 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
768 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
769 if `rhs == 0` or the division results in overflow.
776 use std::", stringify!($SelfT), ";
778 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
779 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
780 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
782 #[stable(feature = "euclidean_division", since = "1.38.0")]
783 #[must_use = "this returns the result of the operation, \
784 without modifying the original"]
786 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
787 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
790 Some(self.rem_euclid(rhs))
796 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
803 ", $Feature, "use std::", stringify!($SelfT), ";
805 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
806 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
809 #[stable(feature = "wrapping", since = "1.7.0")]
811 pub fn checked_neg(self) -> Option<Self> {
812 let (a, b) = self.overflowing_neg();
813 if b {None} else {Some(a)}
818 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
819 than or equal to the number of bits in `self`.
826 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
827 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
830 #[stable(feature = "wrapping", since = "1.7.0")]
831 #[must_use = "this returns the result of the operation, \
832 without modifying the original"]
834 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
835 let (a, b) = self.overflowing_shl(rhs);
836 if b {None} else {Some(a)}
841 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
842 larger than or equal to the number of bits in `self`.
849 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
850 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
853 #[stable(feature = "wrapping", since = "1.7.0")]
854 #[must_use = "this returns the result of the operation, \
855 without modifying the original"]
857 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
858 let (a, b) = self.overflowing_shr(rhs);
859 if b {None} else {Some(a)}
864 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
872 ", $Feature, "use std::", stringify!($SelfT), ";
874 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
875 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
878 #[stable(feature = "no_panic_abs", since = "1.13.0")]
880 pub fn checked_abs(self) -> Option<Self> {
881 if self.is_negative() {
890 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
898 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
899 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
903 #[stable(feature = "no_panic_pow", since = "1.34.0")]
904 #[must_use = "this returns the result of the operation, \
905 without modifying the original"]
907 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
909 let mut acc: Self = 1;
913 acc = acc.checked_mul(base)?;
916 base = base.checked_mul(base)?;
919 // Deal with the final bit of the exponent separately, since
920 // squaring the base afterwards is not necessary and may cause a
921 // needless overflow.
923 acc = acc.checked_mul(base)?;
931 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
932 bounds instead of overflowing.
939 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
940 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
945 #[stable(feature = "rust1", since = "1.0.0")]
946 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
947 #[must_use = "this returns the result of the operation, \
948 without modifying the original"]
950 pub const fn saturating_add(self, rhs: Self) -> Self {
951 intrinsics::saturating_add(self, rhs)
957 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
958 numeric bounds instead of overflowing.
965 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
966 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
970 #[stable(feature = "rust1", since = "1.0.0")]
971 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
972 #[must_use = "this returns the result of the operation, \
973 without modifying the original"]
975 pub const fn saturating_sub(self, rhs: Self) -> Self {
976 intrinsics::saturating_sub(self, rhs)
981 concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
982 instead of overflowing.
989 ", $Feature, "#![feature(saturating_neg)]
990 assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
991 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
992 assert_eq!(", stringify!($SelfT), "::min_value().saturating_neg(), ", stringify!($SelfT),
994 assert_eq!(", stringify!($SelfT), "::max_value().saturating_neg(), ", stringify!($SelfT),
995 "::min_value() + 1);",
999 #[unstable(feature = "saturating_neg", issue = "59983")]
1001 pub fn saturating_neg(self) -> Self {
1002 intrinsics::saturating_sub(0, self)
1007 concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1008 MIN` instead of overflowing.
1015 ", $Feature, "#![feature(saturating_neg)]
1016 assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
1017 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
1018 assert_eq!(", stringify!($SelfT), "::min_value().saturating_abs(), ", stringify!($SelfT),
1020 assert_eq!((", stringify!($SelfT), "::min_value() + 1).saturating_abs(), ", stringify!($SelfT),
1025 #[unstable(feature = "saturating_neg", issue = "59983")]
1027 pub fn saturating_abs(self) -> Self {
1028 if self.is_negative() {
1029 self.saturating_neg()
1037 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1038 numeric bounds instead of overflowing.
1045 ", $Feature, "use std::", stringify!($SelfT), ";
1047 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1048 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1049 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1052 #[stable(feature = "wrapping", since = "1.7.0")]
1053 #[must_use = "this returns the result of the operation, \
1054 without modifying the original"]
1056 pub fn saturating_mul(self, rhs: Self) -> Self {
1057 self.checked_mul(rhs).unwrap_or_else(|| {
1058 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
1068 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1069 saturating at the numeric bounds instead of overflowing.
1076 ", $Feature, "use std::", stringify!($SelfT), ";
1078 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1079 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1080 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1083 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1084 #[must_use = "this returns the result of the operation, \
1085 without modifying the original"]
1087 pub fn saturating_pow(self, exp: u32) -> Self {
1088 match self.checked_pow(exp) {
1090 None if self < 0 && exp % 2 == 1 => Self::min_value(),
1091 None => Self::max_value(),
1097 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1098 boundary of the type.
1105 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1106 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
1107 "::min_value() + 1);",
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 #[must_use = "this returns the result of the operation, \
1112 without modifying the original"]
1114 pub const fn wrapping_add(self, rhs: Self) -> Self {
1115 #[cfg(boostrap_stdarch_ignore_this)] {
1116 intrinsics::overflowing_add(self, rhs)
1119 #[cfg(not(boostrap_stdarch_ignore_this))] {
1120 intrinsics::wrapping_add(self, rhs)
1126 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1127 boundary of the type.
1134 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1135 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1136 stringify!($SelfT), "::max_value());",
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 #[must_use = "this returns the result of the operation, \
1141 without modifying the original"]
1143 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1144 #[cfg(boostrap_stdarch_ignore_this)] {
1145 intrinsics::overflowing_sub(self, rhs)
1148 #[cfg(not(boostrap_stdarch_ignore_this))] {
1149 intrinsics::wrapping_sub(self, rhs)
1155 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1156 the boundary of the type.
1163 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1164 assert_eq!(11i8.wrapping_mul(12), -124);",
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 #[must_use = "this returns the result of the operation, \
1169 without modifying the original"]
1171 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1172 #[cfg(boostrap_stdarch_ignore_this)] {
1173 intrinsics::overflowing_mul(self, rhs)
1176 #[cfg(not(boostrap_stdarch_ignore_this))] {
1177 intrinsics::wrapping_mul(self, rhs)
1183 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1184 boundary of the type.
1186 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1187 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1188 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1192 This function will panic if `rhs` is 0.
1199 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1200 assert_eq!((-128i8).wrapping_div(-1), -128);",
1203 #[stable(feature = "num_wrapping", since = "1.2.0")]
1204 #[must_use = "this returns the result of the operation, \
1205 without modifying the original"]
1207 pub fn wrapping_div(self, rhs: Self) -> Self {
1208 self.overflowing_div(rhs).0
1213 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1214 wrapping around at the boundary of the type.
1216 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1217 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1218 type. In this case, this method returns `MIN` itself.
1222 This function will panic if `rhs` is 0.
1229 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1230 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1232 #[stable(feature = "euclidean_division", since = "1.38.0")]
1233 #[must_use = "this returns the result of the operation, \
1234 without modifying the original"]
1236 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
1237 self.overflowing_div_euclid(rhs).0
1242 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1243 boundary of the type.
1245 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1246 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1247 this function returns `0`.
1251 This function will panic if `rhs` is 0.
1258 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1259 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1262 #[stable(feature = "num_wrapping", since = "1.2.0")]
1263 #[must_use = "this returns the result of the operation, \
1264 without modifying the original"]
1266 pub fn wrapping_rem(self, rhs: Self) -> Self {
1267 self.overflowing_rem(rhs).0
1272 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1273 at the boundary of the type.
1275 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1276 for the type). In this case, this method returns 0.
1280 This function will panic if `rhs` is 0.
1287 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1288 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1290 #[stable(feature = "euclidean_division", since = "1.38.0")]
1291 #[must_use = "this returns the result of the operation, \
1292 without modifying the original"]
1294 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1295 self.overflowing_rem_euclid(rhs).0
1300 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1303 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1304 is the negative minimal value for the type); this is a positive value that is too large to represent
1305 in the type. In such a case, this function returns `MIN` itself.
1312 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1313 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1317 #[stable(feature = "num_wrapping", since = "1.2.0")]
1319 pub const fn wrapping_neg(self) -> Self {
1320 self.overflowing_neg().0
1325 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1326 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1328 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1329 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1330 The primitive integer types all implement a `rotate_left` function, which may be what you want
1338 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1339 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1342 #[stable(feature = "num_wrapping", since = "1.2.0")]
1343 #[must_use = "this returns the result of the operation, \
1344 without modifying the original"]
1346 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1348 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1354 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1355 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1357 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1358 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1359 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1367 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1368 assert_eq!((-128i16).wrapping_shr(64), -128);",
1371 #[stable(feature = "num_wrapping", since = "1.2.0")]
1372 #[must_use = "this returns the result of the operation, \
1373 without modifying the original"]
1375 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1377 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1383 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1384 the boundary of the type.
1386 The only case where such wrapping can occur is when one takes the absolute value of the negative
1387 minimal value for the type this is a positive value that is too large to represent in the type. In
1388 such a case, this function returns `MIN` itself.
1395 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1396 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1397 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1399 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1402 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1404 pub const fn wrapping_abs(self) -> Self {
1405 (self ^ (self >> ($BITS - 1))).wrapping_sub(self >> ($BITS - 1))
1410 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1411 wrapping around at the boundary of the type.
1418 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1419 assert_eq!(3i8.wrapping_pow(5), -13);
1420 assert_eq!(3i8.wrapping_pow(6), -39);",
1423 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1424 #[must_use = "this returns the result of the operation, \
1425 without modifying the original"]
1427 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1428 let mut base = self;
1429 let mut acc: Self = 1;
1433 acc = acc.wrapping_mul(base);
1436 base = base.wrapping_mul(base);
1439 // Deal with the final bit of the exponent separately, since
1440 // squaring the base afterwards is not necessary and may cause a
1441 // needless overflow.
1443 acc = acc.wrapping_mul(base);
1451 concat!("Calculates `self` + `rhs`
1453 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1454 occur. If an overflow would have occurred then the wrapped value is returned.
1461 ", $Feature, "use std::", stringify!($SelfT), ";
1463 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1464 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1465 "::MIN, true));", $EndFeature, "
1467 #[stable(feature = "wrapping", since = "1.7.0")]
1468 #[must_use = "this returns the result of the operation, \
1469 without modifying the original"]
1471 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1472 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1478 concat!("Calculates `self` - `rhs`
1480 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1481 would occur. If an overflow would have occurred then the wrapped value is returned.
1488 ", $Feature, "use std::", stringify!($SelfT), ";
1490 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1491 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1492 "::MAX, true));", $EndFeature, "
1494 #[stable(feature = "wrapping", since = "1.7.0")]
1495 #[must_use = "this returns the result of the operation, \
1496 without modifying the original"]
1498 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1499 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1505 concat!("Calculates the multiplication of `self` and `rhs`.
1507 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1508 would occur. If an overflow would have occurred then the wrapped value is returned.
1515 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1516 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1519 #[stable(feature = "wrapping", since = "1.7.0")]
1520 #[must_use = "this returns the result of the operation, \
1521 without modifying the original"]
1523 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1524 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1530 concat!("Calculates the divisor when `self` is divided by `rhs`.
1532 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1533 occur. If an overflow would occur then self is returned.
1537 This function will panic if `rhs` is 0.
1544 ", $Feature, "use std::", stringify!($SelfT), ";
1546 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1547 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1552 #[stable(feature = "wrapping", since = "1.7.0")]
1553 #[must_use = "this returns the result of the operation, \
1554 without modifying the original"]
1555 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1556 if self == Self::min_value() && rhs == -1 {
1565 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1567 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1568 occur. If an overflow would occur then `self` is returned.
1572 This function will panic if `rhs` is 0.
1579 use std::", stringify!($SelfT), ";
1581 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1582 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1586 #[stable(feature = "euclidean_division", since = "1.38.0")]
1587 #[must_use = "this returns the result of the operation, \
1588 without modifying the original"]
1589 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1590 if self == Self::min_value() && rhs == -1 {
1593 (self.div_euclid(rhs), false)
1599 concat!("Calculates the remainder when `self` is divided by `rhs`.
1601 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1602 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1606 This function will panic if `rhs` is 0.
1613 ", $Feature, "use std::", stringify!($SelfT), ";
1615 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1616 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1620 #[stable(feature = "wrapping", since = "1.7.0")]
1621 #[must_use = "this returns the result of the operation, \
1622 without modifying the original"]
1623 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1624 if self == Self::min_value() && rhs == -1 {
1634 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1636 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1637 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1641 This function will panic if `rhs` is 0.
1648 use std::", stringify!($SelfT), ";
1650 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1651 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1653 #[stable(feature = "euclidean_division", since = "1.38.0")]
1654 #[must_use = "this returns the result of the operation, \
1655 without modifying the original"]
1657 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1658 if self == Self::min_value() && rhs == -1 {
1661 (self.rem_euclid(rhs), false)
1668 concat!("Negates self, overflowing if this is equal to the minimum value.
1670 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1671 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1672 minimum value will be returned again and `true` will be returned for an overflow happening.
1679 ", $Feature, "use std::", stringify!($SelfT), ";
1681 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1682 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1683 "::MIN, true));", $EndFeature, "
1686 #[stable(feature = "wrapping", since = "1.7.0")]
1687 pub const fn overflowing_neg(self) -> (Self, bool) {
1688 ((!self).wrapping_add(1), self == Self::min_value())
1693 concat!("Shifts self left by `rhs` bits.
1695 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1696 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1697 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1704 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1705 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1708 #[stable(feature = "wrapping", since = "1.7.0")]
1709 #[must_use = "this returns the result of the operation, \
1710 without modifying the original"]
1712 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1713 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1718 concat!("Shifts self right by `rhs` bits.
1720 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1721 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1722 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1729 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1730 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1733 #[stable(feature = "wrapping", since = "1.7.0")]
1734 #[must_use = "this returns the result of the operation, \
1735 without modifying the original"]
1737 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1738 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1743 concat!("Computes the absolute value of `self`.
1745 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1746 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1747 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1748 for an overflow happening.
1755 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1756 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1757 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1758 "::min_value(), true));",
1761 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1763 pub const fn overflowing_abs(self) -> (Self, bool) {
1764 (self ^ (self >> ($BITS - 1))).overflowing_sub(self >> ($BITS - 1))
1769 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1771 Returns a tuple of the exponentiation along with a bool indicating
1772 whether an overflow happened.
1779 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1780 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1783 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1784 #[must_use = "this returns the result of the operation, \
1785 without modifying the original"]
1787 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1788 let mut base = self;
1789 let mut acc: Self = 1;
1790 let mut overflown = false;
1791 // Scratch space for storing results of overflowing_mul.
1796 r = acc.overflowing_mul(base);
1801 r = base.overflowing_mul(base);
1806 // Deal with the final bit of the exponent separately, since
1807 // squaring the base afterwards is not necessary and may cause a
1808 // needless overflow.
1810 r = acc.overflowing_mul(base);
1820 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1827 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1829 assert_eq!(x.pow(5), 32);",
1832 #[stable(feature = "rust1", since = "1.0.0")]
1833 #[must_use = "this returns the result of the operation, \
1834 without modifying the original"]
1836 #[rustc_inherit_overflow_checks]
1837 pub fn pow(self, mut exp: u32) -> Self {
1838 let mut base = self;
1849 // Deal with the final bit of the exponent separately, since
1850 // squaring the base afterwards is not necessary and may cause a
1851 // needless overflow.
1861 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1863 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
1864 with `0 <= self.rem_euclid(rhs) < rhs`.
1866 In other words, the result is `self / rhs` rounded to the integer `n`
1867 such that `self >= n * rhs`.
1868 If `self > 0`, this is equal to round towards zero (the default in Rust);
1869 if `self < 0`, this is equal to round towards +/- infinity.
1873 This function will panic if `rhs` is 0.
1880 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1883 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
1884 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
1885 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
1886 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
1888 #[stable(feature = "euclidean_division", since = "1.38.0")]
1889 #[must_use = "this returns the result of the operation, \
1890 without modifying the original"]
1892 #[rustc_inherit_overflow_checks]
1893 pub fn div_euclid(self, rhs: Self) -> Self {
1896 return if rhs > 0 { q - 1 } else { q + 1 }
1904 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
1906 This is done as if by the Euclidean division algorithm -- given
1907 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
1908 `0 <= r < abs(rhs)`.
1912 This function will panic if `rhs` is 0.
1919 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1922 assert_eq!(a.rem_euclid(b), 3);
1923 assert_eq!((-a).rem_euclid(b), 1);
1924 assert_eq!(a.rem_euclid(-b), 3);
1925 assert_eq!((-a).rem_euclid(-b), 1);
1927 #[stable(feature = "euclidean_division", since = "1.38.0")]
1928 #[must_use = "this returns the result of the operation, \
1929 without modifying the original"]
1931 #[rustc_inherit_overflow_checks]
1932 pub fn rem_euclid(self, rhs: Self) -> Self {
1947 concat!("Computes the absolute value of `self`.
1951 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1952 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1953 code in debug mode will trigger a panic on this case and optimized code will return `",
1954 stringify!($SelfT), "::min_value()` without a panic.
1961 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1962 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1965 #[stable(feature = "rust1", since = "1.0.0")]
1967 #[rustc_inherit_overflow_checks]
1968 pub const fn abs(self) -> Self {
1969 // Note that the #[inline] above means that the overflow
1970 // semantics of the subtraction depend on the crate we're being
1972 (self ^ (self >> ($BITS - 1))) - (self >> ($BITS - 1))
1977 concat!("Returns a number representing sign of `self`.
1979 - `0` if the number is zero
1980 - `1` if the number is positive
1981 - `-1` if the number is negative
1988 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1989 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1990 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 #[rustc_const_unstable(feature = "const_int_sign")]
1996 pub const fn signum(self) -> Self {
1997 (self > 0) as Self - (self < 0) as Self
2002 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2010 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2011 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2014 #[stable(feature = "rust1", since = "1.0.0")]
2016 pub const fn is_positive(self) -> bool { self > 0 }
2020 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2028 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2029 assert!(!10", stringify!($SelfT), ".is_negative());",
2032 #[stable(feature = "rust1", since = "1.0.0")]
2034 pub const fn is_negative(self) -> bool { self < 0 }
2038 concat!("Return the memory representation of this integer as a byte array in
2039 big-endian (network) byte order.
2046 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2047 assert_eq!(bytes, ", $be_bytes, ");
2049 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2050 #[rustc_const_unstable(feature = "const_int_conversion")]
2052 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2053 self.to_be().to_ne_bytes()
2058 concat!("Return the memory representation of this integer as a byte array in
2059 little-endian byte order.
2066 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2067 assert_eq!(bytes, ", $le_bytes, ");
2069 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2070 #[rustc_const_unstable(feature = "const_int_conversion")]
2072 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2073 self.to_le().to_ne_bytes()
2079 Return the memory representation of this integer as a byte array in
2082 As the target platform's native endianness is used, portable code
2083 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2088 [`to_be_bytes`]: #method.to_be_bytes
2089 [`to_le_bytes`]: #method.to_le_bytes
2094 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2095 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
2101 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2102 #[rustc_const_unstable(feature = "const_int_conversion")]
2104 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2105 unsafe { mem::transmute(self) }
2110 concat!("Create an integer value from its representation as a byte array in
2118 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2119 assert_eq!(value, ", $swap_op, ");
2122 When starting from a slice rather than an array, fallible conversion APIs can be used:
2125 use std::convert::TryInto;
2127 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2128 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2130 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2133 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2134 #[rustc_const_unstable(feature = "const_int_conversion")]
2136 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2137 Self::from_be(Self::from_ne_bytes(bytes))
2143 Create an integer value from its representation as a byte array in
2151 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2152 assert_eq!(value, ", $swap_op, ");
2155 When starting from a slice rather than an array, fallible conversion APIs can be used:
2158 use std::convert::TryInto;
2160 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2161 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2163 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2166 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2167 #[rustc_const_unstable(feature = "const_int_conversion")]
2169 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2170 Self::from_le(Self::from_ne_bytes(bytes))
2175 concat!("Create an integer value from its memory representation as a byte
2176 array in native endianness.
2178 As the target platform's native endianness is used, portable code
2179 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2180 appropriate instead.
2182 [`from_be_bytes`]: #method.from_be_bytes
2183 [`from_le_bytes`]: #method.from_le_bytes
2190 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2195 assert_eq!(value, ", $swap_op, ");
2198 When starting from a slice rather than an array, fallible conversion APIs can be used:
2201 use std::convert::TryInto;
2203 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2204 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2206 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2209 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2210 #[rustc_const_unstable(feature = "const_int_conversion")]
2212 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2213 unsafe { mem::transmute(bytes) }
2221 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2222 "[0x12]", "[0x12]", "", "" }
2227 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2228 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2233 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2234 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2235 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2240 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2241 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2242 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2243 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2248 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2249 170141183460469231731687303715884105727, "", "", 16,
2250 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2251 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2252 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2253 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2254 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2255 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2258 #[cfg(target_pointer_width = "16")]
2261 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2262 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2263 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2266 #[cfg(target_pointer_width = "32")]
2269 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2270 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2271 "[0x12, 0x34, 0x56, 0x78]",
2272 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2275 #[cfg(target_pointer_width = "64")]
2278 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2279 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2280 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2281 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2282 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2285 // `Int` + `UnsignedInt` implemented for unsigned integers
2286 macro_rules! uint_impl {
2287 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2288 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2289 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2290 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2292 concat!("Returns the smallest value that can be represented by this integer type.
2299 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2301 #[stable(feature = "rust1", since = "1.0.0")]
2304 pub const fn min_value() -> Self { 0 }
2308 concat!("Returns the largest value that can be represented by this integer type.
2315 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2316 stringify!($MaxV), ");", $EndFeature, "
2318 #[stable(feature = "rust1", since = "1.0.0")]
2321 pub const fn max_value() -> Self { !0 }
2325 concat!("Converts a string slice in a given base to an integer.
2327 The string is expected to be an optional `+` sign
2329 Leading and trailing whitespace represent an error.
2330 Digits are a subset of these characters, depending on `radix`:
2338 This function panics if `radix` is not in the range from 2 to 36.
2345 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2348 #[stable(feature = "rust1", since = "1.0.0")]
2349 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2350 from_str_radix(src, radix)
2355 concat!("Returns the number of ones in the binary representation of `self`.
2362 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2364 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2366 #[stable(feature = "rust1", since = "1.0.0")]
2368 pub const fn count_ones(self) -> u32 {
2369 intrinsics::ctpop(self as $ActualT) as u32
2374 concat!("Returns the number of zeros in the binary representation of `self`.
2381 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2383 #[stable(feature = "rust1", since = "1.0.0")]
2385 pub const fn count_zeros(self) -> u32 {
2386 (!self).count_ones()
2391 concat!("Returns the number of leading zeros in the binary representation of `self`.
2398 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2400 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2402 #[stable(feature = "rust1", since = "1.0.0")]
2404 pub const fn leading_zeros(self) -> u32 {
2405 intrinsics::ctlz(self as $ActualT) as u32
2410 concat!("Returns the number of trailing zeros in the binary representation
2418 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2420 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2422 #[stable(feature = "rust1", since = "1.0.0")]
2424 pub const fn trailing_zeros(self) -> u32 {
2425 intrinsics::cttz(self) as u32
2430 concat!("Shifts the bits to the left by a specified amount, `n`,
2431 wrapping the truncated bits to the end of the resulting integer.
2433 Please note this isn't the same operation as the `<<` shifting operator!
2440 let n = ", $rot_op, stringify!($SelfT), ";
2441 let m = ", $rot_result, ";
2443 assert_eq!(n.rotate_left(", $rot, "), m);
2445 #[stable(feature = "rust1", since = "1.0.0")]
2446 #[must_use = "this returns the result of the operation, \
2447 without modifying the original"]
2449 pub const fn rotate_left(self, n: u32) -> Self {
2450 intrinsics::rotate_left(self, n as $SelfT)
2455 concat!("Shifts the bits to the right by a specified amount, `n`,
2456 wrapping the truncated bits to the beginning of the resulting
2459 Please note this isn't the same operation as the `>>` shifting operator!
2466 let n = ", $rot_result, stringify!($SelfT), ";
2467 let m = ", $rot_op, ";
2469 assert_eq!(n.rotate_right(", $rot, "), m);
2471 #[stable(feature = "rust1", since = "1.0.0")]
2472 #[must_use = "this returns the result of the operation, \
2473 without modifying the original"]
2475 pub const fn rotate_right(self, n: u32) -> Self {
2476 intrinsics::rotate_right(self, n as $SelfT)
2482 Reverses the byte order of the integer.
2489 let n = ", $swap_op, stringify!($SelfT), ";
2490 let m = n.swap_bytes();
2492 assert_eq!(m, ", $swapped, ");
2494 #[stable(feature = "rust1", since = "1.0.0")]
2496 pub const fn swap_bytes(self) -> Self {
2497 intrinsics::bswap(self as $ActualT) as Self
2502 concat!("Reverses the bit pattern of the integer.
2509 let n = ", $swap_op, stringify!($SelfT), ";
2510 let m = n.reverse_bits();
2512 assert_eq!(m, ", $reversed, ");
2514 #[stable(feature = "reverse_bits", since = "1.37.0")]
2517 pub const fn reverse_bits(self) -> Self {
2518 intrinsics::bitreverse(self as $ActualT) as Self
2523 concat!("Converts an integer from big endian to the target's endianness.
2525 On big endian this is a no-op. On little endian the bytes are
2533 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2535 if cfg!(target_endian = \"big\") {
2536 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2538 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2541 #[stable(feature = "rust1", since = "1.0.0")]
2543 pub const fn from_be(x: Self) -> Self {
2544 #[cfg(target_endian = "big")]
2548 #[cfg(not(target_endian = "big"))]
2556 concat!("Converts an integer from little endian to the target's endianness.
2558 On little endian this is a no-op. On big endian the bytes are
2566 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2568 if cfg!(target_endian = \"little\") {
2569 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2571 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2574 #[stable(feature = "rust1", since = "1.0.0")]
2576 pub const fn from_le(x: Self) -> Self {
2577 #[cfg(target_endian = "little")]
2581 #[cfg(not(target_endian = "little"))]
2589 concat!("Converts `self` to big endian from the target's endianness.
2591 On big endian this is a no-op. On little endian the bytes are
2599 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2601 if cfg!(target_endian = \"big\") {
2602 assert_eq!(n.to_be(), n)
2604 assert_eq!(n.to_be(), n.swap_bytes())
2607 #[stable(feature = "rust1", since = "1.0.0")]
2609 pub const fn to_be(self) -> Self { // or not to be?
2610 #[cfg(target_endian = "big")]
2614 #[cfg(not(target_endian = "big"))]
2622 concat!("Converts `self` to little endian from the target's endianness.
2624 On little endian this is a no-op. On big endian the bytes are
2632 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2634 if cfg!(target_endian = \"little\") {
2635 assert_eq!(n.to_le(), n)
2637 assert_eq!(n.to_le(), n.swap_bytes())
2640 #[stable(feature = "rust1", since = "1.0.0")]
2642 pub const fn to_le(self) -> Self {
2643 #[cfg(target_endian = "little")]
2647 #[cfg(not(target_endian = "little"))]
2655 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2656 if overflow occurred.
2663 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2664 "Some(", stringify!($SelfT), "::max_value() - 1));
2665 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2667 #[stable(feature = "rust1", since = "1.0.0")]
2668 #[must_use = "this returns the result of the operation, \
2669 without modifying the original"]
2671 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2672 let (a, b) = self.overflowing_add(rhs);
2673 if b {None} else {Some(a)}
2678 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2679 `None` if overflow occurred.
2686 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2687 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2689 #[stable(feature = "rust1", since = "1.0.0")]
2690 #[must_use = "this returns the result of the operation, \
2691 without modifying the original"]
2693 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2694 let (a, b) = self.overflowing_sub(rhs);
2695 if b {None} else {Some(a)}
2700 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2701 `None` if overflow occurred.
2708 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2709 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2711 #[stable(feature = "rust1", since = "1.0.0")]
2712 #[must_use = "this returns the result of the operation, \
2713 without modifying the original"]
2715 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2716 let (a, b) = self.overflowing_mul(rhs);
2717 if b {None} else {Some(a)}
2722 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2730 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2731 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2733 #[stable(feature = "rust1", since = "1.0.0")]
2734 #[must_use = "this returns the result of the operation, \
2735 without modifying the original"]
2737 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2740 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2746 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2754 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
2755 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
2757 #[stable(feature = "euclidean_division", since = "1.38.0")]
2758 #[must_use = "this returns the result of the operation, \
2759 without modifying the original"]
2761 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
2765 Some(self.div_euclid(rhs))
2772 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2780 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2781 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2783 #[stable(feature = "wrapping", since = "1.7.0")]
2784 #[must_use = "this returns the result of the operation, \
2785 without modifying the original"]
2787 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2791 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2797 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
2805 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
2806 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
2808 #[stable(feature = "euclidean_division", since = "1.38.0")]
2809 #[must_use = "this returns the result of the operation, \
2810 without modifying the original"]
2812 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
2816 Some(self.rem_euclid(rhs))
2822 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2825 Note that negating any positive integer will overflow.
2832 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2833 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2835 #[stable(feature = "wrapping", since = "1.7.0")]
2837 pub fn checked_neg(self) -> Option<Self> {
2838 let (a, b) = self.overflowing_neg();
2839 if b {None} else {Some(a)}
2844 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2845 if `rhs` is larger than or equal to the number of bits in `self`.
2852 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2853 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2855 #[stable(feature = "wrapping", since = "1.7.0")]
2856 #[must_use = "this returns the result of the operation, \
2857 without modifying the original"]
2859 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2860 let (a, b) = self.overflowing_shl(rhs);
2861 if b {None} else {Some(a)}
2866 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2867 if `rhs` is larger than or equal to the number of bits in `self`.
2874 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2875 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2877 #[stable(feature = "wrapping", since = "1.7.0")]
2878 #[must_use = "this returns the result of the operation, \
2879 without modifying the original"]
2881 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2882 let (a, b) = self.overflowing_shr(rhs);
2883 if b {None} else {Some(a)}
2888 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2896 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2897 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2899 #[stable(feature = "no_panic_pow", since = "1.34.0")]
2900 #[must_use = "this returns the result of the operation, \
2901 without modifying the original"]
2903 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2904 let mut base = self;
2905 let mut acc: Self = 1;
2909 acc = acc.checked_mul(base)?;
2912 base = base.checked_mul(base)?;
2915 // Deal with the final bit of the exponent separately, since
2916 // squaring the base afterwards is not necessary and may cause a
2917 // needless overflow.
2919 acc = acc.checked_mul(base)?;
2927 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2928 the numeric bounds instead of overflowing.
2935 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2936 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2939 #[stable(feature = "rust1", since = "1.0.0")]
2940 #[must_use = "this returns the result of the operation, \
2941 without modifying the original"]
2942 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
2944 pub const fn saturating_add(self, rhs: Self) -> Self {
2945 intrinsics::saturating_add(self, rhs)
2950 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2951 at the numeric bounds instead of overflowing.
2958 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2959 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2961 #[stable(feature = "rust1", since = "1.0.0")]
2962 #[must_use = "this returns the result of the operation, \
2963 without modifying the original"]
2964 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
2966 pub const fn saturating_sub(self, rhs: Self) -> Self {
2967 intrinsics::saturating_sub(self, rhs)
2972 concat!("Saturating integer multiplication. Computes `self * rhs`,
2973 saturating at the numeric bounds instead of overflowing.
2980 ", $Feature, "use std::", stringify!($SelfT), ";
2982 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2983 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2984 "::MAX);", $EndFeature, "
2986 #[stable(feature = "wrapping", since = "1.7.0")]
2987 #[must_use = "this returns the result of the operation, \
2988 without modifying the original"]
2990 pub fn saturating_mul(self, rhs: Self) -> Self {
2991 self.checked_mul(rhs).unwrap_or(Self::max_value())
2996 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2997 saturating at the numeric bounds instead of overflowing.
3004 ", $Feature, "use std::", stringify!($SelfT), ";
3006 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3007 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3010 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3011 #[must_use = "this returns the result of the operation, \
3012 without modifying the original"]
3014 pub fn saturating_pow(self, exp: u32) -> Self {
3015 match self.checked_pow(exp) {
3017 None => Self::max_value(),
3023 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3024 wrapping around at the boundary of the type.
3031 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3032 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
3035 #[stable(feature = "rust1", since = "1.0.0")]
3036 #[must_use = "this returns the result of the operation, \
3037 without modifying the original"]
3039 pub const fn wrapping_add(self, rhs: Self) -> Self {
3040 #[cfg(boostrap_stdarch_ignore_this)] {
3041 intrinsics::overflowing_add(self, rhs)
3044 #[cfg(not(boostrap_stdarch_ignore_this))] {
3045 intrinsics::wrapping_add(self, rhs)
3051 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3052 wrapping around at the boundary of the type.
3059 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3060 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
3063 #[stable(feature = "rust1", since = "1.0.0")]
3064 #[must_use = "this returns the result of the operation, \
3065 without modifying the original"]
3067 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3068 #[cfg(boostrap_stdarch_ignore_this)] {
3069 intrinsics::overflowing_sub(self, rhs)
3072 #[cfg(not(boostrap_stdarch_ignore_this))] {
3073 intrinsics::wrapping_sub(self, rhs)
3078 /// Wrapping (modular) multiplication. Computes `self *
3079 /// rhs`, wrapping around at the boundary of the type.
3085 /// Please note that this example is shared between integer types.
3086 /// Which explains why `u8` is used here.
3089 /// assert_eq!(10u8.wrapping_mul(12), 120);
3090 /// assert_eq!(25u8.wrapping_mul(12), 44);
3092 #[stable(feature = "rust1", since = "1.0.0")]
3093 #[must_use = "this returns the result of the operation, \
3094 without modifying the original"]
3096 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3097 #[cfg(boostrap_stdarch_ignore_this)] {
3098 intrinsics::overflowing_mul(self, rhs)
3101 #[cfg(not(boostrap_stdarch_ignore_this))] {
3102 intrinsics::wrapping_mul(self, rhs)
3107 concat!("Wrapping (modular) division. Computes `self / rhs`.
3108 Wrapped division on unsigned types is just normal division.
3109 There's no way wrapping could ever happen.
3110 This function exists, so that all operations
3111 are accounted for in the wrapping operations.
3118 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3120 #[stable(feature = "num_wrapping", since = "1.2.0")]
3121 #[must_use = "this returns the result of the operation, \
3122 without modifying the original"]
3124 pub fn wrapping_div(self, rhs: Self) -> Self {
3130 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3131 Wrapped division on unsigned types is just normal division.
3132 There's no way wrapping could ever happen.
3133 This function exists, so that all operations
3134 are accounted for in the wrapping operations.
3135 Since, for the positive integers, all common
3136 definitions of division are equal, this
3137 is exactly equal to `self.wrapping_div(rhs)`.
3144 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3146 #[stable(feature = "euclidean_division", since = "1.38.0")]
3147 #[must_use = "this returns the result of the operation, \
3148 without modifying the original"]
3150 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
3156 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3157 Wrapped remainder calculation on unsigned types is
3158 just the regular remainder calculation.
3159 There's no way wrapping could ever happen.
3160 This function exists, so that all operations
3161 are accounted for in the wrapping operations.
3168 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3170 #[stable(feature = "num_wrapping", since = "1.2.0")]
3171 #[must_use = "this returns the result of the operation, \
3172 without modifying the original"]
3174 pub fn wrapping_rem(self, rhs: Self) -> Self {
3180 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3181 Wrapped modulo calculation on unsigned types is
3182 just the regular remainder calculation.
3183 There's no way wrapping could ever happen.
3184 This function exists, so that all operations
3185 are accounted for in the wrapping operations.
3186 Since, for the positive integers, all common
3187 definitions of division are equal, this
3188 is exactly equal to `self.wrapping_rem(rhs)`.
3195 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3197 #[stable(feature = "euclidean_division", since = "1.38.0")]
3198 #[must_use = "this returns the result of the operation, \
3199 without modifying the original"]
3201 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3206 /// Wrapping (modular) negation. Computes `-self`,
3207 /// wrapping around at the boundary of the type.
3209 /// Since unsigned types do not have negative equivalents
3210 /// all applications of this function will wrap (except for `-0`).
3211 /// For values smaller than the corresponding signed type's maximum
3212 /// the result is the same as casting the corresponding signed value.
3213 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3214 /// `MAX` is the corresponding signed type's maximum.
3220 /// Please note that this example is shared between integer types.
3221 /// Which explains why `i8` is used here.
3224 /// assert_eq!(100i8.wrapping_neg(), -100);
3225 /// assert_eq!((-128i8).wrapping_neg(), -128);
3227 #[stable(feature = "num_wrapping", since = "1.2.0")]
3229 pub const fn wrapping_neg(self) -> Self {
3230 self.overflowing_neg().0
3234 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3235 where `mask` removes any high-order bits of `rhs` that
3236 would cause the shift to exceed the bitwidth of the type.
3238 Note that this is *not* the same as a rotate-left; the
3239 RHS of a wrapping shift-left is restricted to the range
3240 of the type, rather than the bits shifted out of the LHS
3241 being returned to the other end. The primitive integer
3242 types all implement a `rotate_left` function, which may
3243 be what you want instead.
3250 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3251 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3253 #[stable(feature = "num_wrapping", since = "1.2.0")]
3254 #[must_use = "this returns the result of the operation, \
3255 without modifying the original"]
3257 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3259 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3265 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3266 where `mask` removes any high-order bits of `rhs` that
3267 would cause the shift to exceed the bitwidth of the type.
3269 Note that this is *not* the same as a rotate-right; the
3270 RHS of a wrapping shift-right is restricted to the range
3271 of the type, rather than the bits shifted out of the LHS
3272 being returned to the other end. The primitive integer
3273 types all implement a `rotate_right` function, which may
3274 be what you want instead.
3281 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3282 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3284 #[stable(feature = "num_wrapping", since = "1.2.0")]
3285 #[must_use = "this returns the result of the operation, \
3286 without modifying the original"]
3288 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3290 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3296 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3297 wrapping around at the boundary of the type.
3304 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3305 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3307 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3308 #[must_use = "this returns the result of the operation, \
3309 without modifying the original"]
3311 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3312 let mut base = self;
3313 let mut acc: Self = 1;
3317 acc = acc.wrapping_mul(base);
3320 base = base.wrapping_mul(base);
3323 // Deal with the final bit of the exponent separately, since
3324 // squaring the base afterwards is not necessary and may cause a
3325 // needless overflow.
3327 acc = acc.wrapping_mul(base);
3335 concat!("Calculates `self` + `rhs`
3337 Returns a tuple of the addition along with a boolean indicating
3338 whether an arithmetic overflow would occur. If an overflow would
3339 have occurred then the wrapped value is returned.
3346 ", $Feature, "use std::", stringify!($SelfT), ";
3348 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3349 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3351 #[stable(feature = "wrapping", since = "1.7.0")]
3352 #[must_use = "this returns the result of the operation, \
3353 without modifying the original"]
3355 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3356 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3362 concat!("Calculates `self` - `rhs`
3364 Returns a tuple of the subtraction along with a boolean indicating
3365 whether an arithmetic overflow would occur. If an overflow would
3366 have occurred then the wrapped value is returned.
3373 ", $Feature, "use std::", stringify!($SelfT), ";
3375 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3376 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3379 #[stable(feature = "wrapping", since = "1.7.0")]
3380 #[must_use = "this returns the result of the operation, \
3381 without modifying the original"]
3383 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3384 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3389 /// Calculates the multiplication of `self` and `rhs`.
3391 /// Returns a tuple of the multiplication along with a boolean
3392 /// indicating whether an arithmetic overflow would occur. If an
3393 /// overflow would have occurred then the wrapped value is returned.
3399 /// Please note that this example is shared between integer types.
3400 /// Which explains why `u32` is used here.
3403 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3404 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3406 #[stable(feature = "wrapping", since = "1.7.0")]
3407 #[must_use = "this returns the result of the operation, \
3408 without modifying the original"]
3410 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3411 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3416 concat!("Calculates the divisor when `self` is divided by `rhs`.
3418 Returns a tuple of the divisor along with a boolean indicating
3419 whether an arithmetic overflow would occur. Note that for unsigned
3420 integers overflow never occurs, so the second value is always
3425 This function will panic if `rhs` is 0.
3432 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3435 #[stable(feature = "wrapping", since = "1.7.0")]
3436 #[must_use = "this returns the result of the operation, \
3437 without modifying the original"]
3438 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3444 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3446 Returns a tuple of the divisor along with a boolean indicating
3447 whether an arithmetic overflow would occur. Note that for unsigned
3448 integers overflow never occurs, so the second value is always
3450 Since, for the positive integers, all common
3451 definitions of division are equal, this
3452 is exactly equal to `self.overflowing_div(rhs)`.
3456 This function will panic if `rhs` is 0.
3463 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3466 #[stable(feature = "euclidean_division", since = "1.38.0")]
3467 #[must_use = "this returns the result of the operation, \
3468 without modifying the original"]
3469 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3475 concat!("Calculates the remainder when `self` is divided by `rhs`.
3477 Returns a tuple of the remainder after dividing along with a boolean
3478 indicating whether an arithmetic overflow would occur. Note that for
3479 unsigned integers overflow never occurs, so the second value is
3484 This function will panic if `rhs` is 0.
3491 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3494 #[stable(feature = "wrapping", since = "1.7.0")]
3495 #[must_use = "this returns the result of the operation, \
3496 without modifying the original"]
3497 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3503 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3505 Returns a tuple of the modulo after dividing along with a boolean
3506 indicating whether an arithmetic overflow would occur. Note that for
3507 unsigned integers overflow never occurs, so the second value is
3509 Since, for the positive integers, all common
3510 definitions of division are equal, this operation
3511 is exactly equal to `self.overflowing_rem(rhs)`.
3515 This function will panic if `rhs` is 0.
3522 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3525 #[stable(feature = "euclidean_division", since = "1.38.0")]
3526 #[must_use = "this returns the result of the operation, \
3527 without modifying the original"]
3528 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3534 concat!("Negates self in an overflowing fashion.
3536 Returns `!self + 1` using wrapping operations to return the value
3537 that represents the negation of this unsigned value. Note that for
3538 positive unsigned values overflow always occurs, but negating 0 does
3546 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3547 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3548 ", true));", $EndFeature, "
3551 #[stable(feature = "wrapping", since = "1.7.0")]
3552 pub const fn overflowing_neg(self) -> (Self, bool) {
3553 ((!self).wrapping_add(1), self != 0)
3558 concat!("Shifts self left by `rhs` bits.
3560 Returns a tuple of the shifted version of self along with a boolean
3561 indicating whether the shift value was larger than or equal to the
3562 number of bits. If the shift value is too large, then value is
3563 masked (N-1) where N is the number of bits, and this value is then
3564 used to perform the shift.
3571 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3572 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3574 #[stable(feature = "wrapping", since = "1.7.0")]
3575 #[must_use = "this returns the result of the operation, \
3576 without modifying the original"]
3578 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3579 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3584 concat!("Shifts self right by `rhs` bits.
3586 Returns a tuple of the shifted version of self along with a boolean
3587 indicating whether the shift value was larger than or equal to the
3588 number of bits. If the shift value is too large, then value is
3589 masked (N-1) where N is the number of bits, and this value is then
3590 used to perform the shift.
3597 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3598 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3600 #[stable(feature = "wrapping", since = "1.7.0")]
3601 #[must_use = "this returns the result of the operation, \
3602 without modifying the original"]
3604 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3605 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3610 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3612 Returns a tuple of the exponentiation along with a bool indicating
3613 whether an overflow happened.
3620 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3621 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3623 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3624 #[must_use = "this returns the result of the operation, \
3625 without modifying the original"]
3627 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3628 let mut base = self;
3629 let mut acc: Self = 1;
3630 let mut overflown = false;
3631 // Scratch space for storing results of overflowing_mul.
3636 r = acc.overflowing_mul(base);
3641 r = base.overflowing_mul(base);
3646 // Deal with the final bit of the exponent separately, since
3647 // squaring the base afterwards is not necessary and may cause a
3648 // needless overflow.
3650 r = acc.overflowing_mul(base);
3660 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3667 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3669 #[stable(feature = "rust1", since = "1.0.0")]
3670 #[must_use = "this returns the result of the operation, \
3671 without modifying the original"]
3673 #[rustc_inherit_overflow_checks]
3674 pub fn pow(self, mut exp: u32) -> Self {
3675 let mut base = self;
3686 // Deal with the final bit of the exponent separately, since
3687 // squaring the base afterwards is not necessary and may cause a
3688 // needless overflow.
3698 concat!("Performs Euclidean division.
3700 Since, for the positive integers, all common
3701 definitions of division are equal, this
3702 is exactly equal to `self / rhs`.
3709 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
3711 #[stable(feature = "euclidean_division", since = "1.38.0")]
3712 #[must_use = "this returns the result of the operation, \
3713 without modifying the original"]
3715 #[rustc_inherit_overflow_checks]
3716 pub fn div_euclid(self, rhs: Self) -> Self {
3723 concat!("Calculates the least remainder of `self (mod rhs)`.
3725 Since, for the positive integers, all common
3726 definitions of division are equal, this
3727 is exactly equal to `self % rhs`.
3734 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
3736 #[stable(feature = "euclidean_division", since = "1.38.0")]
3737 #[must_use = "this returns the result of the operation, \
3738 without modifying the original"]
3740 #[rustc_inherit_overflow_checks]
3741 pub fn rem_euclid(self, rhs: Self) -> Self {
3747 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3754 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3755 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3757 #[stable(feature = "rust1", since = "1.0.0")]
3759 pub fn is_power_of_two(self) -> bool {
3760 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3764 // Returns one less than next power of two.
3765 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3767 // 8u8.one_less_than_next_power_of_two() == 7
3768 // 6u8.one_less_than_next_power_of_two() == 7
3770 // This method cannot overflow, as in the `next_power_of_two`
3771 // overflow cases it instead ends up returning the maximum value
3772 // of the type, and can return 0 for 0.
3774 fn one_less_than_next_power_of_two(self) -> Self {
3775 if self <= 1 { return 0; }
3777 // Because `p > 0`, it cannot consist entirely of leading zeros.
3778 // That means the shift is always in-bounds, and some processors
3779 // (such as intel pre-haswell) have more efficient ctlz
3780 // intrinsics when the argument is non-zero.
3782 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3783 <$SelfT>::max_value() >> z
3787 concat!("Returns the smallest power of two greater than or equal to `self`.
3789 When return value overflows (i.e., `self > (1 << (N-1))` for type
3790 `uN`), it panics in debug mode and return value is wrapped to 0 in
3791 release mode (the only situation in which method can return 0).
3798 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3799 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3801 #[stable(feature = "rust1", since = "1.0.0")]
3803 pub fn next_power_of_two(self) -> Self {
3804 // Call the trait to get overflow checks
3805 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3810 concat!("Returns the smallest power of two greater than or equal to `n`. If
3811 the next power of two is greater than the type's maximum value,
3812 `None` is returned, otherwise the power of two is wrapped in `Some`.
3819 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3820 ".checked_next_power_of_two(), Some(2));
3821 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3822 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3826 #[stable(feature = "rust1", since = "1.0.0")]
3827 pub fn checked_next_power_of_two(self) -> Option<Self> {
3828 self.one_less_than_next_power_of_two().checked_add(1)
3833 concat!("Returns the smallest power of two greater than or equal to `n`. If
3834 the next power of two is greater than the type's maximum value,
3835 the return value is wrapped to `0`.
3842 #![feature(wrapping_next_power_of_two)]
3844 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3845 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3846 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3849 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3850 reason = "needs decision on wrapping behaviour")]
3851 pub fn wrapping_next_power_of_two(self) -> Self {
3852 self.one_less_than_next_power_of_two().wrapping_add(1)
3857 concat!("Return the memory representation of this integer as a byte array in
3858 big-endian (network) byte order.
3865 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
3866 assert_eq!(bytes, ", $be_bytes, ");
3868 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3869 #[rustc_const_unstable(feature = "const_int_conversion")]
3871 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
3872 self.to_be().to_ne_bytes()
3877 concat!("Return the memory representation of this integer as a byte array in
3878 little-endian byte order.
3885 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
3886 assert_eq!(bytes, ", $le_bytes, ");
3888 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3889 #[rustc_const_unstable(feature = "const_int_conversion")]
3891 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
3892 self.to_le().to_ne_bytes()
3898 Return the memory representation of this integer as a byte array in
3901 As the target platform's native endianness is used, portable code
3902 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3907 [`to_be_bytes`]: #method.to_be_bytes
3908 [`to_le_bytes`]: #method.to_le_bytes
3913 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
3914 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
3920 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3921 #[rustc_const_unstable(feature = "const_int_conversion")]
3923 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
3924 unsafe { mem::transmute(self) }
3929 concat!("Create an integer value from its representation as a byte array in
3937 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
3938 assert_eq!(value, ", $swap_op, ");
3941 When starting from a slice rather than an array, fallible conversion APIs can be used:
3944 use std::convert::TryInto;
3946 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3947 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3949 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
3952 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3953 #[rustc_const_unstable(feature = "const_int_conversion")]
3955 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3956 Self::from_be(Self::from_ne_bytes(bytes))
3962 Create an integer value from its representation as a byte array in
3970 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
3971 assert_eq!(value, ", $swap_op, ");
3974 When starting from a slice rather than an array, fallible conversion APIs can be used:
3977 use std::convert::TryInto;
3979 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3980 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3982 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
3985 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3986 #[rustc_const_unstable(feature = "const_int_conversion")]
3988 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3989 Self::from_le(Self::from_ne_bytes(bytes))
3994 concat!("Create an integer value from its memory representation as a byte
3995 array in native endianness.
3997 As the target platform's native endianness is used, portable code
3998 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3999 appropriate instead.
4001 [`from_be_bytes`]: #method.from_be_bytes
4002 [`from_le_bytes`]: #method.from_le_bytes
4009 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4014 assert_eq!(value, ", $swap_op, ");
4017 When starting from a slice rather than an array, fallible conversion APIs can be used:
4020 use std::convert::TryInto;
4022 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4023 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4025 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4028 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4029 #[rustc_const_unstable(feature = "const_int_conversion")]
4031 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4032 unsafe { mem::transmute(bytes) }
4040 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4044 /// Checks if the value is within the ASCII range.
4049 /// let ascii = 97u8;
4050 /// let non_ascii = 150u8;
4052 /// assert!(ascii.is_ascii());
4053 /// assert!(!non_ascii.is_ascii());
4055 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4057 pub fn is_ascii(&self) -> bool {
4061 /// Makes a copy of the value in its ASCII upper case equivalent.
4063 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4064 /// but non-ASCII letters are unchanged.
4066 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4071 /// let lowercase_a = 97u8;
4073 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4076 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4077 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4079 pub fn to_ascii_uppercase(&self) -> u8 {
4080 // Unset the fith bit if this is a lowercase letter
4081 *self & !((self.is_ascii_lowercase() as u8) << 5)
4084 /// Makes a copy of the value in its ASCII lower case equivalent.
4086 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4087 /// but non-ASCII letters are unchanged.
4089 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4094 /// let uppercase_a = 65u8;
4096 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4099 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4100 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4102 pub fn to_ascii_lowercase(&self) -> u8 {
4103 // Set the fith bit if this is an uppercase letter
4104 *self | ((self.is_ascii_uppercase() as u8) << 5)
4107 /// Checks that two values are an ASCII case-insensitive match.
4109 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4114 /// let lowercase_a = 97u8;
4115 /// let uppercase_a = 65u8;
4117 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4119 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4121 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4122 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4125 /// Converts this value to its ASCII upper case equivalent in-place.
4127 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4128 /// but non-ASCII letters are unchanged.
4130 /// To return a new uppercased value without modifying the existing one, use
4131 /// [`to_ascii_uppercase`].
4136 /// let mut byte = b'a';
4138 /// byte.make_ascii_uppercase();
4140 /// assert_eq!(b'A', byte);
4143 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4144 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4146 pub fn make_ascii_uppercase(&mut self) {
4147 *self = self.to_ascii_uppercase();
4150 /// Converts this value to its ASCII lower case equivalent in-place.
4152 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4153 /// but non-ASCII letters are unchanged.
4155 /// To return a new lowercased value without modifying the existing one, use
4156 /// [`to_ascii_lowercase`].
4161 /// let mut byte = b'A';
4163 /// byte.make_ascii_lowercase();
4165 /// assert_eq!(b'a', byte);
4168 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4169 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4171 pub fn make_ascii_lowercase(&mut self) {
4172 *self = self.to_ascii_lowercase();
4175 /// Checks if the value is an ASCII alphabetic character:
4177 /// - U+0041 'A' ..= U+005A 'Z', or
4178 /// - U+0061 'a' ..= U+007A 'z'.
4183 /// let uppercase_a = b'A';
4184 /// let uppercase_g = b'G';
4187 /// let zero = b'0';
4188 /// let percent = b'%';
4189 /// let space = b' ';
4191 /// let esc = 0x1b_u8;
4193 /// assert!(uppercase_a.is_ascii_alphabetic());
4194 /// assert!(uppercase_g.is_ascii_alphabetic());
4195 /// assert!(a.is_ascii_alphabetic());
4196 /// assert!(g.is_ascii_alphabetic());
4197 /// assert!(!zero.is_ascii_alphabetic());
4198 /// assert!(!percent.is_ascii_alphabetic());
4199 /// assert!(!space.is_ascii_alphabetic());
4200 /// assert!(!lf.is_ascii_alphabetic());
4201 /// assert!(!esc.is_ascii_alphabetic());
4203 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4205 pub fn is_ascii_alphabetic(&self) -> bool {
4207 b'A'..=b'Z' | b'a'..=b'z' => true,
4212 /// Checks if the value is an ASCII uppercase character:
4213 /// U+0041 'A' ..= U+005A 'Z'.
4218 /// let uppercase_a = b'A';
4219 /// let uppercase_g = b'G';
4222 /// let zero = b'0';
4223 /// let percent = b'%';
4224 /// let space = b' ';
4226 /// let esc = 0x1b_u8;
4228 /// assert!(uppercase_a.is_ascii_uppercase());
4229 /// assert!(uppercase_g.is_ascii_uppercase());
4230 /// assert!(!a.is_ascii_uppercase());
4231 /// assert!(!g.is_ascii_uppercase());
4232 /// assert!(!zero.is_ascii_uppercase());
4233 /// assert!(!percent.is_ascii_uppercase());
4234 /// assert!(!space.is_ascii_uppercase());
4235 /// assert!(!lf.is_ascii_uppercase());
4236 /// assert!(!esc.is_ascii_uppercase());
4238 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4240 pub fn is_ascii_uppercase(&self) -> bool {
4242 b'A'..=b'Z' => true,
4247 /// Checks if the value is an ASCII lowercase character:
4248 /// U+0061 'a' ..= U+007A 'z'.
4253 /// let uppercase_a = b'A';
4254 /// let uppercase_g = b'G';
4257 /// let zero = b'0';
4258 /// let percent = b'%';
4259 /// let space = b' ';
4261 /// let esc = 0x1b_u8;
4263 /// assert!(!uppercase_a.is_ascii_lowercase());
4264 /// assert!(!uppercase_g.is_ascii_lowercase());
4265 /// assert!(a.is_ascii_lowercase());
4266 /// assert!(g.is_ascii_lowercase());
4267 /// assert!(!zero.is_ascii_lowercase());
4268 /// assert!(!percent.is_ascii_lowercase());
4269 /// assert!(!space.is_ascii_lowercase());
4270 /// assert!(!lf.is_ascii_lowercase());
4271 /// assert!(!esc.is_ascii_lowercase());
4273 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4275 pub fn is_ascii_lowercase(&self) -> bool {
4277 b'a'..=b'z' => true,
4282 /// Checks if the value is an ASCII alphanumeric character:
4284 /// - U+0041 'A' ..= U+005A 'Z', or
4285 /// - U+0061 'a' ..= U+007A 'z', or
4286 /// - U+0030 '0' ..= U+0039 '9'.
4291 /// let uppercase_a = b'A';
4292 /// let uppercase_g = b'G';
4295 /// let zero = b'0';
4296 /// let percent = b'%';
4297 /// let space = b' ';
4299 /// let esc = 0x1b_u8;
4301 /// assert!(uppercase_a.is_ascii_alphanumeric());
4302 /// assert!(uppercase_g.is_ascii_alphanumeric());
4303 /// assert!(a.is_ascii_alphanumeric());
4304 /// assert!(g.is_ascii_alphanumeric());
4305 /// assert!(zero.is_ascii_alphanumeric());
4306 /// assert!(!percent.is_ascii_alphanumeric());
4307 /// assert!(!space.is_ascii_alphanumeric());
4308 /// assert!(!lf.is_ascii_alphanumeric());
4309 /// assert!(!esc.is_ascii_alphanumeric());
4311 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4313 pub fn is_ascii_alphanumeric(&self) -> bool {
4315 b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' => true,
4320 /// Checks if the value is an ASCII decimal digit:
4321 /// U+0030 '0' ..= U+0039 '9'.
4326 /// let uppercase_a = b'A';
4327 /// let uppercase_g = b'G';
4330 /// let zero = b'0';
4331 /// let percent = b'%';
4332 /// let space = b' ';
4334 /// let esc = 0x1b_u8;
4336 /// assert!(!uppercase_a.is_ascii_digit());
4337 /// assert!(!uppercase_g.is_ascii_digit());
4338 /// assert!(!a.is_ascii_digit());
4339 /// assert!(!g.is_ascii_digit());
4340 /// assert!(zero.is_ascii_digit());
4341 /// assert!(!percent.is_ascii_digit());
4342 /// assert!(!space.is_ascii_digit());
4343 /// assert!(!lf.is_ascii_digit());
4344 /// assert!(!esc.is_ascii_digit());
4346 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4348 pub fn is_ascii_digit(&self) -> bool {
4350 b'0'..=b'9' => true,
4355 /// Checks if the value is an ASCII hexadecimal digit:
4357 /// - U+0030 '0' ..= U+0039 '9', or
4358 /// - U+0041 'A' ..= U+0046 'F', or
4359 /// - U+0061 'a' ..= U+0066 'f'.
4364 /// let uppercase_a = b'A';
4365 /// let uppercase_g = b'G';
4368 /// let zero = b'0';
4369 /// let percent = b'%';
4370 /// let space = b' ';
4372 /// let esc = 0x1b_u8;
4374 /// assert!(uppercase_a.is_ascii_hexdigit());
4375 /// assert!(!uppercase_g.is_ascii_hexdigit());
4376 /// assert!(a.is_ascii_hexdigit());
4377 /// assert!(!g.is_ascii_hexdigit());
4378 /// assert!(zero.is_ascii_hexdigit());
4379 /// assert!(!percent.is_ascii_hexdigit());
4380 /// assert!(!space.is_ascii_hexdigit());
4381 /// assert!(!lf.is_ascii_hexdigit());
4382 /// assert!(!esc.is_ascii_hexdigit());
4384 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4386 pub fn is_ascii_hexdigit(&self) -> bool {
4388 b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f' => true,
4393 /// Checks if the value is an ASCII punctuation character:
4395 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4396 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4397 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4398 /// - U+007B ..= U+007E `{ | } ~`
4403 /// let uppercase_a = b'A';
4404 /// let uppercase_g = b'G';
4407 /// let zero = b'0';
4408 /// let percent = b'%';
4409 /// let space = b' ';
4411 /// let esc = 0x1b_u8;
4413 /// assert!(!uppercase_a.is_ascii_punctuation());
4414 /// assert!(!uppercase_g.is_ascii_punctuation());
4415 /// assert!(!a.is_ascii_punctuation());
4416 /// assert!(!g.is_ascii_punctuation());
4417 /// assert!(!zero.is_ascii_punctuation());
4418 /// assert!(percent.is_ascii_punctuation());
4419 /// assert!(!space.is_ascii_punctuation());
4420 /// assert!(!lf.is_ascii_punctuation());
4421 /// assert!(!esc.is_ascii_punctuation());
4423 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4425 pub fn is_ascii_punctuation(&self) -> bool {
4427 b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~' => true,
4432 /// Checks if the value is an ASCII graphic character:
4433 /// U+0021 '!' ..= U+007E '~'.
4438 /// let uppercase_a = b'A';
4439 /// let uppercase_g = b'G';
4442 /// let zero = b'0';
4443 /// let percent = b'%';
4444 /// let space = b' ';
4446 /// let esc = 0x1b_u8;
4448 /// assert!(uppercase_a.is_ascii_graphic());
4449 /// assert!(uppercase_g.is_ascii_graphic());
4450 /// assert!(a.is_ascii_graphic());
4451 /// assert!(g.is_ascii_graphic());
4452 /// assert!(zero.is_ascii_graphic());
4453 /// assert!(percent.is_ascii_graphic());
4454 /// assert!(!space.is_ascii_graphic());
4455 /// assert!(!lf.is_ascii_graphic());
4456 /// assert!(!esc.is_ascii_graphic());
4458 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4460 pub fn is_ascii_graphic(&self) -> bool {
4462 b'!'..=b'~' => true,
4467 /// Checks if the value is an ASCII whitespace character:
4468 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4469 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4471 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4472 /// whitespace][infra-aw]. There are several other definitions in
4473 /// wide use. For instance, [the POSIX locale][pct] includes
4474 /// U+000B VERTICAL TAB as well as all the above characters,
4475 /// but—from the very same specification—[the default rule for
4476 /// "field splitting" in the Bourne shell][bfs] considers *only*
4477 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4479 /// If you are writing a program that will process an existing
4480 /// file format, check what that format's definition of whitespace is
4481 /// before using this function.
4483 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4484 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4485 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4490 /// let uppercase_a = b'A';
4491 /// let uppercase_g = b'G';
4494 /// let zero = b'0';
4495 /// let percent = b'%';
4496 /// let space = b' ';
4498 /// let esc = 0x1b_u8;
4500 /// assert!(!uppercase_a.is_ascii_whitespace());
4501 /// assert!(!uppercase_g.is_ascii_whitespace());
4502 /// assert!(!a.is_ascii_whitespace());
4503 /// assert!(!g.is_ascii_whitespace());
4504 /// assert!(!zero.is_ascii_whitespace());
4505 /// assert!(!percent.is_ascii_whitespace());
4506 /// assert!(space.is_ascii_whitespace());
4507 /// assert!(lf.is_ascii_whitespace());
4508 /// assert!(!esc.is_ascii_whitespace());
4510 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4512 pub fn is_ascii_whitespace(&self) -> bool {
4514 b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' => true,
4519 /// Checks if the value is an ASCII control character:
4520 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4521 /// Note that most ASCII whitespace characters are control
4522 /// characters, but SPACE is not.
4527 /// let uppercase_a = b'A';
4528 /// let uppercase_g = b'G';
4531 /// let zero = b'0';
4532 /// let percent = b'%';
4533 /// let space = b' ';
4535 /// let esc = 0x1b_u8;
4537 /// assert!(!uppercase_a.is_ascii_control());
4538 /// assert!(!uppercase_g.is_ascii_control());
4539 /// assert!(!a.is_ascii_control());
4540 /// assert!(!g.is_ascii_control());
4541 /// assert!(!zero.is_ascii_control());
4542 /// assert!(!percent.is_ascii_control());
4543 /// assert!(!space.is_ascii_control());
4544 /// assert!(lf.is_ascii_control());
4545 /// assert!(esc.is_ascii_control());
4547 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4549 pub fn is_ascii_control(&self) -> bool {
4551 b'\0'..=b'\x1F' | b'\x7F' => true,
4559 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4560 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4565 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4566 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4571 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4572 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4573 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4574 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4580 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4581 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4582 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4583 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4584 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4585 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4586 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4590 #[cfg(target_pointer_width = "16")]
4593 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4594 "[0x34, 0x12]", "[0x12, 0x34]",
4595 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4597 #[cfg(target_pointer_width = "32")]
4600 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4601 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4602 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4605 #[cfg(target_pointer_width = "64")]
4608 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4609 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4610 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4611 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4612 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4615 /// A classification of floating point numbers.
4617 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4618 /// their documentation for more.
4620 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4621 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4626 /// use std::num::FpCategory;
4629 /// let num = 12.4_f32;
4630 /// let inf = f32::INFINITY;
4631 /// let zero = 0f32;
4632 /// let sub: f32 = 1.1754942e-38;
4633 /// let nan = f32::NAN;
4635 /// assert_eq!(num.classify(), FpCategory::Normal);
4636 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4637 /// assert_eq!(zero.classify(), FpCategory::Zero);
4638 /// assert_eq!(nan.classify(), FpCategory::Nan);
4639 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4641 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4642 #[stable(feature = "rust1", since = "1.0.0")]
4643 pub enum FpCategory {
4644 /// "Not a Number", often obtained by dividing by zero.
4645 #[stable(feature = "rust1", since = "1.0.0")]
4648 /// Positive or negative infinity.
4649 #[stable(feature = "rust1", since = "1.0.0")]
4652 /// Positive or negative zero.
4653 #[stable(feature = "rust1", since = "1.0.0")]
4656 /// De-normalized floating point representation (less precise than `Normal`).
4657 #[stable(feature = "rust1", since = "1.0.0")]
4660 /// A regular floating point number.
4661 #[stable(feature = "rust1", since = "1.0.0")]
4665 macro_rules! from_str_radix_int_impl {
4667 #[stable(feature = "rust1", since = "1.0.0")]
4668 impl FromStr for $t {
4669 type Err = ParseIntError;
4670 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4671 from_str_radix(src, 10)
4676 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4678 /// The error type returned when a checked integral type conversion fails.
4679 #[stable(feature = "try_from", since = "1.34.0")]
4680 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4681 pub struct TryFromIntError(());
4683 impl TryFromIntError {
4684 #[unstable(feature = "int_error_internals",
4685 reason = "available through Error trait and this method should \
4686 not be exposed publicly",
4689 pub fn __description(&self) -> &str {
4690 "out of range integral type conversion attempted"
4694 #[stable(feature = "try_from", since = "1.34.0")]
4695 impl fmt::Display for TryFromIntError {
4696 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4697 self.__description().fmt(fmt)
4701 #[stable(feature = "try_from", since = "1.34.0")]
4702 impl From<Infallible> for TryFromIntError {
4703 fn from(x: Infallible) -> TryFromIntError {
4708 #[unstable(feature = "never_type", issue = "35121")]
4709 impl From<!> for TryFromIntError {
4710 fn from(never: !) -> TryFromIntError {
4711 // Match rather than coerce to make sure that code like
4712 // `From<Infallible> for TryFromIntError` above will keep working
4713 // when `Infallible` becomes an alias to `!`.
4718 // no possible bounds violation
4719 macro_rules! try_from_unbounded {
4720 ($source:ty, $($target:ty),*) => {$(
4721 #[stable(feature = "try_from", since = "1.34.0")]
4722 impl TryFrom<$source> for $target {
4723 type Error = TryFromIntError;
4725 /// Try to create the target number type from a source
4726 /// number type. This returns an error if the source value
4727 /// is outside of the range of the target type.
4729 fn try_from(value: $source) -> Result<Self, Self::Error> {
4730 Ok(value as $target)
4736 // only negative bounds
4737 macro_rules! try_from_lower_bounded {
4738 ($source:ty, $($target:ty),*) => {$(
4739 #[stable(feature = "try_from", since = "1.34.0")]
4740 impl TryFrom<$source> for $target {
4741 type Error = TryFromIntError;
4743 /// Try to create the target number type from a source
4744 /// number type. This returns an error if the source value
4745 /// is outside of the range of the target type.
4747 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4751 Err(TryFromIntError(()))
4758 // unsigned to signed (only positive bound)
4759 macro_rules! try_from_upper_bounded {
4760 ($source:ty, $($target:ty),*) => {$(
4761 #[stable(feature = "try_from", since = "1.34.0")]
4762 impl TryFrom<$source> for $target {
4763 type Error = TryFromIntError;
4765 /// Try to create the target number type from a source
4766 /// number type. This returns an error if the source value
4767 /// is outside of the range of the target type.
4769 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4770 if u > (<$target>::max_value() as $source) {
4771 Err(TryFromIntError(()))
4781 macro_rules! try_from_both_bounded {
4782 ($source:ty, $($target:ty),*) => {$(
4783 #[stable(feature = "try_from", since = "1.34.0")]
4784 impl TryFrom<$source> for $target {
4785 type Error = TryFromIntError;
4787 /// Try to create the target number type from a source
4788 /// number type. This returns an error if the source value
4789 /// is outside of the range of the target type.
4791 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4792 let min = <$target>::min_value() as $source;
4793 let max = <$target>::max_value() as $source;
4794 if u < min || u > max {
4795 Err(TryFromIntError(()))
4805 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4806 $mac!($target, $source);
4810 // intra-sign conversions
4811 try_from_upper_bounded!(u16, u8);
4812 try_from_upper_bounded!(u32, u16, u8);
4813 try_from_upper_bounded!(u64, u32, u16, u8);
4814 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4816 try_from_both_bounded!(i16, i8);
4817 try_from_both_bounded!(i32, i16, i8);
4818 try_from_both_bounded!(i64, i32, i16, i8);
4819 try_from_both_bounded!(i128, i64, i32, i16, i8);
4821 // unsigned-to-signed
4822 try_from_upper_bounded!(u8, i8);
4823 try_from_upper_bounded!(u16, i8, i16);
4824 try_from_upper_bounded!(u32, i8, i16, i32);
4825 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4826 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4828 // signed-to-unsigned
4829 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4830 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4831 try_from_lower_bounded!(i32, u32, u64, u128);
4832 try_from_lower_bounded!(i64, u64, u128);
4833 try_from_lower_bounded!(i128, u128);
4834 try_from_both_bounded!(i16, u8);
4835 try_from_both_bounded!(i32, u16, u8);
4836 try_from_both_bounded!(i64, u32, u16, u8);
4837 try_from_both_bounded!(i128, u64, u32, u16, u8);
4840 try_from_upper_bounded!(usize, isize);
4841 try_from_lower_bounded!(isize, usize);
4843 #[cfg(target_pointer_width = "16")]
4844 mod ptr_try_from_impls {
4845 use super::TryFromIntError;
4846 use crate::convert::TryFrom;
4848 try_from_upper_bounded!(usize, u8);
4849 try_from_unbounded!(usize, u16, u32, u64, u128);
4850 try_from_upper_bounded!(usize, i8, i16);
4851 try_from_unbounded!(usize, i32, i64, i128);
4853 try_from_both_bounded!(isize, u8);
4854 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4855 try_from_both_bounded!(isize, i8);
4856 try_from_unbounded!(isize, i16, i32, i64, i128);
4858 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4859 rev!(try_from_lower_bounded, usize, i8, i16);
4860 rev!(try_from_both_bounded, usize, i32, i64, i128);
4862 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4863 rev!(try_from_both_bounded, isize, i32, i64, i128);
4866 #[cfg(target_pointer_width = "32")]
4867 mod ptr_try_from_impls {
4868 use super::TryFromIntError;
4869 use crate::convert::TryFrom;
4871 try_from_upper_bounded!(usize, u8, u16);
4872 try_from_unbounded!(usize, u32, u64, u128);
4873 try_from_upper_bounded!(usize, i8, i16, i32);
4874 try_from_unbounded!(usize, i64, i128);
4876 try_from_both_bounded!(isize, u8, u16);
4877 try_from_lower_bounded!(isize, u32, u64, u128);
4878 try_from_both_bounded!(isize, i8, i16);
4879 try_from_unbounded!(isize, i32, i64, i128);
4881 rev!(try_from_unbounded, usize, u32);
4882 rev!(try_from_upper_bounded, usize, u64, u128);
4883 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4884 rev!(try_from_both_bounded, usize, i64, i128);
4886 rev!(try_from_unbounded, isize, u16);
4887 rev!(try_from_upper_bounded, isize, u32, u64, u128);
4888 rev!(try_from_unbounded, isize, i32);
4889 rev!(try_from_both_bounded, isize, i64, i128);
4892 #[cfg(target_pointer_width = "64")]
4893 mod ptr_try_from_impls {
4894 use super::TryFromIntError;
4895 use crate::convert::TryFrom;
4897 try_from_upper_bounded!(usize, u8, u16, u32);
4898 try_from_unbounded!(usize, u64, u128);
4899 try_from_upper_bounded!(usize, i8, i16, i32, i64);
4900 try_from_unbounded!(usize, i128);
4902 try_from_both_bounded!(isize, u8, u16, u32);
4903 try_from_lower_bounded!(isize, u64, u128);
4904 try_from_both_bounded!(isize, i8, i16, i32);
4905 try_from_unbounded!(isize, i64, i128);
4907 rev!(try_from_unbounded, usize, u32, u64);
4908 rev!(try_from_upper_bounded, usize, u128);
4909 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4910 rev!(try_from_both_bounded, usize, i128);
4912 rev!(try_from_unbounded, isize, u16, u32);
4913 rev!(try_from_upper_bounded, isize, u64, u128);
4914 rev!(try_from_unbounded, isize, i32, i64);
4915 rev!(try_from_both_bounded, isize, i128);
4919 trait FromStrRadixHelper: PartialOrd + Copy {
4920 fn min_value() -> Self;
4921 fn max_value() -> Self;
4922 fn from_u32(u: u32) -> Self;
4923 fn checked_mul(&self, other: u32) -> Option<Self>;
4924 fn checked_sub(&self, other: u32) -> Option<Self>;
4925 fn checked_add(&self, other: u32) -> Option<Self>;
4929 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4931 fn min_value() -> Self { Self::min_value() }
4933 fn max_value() -> Self { Self::max_value() }
4935 fn from_u32(u: u32) -> Self { u as Self }
4937 fn checked_mul(&self, other: u32) -> Option<Self> {
4938 Self::checked_mul(*self, other as Self)
4941 fn checked_sub(&self, other: u32) -> Option<Self> {
4942 Self::checked_sub(*self, other as Self)
4945 fn checked_add(&self, other: u32) -> Option<Self> {
4946 Self::checked_add(*self, other as Self)
4950 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4952 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4953 use self::IntErrorKind::*;
4954 use self::ParseIntError as PIE;
4956 assert!(radix >= 2 && radix <= 36,
4957 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4961 return Err(PIE { kind: Empty });
4964 let is_signed_ty = T::from_u32(0) > T::min_value();
4966 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4967 // and cast them to chars. .to_digit() will safely return None for anything
4968 // other than a valid ascii digit for the given radix, including the first-byte
4969 // of multi-byte sequences
4970 let src = src.as_bytes();
4972 let (is_positive, digits) = match src[0] {
4973 b'+' => (true, &src[1..]),
4974 b'-' if is_signed_ty => (false, &src[1..]),
4978 if digits.is_empty() {
4979 return Err(PIE { kind: Empty });
4982 let mut result = T::from_u32(0);
4984 // The number is positive
4986 let x = match (c as char).to_digit(radix) {
4988 None => return Err(PIE { kind: InvalidDigit }),
4990 result = match result.checked_mul(radix) {
4991 Some(result) => result,
4992 None => return Err(PIE { kind: Overflow }),
4994 result = match result.checked_add(x) {
4995 Some(result) => result,
4996 None => return Err(PIE { kind: Overflow }),
5000 // The number is negative
5002 let x = match (c as char).to_digit(radix) {
5004 None => return Err(PIE { kind: InvalidDigit }),
5006 result = match result.checked_mul(radix) {
5007 Some(result) => result,
5008 None => return Err(PIE { kind: Underflow }),
5010 result = match result.checked_sub(x) {
5011 Some(result) => result,
5012 None => return Err(PIE { kind: Underflow }),
5019 /// An error which can be returned when parsing an integer.
5021 /// This error is used as the error type for the `from_str_radix()` functions
5022 /// on the primitive integer types, such as [`i8::from_str_radix`].
5024 /// # Potential causes
5026 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5027 /// in the string e.g., when it is obtained from the standard input.
5028 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5030 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5031 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5032 #[derive(Debug, Clone, PartialEq, Eq)]
5033 #[stable(feature = "rust1", since = "1.0.0")]
5034 pub struct ParseIntError {
5038 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5039 #[unstable(feature = "int_error_matching",
5040 reason = "it can be useful to match errors when making error messages \
5041 for integer parsing",
5043 #[derive(Debug, Clone, PartialEq, Eq)]
5045 pub enum IntErrorKind {
5046 /// Value being parsed is empty.
5048 /// Among other causes, this variant will be constructed when parsing an empty string.
5050 /// Contains an invalid digit.
5052 /// Among other causes, this variant will be constructed when parsing a string that
5053 /// contains a letter.
5055 /// Integer is too large to store in target integer type.
5057 /// Integer is too small to store in target integer type.
5061 /// This variant will be emitted when the parsing string has a value of zero, which
5062 /// would be illegal for non-zero types.
5066 impl ParseIntError {
5067 /// Outputs the detailed cause of parsing an integer failing.
5068 #[unstable(feature = "int_error_matching",
5069 reason = "it can be useful to match errors when making error messages \
5070 for integer parsing",
5072 pub fn kind(&self) -> &IntErrorKind {
5075 #[unstable(feature = "int_error_internals",
5076 reason = "available through Error trait and this method should \
5077 not be exposed publicly",
5080 pub fn __description(&self) -> &str {
5082 IntErrorKind::Empty => "cannot parse integer from empty string",
5083 IntErrorKind::InvalidDigit => "invalid digit found in string",
5084 IntErrorKind::Overflow => "number too large to fit in target type",
5085 IntErrorKind::Underflow => "number too small to fit in target type",
5086 IntErrorKind::Zero => "number would be zero for non-zero type",
5091 #[stable(feature = "rust1", since = "1.0.0")]
5092 impl fmt::Display for ParseIntError {
5093 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5094 self.__description().fmt(f)
5098 #[stable(feature = "rust1", since = "1.0.0")]
5099 pub use crate::num::dec2flt::ParseFloatError;
5101 // Conversion traits for primitive integer and float types
5102 // Conversions T -> T are covered by a blanket impl and therefore excluded
5103 // Some conversions from and to usize/isize are not implemented due to portability concerns
5104 macro_rules! impl_from {
5105 ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
5108 impl From<$Small> for $Large {
5110 fn from(small: $Small) -> $Large {
5115 ($Small: ty, $Large: ty, #[$attr:meta]) => {
5119 concat!("Converts `",
5127 macro_rules! impl_from_bool {
5128 ($target: ty, #[$attr:meta]) => {
5129 impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
5130 stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
5136 assert_eq!(", stringify!($target), "::from(true), 1);
5137 assert_eq!(", stringify!($target), "::from(false), 0);
5143 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
5144 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
5145 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
5146 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
5147 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
5148 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
5149 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
5150 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
5151 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
5152 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
5153 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
5154 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
5156 // Unsigned -> Unsigned
5157 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5158 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5159 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5160 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
5161 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5162 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5163 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5164 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
5165 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5166 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
5167 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
5170 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5171 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5172 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5173 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5174 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5175 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5176 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5177 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5178 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5179 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5180 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5182 // Unsigned -> Signed
5183 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5184 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5185 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5186 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5187 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5188 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5189 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5190 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5191 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5192 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5194 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
5195 // which imply that pointer-sized integers must be at least 16 bits:
5196 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
5197 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5198 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5199 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5201 // RISC-V defines the possibility of a 128-bit address space (RV128).
5203 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
5204 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
5205 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
5208 // Note: integers can only be represented with full precision in a float if
5209 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
5210 // Lossy float conversions are not implemented at this time.
5213 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5214 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5215 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5216 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5217 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5219 // Unsigned -> Float
5220 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5221 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5222 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5223 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5224 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5227 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }