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")]
1997 pub fn signum(self) -> Self {
2007 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2015 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2016 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2019 #[stable(feature = "rust1", since = "1.0.0")]
2021 pub const fn is_positive(self) -> bool { self > 0 }
2025 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2033 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2034 assert!(!10", stringify!($SelfT), ".is_negative());",
2037 #[stable(feature = "rust1", since = "1.0.0")]
2039 pub const fn is_negative(self) -> bool { self < 0 }
2043 concat!("Return the memory representation of this integer as a byte array in
2044 big-endian (network) byte order.
2051 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2052 assert_eq!(bytes, ", $be_bytes, ");
2054 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2055 #[rustc_const_unstable(feature = "const_int_conversion")]
2057 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2058 self.to_be().to_ne_bytes()
2063 concat!("Return the memory representation of this integer as a byte array in
2064 little-endian byte order.
2071 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2072 assert_eq!(bytes, ", $le_bytes, ");
2074 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2075 #[rustc_const_unstable(feature = "const_int_conversion")]
2077 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2078 self.to_le().to_ne_bytes()
2084 Return the memory representation of this integer as a byte array in
2087 As the target platform's native endianness is used, portable code
2088 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2093 [`to_be_bytes`]: #method.to_be_bytes
2094 [`to_le_bytes`]: #method.to_le_bytes
2099 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2100 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
2106 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2107 #[rustc_const_unstable(feature = "const_int_conversion")]
2109 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2110 unsafe { mem::transmute(self) }
2115 concat!("Create an integer value from its representation as a byte array in
2123 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2124 assert_eq!(value, ", $swap_op, ");
2127 When starting from a slice rather than an array, fallible conversion APIs can be used:
2130 use std::convert::TryInto;
2132 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2133 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2135 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2138 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2139 #[rustc_const_unstable(feature = "const_int_conversion")]
2141 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2142 Self::from_be(Self::from_ne_bytes(bytes))
2148 Create an integer value from its representation as a byte array in
2156 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2157 assert_eq!(value, ", $swap_op, ");
2160 When starting from a slice rather than an array, fallible conversion APIs can be used:
2163 use std::convert::TryInto;
2165 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2166 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2168 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2171 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2172 #[rustc_const_unstable(feature = "const_int_conversion")]
2174 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2175 Self::from_le(Self::from_ne_bytes(bytes))
2180 concat!("Create an integer value from its memory representation as a byte
2181 array in native endianness.
2183 As the target platform's native endianness is used, portable code
2184 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2185 appropriate instead.
2187 [`from_be_bytes`]: #method.from_be_bytes
2188 [`from_le_bytes`]: #method.from_le_bytes
2195 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2200 assert_eq!(value, ", $swap_op, ");
2203 When starting from a slice rather than an array, fallible conversion APIs can be used:
2206 use std::convert::TryInto;
2208 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2209 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2211 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2214 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2215 #[rustc_const_unstable(feature = "const_int_conversion")]
2217 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2218 unsafe { mem::transmute(bytes) }
2226 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2227 "[0x12]", "[0x12]", "", "" }
2232 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2233 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2238 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2239 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2240 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2245 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2246 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2247 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2248 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2253 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2254 170141183460469231731687303715884105727, "", "", 16,
2255 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2256 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2257 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2258 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2259 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2260 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2263 #[cfg(target_pointer_width = "16")]
2266 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2267 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2268 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2271 #[cfg(target_pointer_width = "32")]
2274 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2275 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2276 "[0x12, 0x34, 0x56, 0x78]",
2277 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2280 #[cfg(target_pointer_width = "64")]
2283 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2284 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2285 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2286 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2287 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2290 // `Int` + `UnsignedInt` implemented for unsigned integers
2291 macro_rules! uint_impl {
2292 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2293 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2294 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2295 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2297 concat!("Returns the smallest value that can be represented by this integer type.
2304 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2306 #[stable(feature = "rust1", since = "1.0.0")]
2309 pub const fn min_value() -> Self { 0 }
2313 concat!("Returns the largest value that can be represented by this integer type.
2320 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2321 stringify!($MaxV), ");", $EndFeature, "
2323 #[stable(feature = "rust1", since = "1.0.0")]
2326 pub const fn max_value() -> Self { !0 }
2330 concat!("Converts a string slice in a given base to an integer.
2332 The string is expected to be an optional `+` sign
2334 Leading and trailing whitespace represent an error.
2335 Digits are a subset of these characters, depending on `radix`:
2343 This function panics if `radix` is not in the range from 2 to 36.
2350 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2353 #[stable(feature = "rust1", since = "1.0.0")]
2354 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2355 from_str_radix(src, radix)
2360 concat!("Returns the number of ones in the binary representation of `self`.
2367 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2369 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2371 #[stable(feature = "rust1", since = "1.0.0")]
2373 pub const fn count_ones(self) -> u32 {
2374 intrinsics::ctpop(self as $ActualT) as u32
2379 concat!("Returns the number of zeros in the binary representation of `self`.
2386 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2388 #[stable(feature = "rust1", since = "1.0.0")]
2390 pub const fn count_zeros(self) -> u32 {
2391 (!self).count_ones()
2396 concat!("Returns the number of leading zeros in the binary representation of `self`.
2403 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2405 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2407 #[stable(feature = "rust1", since = "1.0.0")]
2409 pub const fn leading_zeros(self) -> u32 {
2410 intrinsics::ctlz(self as $ActualT) as u32
2415 concat!("Returns the number of trailing zeros in the binary representation
2423 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2425 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2427 #[stable(feature = "rust1", since = "1.0.0")]
2429 pub const fn trailing_zeros(self) -> u32 {
2430 intrinsics::cttz(self) as u32
2435 concat!("Shifts the bits to the left by a specified amount, `n`,
2436 wrapping the truncated bits to the end of the resulting integer.
2438 Please note this isn't the same operation as the `<<` shifting operator!
2445 let n = ", $rot_op, stringify!($SelfT), ";
2446 let m = ", $rot_result, ";
2448 assert_eq!(n.rotate_left(", $rot, "), m);
2450 #[stable(feature = "rust1", since = "1.0.0")]
2451 #[must_use = "this returns the result of the operation, \
2452 without modifying the original"]
2454 pub const fn rotate_left(self, n: u32) -> Self {
2455 intrinsics::rotate_left(self, n as $SelfT)
2460 concat!("Shifts the bits to the right by a specified amount, `n`,
2461 wrapping the truncated bits to the beginning of the resulting
2464 Please note this isn't the same operation as the `>>` shifting operator!
2471 let n = ", $rot_result, stringify!($SelfT), ";
2472 let m = ", $rot_op, ";
2474 assert_eq!(n.rotate_right(", $rot, "), m);
2476 #[stable(feature = "rust1", since = "1.0.0")]
2477 #[must_use = "this returns the result of the operation, \
2478 without modifying the original"]
2480 pub const fn rotate_right(self, n: u32) -> Self {
2481 intrinsics::rotate_right(self, n as $SelfT)
2487 Reverses the byte order of the integer.
2494 let n = ", $swap_op, stringify!($SelfT), ";
2495 let m = n.swap_bytes();
2497 assert_eq!(m, ", $swapped, ");
2499 #[stable(feature = "rust1", since = "1.0.0")]
2501 pub const fn swap_bytes(self) -> Self {
2502 intrinsics::bswap(self as $ActualT) as Self
2507 concat!("Reverses the bit pattern of the integer.
2514 let n = ", $swap_op, stringify!($SelfT), ";
2515 let m = n.reverse_bits();
2517 assert_eq!(m, ", $reversed, ");
2519 #[stable(feature = "reverse_bits", since = "1.37.0")]
2522 pub const fn reverse_bits(self) -> Self {
2523 intrinsics::bitreverse(self as $ActualT) as Self
2528 concat!("Converts an integer from big endian to the target's endianness.
2530 On big endian this is a no-op. On little endian the bytes are
2538 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2540 if cfg!(target_endian = \"big\") {
2541 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2543 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2546 #[stable(feature = "rust1", since = "1.0.0")]
2548 pub const fn from_be(x: Self) -> Self {
2549 #[cfg(target_endian = "big")]
2553 #[cfg(not(target_endian = "big"))]
2561 concat!("Converts an integer from little endian to the target's endianness.
2563 On little endian this is a no-op. On big endian the bytes are
2571 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2573 if cfg!(target_endian = \"little\") {
2574 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2576 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2579 #[stable(feature = "rust1", since = "1.0.0")]
2581 pub const fn from_le(x: Self) -> Self {
2582 #[cfg(target_endian = "little")]
2586 #[cfg(not(target_endian = "little"))]
2594 concat!("Converts `self` to big endian from the target's endianness.
2596 On big endian this is a no-op. On little endian the bytes are
2604 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2606 if cfg!(target_endian = \"big\") {
2607 assert_eq!(n.to_be(), n)
2609 assert_eq!(n.to_be(), n.swap_bytes())
2612 #[stable(feature = "rust1", since = "1.0.0")]
2614 pub const fn to_be(self) -> Self { // or not to be?
2615 #[cfg(target_endian = "big")]
2619 #[cfg(not(target_endian = "big"))]
2627 concat!("Converts `self` to little endian from the target's endianness.
2629 On little endian this is a no-op. On big endian the bytes are
2637 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2639 if cfg!(target_endian = \"little\") {
2640 assert_eq!(n.to_le(), n)
2642 assert_eq!(n.to_le(), n.swap_bytes())
2645 #[stable(feature = "rust1", since = "1.0.0")]
2647 pub const fn to_le(self) -> Self {
2648 #[cfg(target_endian = "little")]
2652 #[cfg(not(target_endian = "little"))]
2660 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2661 if overflow occurred.
2668 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2669 "Some(", stringify!($SelfT), "::max_value() - 1));
2670 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2672 #[stable(feature = "rust1", since = "1.0.0")]
2673 #[must_use = "this returns the result of the operation, \
2674 without modifying the original"]
2676 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2677 let (a, b) = self.overflowing_add(rhs);
2678 if b {None} else {Some(a)}
2683 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2684 `None` if overflow occurred.
2691 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2692 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2694 #[stable(feature = "rust1", since = "1.0.0")]
2695 #[must_use = "this returns the result of the operation, \
2696 without modifying the original"]
2698 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2699 let (a, b) = self.overflowing_sub(rhs);
2700 if b {None} else {Some(a)}
2705 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2706 `None` if overflow occurred.
2713 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2714 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2716 #[stable(feature = "rust1", since = "1.0.0")]
2717 #[must_use = "this returns the result of the operation, \
2718 without modifying the original"]
2720 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2721 let (a, b) = self.overflowing_mul(rhs);
2722 if b {None} else {Some(a)}
2727 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2735 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2736 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2738 #[stable(feature = "rust1", since = "1.0.0")]
2739 #[must_use = "this returns the result of the operation, \
2740 without modifying the original"]
2742 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2745 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2751 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2759 #![feature(euclidean_division)]
2760 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
2761 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
2763 #[unstable(feature = "euclidean_division", issue = "49048")]
2764 #[must_use = "this returns the result of the operation, \
2765 without modifying the original"]
2767 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
2771 Some(self.div_euclid(rhs))
2778 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2786 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2787 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2789 #[stable(feature = "wrapping", since = "1.7.0")]
2790 #[must_use = "this returns the result of the operation, \
2791 without modifying the original"]
2793 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2797 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2803 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
2811 #![feature(euclidean_division)]
2812 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
2813 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
2815 #[unstable(feature = "euclidean_division", issue = "49048")]
2816 #[must_use = "this returns the result of the operation, \
2817 without modifying the original"]
2819 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
2823 Some(self.rem_euclid(rhs))
2829 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2832 Note that negating any positive integer will overflow.
2839 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2840 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2842 #[stable(feature = "wrapping", since = "1.7.0")]
2844 pub fn checked_neg(self) -> Option<Self> {
2845 let (a, b) = self.overflowing_neg();
2846 if b {None} else {Some(a)}
2851 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2852 if `rhs` is larger than or equal to the number of bits in `self`.
2859 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2860 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2862 #[stable(feature = "wrapping", since = "1.7.0")]
2863 #[must_use = "this returns the result of the operation, \
2864 without modifying the original"]
2866 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2867 let (a, b) = self.overflowing_shl(rhs);
2868 if b {None} else {Some(a)}
2873 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2874 if `rhs` is larger than or equal to the number of bits in `self`.
2881 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2882 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2884 #[stable(feature = "wrapping", since = "1.7.0")]
2885 #[must_use = "this returns the result of the operation, \
2886 without modifying the original"]
2888 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2889 let (a, b) = self.overflowing_shr(rhs);
2890 if b {None} else {Some(a)}
2895 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2903 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2904 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2906 #[stable(feature = "no_panic_pow", since = "1.34.0")]
2907 #[must_use = "this returns the result of the operation, \
2908 without modifying the original"]
2910 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2911 let mut base = self;
2912 let mut acc: Self = 1;
2916 acc = acc.checked_mul(base)?;
2919 base = base.checked_mul(base)?;
2922 // Deal with the final bit of the exponent separately, since
2923 // squaring the base afterwards is not necessary and may cause a
2924 // needless overflow.
2926 acc = acc.checked_mul(base)?;
2934 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2935 the numeric bounds instead of overflowing.
2942 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2943 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2946 #[stable(feature = "rust1", since = "1.0.0")]
2947 #[must_use = "this returns the result of the operation, \
2948 without modifying the original"]
2949 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
2951 pub const fn saturating_add(self, rhs: Self) -> Self {
2952 intrinsics::saturating_add(self, rhs)
2957 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2958 at the numeric bounds instead of overflowing.
2965 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2966 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2968 #[stable(feature = "rust1", since = "1.0.0")]
2969 #[must_use = "this returns the result of the operation, \
2970 without modifying the original"]
2971 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
2973 pub const fn saturating_sub(self, rhs: Self) -> Self {
2974 intrinsics::saturating_sub(self, rhs)
2979 concat!("Saturating integer multiplication. Computes `self * rhs`,
2980 saturating at the numeric bounds instead of overflowing.
2987 ", $Feature, "use std::", stringify!($SelfT), ";
2989 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2990 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2991 "::MAX);", $EndFeature, "
2993 #[stable(feature = "wrapping", since = "1.7.0")]
2994 #[must_use = "this returns the result of the operation, \
2995 without modifying the original"]
2997 pub fn saturating_mul(self, rhs: Self) -> Self {
2998 self.checked_mul(rhs).unwrap_or(Self::max_value())
3003 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3004 saturating at the numeric bounds instead of overflowing.
3011 ", $Feature, "use std::", stringify!($SelfT), ";
3013 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3014 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3017 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3018 #[must_use = "this returns the result of the operation, \
3019 without modifying the original"]
3021 pub fn saturating_pow(self, exp: u32) -> Self {
3022 match self.checked_pow(exp) {
3024 None => Self::max_value(),
3030 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3031 wrapping around at the boundary of the type.
3038 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3039 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
3042 #[stable(feature = "rust1", since = "1.0.0")]
3043 #[must_use = "this returns the result of the operation, \
3044 without modifying the original"]
3046 pub const fn wrapping_add(self, rhs: Self) -> Self {
3047 intrinsics::overflowing_add(self, rhs)
3052 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3053 wrapping around at the boundary of the type.
3060 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3061 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
3064 #[stable(feature = "rust1", since = "1.0.0")]
3065 #[must_use = "this returns the result of the operation, \
3066 without modifying the original"]
3068 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3069 intrinsics::overflowing_sub(self, rhs)
3073 /// Wrapping (modular) multiplication. Computes `self *
3074 /// rhs`, wrapping around at the boundary of the type.
3080 /// Please note that this example is shared between integer types.
3081 /// Which explains why `u8` is used here.
3084 /// assert_eq!(10u8.wrapping_mul(12), 120);
3085 /// assert_eq!(25u8.wrapping_mul(12), 44);
3087 #[stable(feature = "rust1", since = "1.0.0")]
3088 #[must_use = "this returns the result of the operation, \
3089 without modifying the original"]
3091 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3092 intrinsics::overflowing_mul(self, rhs)
3096 concat!("Wrapping (modular) division. Computes `self / rhs`.
3097 Wrapped division on unsigned types is just normal division.
3098 There's no way wrapping could ever happen.
3099 This function exists, so that all operations
3100 are accounted for in the wrapping operations.
3107 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3109 #[stable(feature = "num_wrapping", since = "1.2.0")]
3110 #[must_use = "this returns the result of the operation, \
3111 without modifying the original"]
3113 pub fn wrapping_div(self, rhs: Self) -> Self {
3119 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3120 Wrapped division on unsigned types is just normal division.
3121 There's no way wrapping could ever happen.
3122 This function exists, so that all operations
3123 are accounted for in the wrapping operations.
3124 Since, for the positive integers, all common
3125 definitions of division are equal, this
3126 is exactly equal to `self.wrapping_div(rhs)`.
3133 #![feature(euclidean_division)]
3134 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3136 #[unstable(feature = "euclidean_division", issue = "49048")]
3137 #[must_use = "this returns the result of the operation, \
3138 without modifying the original"]
3140 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
3146 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3147 Wrapped remainder calculation on unsigned types is
3148 just the regular remainder calculation.
3149 There's no way wrapping could ever happen.
3150 This function exists, so that all operations
3151 are accounted for in the wrapping operations.
3158 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3160 #[stable(feature = "num_wrapping", since = "1.2.0")]
3161 #[must_use = "this returns the result of the operation, \
3162 without modifying the original"]
3164 pub fn wrapping_rem(self, rhs: Self) -> Self {
3170 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3171 Wrapped modulo calculation on unsigned types is
3172 just the regular remainder calculation.
3173 There's no way wrapping could ever happen.
3174 This function exists, so that all operations
3175 are accounted for in the wrapping operations.
3176 Since, for the positive integers, all common
3177 definitions of division are equal, this
3178 is exactly equal to `self.wrapping_rem(rhs)`.
3185 #![feature(euclidean_division)]
3186 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3188 #[unstable(feature = "euclidean_division", issue = "49048")]
3189 #[must_use = "this returns the result of the operation, \
3190 without modifying the original"]
3192 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3197 /// Wrapping (modular) negation. Computes `-self`,
3198 /// wrapping around at the boundary of the type.
3200 /// Since unsigned types do not have negative equivalents
3201 /// all applications of this function will wrap (except for `-0`).
3202 /// For values smaller than the corresponding signed type's maximum
3203 /// the result is the same as casting the corresponding signed value.
3204 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3205 /// `MAX` is the corresponding signed type's maximum.
3211 /// Please note that this example is shared between integer types.
3212 /// Which explains why `i8` is used here.
3215 /// assert_eq!(100i8.wrapping_neg(), -100);
3216 /// assert_eq!((-128i8).wrapping_neg(), -128);
3218 #[stable(feature = "num_wrapping", since = "1.2.0")]
3220 pub const fn wrapping_neg(self) -> Self {
3221 self.overflowing_neg().0
3225 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3226 where `mask` removes any high-order bits of `rhs` that
3227 would cause the shift to exceed the bitwidth of the type.
3229 Note that this is *not* the same as a rotate-left; the
3230 RHS of a wrapping shift-left is restricted to the range
3231 of the type, rather than the bits shifted out of the LHS
3232 being returned to the other end. The primitive integer
3233 types all implement a `rotate_left` function, which may
3234 be what you want instead.
3241 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3242 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3244 #[stable(feature = "num_wrapping", since = "1.2.0")]
3245 #[must_use = "this returns the result of the operation, \
3246 without modifying the original"]
3248 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3250 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3256 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3257 where `mask` removes any high-order bits of `rhs` that
3258 would cause the shift to exceed the bitwidth of the type.
3260 Note that this is *not* the same as a rotate-right; the
3261 RHS of a wrapping shift-right is restricted to the range
3262 of the type, rather than the bits shifted out of the LHS
3263 being returned to the other end. The primitive integer
3264 types all implement a `rotate_right` function, which may
3265 be what you want instead.
3272 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3273 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3275 #[stable(feature = "num_wrapping", since = "1.2.0")]
3276 #[must_use = "this returns the result of the operation, \
3277 without modifying the original"]
3279 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3281 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3287 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3288 wrapping around at the boundary of the type.
3295 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3296 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3298 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3299 #[must_use = "this returns the result of the operation, \
3300 without modifying the original"]
3302 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3303 let mut base = self;
3304 let mut acc: Self = 1;
3308 acc = acc.wrapping_mul(base);
3311 base = base.wrapping_mul(base);
3314 // Deal with the final bit of the exponent separately, since
3315 // squaring the base afterwards is not necessary and may cause a
3316 // needless overflow.
3318 acc = acc.wrapping_mul(base);
3326 concat!("Calculates `self` + `rhs`
3328 Returns a tuple of the addition along with a boolean indicating
3329 whether an arithmetic overflow would occur. If an overflow would
3330 have occurred then the wrapped value is returned.
3337 ", $Feature, "use std::", stringify!($SelfT), ";
3339 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3340 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3342 #[stable(feature = "wrapping", since = "1.7.0")]
3343 #[must_use = "this returns the result of the operation, \
3344 without modifying the original"]
3346 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3347 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3353 concat!("Calculates `self` - `rhs`
3355 Returns a tuple of the subtraction along with a boolean indicating
3356 whether an arithmetic overflow would occur. If an overflow would
3357 have occurred then the wrapped value is returned.
3364 ", $Feature, "use std::", stringify!($SelfT), ";
3366 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3367 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3370 #[stable(feature = "wrapping", since = "1.7.0")]
3371 #[must_use = "this returns the result of the operation, \
3372 without modifying the original"]
3374 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3375 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3380 /// Calculates the multiplication of `self` and `rhs`.
3382 /// Returns a tuple of the multiplication along with a boolean
3383 /// indicating whether an arithmetic overflow would occur. If an
3384 /// overflow would have occurred then the wrapped value is returned.
3390 /// Please note that this example is shared between integer types.
3391 /// Which explains why `u32` is used here.
3394 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3395 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3397 #[stable(feature = "wrapping", since = "1.7.0")]
3398 #[must_use = "this returns the result of the operation, \
3399 without modifying the original"]
3401 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3402 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3407 concat!("Calculates the divisor when `self` is divided by `rhs`.
3409 Returns a tuple of the divisor along with a boolean indicating
3410 whether an arithmetic overflow would occur. Note that for unsigned
3411 integers overflow never occurs, so the second value is always
3416 This function will panic if `rhs` is 0.
3423 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3426 #[stable(feature = "wrapping", since = "1.7.0")]
3427 #[must_use = "this returns the result of the operation, \
3428 without modifying the original"]
3429 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3435 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3437 Returns a tuple of the divisor along with a boolean indicating
3438 whether an arithmetic overflow would occur. Note that for unsigned
3439 integers overflow never occurs, so the second value is always
3441 Since, for the positive integers, all common
3442 definitions of division are equal, this
3443 is exactly equal to `self.overflowing_div(rhs)`.
3447 This function will panic if `rhs` is 0.
3454 #![feature(euclidean_division)]
3455 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3458 #[unstable(feature = "euclidean_division", issue = "49048")]
3459 #[must_use = "this returns the result of the operation, \
3460 without modifying the original"]
3461 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3467 concat!("Calculates the remainder when `self` is divided by `rhs`.
3469 Returns a tuple of the remainder after dividing along with a boolean
3470 indicating whether an arithmetic overflow would occur. Note that for
3471 unsigned integers overflow never occurs, so the second value is
3476 This function will panic if `rhs` is 0.
3483 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3486 #[stable(feature = "wrapping", since = "1.7.0")]
3487 #[must_use = "this returns the result of the operation, \
3488 without modifying the original"]
3489 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3495 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3497 Returns a tuple of the modulo after dividing along with a boolean
3498 indicating whether an arithmetic overflow would occur. Note that for
3499 unsigned integers overflow never occurs, so the second value is
3501 Since, for the positive integers, all common
3502 definitions of division are equal, this operation
3503 is exactly equal to `self.overflowing_rem(rhs)`.
3507 This function will panic if `rhs` is 0.
3514 #![feature(euclidean_division)]
3515 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3518 #[unstable(feature = "euclidean_division", issue = "49048")]
3519 #[must_use = "this returns the result of the operation, \
3520 without modifying the original"]
3521 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3527 concat!("Negates self in an overflowing fashion.
3529 Returns `!self + 1` using wrapping operations to return the value
3530 that represents the negation of this unsigned value. Note that for
3531 positive unsigned values overflow always occurs, but negating 0 does
3539 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3540 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3541 ", true));", $EndFeature, "
3544 #[stable(feature = "wrapping", since = "1.7.0")]
3545 pub const fn overflowing_neg(self) -> (Self, bool) {
3546 ((!self).wrapping_add(1), self != 0)
3551 concat!("Shifts self left by `rhs` bits.
3553 Returns a tuple of the shifted version of self along with a boolean
3554 indicating whether the shift value was larger than or equal to the
3555 number of bits. If the shift value is too large, then value is
3556 masked (N-1) where N is the number of bits, and this value is then
3557 used to perform the shift.
3564 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3565 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3567 #[stable(feature = "wrapping", since = "1.7.0")]
3568 #[must_use = "this returns the result of the operation, \
3569 without modifying the original"]
3571 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3572 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3577 concat!("Shifts self right by `rhs` bits.
3579 Returns a tuple of the shifted version of self along with a boolean
3580 indicating whether the shift value was larger than or equal to the
3581 number of bits. If the shift value is too large, then value is
3582 masked (N-1) where N is the number of bits, and this value is then
3583 used to perform the shift.
3590 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3591 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3593 #[stable(feature = "wrapping", since = "1.7.0")]
3594 #[must_use = "this returns the result of the operation, \
3595 without modifying the original"]
3597 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3598 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3603 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3605 Returns a tuple of the exponentiation along with a bool indicating
3606 whether an overflow happened.
3613 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3614 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3616 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3617 #[must_use = "this returns the result of the operation, \
3618 without modifying the original"]
3620 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3621 let mut base = self;
3622 let mut acc: Self = 1;
3623 let mut overflown = false;
3624 // Scratch space for storing results of overflowing_mul.
3629 r = acc.overflowing_mul(base);
3634 r = base.overflowing_mul(base);
3639 // Deal with the final bit of the exponent separately, since
3640 // squaring the base afterwards is not necessary and may cause a
3641 // needless overflow.
3643 r = acc.overflowing_mul(base);
3653 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3660 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3662 #[stable(feature = "rust1", since = "1.0.0")]
3663 #[must_use = "this returns the result of the operation, \
3664 without modifying the original"]
3666 #[rustc_inherit_overflow_checks]
3667 pub fn pow(self, mut exp: u32) -> Self {
3668 let mut base = self;
3679 // Deal with the final bit of the exponent separately, since
3680 // squaring the base afterwards is not necessary and may cause a
3681 // needless overflow.
3691 concat!("Performs Euclidean division.
3693 Since, for the positive integers, all common
3694 definitions of division are equal, this
3695 is exactly equal to `self / rhs`.
3702 #![feature(euclidean_division)]
3703 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
3705 #[unstable(feature = "euclidean_division", issue = "49048")]
3706 #[must_use = "this returns the result of the operation, \
3707 without modifying the original"]
3709 #[rustc_inherit_overflow_checks]
3710 pub fn div_euclid(self, rhs: Self) -> Self {
3717 concat!("Calculates the least remainder of `self (mod rhs)`.
3719 Since, for the positive integers, all common
3720 definitions of division are equal, this
3721 is exactly equal to `self % rhs`.
3728 #![feature(euclidean_division)]
3729 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
3731 #[unstable(feature = "euclidean_division", issue = "49048")]
3732 #[must_use = "this returns the result of the operation, \
3733 without modifying the original"]
3735 #[rustc_inherit_overflow_checks]
3736 pub fn rem_euclid(self, rhs: Self) -> Self {
3742 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3749 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3750 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3752 #[stable(feature = "rust1", since = "1.0.0")]
3754 pub fn is_power_of_two(self) -> bool {
3755 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3759 // Returns one less than next power of two.
3760 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3762 // 8u8.one_less_than_next_power_of_two() == 7
3763 // 6u8.one_less_than_next_power_of_two() == 7
3765 // This method cannot overflow, as in the `next_power_of_two`
3766 // overflow cases it instead ends up returning the maximum value
3767 // of the type, and can return 0 for 0.
3769 fn one_less_than_next_power_of_two(self) -> Self {
3770 if self <= 1 { return 0; }
3772 // Because `p > 0`, it cannot consist entirely of leading zeros.
3773 // That means the shift is always in-bounds, and some processors
3774 // (such as intel pre-haswell) have more efficient ctlz
3775 // intrinsics when the argument is non-zero.
3777 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3778 <$SelfT>::max_value() >> z
3782 concat!("Returns the smallest power of two greater than or equal to `self`.
3784 When return value overflows (i.e., `self > (1 << (N-1))` for type
3785 `uN`), it panics in debug mode and return value is wrapped to 0 in
3786 release mode (the only situation in which method can return 0).
3793 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3794 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3796 #[stable(feature = "rust1", since = "1.0.0")]
3798 pub fn next_power_of_two(self) -> Self {
3799 // Call the trait to get overflow checks
3800 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3805 concat!("Returns the smallest power of two greater than or equal to `n`. If
3806 the next power of two is greater than the type's maximum value,
3807 `None` is returned, otherwise the power of two is wrapped in `Some`.
3814 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3815 ".checked_next_power_of_two(), Some(2));
3816 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3817 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3821 #[stable(feature = "rust1", since = "1.0.0")]
3822 pub fn checked_next_power_of_two(self) -> Option<Self> {
3823 self.one_less_than_next_power_of_two().checked_add(1)
3828 concat!("Returns the smallest power of two greater than or equal to `n`. If
3829 the next power of two is greater than the type's maximum value,
3830 the return value is wrapped to `0`.
3837 #![feature(wrapping_next_power_of_two)]
3839 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3840 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3841 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3844 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3845 reason = "needs decision on wrapping behaviour")]
3846 pub fn wrapping_next_power_of_two(self) -> Self {
3847 self.one_less_than_next_power_of_two().wrapping_add(1)
3852 concat!("Return the memory representation of this integer as a byte array in
3853 big-endian (network) byte order.
3860 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
3861 assert_eq!(bytes, ", $be_bytes, ");
3863 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3864 #[rustc_const_unstable(feature = "const_int_conversion")]
3866 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
3867 self.to_be().to_ne_bytes()
3872 concat!("Return the memory representation of this integer as a byte array in
3873 little-endian byte order.
3880 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
3881 assert_eq!(bytes, ", $le_bytes, ");
3883 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3884 #[rustc_const_unstable(feature = "const_int_conversion")]
3886 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
3887 self.to_le().to_ne_bytes()
3893 Return the memory representation of this integer as a byte array in
3896 As the target platform's native endianness is used, portable code
3897 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3902 [`to_be_bytes`]: #method.to_be_bytes
3903 [`to_le_bytes`]: #method.to_le_bytes
3908 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
3909 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
3915 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3916 #[rustc_const_unstable(feature = "const_int_conversion")]
3918 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
3919 unsafe { mem::transmute(self) }
3924 concat!("Create an integer value from its representation as a byte array in
3932 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
3933 assert_eq!(value, ", $swap_op, ");
3936 When starting from a slice rather than an array, fallible conversion APIs can be used:
3939 use std::convert::TryInto;
3941 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3942 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3944 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
3947 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3948 #[rustc_const_unstable(feature = "const_int_conversion")]
3950 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3951 Self::from_be(Self::from_ne_bytes(bytes))
3957 Create an integer value from its representation as a byte array in
3965 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
3966 assert_eq!(value, ", $swap_op, ");
3969 When starting from a slice rather than an array, fallible conversion APIs can be used:
3972 use std::convert::TryInto;
3974 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3975 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3977 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
3980 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3981 #[rustc_const_unstable(feature = "const_int_conversion")]
3983 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3984 Self::from_le(Self::from_ne_bytes(bytes))
3989 concat!("Create an integer value from its memory representation as a byte
3990 array in native endianness.
3992 As the target platform's native endianness is used, portable code
3993 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3994 appropriate instead.
3996 [`from_be_bytes`]: #method.from_be_bytes
3997 [`from_le_bytes`]: #method.from_le_bytes
4004 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4009 assert_eq!(value, ", $swap_op, ");
4012 When starting from a slice rather than an array, fallible conversion APIs can be used:
4015 use std::convert::TryInto;
4017 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4018 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4020 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4023 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4024 #[rustc_const_unstable(feature = "const_int_conversion")]
4026 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4027 unsafe { mem::transmute(bytes) }
4035 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4039 /// Checks if the value is within the ASCII range.
4044 /// let ascii = 97u8;
4045 /// let non_ascii = 150u8;
4047 /// assert!(ascii.is_ascii());
4048 /// assert!(!non_ascii.is_ascii());
4050 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4052 pub fn is_ascii(&self) -> bool {
4056 /// Makes a copy of the value in its ASCII upper case equivalent.
4058 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4059 /// but non-ASCII letters are unchanged.
4061 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4066 /// let lowercase_a = 97u8;
4068 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4071 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4072 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4074 pub fn to_ascii_uppercase(&self) -> u8 {
4075 // Unset the fith bit if this is a lowercase letter
4076 *self & !((self.is_ascii_lowercase() as u8) << 5)
4079 /// Makes a copy of the value in its ASCII lower case equivalent.
4081 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4082 /// but non-ASCII letters are unchanged.
4084 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4089 /// let uppercase_a = 65u8;
4091 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4094 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4095 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4097 pub fn to_ascii_lowercase(&self) -> u8 {
4098 // Set the fith bit if this is an uppercase letter
4099 *self | ((self.is_ascii_uppercase() as u8) << 5)
4102 /// Checks that two values are an ASCII case-insensitive match.
4104 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4109 /// let lowercase_a = 97u8;
4110 /// let uppercase_a = 65u8;
4112 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4114 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4116 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4117 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4120 /// Converts this value to its ASCII upper case equivalent in-place.
4122 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4123 /// but non-ASCII letters are unchanged.
4125 /// To return a new uppercased value without modifying the existing one, use
4126 /// [`to_ascii_uppercase`].
4131 /// let mut byte = b'a';
4133 /// byte.make_ascii_uppercase();
4135 /// assert_eq!(b'A', byte);
4138 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4139 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4141 pub fn make_ascii_uppercase(&mut self) {
4142 *self = self.to_ascii_uppercase();
4145 /// Converts this value to its ASCII lower case equivalent in-place.
4147 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4148 /// but non-ASCII letters are unchanged.
4150 /// To return a new lowercased value without modifying the existing one, use
4151 /// [`to_ascii_lowercase`].
4156 /// let mut byte = b'A';
4158 /// byte.make_ascii_lowercase();
4160 /// assert_eq!(b'a', byte);
4163 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4164 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4166 pub fn make_ascii_lowercase(&mut self) {
4167 *self = self.to_ascii_lowercase();
4170 /// Checks if the value is an ASCII alphabetic character:
4172 /// - U+0041 'A' ... U+005A 'Z', or
4173 /// - U+0061 'a' ... U+007A 'z'.
4178 /// let uppercase_a = b'A';
4179 /// let uppercase_g = b'G';
4182 /// let zero = b'0';
4183 /// let percent = b'%';
4184 /// let space = b' ';
4186 /// let esc = 0x1b_u8;
4188 /// assert!(uppercase_a.is_ascii_alphabetic());
4189 /// assert!(uppercase_g.is_ascii_alphabetic());
4190 /// assert!(a.is_ascii_alphabetic());
4191 /// assert!(g.is_ascii_alphabetic());
4192 /// assert!(!zero.is_ascii_alphabetic());
4193 /// assert!(!percent.is_ascii_alphabetic());
4194 /// assert!(!space.is_ascii_alphabetic());
4195 /// assert!(!lf.is_ascii_alphabetic());
4196 /// assert!(!esc.is_ascii_alphabetic());
4198 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4200 pub fn is_ascii_alphabetic(&self) -> bool {
4202 b'A'..=b'Z' | b'a'..=b'z' => true,
4207 /// Checks if the value is an ASCII uppercase character:
4208 /// U+0041 'A' ... U+005A 'Z'.
4213 /// let uppercase_a = b'A';
4214 /// let uppercase_g = b'G';
4217 /// let zero = b'0';
4218 /// let percent = b'%';
4219 /// let space = b' ';
4221 /// let esc = 0x1b_u8;
4223 /// assert!(uppercase_a.is_ascii_uppercase());
4224 /// assert!(uppercase_g.is_ascii_uppercase());
4225 /// assert!(!a.is_ascii_uppercase());
4226 /// assert!(!g.is_ascii_uppercase());
4227 /// assert!(!zero.is_ascii_uppercase());
4228 /// assert!(!percent.is_ascii_uppercase());
4229 /// assert!(!space.is_ascii_uppercase());
4230 /// assert!(!lf.is_ascii_uppercase());
4231 /// assert!(!esc.is_ascii_uppercase());
4233 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4235 pub fn is_ascii_uppercase(&self) -> bool {
4237 b'A'..=b'Z' => true,
4242 /// Checks if the value is an ASCII lowercase character:
4243 /// U+0061 'a' ... U+007A 'z'.
4248 /// let uppercase_a = b'A';
4249 /// let uppercase_g = b'G';
4252 /// let zero = b'0';
4253 /// let percent = b'%';
4254 /// let space = b' ';
4256 /// let esc = 0x1b_u8;
4258 /// assert!(!uppercase_a.is_ascii_lowercase());
4259 /// assert!(!uppercase_g.is_ascii_lowercase());
4260 /// assert!(a.is_ascii_lowercase());
4261 /// assert!(g.is_ascii_lowercase());
4262 /// assert!(!zero.is_ascii_lowercase());
4263 /// assert!(!percent.is_ascii_lowercase());
4264 /// assert!(!space.is_ascii_lowercase());
4265 /// assert!(!lf.is_ascii_lowercase());
4266 /// assert!(!esc.is_ascii_lowercase());
4268 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4270 pub fn is_ascii_lowercase(&self) -> bool {
4272 b'a'..=b'z' => true,
4277 /// Checks if the value is an ASCII alphanumeric character:
4279 /// - U+0041 'A' ... U+005A 'Z', or
4280 /// - U+0061 'a' ... U+007A 'z', or
4281 /// - U+0030 '0' ... U+0039 '9'.
4286 /// let uppercase_a = b'A';
4287 /// let uppercase_g = b'G';
4290 /// let zero = b'0';
4291 /// let percent = b'%';
4292 /// let space = b' ';
4294 /// let esc = 0x1b_u8;
4296 /// assert!(uppercase_a.is_ascii_alphanumeric());
4297 /// assert!(uppercase_g.is_ascii_alphanumeric());
4298 /// assert!(a.is_ascii_alphanumeric());
4299 /// assert!(g.is_ascii_alphanumeric());
4300 /// assert!(zero.is_ascii_alphanumeric());
4301 /// assert!(!percent.is_ascii_alphanumeric());
4302 /// assert!(!space.is_ascii_alphanumeric());
4303 /// assert!(!lf.is_ascii_alphanumeric());
4304 /// assert!(!esc.is_ascii_alphanumeric());
4306 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4308 pub fn is_ascii_alphanumeric(&self) -> bool {
4310 b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' => true,
4315 /// Checks if the value is an ASCII decimal digit:
4316 /// U+0030 '0' ... U+0039 '9'.
4321 /// let uppercase_a = b'A';
4322 /// let uppercase_g = b'G';
4325 /// let zero = b'0';
4326 /// let percent = b'%';
4327 /// let space = b' ';
4329 /// let esc = 0x1b_u8;
4331 /// assert!(!uppercase_a.is_ascii_digit());
4332 /// assert!(!uppercase_g.is_ascii_digit());
4333 /// assert!(!a.is_ascii_digit());
4334 /// assert!(!g.is_ascii_digit());
4335 /// assert!(zero.is_ascii_digit());
4336 /// assert!(!percent.is_ascii_digit());
4337 /// assert!(!space.is_ascii_digit());
4338 /// assert!(!lf.is_ascii_digit());
4339 /// assert!(!esc.is_ascii_digit());
4341 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4343 pub fn is_ascii_digit(&self) -> bool {
4345 b'0'..=b'9' => true,
4350 /// Checks if the value is an ASCII hexadecimal digit:
4352 /// - U+0030 '0' ... U+0039 '9', or
4353 /// - U+0041 'A' ... U+0046 'F', or
4354 /// - U+0061 'a' ... U+0066 'f'.
4359 /// let uppercase_a = b'A';
4360 /// let uppercase_g = b'G';
4363 /// let zero = b'0';
4364 /// let percent = b'%';
4365 /// let space = b' ';
4367 /// let esc = 0x1b_u8;
4369 /// assert!(uppercase_a.is_ascii_hexdigit());
4370 /// assert!(!uppercase_g.is_ascii_hexdigit());
4371 /// assert!(a.is_ascii_hexdigit());
4372 /// assert!(!g.is_ascii_hexdigit());
4373 /// assert!(zero.is_ascii_hexdigit());
4374 /// assert!(!percent.is_ascii_hexdigit());
4375 /// assert!(!space.is_ascii_hexdigit());
4376 /// assert!(!lf.is_ascii_hexdigit());
4377 /// assert!(!esc.is_ascii_hexdigit());
4379 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4381 pub fn is_ascii_hexdigit(&self) -> bool {
4383 b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f' => true,
4388 /// Checks if the value is an ASCII punctuation character:
4390 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
4391 /// - U+003A ... U+0040 `: ; < = > ? @`, or
4392 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
4393 /// - U+007B ... U+007E `{ | } ~`
4398 /// let uppercase_a = b'A';
4399 /// let uppercase_g = b'G';
4402 /// let zero = b'0';
4403 /// let percent = b'%';
4404 /// let space = b' ';
4406 /// let esc = 0x1b_u8;
4408 /// assert!(!uppercase_a.is_ascii_punctuation());
4409 /// assert!(!uppercase_g.is_ascii_punctuation());
4410 /// assert!(!a.is_ascii_punctuation());
4411 /// assert!(!g.is_ascii_punctuation());
4412 /// assert!(!zero.is_ascii_punctuation());
4413 /// assert!(percent.is_ascii_punctuation());
4414 /// assert!(!space.is_ascii_punctuation());
4415 /// assert!(!lf.is_ascii_punctuation());
4416 /// assert!(!esc.is_ascii_punctuation());
4418 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4420 pub fn is_ascii_punctuation(&self) -> bool {
4422 b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~' => true,
4427 /// Checks if the value is an ASCII graphic character:
4428 /// U+0021 '!' ... U+007E '~'.
4433 /// let uppercase_a = b'A';
4434 /// let uppercase_g = b'G';
4437 /// let zero = b'0';
4438 /// let percent = b'%';
4439 /// let space = b' ';
4441 /// let esc = 0x1b_u8;
4443 /// assert!(uppercase_a.is_ascii_graphic());
4444 /// assert!(uppercase_g.is_ascii_graphic());
4445 /// assert!(a.is_ascii_graphic());
4446 /// assert!(g.is_ascii_graphic());
4447 /// assert!(zero.is_ascii_graphic());
4448 /// assert!(percent.is_ascii_graphic());
4449 /// assert!(!space.is_ascii_graphic());
4450 /// assert!(!lf.is_ascii_graphic());
4451 /// assert!(!esc.is_ascii_graphic());
4453 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4455 pub fn is_ascii_graphic(&self) -> bool {
4457 b'!'..=b'~' => true,
4462 /// Checks if the value is an ASCII whitespace character:
4463 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4464 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4466 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4467 /// whitespace][infra-aw]. There are several other definitions in
4468 /// wide use. For instance, [the POSIX locale][pct] includes
4469 /// U+000B VERTICAL TAB as well as all the above characters,
4470 /// but—from the very same specification—[the default rule for
4471 /// "field splitting" in the Bourne shell][bfs] considers *only*
4472 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4474 /// If you are writing a program that will process an existing
4475 /// file format, check what that format's definition of whitespace is
4476 /// before using this function.
4478 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4479 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4480 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4485 /// let uppercase_a = b'A';
4486 /// let uppercase_g = b'G';
4489 /// let zero = b'0';
4490 /// let percent = b'%';
4491 /// let space = b' ';
4493 /// let esc = 0x1b_u8;
4495 /// assert!(!uppercase_a.is_ascii_whitespace());
4496 /// assert!(!uppercase_g.is_ascii_whitespace());
4497 /// assert!(!a.is_ascii_whitespace());
4498 /// assert!(!g.is_ascii_whitespace());
4499 /// assert!(!zero.is_ascii_whitespace());
4500 /// assert!(!percent.is_ascii_whitespace());
4501 /// assert!(space.is_ascii_whitespace());
4502 /// assert!(lf.is_ascii_whitespace());
4503 /// assert!(!esc.is_ascii_whitespace());
4505 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4507 pub fn is_ascii_whitespace(&self) -> bool {
4509 b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' => true,
4514 /// Checks if the value is an ASCII control character:
4515 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4516 /// Note that most ASCII whitespace characters are control
4517 /// characters, but SPACE is not.
4522 /// let uppercase_a = b'A';
4523 /// let uppercase_g = b'G';
4526 /// let zero = b'0';
4527 /// let percent = b'%';
4528 /// let space = b' ';
4530 /// let esc = 0x1b_u8;
4532 /// assert!(!uppercase_a.is_ascii_control());
4533 /// assert!(!uppercase_g.is_ascii_control());
4534 /// assert!(!a.is_ascii_control());
4535 /// assert!(!g.is_ascii_control());
4536 /// assert!(!zero.is_ascii_control());
4537 /// assert!(!percent.is_ascii_control());
4538 /// assert!(!space.is_ascii_control());
4539 /// assert!(lf.is_ascii_control());
4540 /// assert!(esc.is_ascii_control());
4542 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4544 pub fn is_ascii_control(&self) -> bool {
4546 b'\0'..=b'\x1F' | b'\x7F' => true,
4554 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4555 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4560 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4561 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4566 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4567 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4568 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4569 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4575 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4576 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4577 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4578 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4579 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4580 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4581 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4585 #[cfg(target_pointer_width = "16")]
4588 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4589 "[0x34, 0x12]", "[0x12, 0x34]",
4590 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4592 #[cfg(target_pointer_width = "32")]
4595 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4596 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4597 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4600 #[cfg(target_pointer_width = "64")]
4603 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4604 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4605 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4606 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4607 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4610 /// A classification of floating point numbers.
4612 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4613 /// their documentation for more.
4615 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4616 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4621 /// use std::num::FpCategory;
4624 /// let num = 12.4_f32;
4625 /// let inf = f32::INFINITY;
4626 /// let zero = 0f32;
4627 /// let sub: f32 = 1.1754942e-38;
4628 /// let nan = f32::NAN;
4630 /// assert_eq!(num.classify(), FpCategory::Normal);
4631 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4632 /// assert_eq!(zero.classify(), FpCategory::Zero);
4633 /// assert_eq!(nan.classify(), FpCategory::Nan);
4634 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4636 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4637 #[stable(feature = "rust1", since = "1.0.0")]
4638 pub enum FpCategory {
4639 /// "Not a Number", often obtained by dividing by zero.
4640 #[stable(feature = "rust1", since = "1.0.0")]
4643 /// Positive or negative infinity.
4644 #[stable(feature = "rust1", since = "1.0.0")]
4647 /// Positive or negative zero.
4648 #[stable(feature = "rust1", since = "1.0.0")]
4651 /// De-normalized floating point representation (less precise than `Normal`).
4652 #[stable(feature = "rust1", since = "1.0.0")]
4655 /// A regular floating point number.
4656 #[stable(feature = "rust1", since = "1.0.0")]
4660 macro_rules! from_str_radix_int_impl {
4662 #[stable(feature = "rust1", since = "1.0.0")]
4663 impl FromStr for $t {
4664 type Err = ParseIntError;
4665 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4666 from_str_radix(src, 10)
4671 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4673 /// The error type returned when a checked integral type conversion fails.
4674 #[stable(feature = "try_from", since = "1.34.0")]
4675 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4676 pub struct TryFromIntError(());
4678 impl TryFromIntError {
4679 #[unstable(feature = "int_error_internals",
4680 reason = "available through Error trait and this method should \
4681 not be exposed publicly",
4684 pub fn __description(&self) -> &str {
4685 "out of range integral type conversion attempted"
4689 #[stable(feature = "try_from", since = "1.34.0")]
4690 impl fmt::Display for TryFromIntError {
4691 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4692 self.__description().fmt(fmt)
4696 #[stable(feature = "try_from", since = "1.34.0")]
4697 impl From<Infallible> for TryFromIntError {
4698 fn from(x: Infallible) -> TryFromIntError {
4703 #[unstable(feature = "never_type", issue = "35121")]
4704 impl From<!> for TryFromIntError {
4705 fn from(never: !) -> TryFromIntError {
4706 // Match rather than coerce to make sure that code like
4707 // `From<Infallible> for TryFromIntError` above will keep working
4708 // when `Infallible` becomes an alias to `!`.
4713 // no possible bounds violation
4714 macro_rules! try_from_unbounded {
4715 ($source:ty, $($target:ty),*) => {$(
4716 #[stable(feature = "try_from", since = "1.34.0")]
4717 impl TryFrom<$source> for $target {
4718 type Error = TryFromIntError;
4720 /// Try to create the target number type from a source
4721 /// number type. This returns an error if the source value
4722 /// is outside of the range of the target type.
4724 fn try_from(value: $source) -> Result<Self, Self::Error> {
4725 Ok(value as $target)
4731 // only negative bounds
4732 macro_rules! try_from_lower_bounded {
4733 ($source:ty, $($target:ty),*) => {$(
4734 #[stable(feature = "try_from", since = "1.34.0")]
4735 impl TryFrom<$source> for $target {
4736 type Error = TryFromIntError;
4738 /// Try to create the target number type from a source
4739 /// number type. This returns an error if the source value
4740 /// is outside of the range of the target type.
4742 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4746 Err(TryFromIntError(()))
4753 // unsigned to signed (only positive bound)
4754 macro_rules! try_from_upper_bounded {
4755 ($source:ty, $($target:ty),*) => {$(
4756 #[stable(feature = "try_from", since = "1.34.0")]
4757 impl TryFrom<$source> for $target {
4758 type Error = TryFromIntError;
4760 /// Try to create the target number type from a source
4761 /// number type. This returns an error if the source value
4762 /// is outside of the range of the target type.
4764 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4765 if u > (<$target>::max_value() as $source) {
4766 Err(TryFromIntError(()))
4776 macro_rules! try_from_both_bounded {
4777 ($source:ty, $($target:ty),*) => {$(
4778 #[stable(feature = "try_from", since = "1.34.0")]
4779 impl TryFrom<$source> for $target {
4780 type Error = TryFromIntError;
4782 /// Try to create the target number type from a source
4783 /// number type. This returns an error if the source value
4784 /// is outside of the range of the target type.
4786 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4787 let min = <$target>::min_value() as $source;
4788 let max = <$target>::max_value() as $source;
4789 if u < min || u > max {
4790 Err(TryFromIntError(()))
4800 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4801 $mac!($target, $source);
4805 // intra-sign conversions
4806 try_from_upper_bounded!(u16, u8);
4807 try_from_upper_bounded!(u32, u16, u8);
4808 try_from_upper_bounded!(u64, u32, u16, u8);
4809 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4811 try_from_both_bounded!(i16, i8);
4812 try_from_both_bounded!(i32, i16, i8);
4813 try_from_both_bounded!(i64, i32, i16, i8);
4814 try_from_both_bounded!(i128, i64, i32, i16, i8);
4816 // unsigned-to-signed
4817 try_from_upper_bounded!(u8, i8);
4818 try_from_upper_bounded!(u16, i8, i16);
4819 try_from_upper_bounded!(u32, i8, i16, i32);
4820 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4821 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4823 // signed-to-unsigned
4824 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4825 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4826 try_from_lower_bounded!(i32, u32, u64, u128);
4827 try_from_lower_bounded!(i64, u64, u128);
4828 try_from_lower_bounded!(i128, u128);
4829 try_from_both_bounded!(i16, u8);
4830 try_from_both_bounded!(i32, u16, u8);
4831 try_from_both_bounded!(i64, u32, u16, u8);
4832 try_from_both_bounded!(i128, u64, u32, u16, u8);
4835 try_from_upper_bounded!(usize, isize);
4836 try_from_lower_bounded!(isize, usize);
4838 #[cfg(target_pointer_width = "16")]
4839 mod ptr_try_from_impls {
4840 use super::TryFromIntError;
4841 use crate::convert::TryFrom;
4843 try_from_upper_bounded!(usize, u8);
4844 try_from_unbounded!(usize, u16, u32, u64, u128);
4845 try_from_upper_bounded!(usize, i8, i16);
4846 try_from_unbounded!(usize, i32, i64, i128);
4848 try_from_both_bounded!(isize, u8);
4849 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4850 try_from_both_bounded!(isize, i8);
4851 try_from_unbounded!(isize, i16, i32, i64, i128);
4853 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4854 rev!(try_from_lower_bounded, usize, i8, i16);
4855 rev!(try_from_both_bounded, usize, i32, i64, i128);
4857 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4858 rev!(try_from_both_bounded, isize, i32, i64, i128);
4861 #[cfg(target_pointer_width = "32")]
4862 mod ptr_try_from_impls {
4863 use super::TryFromIntError;
4864 use crate::convert::TryFrom;
4866 try_from_upper_bounded!(usize, u8, u16);
4867 try_from_unbounded!(usize, u32, u64, u128);
4868 try_from_upper_bounded!(usize, i8, i16, i32);
4869 try_from_unbounded!(usize, i64, i128);
4871 try_from_both_bounded!(isize, u8, u16);
4872 try_from_lower_bounded!(isize, u32, u64, u128);
4873 try_from_both_bounded!(isize, i8, i16);
4874 try_from_unbounded!(isize, i32, i64, i128);
4876 rev!(try_from_unbounded, usize, u32);
4877 rev!(try_from_upper_bounded, usize, u64, u128);
4878 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4879 rev!(try_from_both_bounded, usize, i64, i128);
4881 rev!(try_from_unbounded, isize, u16);
4882 rev!(try_from_upper_bounded, isize, u32, u64, u128);
4883 rev!(try_from_unbounded, isize, i32);
4884 rev!(try_from_both_bounded, isize, i64, i128);
4887 #[cfg(target_pointer_width = "64")]
4888 mod ptr_try_from_impls {
4889 use super::TryFromIntError;
4890 use crate::convert::TryFrom;
4892 try_from_upper_bounded!(usize, u8, u16, u32);
4893 try_from_unbounded!(usize, u64, u128);
4894 try_from_upper_bounded!(usize, i8, i16, i32, i64);
4895 try_from_unbounded!(usize, i128);
4897 try_from_both_bounded!(isize, u8, u16, u32);
4898 try_from_lower_bounded!(isize, u64, u128);
4899 try_from_both_bounded!(isize, i8, i16, i32);
4900 try_from_unbounded!(isize, i64, i128);
4902 rev!(try_from_unbounded, usize, u32, u64);
4903 rev!(try_from_upper_bounded, usize, u128);
4904 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4905 rev!(try_from_both_bounded, usize, i128);
4907 rev!(try_from_unbounded, isize, u16, u32);
4908 rev!(try_from_upper_bounded, isize, u64, u128);
4909 rev!(try_from_unbounded, isize, i32, i64);
4910 rev!(try_from_both_bounded, isize, i128);
4914 trait FromStrRadixHelper: PartialOrd + Copy {
4915 fn min_value() -> Self;
4916 fn max_value() -> Self;
4917 fn from_u32(u: u32) -> Self;
4918 fn checked_mul(&self, other: u32) -> Option<Self>;
4919 fn checked_sub(&self, other: u32) -> Option<Self>;
4920 fn checked_add(&self, other: u32) -> Option<Self>;
4924 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4926 fn min_value() -> Self { Self::min_value() }
4928 fn max_value() -> Self { Self::max_value() }
4930 fn from_u32(u: u32) -> Self { u as Self }
4932 fn checked_mul(&self, other: u32) -> Option<Self> {
4933 Self::checked_mul(*self, other as Self)
4936 fn checked_sub(&self, other: u32) -> Option<Self> {
4937 Self::checked_sub(*self, other as Self)
4940 fn checked_add(&self, other: u32) -> Option<Self> {
4941 Self::checked_add(*self, other as Self)
4945 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4947 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4948 use self::IntErrorKind::*;
4949 use self::ParseIntError as PIE;
4951 assert!(radix >= 2 && radix <= 36,
4952 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4956 return Err(PIE { kind: Empty });
4959 let is_signed_ty = T::from_u32(0) > T::min_value();
4961 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4962 // and cast them to chars. .to_digit() will safely return None for anything
4963 // other than a valid ascii digit for the given radix, including the first-byte
4964 // of multi-byte sequences
4965 let src = src.as_bytes();
4967 let (is_positive, digits) = match src[0] {
4968 b'+' => (true, &src[1..]),
4969 b'-' if is_signed_ty => (false, &src[1..]),
4973 if digits.is_empty() {
4974 return Err(PIE { kind: Empty });
4977 let mut result = T::from_u32(0);
4979 // The number is positive
4981 let x = match (c as char).to_digit(radix) {
4983 None => return Err(PIE { kind: InvalidDigit }),
4985 result = match result.checked_mul(radix) {
4986 Some(result) => result,
4987 None => return Err(PIE { kind: Overflow }),
4989 result = match result.checked_add(x) {
4990 Some(result) => result,
4991 None => return Err(PIE { kind: Overflow }),
4995 // The number is negative
4997 let x = match (c as char).to_digit(radix) {
4999 None => return Err(PIE { kind: InvalidDigit }),
5001 result = match result.checked_mul(radix) {
5002 Some(result) => result,
5003 None => return Err(PIE { kind: Underflow }),
5005 result = match result.checked_sub(x) {
5006 Some(result) => result,
5007 None => return Err(PIE { kind: Underflow }),
5014 /// An error which can be returned when parsing an integer.
5016 /// This error is used as the error type for the `from_str_radix()` functions
5017 /// on the primitive integer types, such as [`i8::from_str_radix`].
5019 /// # Potential causes
5021 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5022 /// in the string e.g., when it is obtained from the standard input.
5023 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5025 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5026 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5027 #[derive(Debug, Clone, PartialEq, Eq)]
5028 #[stable(feature = "rust1", since = "1.0.0")]
5029 pub struct ParseIntError {
5033 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5034 #[unstable(feature = "int_error_matching",
5035 reason = "it can be useful to match errors when making error messages \
5036 for integer parsing",
5038 #[derive(Debug, Clone, PartialEq, Eq)]
5040 pub enum IntErrorKind {
5041 /// Value being parsed is empty.
5043 /// Among other causes, this variant will be constructed when parsing an empty string.
5045 /// Contains an invalid digit.
5047 /// Among other causes, this variant will be constructed when parsing a string that
5048 /// contains a letter.
5050 /// Integer is too large to store in target integer type.
5052 /// Integer is too small to store in target integer type.
5056 /// This variant will be emitted when the parsing string has a value of zero, which
5057 /// would be illegal for non-zero types.
5061 impl ParseIntError {
5062 /// Outputs the detailed cause of parsing an integer failing.
5063 #[unstable(feature = "int_error_matching",
5064 reason = "it can be useful to match errors when making error messages \
5065 for integer parsing",
5067 pub fn kind(&self) -> &IntErrorKind {
5070 #[unstable(feature = "int_error_internals",
5071 reason = "available through Error trait and this method should \
5072 not be exposed publicly",
5075 pub fn __description(&self) -> &str {
5077 IntErrorKind::Empty => "cannot parse integer from empty string",
5078 IntErrorKind::InvalidDigit => "invalid digit found in string",
5079 IntErrorKind::Overflow => "number too large to fit in target type",
5080 IntErrorKind::Underflow => "number too small to fit in target type",
5081 IntErrorKind::Zero => "number would be zero for non-zero type",
5086 #[stable(feature = "rust1", since = "1.0.0")]
5087 impl fmt::Display for ParseIntError {
5088 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5089 self.__description().fmt(f)
5093 #[stable(feature = "rust1", since = "1.0.0")]
5094 pub use crate::num::dec2flt::ParseFloatError;
5096 // Conversion traits for primitive integer and float types
5097 // Conversions T -> T are covered by a blanket impl and therefore excluded
5098 // Some conversions from and to usize/isize are not implemented due to portability concerns
5099 macro_rules! impl_from {
5100 ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
5103 impl From<$Small> for $Large {
5105 fn from(small: $Small) -> $Large {
5110 ($Small: ty, $Large: ty, #[$attr:meta]) => {
5114 concat!("Converts `",
5122 macro_rules! impl_from_bool {
5123 ($target: ty, #[$attr:meta]) => {
5124 impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
5125 stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
5131 assert_eq!(", stringify!($target), "::from(true), 1);
5132 assert_eq!(", stringify!($target), "::from(false), 0);
5138 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
5139 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
5140 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
5141 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
5142 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
5143 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
5144 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
5145 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
5146 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
5147 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
5148 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
5149 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
5151 // Unsigned -> Unsigned
5152 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5153 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5154 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5155 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
5156 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5157 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5158 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5159 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
5160 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5161 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
5162 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
5165 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5166 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5167 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5168 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5169 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5170 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5171 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5172 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5173 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5174 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5175 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5177 // Unsigned -> Signed
5178 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5179 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5180 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5181 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5182 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5183 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5184 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5185 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5186 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5187 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5189 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
5190 // which imply that pointer-sized integers must be at least 16 bits:
5191 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
5192 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5193 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5194 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5196 // RISC-V defines the possibility of a 128-bit address space (RV128).
5198 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
5199 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
5200 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
5203 // Note: integers can only be represented with full precision in a float if
5204 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
5205 // Lossy float conversions are not implemented at this time.
5208 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5209 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5210 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5211 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5212 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5214 // Unsigned -> Float
5215 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5216 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5217 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5218 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5219 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5222 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }