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 #[cfg_attr(not(bootstrap), 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 #![feature(euclidean_division)]
721 assert_eq!((", stringify!($SelfT),
722 "::min_value() + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
723 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euclid(-1), None);
724 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
726 #[unstable(feature = "euclidean_division", issue = "49048")]
727 #[must_use = "this returns the result of the operation, \
728 without modifying the original"]
730 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
731 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
734 Some(self.div_euclid(rhs))
740 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
741 `rhs == 0` or the division results in overflow.
748 ", $Feature, "use std::", stringify!($SelfT), ";
750 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
751 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
752 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
755 #[stable(feature = "wrapping", since = "1.7.0")]
756 #[must_use = "this returns the result of the operation, \
757 without modifying the original"]
759 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
760 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
763 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
769 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
770 if `rhs == 0` or the division results in overflow.
777 #![feature(euclidean_division)]
778 use std::", stringify!($SelfT), ";
780 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
781 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
782 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
784 #[unstable(feature = "euclidean_division", issue = "49048")]
785 #[must_use = "this returns the result of the operation, \
786 without modifying the original"]
788 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
789 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
792 Some(self.rem_euclid(rhs))
798 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
805 ", $Feature, "use std::", stringify!($SelfT), ";
807 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
808 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
811 #[stable(feature = "wrapping", since = "1.7.0")]
813 pub fn checked_neg(self) -> Option<Self> {
814 let (a, b) = self.overflowing_neg();
815 if b {None} else {Some(a)}
820 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
821 than or equal to the number of bits in `self`.
828 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
829 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
832 #[stable(feature = "wrapping", since = "1.7.0")]
833 #[must_use = "this returns the result of the operation, \
834 without modifying the original"]
836 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
837 let (a, b) = self.overflowing_shl(rhs);
838 if b {None} else {Some(a)}
843 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
844 larger than or equal to the number of bits in `self`.
851 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
852 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
855 #[stable(feature = "wrapping", since = "1.7.0")]
856 #[must_use = "this returns the result of the operation, \
857 without modifying the original"]
859 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
860 let (a, b) = self.overflowing_shr(rhs);
861 if b {None} else {Some(a)}
866 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
874 ", $Feature, "use std::", stringify!($SelfT), ";
876 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
877 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
880 #[stable(feature = "no_panic_abs", since = "1.13.0")]
882 pub fn checked_abs(self) -> Option<Self> {
883 if self.is_negative() {
892 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
900 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
901 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
905 #[stable(feature = "no_panic_pow", since = "1.34.0")]
906 #[must_use = "this returns the result of the operation, \
907 without modifying the original"]
909 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
911 let mut acc: Self = 1;
915 acc = acc.checked_mul(base)?;
918 base = base.checked_mul(base)?;
921 // Deal with the final bit of the exponent separately, since
922 // squaring the base afterwards is not necessary and may cause a
923 // needless overflow.
925 acc = acc.checked_mul(base)?;
933 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
934 bounds instead of overflowing.
941 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
942 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
947 #[stable(feature = "rust1", since = "1.0.0")]
948 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
949 #[must_use = "this returns the result of the operation, \
950 without modifying the original"]
952 pub const fn saturating_add(self, rhs: Self) -> Self {
953 intrinsics::saturating_add(self, rhs)
959 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
960 numeric bounds instead of overflowing.
967 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
968 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
972 #[stable(feature = "rust1", since = "1.0.0")]
973 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
974 #[must_use = "this returns the result of the operation, \
975 without modifying the original"]
977 pub const fn saturating_sub(self, rhs: Self) -> Self {
978 intrinsics::saturating_sub(self, rhs)
983 concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
984 instead of overflowing.
991 ", $Feature, "#![feature(saturating_neg)]
992 assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
993 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
994 assert_eq!(", stringify!($SelfT), "::min_value().saturating_neg(), ", stringify!($SelfT),
996 assert_eq!(", stringify!($SelfT), "::max_value().saturating_neg(), ", stringify!($SelfT),
997 "::min_value() + 1);",
1001 #[unstable(feature = "saturating_neg", issue = "59983")]
1003 pub fn saturating_neg(self) -> Self {
1004 intrinsics::saturating_sub(0, self)
1009 concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1010 MIN` instead of overflowing.
1017 ", $Feature, "#![feature(saturating_neg)]
1018 assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
1019 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
1020 assert_eq!(", stringify!($SelfT), "::min_value().saturating_abs(), ", stringify!($SelfT),
1022 assert_eq!((", stringify!($SelfT), "::min_value() + 1).saturating_abs(), ", stringify!($SelfT),
1027 #[unstable(feature = "saturating_neg", issue = "59983")]
1029 pub fn saturating_abs(self) -> Self {
1030 if self.is_negative() {
1031 self.saturating_neg()
1039 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1040 numeric bounds instead of overflowing.
1047 ", $Feature, "use std::", stringify!($SelfT), ";
1049 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1050 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1051 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1054 #[stable(feature = "wrapping", since = "1.7.0")]
1055 #[must_use = "this returns the result of the operation, \
1056 without modifying the original"]
1058 pub fn saturating_mul(self, rhs: Self) -> Self {
1059 self.checked_mul(rhs).unwrap_or_else(|| {
1060 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
1070 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1071 saturating at the numeric bounds instead of overflowing.
1078 ", $Feature, "use std::", stringify!($SelfT), ";
1080 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1081 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1082 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1085 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1086 #[must_use = "this returns the result of the operation, \
1087 without modifying the original"]
1089 pub fn saturating_pow(self, exp: u32) -> Self {
1090 match self.checked_pow(exp) {
1092 None if self < 0 && exp % 2 == 1 => Self::min_value(),
1093 None => Self::max_value(),
1099 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1100 boundary of the type.
1107 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1108 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
1109 "::min_value() + 1);",
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 #[must_use = "this returns the result of the operation, \
1114 without modifying the original"]
1116 pub const fn wrapping_add(self, rhs: Self) -> Self {
1117 intrinsics::overflowing_add(self, rhs)
1122 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1123 boundary of the type.
1130 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1131 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1132 stringify!($SelfT), "::max_value());",
1135 #[stable(feature = "rust1", since = "1.0.0")]
1136 #[must_use = "this returns the result of the operation, \
1137 without modifying the original"]
1139 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1140 intrinsics::overflowing_sub(self, rhs)
1145 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1146 the boundary of the type.
1153 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1154 assert_eq!(11i8.wrapping_mul(12), -124);",
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 #[must_use = "this returns the result of the operation, \
1159 without modifying the original"]
1161 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1162 intrinsics::overflowing_mul(self, rhs)
1167 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1168 boundary of the type.
1170 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1171 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1172 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1176 This function will panic if `rhs` is 0.
1183 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1184 assert_eq!((-128i8).wrapping_div(-1), -128);",
1187 #[stable(feature = "num_wrapping", since = "1.2.0")]
1188 #[must_use = "this returns the result of the operation, \
1189 without modifying the original"]
1191 pub fn wrapping_div(self, rhs: Self) -> Self {
1192 self.overflowing_div(rhs).0
1197 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1198 wrapping around at the boundary of the type.
1200 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1201 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1202 type. In this case, this method returns `MIN` itself.
1206 This function will panic if `rhs` is 0.
1213 #![feature(euclidean_division)]
1214 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1215 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1217 #[unstable(feature = "euclidean_division", issue = "49048")]
1218 #[must_use = "this returns the result of the operation, \
1219 without modifying the original"]
1221 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
1222 self.overflowing_div_euclid(rhs).0
1227 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1228 boundary of the type.
1230 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1231 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1232 this function returns `0`.
1236 This function will panic if `rhs` is 0.
1243 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1244 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1247 #[stable(feature = "num_wrapping", since = "1.2.0")]
1248 #[must_use = "this returns the result of the operation, \
1249 without modifying the original"]
1251 pub fn wrapping_rem(self, rhs: Self) -> Self {
1252 self.overflowing_rem(rhs).0
1257 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1258 at the boundary of the type.
1260 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1261 for the type). In this case, this method returns 0.
1265 This function will panic if `rhs` is 0.
1272 #![feature(euclidean_division)]
1273 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1274 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1276 #[unstable(feature = "euclidean_division", issue = "49048")]
1277 #[must_use = "this returns the result of the operation, \
1278 without modifying the original"]
1280 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1281 self.overflowing_rem_euclid(rhs).0
1286 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1289 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1290 is the negative minimal value for the type); this is a positive value that is too large to represent
1291 in the type. In such a case, this function returns `MIN` itself.
1298 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1299 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1303 #[stable(feature = "num_wrapping", since = "1.2.0")]
1305 pub const fn wrapping_neg(self) -> Self {
1306 self.overflowing_neg().0
1311 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1312 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1314 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1315 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1316 The primitive integer types all implement a `rotate_left` function, which may be what you want
1324 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1325 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1328 #[stable(feature = "num_wrapping", since = "1.2.0")]
1329 #[must_use = "this returns the result of the operation, \
1330 without modifying the original"]
1332 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1334 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1340 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1341 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1343 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1344 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1345 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1353 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1354 assert_eq!((-128i16).wrapping_shr(64), -128);",
1357 #[stable(feature = "num_wrapping", since = "1.2.0")]
1358 #[must_use = "this returns the result of the operation, \
1359 without modifying the original"]
1361 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1363 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1369 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1370 the boundary of the type.
1372 The only case where such wrapping can occur is when one takes the absolute value of the negative
1373 minimal value for the type this is a positive value that is too large to represent in the type. In
1374 such a case, this function returns `MIN` itself.
1381 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1382 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1383 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1385 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1388 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1390 pub fn wrapping_abs(self) -> Self {
1391 if self.is_negative() {
1400 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1401 wrapping around at the boundary of the type.
1408 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1409 assert_eq!(3i8.wrapping_pow(5), -13);
1410 assert_eq!(3i8.wrapping_pow(6), -39);",
1413 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1414 #[must_use = "this returns the result of the operation, \
1415 without modifying the original"]
1417 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1418 let mut base = self;
1419 let mut acc: Self = 1;
1423 acc = acc.wrapping_mul(base);
1426 base = base.wrapping_mul(base);
1429 // Deal with the final bit of the exponent separately, since
1430 // squaring the base afterwards is not necessary and may cause a
1431 // needless overflow.
1433 acc = acc.wrapping_mul(base);
1441 concat!("Calculates `self` + `rhs`
1443 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1444 occur. If an overflow would have occurred then the wrapped value is returned.
1451 ", $Feature, "use std::", stringify!($SelfT), ";
1453 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1454 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1455 "::MIN, true));", $EndFeature, "
1457 #[stable(feature = "wrapping", since = "1.7.0")]
1458 #[must_use = "this returns the result of the operation, \
1459 without modifying the original"]
1461 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1462 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1468 concat!("Calculates `self` - `rhs`
1470 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1471 would occur. If an overflow would have occurred then the wrapped value is returned.
1478 ", $Feature, "use std::", stringify!($SelfT), ";
1480 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1481 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1482 "::MAX, true));", $EndFeature, "
1484 #[stable(feature = "wrapping", since = "1.7.0")]
1485 #[must_use = "this returns the result of the operation, \
1486 without modifying the original"]
1488 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1489 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1495 concat!("Calculates the multiplication of `self` and `rhs`.
1497 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1498 would occur. If an overflow would have occurred then the wrapped value is returned.
1505 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1506 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1509 #[stable(feature = "wrapping", since = "1.7.0")]
1510 #[must_use = "this returns the result of the operation, \
1511 without modifying the original"]
1513 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1514 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1520 concat!("Calculates the divisor when `self` is divided by `rhs`.
1522 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1523 occur. If an overflow would occur then self is returned.
1527 This function will panic if `rhs` is 0.
1534 ", $Feature, "use std::", stringify!($SelfT), ";
1536 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1537 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1542 #[stable(feature = "wrapping", since = "1.7.0")]
1543 #[must_use = "this returns the result of the operation, \
1544 without modifying the original"]
1545 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1546 if self == Self::min_value() && rhs == -1 {
1555 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1557 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1558 occur. If an overflow would occur then `self` is returned.
1562 This function will panic if `rhs` is 0.
1569 #![feature(euclidean_division)]
1570 use std::", stringify!($SelfT), ";
1572 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1573 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1577 #[unstable(feature = "euclidean_division", issue = "49048")]
1578 #[must_use = "this returns the result of the operation, \
1579 without modifying the original"]
1580 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1581 if self == Self::min_value() && rhs == -1 {
1584 (self.div_euclid(rhs), false)
1590 concat!("Calculates the remainder when `self` is divided by `rhs`.
1592 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1593 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1597 This function will panic if `rhs` is 0.
1604 ", $Feature, "use std::", stringify!($SelfT), ";
1606 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1607 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1611 #[stable(feature = "wrapping", since = "1.7.0")]
1612 #[must_use = "this returns the result of the operation, \
1613 without modifying the original"]
1614 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1615 if self == Self::min_value() && rhs == -1 {
1625 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1627 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1628 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1632 This function will panic if `rhs` is 0.
1639 #![feature(euclidean_division)]
1640 use std::", stringify!($SelfT), ";
1642 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1643 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1645 #[unstable(feature = "euclidean_division", issue = "49048")]
1646 #[must_use = "this returns the result of the operation, \
1647 without modifying the original"]
1649 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1650 if self == Self::min_value() && rhs == -1 {
1653 (self.rem_euclid(rhs), false)
1660 concat!("Negates self, overflowing if this is equal to the minimum value.
1662 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1663 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1664 minimum value will be returned again and `true` will be returned for an overflow happening.
1671 ", $Feature, "use std::", stringify!($SelfT), ";
1673 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1674 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1675 "::MIN, true));", $EndFeature, "
1678 #[stable(feature = "wrapping", since = "1.7.0")]
1679 pub const fn overflowing_neg(self) -> (Self, bool) {
1680 ((!self).wrapping_add(1), self == Self::min_value())
1685 concat!("Shifts self left by `rhs` bits.
1687 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1688 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1689 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1696 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1697 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1700 #[stable(feature = "wrapping", since = "1.7.0")]
1701 #[must_use = "this returns the result of the operation, \
1702 without modifying the original"]
1704 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1705 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1710 concat!("Shifts self right by `rhs` bits.
1712 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1713 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1714 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1721 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1722 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1725 #[stable(feature = "wrapping", since = "1.7.0")]
1726 #[must_use = "this returns the result of the operation, \
1727 without modifying the original"]
1729 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1730 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1735 concat!("Computes the absolute value of `self`.
1737 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1738 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1739 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1740 for an overflow happening.
1747 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1748 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1749 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1750 "::min_value(), true));",
1753 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1755 pub fn overflowing_abs(self) -> (Self, bool) {
1756 if self.is_negative() {
1757 self.overflowing_neg()
1765 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1767 Returns a tuple of the exponentiation along with a bool indicating
1768 whether an overflow happened.
1775 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1776 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1779 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1780 #[must_use = "this returns the result of the operation, \
1781 without modifying the original"]
1783 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1784 let mut base = self;
1785 let mut acc: Self = 1;
1786 let mut overflown = false;
1787 // Scratch space for storing results of overflowing_mul.
1792 r = acc.overflowing_mul(base);
1797 r = base.overflowing_mul(base);
1802 // Deal with the final bit of the exponent separately, since
1803 // squaring the base afterwards is not necessary and may cause a
1804 // needless overflow.
1806 r = acc.overflowing_mul(base);
1816 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1823 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1825 assert_eq!(x.pow(5), 32);",
1828 #[stable(feature = "rust1", since = "1.0.0")]
1829 #[must_use = "this returns the result of the operation, \
1830 without modifying the original"]
1832 #[rustc_inherit_overflow_checks]
1833 pub fn pow(self, mut exp: u32) -> Self {
1834 let mut base = self;
1845 // Deal with the final bit of the exponent separately, since
1846 // squaring the base afterwards is not necessary and may cause a
1847 // needless overflow.
1857 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1859 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
1860 with `0 <= self.rem_euclid(rhs) < rhs`.
1862 In other words, the result is `self / rhs` rounded to the integer `n`
1863 such that `self >= n * rhs`.
1864 If `self > 0`, this is equal to round towards zero (the default in Rust);
1865 if `self < 0`, this is equal to round towards +/- infinity.
1869 This function will panic if `rhs` is 0.
1876 #![feature(euclidean_division)]
1877 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1880 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
1881 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
1882 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
1883 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
1885 #[unstable(feature = "euclidean_division", issue = "49048")]
1886 #[must_use = "this returns the result of the operation, \
1887 without modifying the original"]
1889 #[rustc_inherit_overflow_checks]
1890 pub fn div_euclid(self, rhs: Self) -> Self {
1893 return if rhs > 0 { q - 1 } else { q + 1 }
1901 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
1903 This is done as if by the Euclidean division algorithm -- given
1904 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
1905 `0 <= r < abs(rhs)`.
1909 This function will panic if `rhs` is 0.
1916 #![feature(euclidean_division)]
1917 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1920 assert_eq!(a.rem_euclid(b), 3);
1921 assert_eq!((-a).rem_euclid(b), 1);
1922 assert_eq!(a.rem_euclid(-b), 3);
1923 assert_eq!((-a).rem_euclid(-b), 1);
1925 #[unstable(feature = "euclidean_division", issue = "49048")]
1926 #[must_use = "this returns the result of the operation, \
1927 without modifying the original"]
1929 #[rustc_inherit_overflow_checks]
1930 pub fn rem_euclid(self, rhs: Self) -> Self {
1945 concat!("Computes the absolute value of `self`.
1949 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1950 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1951 code in debug mode will trigger a panic on this case and optimized code will return `",
1952 stringify!($SelfT), "::min_value()` without a panic.
1959 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1960 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1963 #[stable(feature = "rust1", since = "1.0.0")]
1965 #[rustc_inherit_overflow_checks]
1966 pub fn abs(self) -> Self {
1967 if self.is_negative() {
1968 // Note that the #[inline] above means that the overflow
1969 // semantics of this negation depend on the crate we're being
1979 concat!("Returns a number representing sign of `self`.
1981 - `0` if the number is zero
1982 - `1` if the number is positive
1983 - `-1` if the number is negative
1990 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1991 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1992 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1995 #[stable(feature = "rust1", since = "1.0.0")]
1996 #[rustc_const_unstable(feature = "const_int_sign")]
1998 pub const fn signum(self) -> Self {
1999 (self > 0) as Self - (self < 0) as Self
2004 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2012 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2013 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2016 #[stable(feature = "rust1", since = "1.0.0")]
2018 pub const fn is_positive(self) -> bool { self > 0 }
2022 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2030 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2031 assert!(!10", stringify!($SelfT), ".is_negative());",
2034 #[stable(feature = "rust1", since = "1.0.0")]
2036 pub const fn is_negative(self) -> bool { self < 0 }
2040 concat!("Return the memory representation of this integer as a byte array in
2041 big-endian (network) byte order.
2048 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2049 assert_eq!(bytes, ", $be_bytes, ");
2051 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2052 #[rustc_const_unstable(feature = "const_int_conversion")]
2054 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2055 self.to_be().to_ne_bytes()
2060 concat!("Return the memory representation of this integer as a byte array in
2061 little-endian byte order.
2068 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2069 assert_eq!(bytes, ", $le_bytes, ");
2071 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2072 #[rustc_const_unstable(feature = "const_int_conversion")]
2074 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2075 self.to_le().to_ne_bytes()
2081 Return the memory representation of this integer as a byte array in
2084 As the target platform's native endianness is used, portable code
2085 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2090 [`to_be_bytes`]: #method.to_be_bytes
2091 [`to_le_bytes`]: #method.to_le_bytes
2096 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2097 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
2103 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2104 #[rustc_const_unstable(feature = "const_int_conversion")]
2106 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2107 unsafe { mem::transmute(self) }
2112 concat!("Create an integer value from its representation as a byte array in
2120 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2121 assert_eq!(value, ", $swap_op, ");
2124 When starting from a slice rather than an array, fallible conversion APIs can be used:
2127 use std::convert::TryInto;
2129 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2130 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2132 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2135 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2136 #[rustc_const_unstable(feature = "const_int_conversion")]
2138 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2139 Self::from_be(Self::from_ne_bytes(bytes))
2145 Create an integer value from its representation as a byte array in
2153 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2154 assert_eq!(value, ", $swap_op, ");
2157 When starting from a slice rather than an array, fallible conversion APIs can be used:
2160 use std::convert::TryInto;
2162 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2163 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2165 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2168 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2169 #[rustc_const_unstable(feature = "const_int_conversion")]
2171 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2172 Self::from_le(Self::from_ne_bytes(bytes))
2177 concat!("Create an integer value from its memory representation as a byte
2178 array in native endianness.
2180 As the target platform's native endianness is used, portable code
2181 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2182 appropriate instead.
2184 [`from_be_bytes`]: #method.from_be_bytes
2185 [`from_le_bytes`]: #method.from_le_bytes
2192 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2197 assert_eq!(value, ", $swap_op, ");
2200 When starting from a slice rather than an array, fallible conversion APIs can be used:
2203 use std::convert::TryInto;
2205 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2206 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2208 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2211 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2212 #[rustc_const_unstable(feature = "const_int_conversion")]
2214 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2215 unsafe { mem::transmute(bytes) }
2223 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2224 "[0x12]", "[0x12]", "", "" }
2229 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2230 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2235 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2236 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2237 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2242 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2243 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2244 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2245 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2250 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2251 170141183460469231731687303715884105727, "", "", 16,
2252 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2253 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2254 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2255 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2256 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2257 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2260 #[cfg(target_pointer_width = "16")]
2263 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2264 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2265 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2268 #[cfg(target_pointer_width = "32")]
2271 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2272 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2273 "[0x12, 0x34, 0x56, 0x78]",
2274 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2277 #[cfg(target_pointer_width = "64")]
2280 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2281 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2282 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2283 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2284 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2287 // `Int` + `UnsignedInt` implemented for unsigned integers
2288 macro_rules! uint_impl {
2289 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2290 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2291 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2292 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2294 concat!("Returns the smallest value that can be represented by this integer type.
2301 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2303 #[stable(feature = "rust1", since = "1.0.0")]
2306 pub const fn min_value() -> Self { 0 }
2310 concat!("Returns the largest value that can be represented by this integer type.
2317 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2318 stringify!($MaxV), ");", $EndFeature, "
2320 #[stable(feature = "rust1", since = "1.0.0")]
2323 pub const fn max_value() -> Self { !0 }
2327 concat!("Converts a string slice in a given base to an integer.
2329 The string is expected to be an optional `+` sign
2331 Leading and trailing whitespace represent an error.
2332 Digits are a subset of these characters, depending on `radix`:
2340 This function panics if `radix` is not in the range from 2 to 36.
2347 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2350 #[stable(feature = "rust1", since = "1.0.0")]
2351 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2352 from_str_radix(src, radix)
2357 concat!("Returns the number of ones in the binary representation of `self`.
2364 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2366 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2368 #[stable(feature = "rust1", since = "1.0.0")]
2370 pub const fn count_ones(self) -> u32 {
2371 intrinsics::ctpop(self as $ActualT) as u32
2376 concat!("Returns the number of zeros in the binary representation of `self`.
2383 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2385 #[stable(feature = "rust1", since = "1.0.0")]
2387 pub const fn count_zeros(self) -> u32 {
2388 (!self).count_ones()
2393 concat!("Returns the number of leading zeros in the binary representation of `self`.
2400 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2402 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2404 #[stable(feature = "rust1", since = "1.0.0")]
2406 pub const fn leading_zeros(self) -> u32 {
2407 intrinsics::ctlz(self as $ActualT) as u32
2412 concat!("Returns the number of trailing zeros in the binary representation
2420 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2422 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2424 #[stable(feature = "rust1", since = "1.0.0")]
2426 pub const fn trailing_zeros(self) -> u32 {
2427 intrinsics::cttz(self) as u32
2432 concat!("Shifts the bits to the left by a specified amount, `n`,
2433 wrapping the truncated bits to the end of the resulting integer.
2435 Please note this isn't the same operation as the `<<` shifting operator!
2442 let n = ", $rot_op, stringify!($SelfT), ";
2443 let m = ", $rot_result, ";
2445 assert_eq!(n.rotate_left(", $rot, "), m);
2447 #[stable(feature = "rust1", since = "1.0.0")]
2448 #[must_use = "this returns the result of the operation, \
2449 without modifying the original"]
2451 pub const fn rotate_left(self, n: u32) -> Self {
2452 intrinsics::rotate_left(self, n as $SelfT)
2457 concat!("Shifts the bits to the right by a specified amount, `n`,
2458 wrapping the truncated bits to the beginning of the resulting
2461 Please note this isn't the same operation as the `>>` shifting operator!
2468 let n = ", $rot_result, stringify!($SelfT), ";
2469 let m = ", $rot_op, ";
2471 assert_eq!(n.rotate_right(", $rot, "), m);
2473 #[stable(feature = "rust1", since = "1.0.0")]
2474 #[must_use = "this returns the result of the operation, \
2475 without modifying the original"]
2477 pub const fn rotate_right(self, n: u32) -> Self {
2478 intrinsics::rotate_right(self, n as $SelfT)
2484 Reverses the byte order of the integer.
2491 let n = ", $swap_op, stringify!($SelfT), ";
2492 let m = n.swap_bytes();
2494 assert_eq!(m, ", $swapped, ");
2496 #[stable(feature = "rust1", since = "1.0.0")]
2498 pub const fn swap_bytes(self) -> Self {
2499 intrinsics::bswap(self as $ActualT) as Self
2504 concat!("Reverses the bit pattern of the integer.
2511 let n = ", $swap_op, stringify!($SelfT), ";
2512 let m = n.reverse_bits();
2514 assert_eq!(m, ", $reversed, ");
2516 #[stable(feature = "reverse_bits", since = "1.37.0")]
2519 pub const fn reverse_bits(self) -> Self {
2520 intrinsics::bitreverse(self as $ActualT) as Self
2525 concat!("Converts an integer from big endian to the target's endianness.
2527 On big endian this is a no-op. On little endian the bytes are
2535 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2537 if cfg!(target_endian = \"big\") {
2538 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2540 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2543 #[stable(feature = "rust1", since = "1.0.0")]
2545 pub const fn from_be(x: Self) -> Self {
2546 #[cfg(target_endian = "big")]
2550 #[cfg(not(target_endian = "big"))]
2558 concat!("Converts an integer from little endian to the target's endianness.
2560 On little endian this is a no-op. On big endian the bytes are
2568 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2570 if cfg!(target_endian = \"little\") {
2571 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2573 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2576 #[stable(feature = "rust1", since = "1.0.0")]
2578 pub const fn from_le(x: Self) -> Self {
2579 #[cfg(target_endian = "little")]
2583 #[cfg(not(target_endian = "little"))]
2591 concat!("Converts `self` to big endian from the target's endianness.
2593 On big endian this is a no-op. On little endian the bytes are
2601 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2603 if cfg!(target_endian = \"big\") {
2604 assert_eq!(n.to_be(), n)
2606 assert_eq!(n.to_be(), n.swap_bytes())
2609 #[stable(feature = "rust1", since = "1.0.0")]
2611 pub const fn to_be(self) -> Self { // or not to be?
2612 #[cfg(target_endian = "big")]
2616 #[cfg(not(target_endian = "big"))]
2624 concat!("Converts `self` to little endian from the target's endianness.
2626 On little endian this is a no-op. On big endian the bytes are
2634 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2636 if cfg!(target_endian = \"little\") {
2637 assert_eq!(n.to_le(), n)
2639 assert_eq!(n.to_le(), n.swap_bytes())
2642 #[stable(feature = "rust1", since = "1.0.0")]
2644 pub const fn to_le(self) -> Self {
2645 #[cfg(target_endian = "little")]
2649 #[cfg(not(target_endian = "little"))]
2657 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2658 if overflow occurred.
2665 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2666 "Some(", stringify!($SelfT), "::max_value() - 1));
2667 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2669 #[stable(feature = "rust1", since = "1.0.0")]
2670 #[must_use = "this returns the result of the operation, \
2671 without modifying the original"]
2673 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2674 let (a, b) = self.overflowing_add(rhs);
2675 if b {None} else {Some(a)}
2680 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2681 `None` if overflow occurred.
2688 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2689 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2691 #[stable(feature = "rust1", since = "1.0.0")]
2692 #[must_use = "this returns the result of the operation, \
2693 without modifying the original"]
2695 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2696 let (a, b) = self.overflowing_sub(rhs);
2697 if b {None} else {Some(a)}
2702 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2703 `None` if overflow occurred.
2710 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2711 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2713 #[stable(feature = "rust1", since = "1.0.0")]
2714 #[must_use = "this returns the result of the operation, \
2715 without modifying the original"]
2717 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2718 let (a, b) = self.overflowing_mul(rhs);
2719 if b {None} else {Some(a)}
2724 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2732 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2733 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2735 #[stable(feature = "rust1", since = "1.0.0")]
2736 #[must_use = "this returns the result of the operation, \
2737 without modifying the original"]
2739 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2742 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2748 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2756 #![feature(euclidean_division)]
2757 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
2758 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
2760 #[unstable(feature = "euclidean_division", issue = "49048")]
2761 #[must_use = "this returns the result of the operation, \
2762 without modifying the original"]
2764 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
2768 Some(self.div_euclid(rhs))
2775 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2783 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2784 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2786 #[stable(feature = "wrapping", since = "1.7.0")]
2787 #[must_use = "this returns the result of the operation, \
2788 without modifying the original"]
2790 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2794 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2800 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
2808 #![feature(euclidean_division)]
2809 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
2810 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
2812 #[unstable(feature = "euclidean_division", issue = "49048")]
2813 #[must_use = "this returns the result of the operation, \
2814 without modifying the original"]
2816 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
2820 Some(self.rem_euclid(rhs))
2826 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2829 Note that negating any positive integer will overflow.
2836 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2837 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2839 #[stable(feature = "wrapping", since = "1.7.0")]
2841 pub fn checked_neg(self) -> Option<Self> {
2842 let (a, b) = self.overflowing_neg();
2843 if b {None} else {Some(a)}
2848 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2849 if `rhs` is larger than or equal to the number of bits in `self`.
2856 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2857 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2859 #[stable(feature = "wrapping", since = "1.7.0")]
2860 #[must_use = "this returns the result of the operation, \
2861 without modifying the original"]
2863 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2864 let (a, b) = self.overflowing_shl(rhs);
2865 if b {None} else {Some(a)}
2870 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2871 if `rhs` is larger than or equal to the number of bits in `self`.
2878 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2879 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2881 #[stable(feature = "wrapping", since = "1.7.0")]
2882 #[must_use = "this returns the result of the operation, \
2883 without modifying the original"]
2885 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2886 let (a, b) = self.overflowing_shr(rhs);
2887 if b {None} else {Some(a)}
2892 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2900 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2901 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2903 #[stable(feature = "no_panic_pow", since = "1.34.0")]
2904 #[must_use = "this returns the result of the operation, \
2905 without modifying the original"]
2907 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2908 let mut base = self;
2909 let mut acc: Self = 1;
2913 acc = acc.checked_mul(base)?;
2916 base = base.checked_mul(base)?;
2919 // Deal with the final bit of the exponent separately, since
2920 // squaring the base afterwards is not necessary and may cause a
2921 // needless overflow.
2923 acc = acc.checked_mul(base)?;
2931 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2932 the numeric bounds instead of overflowing.
2939 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2940 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2943 #[stable(feature = "rust1", since = "1.0.0")]
2944 #[must_use = "this returns the result of the operation, \
2945 without modifying the original"]
2946 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
2948 pub const fn saturating_add(self, rhs: Self) -> Self {
2949 intrinsics::saturating_add(self, rhs)
2954 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2955 at the numeric bounds instead of overflowing.
2962 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2963 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2965 #[stable(feature = "rust1", since = "1.0.0")]
2966 #[must_use = "this returns the result of the operation, \
2967 without modifying the original"]
2968 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
2970 pub const fn saturating_sub(self, rhs: Self) -> Self {
2971 intrinsics::saturating_sub(self, rhs)
2976 concat!("Saturating integer multiplication. Computes `self * rhs`,
2977 saturating at the numeric bounds instead of overflowing.
2984 ", $Feature, "use std::", stringify!($SelfT), ";
2986 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2987 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2988 "::MAX);", $EndFeature, "
2990 #[stable(feature = "wrapping", since = "1.7.0")]
2991 #[must_use = "this returns the result of the operation, \
2992 without modifying the original"]
2994 pub fn saturating_mul(self, rhs: Self) -> Self {
2995 self.checked_mul(rhs).unwrap_or(Self::max_value())
3000 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3001 saturating at the numeric bounds instead of overflowing.
3008 ", $Feature, "use std::", stringify!($SelfT), ";
3010 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3011 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3014 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3015 #[must_use = "this returns the result of the operation, \
3016 without modifying the original"]
3018 pub fn saturating_pow(self, exp: u32) -> Self {
3019 match self.checked_pow(exp) {
3021 None => Self::max_value(),
3027 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3028 wrapping around at the boundary of the type.
3035 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3036 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
3039 #[stable(feature = "rust1", since = "1.0.0")]
3040 #[must_use = "this returns the result of the operation, \
3041 without modifying the original"]
3043 pub const fn wrapping_add(self, rhs: Self) -> Self {
3044 intrinsics::overflowing_add(self, rhs)
3049 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3050 wrapping around at the boundary of the type.
3057 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3058 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
3061 #[stable(feature = "rust1", since = "1.0.0")]
3062 #[must_use = "this returns the result of the operation, \
3063 without modifying the original"]
3065 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3066 intrinsics::overflowing_sub(self, rhs)
3070 /// Wrapping (modular) multiplication. Computes `self *
3071 /// rhs`, wrapping around at the boundary of the type.
3077 /// Please note that this example is shared between integer types.
3078 /// Which explains why `u8` is used here.
3081 /// assert_eq!(10u8.wrapping_mul(12), 120);
3082 /// assert_eq!(25u8.wrapping_mul(12), 44);
3084 #[stable(feature = "rust1", since = "1.0.0")]
3085 #[must_use = "this returns the result of the operation, \
3086 without modifying the original"]
3088 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3089 intrinsics::overflowing_mul(self, rhs)
3093 concat!("Wrapping (modular) division. Computes `self / rhs`.
3094 Wrapped division on unsigned types is just normal division.
3095 There's no way wrapping could ever happen.
3096 This function exists, so that all operations
3097 are accounted for in the wrapping operations.
3104 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3106 #[stable(feature = "num_wrapping", since = "1.2.0")]
3107 #[must_use = "this returns the result of the operation, \
3108 without modifying the original"]
3110 pub fn wrapping_div(self, rhs: Self) -> Self {
3116 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3117 Wrapped division on unsigned types is just normal division.
3118 There's no way wrapping could ever happen.
3119 This function exists, so that all operations
3120 are accounted for in the wrapping operations.
3121 Since, for the positive integers, all common
3122 definitions of division are equal, this
3123 is exactly equal to `self.wrapping_div(rhs)`.
3130 #![feature(euclidean_division)]
3131 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3133 #[unstable(feature = "euclidean_division", issue = "49048")]
3134 #[must_use = "this returns the result of the operation, \
3135 without modifying the original"]
3137 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
3143 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3144 Wrapped remainder calculation on unsigned types is
3145 just the regular remainder calculation.
3146 There's no way wrapping could ever happen.
3147 This function exists, so that all operations
3148 are accounted for in the wrapping operations.
3155 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3157 #[stable(feature = "num_wrapping", since = "1.2.0")]
3158 #[must_use = "this returns the result of the operation, \
3159 without modifying the original"]
3161 pub fn wrapping_rem(self, rhs: Self) -> Self {
3167 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3168 Wrapped modulo calculation on unsigned types is
3169 just the regular remainder calculation.
3170 There's no way wrapping could ever happen.
3171 This function exists, so that all operations
3172 are accounted for in the wrapping operations.
3173 Since, for the positive integers, all common
3174 definitions of division are equal, this
3175 is exactly equal to `self.wrapping_rem(rhs)`.
3182 #![feature(euclidean_division)]
3183 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3185 #[unstable(feature = "euclidean_division", issue = "49048")]
3186 #[must_use = "this returns the result of the operation, \
3187 without modifying the original"]
3189 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3194 /// Wrapping (modular) negation. Computes `-self`,
3195 /// wrapping around at the boundary of the type.
3197 /// Since unsigned types do not have negative equivalents
3198 /// all applications of this function will wrap (except for `-0`).
3199 /// For values smaller than the corresponding signed type's maximum
3200 /// the result is the same as casting the corresponding signed value.
3201 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3202 /// `MAX` is the corresponding signed type's maximum.
3208 /// Please note that this example is shared between integer types.
3209 /// Which explains why `i8` is used here.
3212 /// assert_eq!(100i8.wrapping_neg(), -100);
3213 /// assert_eq!((-128i8).wrapping_neg(), -128);
3215 #[stable(feature = "num_wrapping", since = "1.2.0")]
3217 pub const fn wrapping_neg(self) -> Self {
3218 self.overflowing_neg().0
3222 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3223 where `mask` removes any high-order bits of `rhs` that
3224 would cause the shift to exceed the bitwidth of the type.
3226 Note that this is *not* the same as a rotate-left; the
3227 RHS of a wrapping shift-left is restricted to the range
3228 of the type, rather than the bits shifted out of the LHS
3229 being returned to the other end. The primitive integer
3230 types all implement a `rotate_left` function, which may
3231 be what you want instead.
3238 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3239 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3241 #[stable(feature = "num_wrapping", since = "1.2.0")]
3242 #[must_use = "this returns the result of the operation, \
3243 without modifying the original"]
3245 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3247 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3253 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3254 where `mask` removes any high-order bits of `rhs` that
3255 would cause the shift to exceed the bitwidth of the type.
3257 Note that this is *not* the same as a rotate-right; the
3258 RHS of a wrapping shift-right is restricted to the range
3259 of the type, rather than the bits shifted out of the LHS
3260 being returned to the other end. The primitive integer
3261 types all implement a `rotate_right` function, which may
3262 be what you want instead.
3269 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3270 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3272 #[stable(feature = "num_wrapping", since = "1.2.0")]
3273 #[must_use = "this returns the result of the operation, \
3274 without modifying the original"]
3276 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3278 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3284 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3285 wrapping around at the boundary of the type.
3292 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3293 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3295 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3296 #[must_use = "this returns the result of the operation, \
3297 without modifying the original"]
3299 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3300 let mut base = self;
3301 let mut acc: Self = 1;
3305 acc = acc.wrapping_mul(base);
3308 base = base.wrapping_mul(base);
3311 // Deal with the final bit of the exponent separately, since
3312 // squaring the base afterwards is not necessary and may cause a
3313 // needless overflow.
3315 acc = acc.wrapping_mul(base);
3323 concat!("Calculates `self` + `rhs`
3325 Returns a tuple of the addition along with a boolean indicating
3326 whether an arithmetic overflow would occur. If an overflow would
3327 have occurred then the wrapped value is returned.
3334 ", $Feature, "use std::", stringify!($SelfT), ";
3336 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3337 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3339 #[stable(feature = "wrapping", since = "1.7.0")]
3340 #[must_use = "this returns the result of the operation, \
3341 without modifying the original"]
3343 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3344 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3350 concat!("Calculates `self` - `rhs`
3352 Returns a tuple of the subtraction along with a boolean indicating
3353 whether an arithmetic overflow would occur. If an overflow would
3354 have occurred then the wrapped value is returned.
3361 ", $Feature, "use std::", stringify!($SelfT), ";
3363 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3364 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3367 #[stable(feature = "wrapping", since = "1.7.0")]
3368 #[must_use = "this returns the result of the operation, \
3369 without modifying the original"]
3371 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3372 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3377 /// Calculates the multiplication of `self` and `rhs`.
3379 /// Returns a tuple of the multiplication along with a boolean
3380 /// indicating whether an arithmetic overflow would occur. If an
3381 /// overflow would have occurred then the wrapped value is returned.
3387 /// Please note that this example is shared between integer types.
3388 /// Which explains why `u32` is used here.
3391 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3392 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3394 #[stable(feature = "wrapping", since = "1.7.0")]
3395 #[must_use = "this returns the result of the operation, \
3396 without modifying the original"]
3398 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3399 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3404 concat!("Calculates the divisor when `self` is divided by `rhs`.
3406 Returns a tuple of the divisor along with a boolean indicating
3407 whether an arithmetic overflow would occur. Note that for unsigned
3408 integers overflow never occurs, so the second value is always
3413 This function will panic if `rhs` is 0.
3420 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3423 #[stable(feature = "wrapping", since = "1.7.0")]
3424 #[must_use = "this returns the result of the operation, \
3425 without modifying the original"]
3426 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3432 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3434 Returns a tuple of the divisor along with a boolean indicating
3435 whether an arithmetic overflow would occur. Note that for unsigned
3436 integers overflow never occurs, so the second value is always
3438 Since, for the positive integers, all common
3439 definitions of division are equal, this
3440 is exactly equal to `self.overflowing_div(rhs)`.
3444 This function will panic if `rhs` is 0.
3451 #![feature(euclidean_division)]
3452 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3455 #[unstable(feature = "euclidean_division", issue = "49048")]
3456 #[must_use = "this returns the result of the operation, \
3457 without modifying the original"]
3458 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3464 concat!("Calculates the remainder when `self` is divided by `rhs`.
3466 Returns a tuple of the remainder after dividing along with a boolean
3467 indicating whether an arithmetic overflow would occur. Note that for
3468 unsigned integers overflow never occurs, so the second value is
3473 This function will panic if `rhs` is 0.
3480 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3483 #[stable(feature = "wrapping", since = "1.7.0")]
3484 #[must_use = "this returns the result of the operation, \
3485 without modifying the original"]
3486 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3492 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3494 Returns a tuple of the modulo after dividing along with a boolean
3495 indicating whether an arithmetic overflow would occur. Note that for
3496 unsigned integers overflow never occurs, so the second value is
3498 Since, for the positive integers, all common
3499 definitions of division are equal, this operation
3500 is exactly equal to `self.overflowing_rem(rhs)`.
3504 This function will panic if `rhs` is 0.
3511 #![feature(euclidean_division)]
3512 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3515 #[unstable(feature = "euclidean_division", issue = "49048")]
3516 #[must_use = "this returns the result of the operation, \
3517 without modifying the original"]
3518 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3524 concat!("Negates self in an overflowing fashion.
3526 Returns `!self + 1` using wrapping operations to return the value
3527 that represents the negation of this unsigned value. Note that for
3528 positive unsigned values overflow always occurs, but negating 0 does
3536 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3537 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3538 ", true));", $EndFeature, "
3541 #[stable(feature = "wrapping", since = "1.7.0")]
3542 pub const fn overflowing_neg(self) -> (Self, bool) {
3543 ((!self).wrapping_add(1), self != 0)
3548 concat!("Shifts self left by `rhs` bits.
3550 Returns a tuple of the shifted version of self along with a boolean
3551 indicating whether the shift value was larger than or equal to the
3552 number of bits. If the shift value is too large, then value is
3553 masked (N-1) where N is the number of bits, and this value is then
3554 used to perform the shift.
3561 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3562 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3564 #[stable(feature = "wrapping", since = "1.7.0")]
3565 #[must_use = "this returns the result of the operation, \
3566 without modifying the original"]
3568 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3569 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3574 concat!("Shifts self right by `rhs` bits.
3576 Returns a tuple of the shifted version of self along with a boolean
3577 indicating whether the shift value was larger than or equal to the
3578 number of bits. If the shift value is too large, then value is
3579 masked (N-1) where N is the number of bits, and this value is then
3580 used to perform the shift.
3587 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3588 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3590 #[stable(feature = "wrapping", since = "1.7.0")]
3591 #[must_use = "this returns the result of the operation, \
3592 without modifying the original"]
3594 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3595 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3600 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3602 Returns a tuple of the exponentiation along with a bool indicating
3603 whether an overflow happened.
3610 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3611 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3613 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3614 #[must_use = "this returns the result of the operation, \
3615 without modifying the original"]
3617 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3618 let mut base = self;
3619 let mut acc: Self = 1;
3620 let mut overflown = false;
3621 // Scratch space for storing results of overflowing_mul.
3626 r = acc.overflowing_mul(base);
3631 r = base.overflowing_mul(base);
3636 // Deal with the final bit of the exponent separately, since
3637 // squaring the base afterwards is not necessary and may cause a
3638 // needless overflow.
3640 r = acc.overflowing_mul(base);
3650 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3657 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3659 #[stable(feature = "rust1", since = "1.0.0")]
3660 #[must_use = "this returns the result of the operation, \
3661 without modifying the original"]
3663 #[rustc_inherit_overflow_checks]
3664 pub fn pow(self, mut exp: u32) -> Self {
3665 let mut base = self;
3676 // Deal with the final bit of the exponent separately, since
3677 // squaring the base afterwards is not necessary and may cause a
3678 // needless overflow.
3688 concat!("Performs Euclidean division.
3690 Since, for the positive integers, all common
3691 definitions of division are equal, this
3692 is exactly equal to `self / rhs`.
3699 #![feature(euclidean_division)]
3700 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
3702 #[unstable(feature = "euclidean_division", issue = "49048")]
3703 #[must_use = "this returns the result of the operation, \
3704 without modifying the original"]
3706 #[rustc_inherit_overflow_checks]
3707 pub fn div_euclid(self, rhs: Self) -> Self {
3714 concat!("Calculates the least remainder of `self (mod rhs)`.
3716 Since, for the positive integers, all common
3717 definitions of division are equal, this
3718 is exactly equal to `self % rhs`.
3725 #![feature(euclidean_division)]
3726 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
3728 #[unstable(feature = "euclidean_division", issue = "49048")]
3729 #[must_use = "this returns the result of the operation, \
3730 without modifying the original"]
3732 #[rustc_inherit_overflow_checks]
3733 pub fn rem_euclid(self, rhs: Self) -> Self {
3739 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3746 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3747 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3749 #[stable(feature = "rust1", since = "1.0.0")]
3751 pub fn is_power_of_two(self) -> bool {
3752 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3756 // Returns one less than next power of two.
3757 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3759 // 8u8.one_less_than_next_power_of_two() == 7
3760 // 6u8.one_less_than_next_power_of_two() == 7
3762 // This method cannot overflow, as in the `next_power_of_two`
3763 // overflow cases it instead ends up returning the maximum value
3764 // of the type, and can return 0 for 0.
3766 fn one_less_than_next_power_of_two(self) -> Self {
3767 if self <= 1 { return 0; }
3769 // Because `p > 0`, it cannot consist entirely of leading zeros.
3770 // That means the shift is always in-bounds, and some processors
3771 // (such as intel pre-haswell) have more efficient ctlz
3772 // intrinsics when the argument is non-zero.
3774 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3775 <$SelfT>::max_value() >> z
3779 concat!("Returns the smallest power of two greater than or equal to `self`.
3781 When return value overflows (i.e., `self > (1 << (N-1))` for type
3782 `uN`), it panics in debug mode and return value is wrapped to 0 in
3783 release mode (the only situation in which method can return 0).
3790 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3791 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3793 #[stable(feature = "rust1", since = "1.0.0")]
3795 pub fn next_power_of_two(self) -> Self {
3796 // Call the trait to get overflow checks
3797 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3802 concat!("Returns the smallest power of two greater than or equal to `n`. If
3803 the next power of two is greater than the type's maximum value,
3804 `None` is returned, otherwise the power of two is wrapped in `Some`.
3811 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3812 ".checked_next_power_of_two(), Some(2));
3813 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3814 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3818 #[stable(feature = "rust1", since = "1.0.0")]
3819 pub fn checked_next_power_of_two(self) -> Option<Self> {
3820 self.one_less_than_next_power_of_two().checked_add(1)
3825 concat!("Returns the smallest power of two greater than or equal to `n`. If
3826 the next power of two is greater than the type's maximum value,
3827 the return value is wrapped to `0`.
3834 #![feature(wrapping_next_power_of_two)]
3836 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3837 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3838 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3841 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3842 reason = "needs decision on wrapping behaviour")]
3843 pub fn wrapping_next_power_of_two(self) -> Self {
3844 self.one_less_than_next_power_of_two().wrapping_add(1)
3849 concat!("Return the memory representation of this integer as a byte array in
3850 big-endian (network) byte order.
3857 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
3858 assert_eq!(bytes, ", $be_bytes, ");
3860 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3861 #[rustc_const_unstable(feature = "const_int_conversion")]
3863 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
3864 self.to_be().to_ne_bytes()
3869 concat!("Return the memory representation of this integer as a byte array in
3870 little-endian byte order.
3877 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
3878 assert_eq!(bytes, ", $le_bytes, ");
3880 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3881 #[rustc_const_unstable(feature = "const_int_conversion")]
3883 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
3884 self.to_le().to_ne_bytes()
3890 Return the memory representation of this integer as a byte array in
3893 As the target platform's native endianness is used, portable code
3894 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3899 [`to_be_bytes`]: #method.to_be_bytes
3900 [`to_le_bytes`]: #method.to_le_bytes
3905 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
3906 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
3912 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3913 #[rustc_const_unstable(feature = "const_int_conversion")]
3915 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
3916 unsafe { mem::transmute(self) }
3921 concat!("Create an integer value from its representation as a byte array in
3929 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
3930 assert_eq!(value, ", $swap_op, ");
3933 When starting from a slice rather than an array, fallible conversion APIs can be used:
3936 use std::convert::TryInto;
3938 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3939 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3941 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
3944 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3945 #[rustc_const_unstable(feature = "const_int_conversion")]
3947 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3948 Self::from_be(Self::from_ne_bytes(bytes))
3954 Create an integer value from its representation as a byte array in
3962 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
3963 assert_eq!(value, ", $swap_op, ");
3966 When starting from a slice rather than an array, fallible conversion APIs can be used:
3969 use std::convert::TryInto;
3971 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3972 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3974 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
3977 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3978 #[rustc_const_unstable(feature = "const_int_conversion")]
3980 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3981 Self::from_le(Self::from_ne_bytes(bytes))
3986 concat!("Create an integer value from its memory representation as a byte
3987 array in native endianness.
3989 As the target platform's native endianness is used, portable code
3990 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3991 appropriate instead.
3993 [`from_be_bytes`]: #method.from_be_bytes
3994 [`from_le_bytes`]: #method.from_le_bytes
4001 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4006 assert_eq!(value, ", $swap_op, ");
4009 When starting from a slice rather than an array, fallible conversion APIs can be used:
4012 use std::convert::TryInto;
4014 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4015 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4017 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4020 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4021 #[rustc_const_unstable(feature = "const_int_conversion")]
4023 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4024 unsafe { mem::transmute(bytes) }
4032 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4036 /// Checks if the value is within the ASCII range.
4041 /// let ascii = 97u8;
4042 /// let non_ascii = 150u8;
4044 /// assert!(ascii.is_ascii());
4045 /// assert!(!non_ascii.is_ascii());
4047 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4049 pub fn is_ascii(&self) -> bool {
4053 /// Makes a copy of the value in its ASCII upper case equivalent.
4055 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4056 /// but non-ASCII letters are unchanged.
4058 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4063 /// let lowercase_a = 97u8;
4065 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4068 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4069 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4071 pub fn to_ascii_uppercase(&self) -> u8 {
4072 // Unset the fith bit if this is a lowercase letter
4073 *self & !((self.is_ascii_lowercase() as u8) << 5)
4076 /// Makes a copy of the value in its ASCII lower case equivalent.
4078 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4079 /// but non-ASCII letters are unchanged.
4081 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4086 /// let uppercase_a = 65u8;
4088 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4091 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4092 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4094 pub fn to_ascii_lowercase(&self) -> u8 {
4095 // Set the fith bit if this is an uppercase letter
4096 *self | ((self.is_ascii_uppercase() as u8) << 5)
4099 /// Checks that two values are an ASCII case-insensitive match.
4101 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4106 /// let lowercase_a = 97u8;
4107 /// let uppercase_a = 65u8;
4109 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4111 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4113 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4114 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4117 /// Converts this value to its ASCII upper case equivalent in-place.
4119 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4120 /// but non-ASCII letters are unchanged.
4122 /// To return a new uppercased value without modifying the existing one, use
4123 /// [`to_ascii_uppercase`].
4128 /// let mut byte = b'a';
4130 /// byte.make_ascii_uppercase();
4132 /// assert_eq!(b'A', byte);
4135 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4136 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4138 pub fn make_ascii_uppercase(&mut self) {
4139 *self = self.to_ascii_uppercase();
4142 /// Converts this value to its ASCII lower case equivalent in-place.
4144 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4145 /// but non-ASCII letters are unchanged.
4147 /// To return a new lowercased value without modifying the existing one, use
4148 /// [`to_ascii_lowercase`].
4153 /// let mut byte = b'A';
4155 /// byte.make_ascii_lowercase();
4157 /// assert_eq!(b'a', byte);
4160 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4161 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4163 pub fn make_ascii_lowercase(&mut self) {
4164 *self = self.to_ascii_lowercase();
4167 /// Checks if the value is an ASCII alphabetic character:
4169 /// - U+0041 'A' ... U+005A 'Z', or
4170 /// - U+0061 'a' ... U+007A 'z'.
4175 /// let uppercase_a = b'A';
4176 /// let uppercase_g = b'G';
4179 /// let zero = b'0';
4180 /// let percent = b'%';
4181 /// let space = b' ';
4183 /// let esc = 0x1b_u8;
4185 /// assert!(uppercase_a.is_ascii_alphabetic());
4186 /// assert!(uppercase_g.is_ascii_alphabetic());
4187 /// assert!(a.is_ascii_alphabetic());
4188 /// assert!(g.is_ascii_alphabetic());
4189 /// assert!(!zero.is_ascii_alphabetic());
4190 /// assert!(!percent.is_ascii_alphabetic());
4191 /// assert!(!space.is_ascii_alphabetic());
4192 /// assert!(!lf.is_ascii_alphabetic());
4193 /// assert!(!esc.is_ascii_alphabetic());
4195 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4197 pub fn is_ascii_alphabetic(&self) -> bool {
4199 b'A'..=b'Z' | b'a'..=b'z' => true,
4204 /// Checks if the value is an ASCII uppercase character:
4205 /// U+0041 'A' ... U+005A 'Z'.
4210 /// let uppercase_a = b'A';
4211 /// let uppercase_g = b'G';
4214 /// let zero = b'0';
4215 /// let percent = b'%';
4216 /// let space = b' ';
4218 /// let esc = 0x1b_u8;
4220 /// assert!(uppercase_a.is_ascii_uppercase());
4221 /// assert!(uppercase_g.is_ascii_uppercase());
4222 /// assert!(!a.is_ascii_uppercase());
4223 /// assert!(!g.is_ascii_uppercase());
4224 /// assert!(!zero.is_ascii_uppercase());
4225 /// assert!(!percent.is_ascii_uppercase());
4226 /// assert!(!space.is_ascii_uppercase());
4227 /// assert!(!lf.is_ascii_uppercase());
4228 /// assert!(!esc.is_ascii_uppercase());
4230 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4232 pub fn is_ascii_uppercase(&self) -> bool {
4234 b'A'..=b'Z' => true,
4239 /// Checks if the value is an ASCII lowercase character:
4240 /// U+0061 'a' ... U+007A 'z'.
4245 /// let uppercase_a = b'A';
4246 /// let uppercase_g = b'G';
4249 /// let zero = b'0';
4250 /// let percent = b'%';
4251 /// let space = b' ';
4253 /// let esc = 0x1b_u8;
4255 /// assert!(!uppercase_a.is_ascii_lowercase());
4256 /// assert!(!uppercase_g.is_ascii_lowercase());
4257 /// assert!(a.is_ascii_lowercase());
4258 /// assert!(g.is_ascii_lowercase());
4259 /// assert!(!zero.is_ascii_lowercase());
4260 /// assert!(!percent.is_ascii_lowercase());
4261 /// assert!(!space.is_ascii_lowercase());
4262 /// assert!(!lf.is_ascii_lowercase());
4263 /// assert!(!esc.is_ascii_lowercase());
4265 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4267 pub fn is_ascii_lowercase(&self) -> bool {
4269 b'a'..=b'z' => true,
4274 /// Checks if the value is an ASCII alphanumeric character:
4276 /// - U+0041 'A' ... U+005A 'Z', or
4277 /// - U+0061 'a' ... U+007A 'z', or
4278 /// - U+0030 '0' ... U+0039 '9'.
4283 /// let uppercase_a = b'A';
4284 /// let uppercase_g = b'G';
4287 /// let zero = b'0';
4288 /// let percent = b'%';
4289 /// let space = b' ';
4291 /// let esc = 0x1b_u8;
4293 /// assert!(uppercase_a.is_ascii_alphanumeric());
4294 /// assert!(uppercase_g.is_ascii_alphanumeric());
4295 /// assert!(a.is_ascii_alphanumeric());
4296 /// assert!(g.is_ascii_alphanumeric());
4297 /// assert!(zero.is_ascii_alphanumeric());
4298 /// assert!(!percent.is_ascii_alphanumeric());
4299 /// assert!(!space.is_ascii_alphanumeric());
4300 /// assert!(!lf.is_ascii_alphanumeric());
4301 /// assert!(!esc.is_ascii_alphanumeric());
4303 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4305 pub fn is_ascii_alphanumeric(&self) -> bool {
4307 b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' => true,
4312 /// Checks if the value is an ASCII decimal digit:
4313 /// U+0030 '0' ... U+0039 '9'.
4318 /// let uppercase_a = b'A';
4319 /// let uppercase_g = b'G';
4322 /// let zero = b'0';
4323 /// let percent = b'%';
4324 /// let space = b' ';
4326 /// let esc = 0x1b_u8;
4328 /// assert!(!uppercase_a.is_ascii_digit());
4329 /// assert!(!uppercase_g.is_ascii_digit());
4330 /// assert!(!a.is_ascii_digit());
4331 /// assert!(!g.is_ascii_digit());
4332 /// assert!(zero.is_ascii_digit());
4333 /// assert!(!percent.is_ascii_digit());
4334 /// assert!(!space.is_ascii_digit());
4335 /// assert!(!lf.is_ascii_digit());
4336 /// assert!(!esc.is_ascii_digit());
4338 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4340 pub fn is_ascii_digit(&self) -> bool {
4342 b'0'..=b'9' => true,
4347 /// Checks if the value is an ASCII hexadecimal digit:
4349 /// - U+0030 '0' ... U+0039 '9', or
4350 /// - U+0041 'A' ... U+0046 'F', or
4351 /// - U+0061 'a' ... U+0066 'f'.
4356 /// let uppercase_a = b'A';
4357 /// let uppercase_g = b'G';
4360 /// let zero = b'0';
4361 /// let percent = b'%';
4362 /// let space = b' ';
4364 /// let esc = 0x1b_u8;
4366 /// assert!(uppercase_a.is_ascii_hexdigit());
4367 /// assert!(!uppercase_g.is_ascii_hexdigit());
4368 /// assert!(a.is_ascii_hexdigit());
4369 /// assert!(!g.is_ascii_hexdigit());
4370 /// assert!(zero.is_ascii_hexdigit());
4371 /// assert!(!percent.is_ascii_hexdigit());
4372 /// assert!(!space.is_ascii_hexdigit());
4373 /// assert!(!lf.is_ascii_hexdigit());
4374 /// assert!(!esc.is_ascii_hexdigit());
4376 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4378 pub fn is_ascii_hexdigit(&self) -> bool {
4380 b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f' => true,
4385 /// Checks if the value is an ASCII punctuation character:
4387 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
4388 /// - U+003A ... U+0040 `: ; < = > ? @`, or
4389 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
4390 /// - U+007B ... U+007E `{ | } ~`
4395 /// let uppercase_a = b'A';
4396 /// let uppercase_g = b'G';
4399 /// let zero = b'0';
4400 /// let percent = b'%';
4401 /// let space = b' ';
4403 /// let esc = 0x1b_u8;
4405 /// assert!(!uppercase_a.is_ascii_punctuation());
4406 /// assert!(!uppercase_g.is_ascii_punctuation());
4407 /// assert!(!a.is_ascii_punctuation());
4408 /// assert!(!g.is_ascii_punctuation());
4409 /// assert!(!zero.is_ascii_punctuation());
4410 /// assert!(percent.is_ascii_punctuation());
4411 /// assert!(!space.is_ascii_punctuation());
4412 /// assert!(!lf.is_ascii_punctuation());
4413 /// assert!(!esc.is_ascii_punctuation());
4415 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4417 pub fn is_ascii_punctuation(&self) -> bool {
4419 b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~' => true,
4424 /// Checks if the value is an ASCII graphic character:
4425 /// U+0021 '!' ... U+007E '~'.
4430 /// let uppercase_a = b'A';
4431 /// let uppercase_g = b'G';
4434 /// let zero = b'0';
4435 /// let percent = b'%';
4436 /// let space = b' ';
4438 /// let esc = 0x1b_u8;
4440 /// assert!(uppercase_a.is_ascii_graphic());
4441 /// assert!(uppercase_g.is_ascii_graphic());
4442 /// assert!(a.is_ascii_graphic());
4443 /// assert!(g.is_ascii_graphic());
4444 /// assert!(zero.is_ascii_graphic());
4445 /// assert!(percent.is_ascii_graphic());
4446 /// assert!(!space.is_ascii_graphic());
4447 /// assert!(!lf.is_ascii_graphic());
4448 /// assert!(!esc.is_ascii_graphic());
4450 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4452 pub fn is_ascii_graphic(&self) -> bool {
4454 b'!'..=b'~' => true,
4459 /// Checks if the value is an ASCII whitespace character:
4460 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4461 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4463 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4464 /// whitespace][infra-aw]. There are several other definitions in
4465 /// wide use. For instance, [the POSIX locale][pct] includes
4466 /// U+000B VERTICAL TAB as well as all the above characters,
4467 /// but—from the very same specification—[the default rule for
4468 /// "field splitting" in the Bourne shell][bfs] considers *only*
4469 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4471 /// If you are writing a program that will process an existing
4472 /// file format, check what that format's definition of whitespace is
4473 /// before using this function.
4475 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4476 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4477 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4482 /// let uppercase_a = b'A';
4483 /// let uppercase_g = b'G';
4486 /// let zero = b'0';
4487 /// let percent = b'%';
4488 /// let space = b' ';
4490 /// let esc = 0x1b_u8;
4492 /// assert!(!uppercase_a.is_ascii_whitespace());
4493 /// assert!(!uppercase_g.is_ascii_whitespace());
4494 /// assert!(!a.is_ascii_whitespace());
4495 /// assert!(!g.is_ascii_whitespace());
4496 /// assert!(!zero.is_ascii_whitespace());
4497 /// assert!(!percent.is_ascii_whitespace());
4498 /// assert!(space.is_ascii_whitespace());
4499 /// assert!(lf.is_ascii_whitespace());
4500 /// assert!(!esc.is_ascii_whitespace());
4502 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4504 pub fn is_ascii_whitespace(&self) -> bool {
4506 b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' => true,
4511 /// Checks if the value is an ASCII control character:
4512 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4513 /// Note that most ASCII whitespace characters are control
4514 /// characters, but SPACE is not.
4519 /// let uppercase_a = b'A';
4520 /// let uppercase_g = b'G';
4523 /// let zero = b'0';
4524 /// let percent = b'%';
4525 /// let space = b' ';
4527 /// let esc = 0x1b_u8;
4529 /// assert!(!uppercase_a.is_ascii_control());
4530 /// assert!(!uppercase_g.is_ascii_control());
4531 /// assert!(!a.is_ascii_control());
4532 /// assert!(!g.is_ascii_control());
4533 /// assert!(!zero.is_ascii_control());
4534 /// assert!(!percent.is_ascii_control());
4535 /// assert!(!space.is_ascii_control());
4536 /// assert!(lf.is_ascii_control());
4537 /// assert!(esc.is_ascii_control());
4539 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4541 pub fn is_ascii_control(&self) -> bool {
4543 b'\0'..=b'\x1F' | b'\x7F' => true,
4551 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4552 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4557 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4558 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4563 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4564 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4565 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4566 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4572 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4573 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4574 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4575 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4576 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4577 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4578 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4582 #[cfg(target_pointer_width = "16")]
4585 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4586 "[0x34, 0x12]", "[0x12, 0x34]",
4587 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4589 #[cfg(target_pointer_width = "32")]
4592 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4593 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4594 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4597 #[cfg(target_pointer_width = "64")]
4600 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4601 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4602 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4603 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4604 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4607 /// A classification of floating point numbers.
4609 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4610 /// their documentation for more.
4612 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4613 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4618 /// use std::num::FpCategory;
4621 /// let num = 12.4_f32;
4622 /// let inf = f32::INFINITY;
4623 /// let zero = 0f32;
4624 /// let sub: f32 = 1.1754942e-38;
4625 /// let nan = f32::NAN;
4627 /// assert_eq!(num.classify(), FpCategory::Normal);
4628 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4629 /// assert_eq!(zero.classify(), FpCategory::Zero);
4630 /// assert_eq!(nan.classify(), FpCategory::Nan);
4631 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4633 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4634 #[stable(feature = "rust1", since = "1.0.0")]
4635 pub enum FpCategory {
4636 /// "Not a Number", often obtained by dividing by zero.
4637 #[stable(feature = "rust1", since = "1.0.0")]
4640 /// Positive or negative infinity.
4641 #[stable(feature = "rust1", since = "1.0.0")]
4644 /// Positive or negative zero.
4645 #[stable(feature = "rust1", since = "1.0.0")]
4648 /// De-normalized floating point representation (less precise than `Normal`).
4649 #[stable(feature = "rust1", since = "1.0.0")]
4652 /// A regular floating point number.
4653 #[stable(feature = "rust1", since = "1.0.0")]
4657 macro_rules! from_str_radix_int_impl {
4659 #[stable(feature = "rust1", since = "1.0.0")]
4660 impl FromStr for $t {
4661 type Err = ParseIntError;
4662 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4663 from_str_radix(src, 10)
4668 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4670 /// The error type returned when a checked integral type conversion fails.
4671 #[stable(feature = "try_from", since = "1.34.0")]
4672 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4673 pub struct TryFromIntError(());
4675 impl TryFromIntError {
4676 #[unstable(feature = "int_error_internals",
4677 reason = "available through Error trait and this method should \
4678 not be exposed publicly",
4681 pub fn __description(&self) -> &str {
4682 "out of range integral type conversion attempted"
4686 #[stable(feature = "try_from", since = "1.34.0")]
4687 impl fmt::Display for TryFromIntError {
4688 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4689 self.__description().fmt(fmt)
4693 #[stable(feature = "try_from", since = "1.34.0")]
4694 impl From<Infallible> for TryFromIntError {
4695 fn from(x: Infallible) -> TryFromIntError {
4700 #[unstable(feature = "never_type", issue = "35121")]
4701 impl From<!> for TryFromIntError {
4702 fn from(never: !) -> TryFromIntError {
4703 // Match rather than coerce to make sure that code like
4704 // `From<Infallible> for TryFromIntError` above will keep working
4705 // when `Infallible` becomes an alias to `!`.
4710 // no possible bounds violation
4711 macro_rules! try_from_unbounded {
4712 ($source:ty, $($target:ty),*) => {$(
4713 #[stable(feature = "try_from", since = "1.34.0")]
4714 impl TryFrom<$source> for $target {
4715 type Error = TryFromIntError;
4717 /// Try to create the target number type from a source
4718 /// number type. This returns an error if the source value
4719 /// is outside of the range of the target type.
4721 fn try_from(value: $source) -> Result<Self, Self::Error> {
4722 Ok(value as $target)
4728 // only negative bounds
4729 macro_rules! try_from_lower_bounded {
4730 ($source:ty, $($target:ty),*) => {$(
4731 #[stable(feature = "try_from", since = "1.34.0")]
4732 impl TryFrom<$source> for $target {
4733 type Error = TryFromIntError;
4735 /// Try to create the target number type from a source
4736 /// number type. This returns an error if the source value
4737 /// is outside of the range of the target type.
4739 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4743 Err(TryFromIntError(()))
4750 // unsigned to signed (only positive bound)
4751 macro_rules! try_from_upper_bounded {
4752 ($source:ty, $($target:ty),*) => {$(
4753 #[stable(feature = "try_from", since = "1.34.0")]
4754 impl TryFrom<$source> for $target {
4755 type Error = TryFromIntError;
4757 /// Try to create the target number type from a source
4758 /// number type. This returns an error if the source value
4759 /// is outside of the range of the target type.
4761 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4762 if u > (<$target>::max_value() as $source) {
4763 Err(TryFromIntError(()))
4773 macro_rules! try_from_both_bounded {
4774 ($source:ty, $($target:ty),*) => {$(
4775 #[stable(feature = "try_from", since = "1.34.0")]
4776 impl TryFrom<$source> for $target {
4777 type Error = TryFromIntError;
4779 /// Try to create the target number type from a source
4780 /// number type. This returns an error if the source value
4781 /// is outside of the range of the target type.
4783 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4784 let min = <$target>::min_value() as $source;
4785 let max = <$target>::max_value() as $source;
4786 if u < min || u > max {
4787 Err(TryFromIntError(()))
4797 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4798 $mac!($target, $source);
4802 // intra-sign conversions
4803 try_from_upper_bounded!(u16, u8);
4804 try_from_upper_bounded!(u32, u16, u8);
4805 try_from_upper_bounded!(u64, u32, u16, u8);
4806 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4808 try_from_both_bounded!(i16, i8);
4809 try_from_both_bounded!(i32, i16, i8);
4810 try_from_both_bounded!(i64, i32, i16, i8);
4811 try_from_both_bounded!(i128, i64, i32, i16, i8);
4813 // unsigned-to-signed
4814 try_from_upper_bounded!(u8, i8);
4815 try_from_upper_bounded!(u16, i8, i16);
4816 try_from_upper_bounded!(u32, i8, i16, i32);
4817 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4818 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4820 // signed-to-unsigned
4821 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4822 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4823 try_from_lower_bounded!(i32, u32, u64, u128);
4824 try_from_lower_bounded!(i64, u64, u128);
4825 try_from_lower_bounded!(i128, u128);
4826 try_from_both_bounded!(i16, u8);
4827 try_from_both_bounded!(i32, u16, u8);
4828 try_from_both_bounded!(i64, u32, u16, u8);
4829 try_from_both_bounded!(i128, u64, u32, u16, u8);
4832 try_from_upper_bounded!(usize, isize);
4833 try_from_lower_bounded!(isize, usize);
4835 #[cfg(target_pointer_width = "16")]
4836 mod ptr_try_from_impls {
4837 use super::TryFromIntError;
4838 use crate::convert::TryFrom;
4840 try_from_upper_bounded!(usize, u8);
4841 try_from_unbounded!(usize, u16, u32, u64, u128);
4842 try_from_upper_bounded!(usize, i8, i16);
4843 try_from_unbounded!(usize, i32, i64, i128);
4845 try_from_both_bounded!(isize, u8);
4846 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4847 try_from_both_bounded!(isize, i8);
4848 try_from_unbounded!(isize, i16, i32, i64, i128);
4850 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4851 rev!(try_from_lower_bounded, usize, i8, i16);
4852 rev!(try_from_both_bounded, usize, i32, i64, i128);
4854 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4855 rev!(try_from_both_bounded, isize, i32, i64, i128);
4858 #[cfg(target_pointer_width = "32")]
4859 mod ptr_try_from_impls {
4860 use super::TryFromIntError;
4861 use crate::convert::TryFrom;
4863 try_from_upper_bounded!(usize, u8, u16);
4864 try_from_unbounded!(usize, u32, u64, u128);
4865 try_from_upper_bounded!(usize, i8, i16, i32);
4866 try_from_unbounded!(usize, i64, i128);
4868 try_from_both_bounded!(isize, u8, u16);
4869 try_from_lower_bounded!(isize, u32, u64, u128);
4870 try_from_both_bounded!(isize, i8, i16);
4871 try_from_unbounded!(isize, i32, i64, i128);
4873 rev!(try_from_unbounded, usize, u32);
4874 rev!(try_from_upper_bounded, usize, u64, u128);
4875 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4876 rev!(try_from_both_bounded, usize, i64, i128);
4878 rev!(try_from_unbounded, isize, u16);
4879 rev!(try_from_upper_bounded, isize, u32, u64, u128);
4880 rev!(try_from_unbounded, isize, i32);
4881 rev!(try_from_both_bounded, isize, i64, i128);
4884 #[cfg(target_pointer_width = "64")]
4885 mod ptr_try_from_impls {
4886 use super::TryFromIntError;
4887 use crate::convert::TryFrom;
4889 try_from_upper_bounded!(usize, u8, u16, u32);
4890 try_from_unbounded!(usize, u64, u128);
4891 try_from_upper_bounded!(usize, i8, i16, i32, i64);
4892 try_from_unbounded!(usize, i128);
4894 try_from_both_bounded!(isize, u8, u16, u32);
4895 try_from_lower_bounded!(isize, u64, u128);
4896 try_from_both_bounded!(isize, i8, i16, i32);
4897 try_from_unbounded!(isize, i64, i128);
4899 rev!(try_from_unbounded, usize, u32, u64);
4900 rev!(try_from_upper_bounded, usize, u128);
4901 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4902 rev!(try_from_both_bounded, usize, i128);
4904 rev!(try_from_unbounded, isize, u16, u32);
4905 rev!(try_from_upper_bounded, isize, u64, u128);
4906 rev!(try_from_unbounded, isize, i32, i64);
4907 rev!(try_from_both_bounded, isize, i128);
4911 trait FromStrRadixHelper: PartialOrd + Copy {
4912 fn min_value() -> Self;
4913 fn max_value() -> Self;
4914 fn from_u32(u: u32) -> Self;
4915 fn checked_mul(&self, other: u32) -> Option<Self>;
4916 fn checked_sub(&self, other: u32) -> Option<Self>;
4917 fn checked_add(&self, other: u32) -> Option<Self>;
4921 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4923 fn min_value() -> Self { Self::min_value() }
4925 fn max_value() -> Self { Self::max_value() }
4927 fn from_u32(u: u32) -> Self { u as Self }
4929 fn checked_mul(&self, other: u32) -> Option<Self> {
4930 Self::checked_mul(*self, other as Self)
4933 fn checked_sub(&self, other: u32) -> Option<Self> {
4934 Self::checked_sub(*self, other as Self)
4937 fn checked_add(&self, other: u32) -> Option<Self> {
4938 Self::checked_add(*self, other as Self)
4942 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4944 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4945 use self::IntErrorKind::*;
4946 use self::ParseIntError as PIE;
4948 assert!(radix >= 2 && radix <= 36,
4949 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4953 return Err(PIE { kind: Empty });
4956 let is_signed_ty = T::from_u32(0) > T::min_value();
4958 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4959 // and cast them to chars. .to_digit() will safely return None for anything
4960 // other than a valid ascii digit for the given radix, including the first-byte
4961 // of multi-byte sequences
4962 let src = src.as_bytes();
4964 let (is_positive, digits) = match src[0] {
4965 b'+' => (true, &src[1..]),
4966 b'-' if is_signed_ty => (false, &src[1..]),
4970 if digits.is_empty() {
4971 return Err(PIE { kind: Empty });
4974 let mut result = T::from_u32(0);
4976 // The number is positive
4978 let x = match (c as char).to_digit(radix) {
4980 None => return Err(PIE { kind: InvalidDigit }),
4982 result = match result.checked_mul(radix) {
4983 Some(result) => result,
4984 None => return Err(PIE { kind: Overflow }),
4986 result = match result.checked_add(x) {
4987 Some(result) => result,
4988 None => return Err(PIE { kind: Overflow }),
4992 // The number is negative
4994 let x = match (c as char).to_digit(radix) {
4996 None => return Err(PIE { kind: InvalidDigit }),
4998 result = match result.checked_mul(radix) {
4999 Some(result) => result,
5000 None => return Err(PIE { kind: Underflow }),
5002 result = match result.checked_sub(x) {
5003 Some(result) => result,
5004 None => return Err(PIE { kind: Underflow }),
5011 /// An error which can be returned when parsing an integer.
5013 /// This error is used as the error type for the `from_str_radix()` functions
5014 /// on the primitive integer types, such as [`i8::from_str_radix`].
5016 /// # Potential causes
5018 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5019 /// in the string e.g., when it is obtained from the standard input.
5020 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5022 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5023 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5024 #[derive(Debug, Clone, PartialEq, Eq)]
5025 #[stable(feature = "rust1", since = "1.0.0")]
5026 pub struct ParseIntError {
5030 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5031 #[unstable(feature = "int_error_matching",
5032 reason = "it can be useful to match errors when making error messages \
5033 for integer parsing",
5035 #[derive(Debug, Clone, PartialEq, Eq)]
5037 pub enum IntErrorKind {
5038 /// Value being parsed is empty.
5040 /// Among other causes, this variant will be constructed when parsing an empty string.
5042 /// Contains an invalid digit.
5044 /// Among other causes, this variant will be constructed when parsing a string that
5045 /// contains a letter.
5047 /// Integer is too large to store in target integer type.
5049 /// Integer is too small to store in target integer type.
5053 /// This variant will be emitted when the parsing string has a value of zero, which
5054 /// would be illegal for non-zero types.
5058 impl ParseIntError {
5059 /// Outputs the detailed cause of parsing an integer failing.
5060 #[unstable(feature = "int_error_matching",
5061 reason = "it can be useful to match errors when making error messages \
5062 for integer parsing",
5064 pub fn kind(&self) -> &IntErrorKind {
5067 #[unstable(feature = "int_error_internals",
5068 reason = "available through Error trait and this method should \
5069 not be exposed publicly",
5072 pub fn __description(&self) -> &str {
5074 IntErrorKind::Empty => "cannot parse integer from empty string",
5075 IntErrorKind::InvalidDigit => "invalid digit found in string",
5076 IntErrorKind::Overflow => "number too large to fit in target type",
5077 IntErrorKind::Underflow => "number too small to fit in target type",
5078 IntErrorKind::Zero => "number would be zero for non-zero type",
5083 #[stable(feature = "rust1", since = "1.0.0")]
5084 impl fmt::Display for ParseIntError {
5085 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5086 self.__description().fmt(f)
5090 #[stable(feature = "rust1", since = "1.0.0")]
5091 pub use crate::num::dec2flt::ParseFloatError;
5093 // Conversion traits for primitive integer and float types
5094 // Conversions T -> T are covered by a blanket impl and therefore excluded
5095 // Some conversions from and to usize/isize are not implemented due to portability concerns
5096 macro_rules! impl_from {
5097 ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
5100 impl From<$Small> for $Large {
5102 fn from(small: $Small) -> $Large {
5107 ($Small: ty, $Large: ty, #[$attr:meta]) => {
5111 concat!("Converts `",
5119 macro_rules! impl_from_bool {
5120 ($target: ty, #[$attr:meta]) => {
5121 impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
5122 stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
5128 assert_eq!(", stringify!($target), "::from(true), 1);
5129 assert_eq!(", stringify!($target), "::from(false), 0);
5135 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
5136 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
5137 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
5138 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
5139 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
5140 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
5141 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
5142 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
5143 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
5144 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
5145 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
5146 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
5148 // Unsigned -> Unsigned
5149 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5150 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5151 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5152 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
5153 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5154 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5155 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5156 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
5157 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5158 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
5159 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
5162 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5163 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5164 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5165 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5166 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5167 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5168 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5169 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5170 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5171 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5172 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5174 // Unsigned -> Signed
5175 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5176 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5177 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5178 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5179 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5180 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5181 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5182 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5183 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5184 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5186 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
5187 // which imply that pointer-sized integers must be at least 16 bits:
5188 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
5189 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5190 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5191 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5193 // RISC-V defines the possibility of a 128-bit address space (RV128).
5195 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
5196 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
5197 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
5200 // Note: integers can only be represented with full precision in a float if
5201 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
5202 // Lossy float conversions are not implemented at this time.
5205 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5206 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5207 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5208 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5209 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5211 // Unsigned -> Float
5212 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5213 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5214 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5215 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5216 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5219 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }