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(stage0), 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 #![feature(reverse_bits)]
468 let n = ", $swap_op, stringify!($SelfT), ";
469 let m = n.reverse_bits();
471 assert_eq!(m, ", $reversed, ");
473 #[unstable(feature = "reverse_bits", issue = "48763")]
474 #[rustc_const_unstable(feature = "const_int_conversion")]
476 pub const fn reverse_bits(self) -> Self {
477 (self as $UnsignedT).reverse_bits() as Self
482 concat!("Converts an integer from big endian to the target's endianness.
484 On big endian this is a no-op. On little endian the bytes are swapped.
491 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
493 if cfg!(target_endian = \"big\") {
494 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
496 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
500 #[stable(feature = "rust1", since = "1.0.0")]
502 pub const fn from_be(x: Self) -> Self {
503 #[cfg(target_endian = "big")]
507 #[cfg(not(target_endian = "big"))]
515 concat!("Converts an integer from little endian to the target's endianness.
517 On little endian this is a no-op. On big endian the bytes are swapped.
524 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
526 if cfg!(target_endian = \"little\") {
527 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
529 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
533 #[stable(feature = "rust1", since = "1.0.0")]
535 pub const fn from_le(x: Self) -> Self {
536 #[cfg(target_endian = "little")]
540 #[cfg(not(target_endian = "little"))]
548 concat!("Converts `self` to big endian from the target's endianness.
550 On big endian this is a no-op. On little endian the bytes are swapped.
557 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
559 if cfg!(target_endian = \"big\") {
560 assert_eq!(n.to_be(), n)
562 assert_eq!(n.to_be(), n.swap_bytes())
566 #[stable(feature = "rust1", since = "1.0.0")]
568 pub const fn to_be(self) -> Self { // or not to be?
569 #[cfg(target_endian = "big")]
573 #[cfg(not(target_endian = "big"))]
581 concat!("Converts `self` to little endian from the target's endianness.
583 On little endian this is a no-op. On big endian the bytes are swapped.
590 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
592 if cfg!(target_endian = \"little\") {
593 assert_eq!(n.to_le(), n)
595 assert_eq!(n.to_le(), n.swap_bytes())
599 #[stable(feature = "rust1", since = "1.0.0")]
601 pub const fn to_le(self) -> Self {
602 #[cfg(target_endian = "little")]
606 #[cfg(not(target_endian = "little"))]
614 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
615 if overflow occurred.
622 ", $Feature, "assert_eq!((", stringify!($SelfT),
623 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
624 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
627 #[stable(feature = "rust1", since = "1.0.0")]
628 #[must_use = "this returns the result of the operation, \
629 without modifying the original"]
631 pub fn checked_add(self, rhs: Self) -> Option<Self> {
632 let (a, b) = self.overflowing_add(rhs);
633 if b {None} else {Some(a)}
638 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
646 ", $Feature, "assert_eq!((", stringify!($SelfT),
647 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
648 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
651 #[stable(feature = "rust1", since = "1.0.0")]
652 #[must_use = "this returns the result of the operation, \
653 without modifying the original"]
655 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
656 let (a, b) = self.overflowing_sub(rhs);
657 if b {None} else {Some(a)}
662 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
670 ", $Feature, "assert_eq!(", stringify!($SelfT),
671 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
672 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
675 #[stable(feature = "rust1", since = "1.0.0")]
676 #[must_use = "this returns the result of the operation, \
677 without modifying the original"]
679 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
680 let (a, b) = self.overflowing_mul(rhs);
681 if b {None} else {Some(a)}
686 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
687 or the division results in overflow.
694 ", $Feature, "assert_eq!((", stringify!($SelfT),
695 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
696 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
697 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
700 #[stable(feature = "rust1", since = "1.0.0")]
701 #[must_use = "this returns the result of the operation, \
702 without modifying the original"]
704 pub fn checked_div(self, rhs: Self) -> Option<Self> {
705 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
708 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
714 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
715 returning `None` if `rhs == 0` or the division results in overflow.
722 #![feature(euclidean_division)]
723 assert_eq!((", stringify!($SelfT),
724 "::min_value() + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
725 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euclid(-1), None);
726 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
728 #[unstable(feature = "euclidean_division", issue = "49048")]
729 #[must_use = "this returns the result of the operation, \
730 without modifying the original"]
732 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
733 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
736 Some(self.div_euclid(rhs))
742 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
743 `rhs == 0` or the division results in overflow.
750 ", $Feature, "use std::", stringify!($SelfT), ";
752 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
753 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
754 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
757 #[stable(feature = "wrapping", since = "1.7.0")]
758 #[must_use = "this returns the result of the operation, \
759 without modifying the original"]
761 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
762 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
765 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
771 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
772 if `rhs == 0` or the division results in overflow.
779 #![feature(euclidean_division)]
780 use std::", stringify!($SelfT), ";
782 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
783 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
784 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
786 #[unstable(feature = "euclidean_division", issue = "49048")]
787 #[must_use = "this returns the result of the operation, \
788 without modifying the original"]
790 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
791 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
794 Some(self.rem_euclid(rhs))
800 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
807 ", $Feature, "use std::", stringify!($SelfT), ";
809 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
810 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
813 #[stable(feature = "wrapping", since = "1.7.0")]
815 pub fn checked_neg(self) -> Option<Self> {
816 let (a, b) = self.overflowing_neg();
817 if b {None} else {Some(a)}
822 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
823 than or equal to the number of bits in `self`.
830 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
831 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
834 #[stable(feature = "wrapping", since = "1.7.0")]
835 #[must_use = "this returns the result of the operation, \
836 without modifying the original"]
838 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
839 let (a, b) = self.overflowing_shl(rhs);
840 if b {None} else {Some(a)}
845 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
846 larger than or equal to the number of bits in `self`.
853 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
854 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
857 #[stable(feature = "wrapping", since = "1.7.0")]
858 #[must_use = "this returns the result of the operation, \
859 without modifying the original"]
861 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
862 let (a, b) = self.overflowing_shr(rhs);
863 if b {None} else {Some(a)}
868 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
876 ", $Feature, "use std::", stringify!($SelfT), ";
878 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
879 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
882 #[stable(feature = "no_panic_abs", since = "1.13.0")]
884 pub fn checked_abs(self) -> Option<Self> {
885 if self.is_negative() {
894 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
902 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
903 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
907 #[stable(feature = "no_panic_pow", since = "1.34.0")]
908 #[must_use = "this returns the result of the operation, \
909 without modifying the original"]
911 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
913 let mut acc: Self = 1;
917 acc = acc.checked_mul(base)?;
920 base = base.checked_mul(base)?;
923 // Deal with the final bit of the exponent separately, since
924 // squaring the base afterwards is not necessary and may cause a
925 // needless overflow.
927 acc = acc.checked_mul(base)?;
935 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
936 bounds instead of overflowing.
943 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
944 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
949 #[stable(feature = "rust1", since = "1.0.0")]
950 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
951 #[must_use = "this returns the result of the operation, \
952 without modifying the original"]
954 pub const fn saturating_add(self, rhs: Self) -> Self {
955 intrinsics::saturating_add(self, rhs)
961 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
962 numeric bounds instead of overflowing.
969 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
970 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
974 #[stable(feature = "rust1", since = "1.0.0")]
975 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
976 #[must_use = "this returns the result of the operation, \
977 without modifying the original"]
979 pub const fn saturating_sub(self, rhs: Self) -> Self {
980 intrinsics::saturating_sub(self, rhs)
985 concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
986 instead of overflowing.
993 ", $Feature, "#![feature(saturating_neg)]
994 assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
995 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
996 assert_eq!(", stringify!($SelfT), "::min_value().saturating_neg(), ", stringify!($SelfT),
998 assert_eq!(", stringify!($SelfT), "::max_value().saturating_neg(), ", stringify!($SelfT),
999 "::min_value() + 1);",
1003 #[unstable(feature = "saturating_neg", issue = "59983")]
1005 pub fn saturating_neg(self) -> Self {
1006 intrinsics::saturating_sub(0, self)
1011 concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1012 MIN` instead of overflowing.
1019 ", $Feature, "#![feature(saturating_neg)]
1020 assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
1021 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
1022 assert_eq!(", stringify!($SelfT), "::min_value().saturating_abs(), ", stringify!($SelfT),
1024 assert_eq!((", stringify!($SelfT), "::min_value() + 1).saturating_abs(), ", stringify!($SelfT),
1029 #[unstable(feature = "saturating_neg", issue = "59983")]
1031 pub fn saturating_abs(self) -> Self {
1032 if self.is_negative() {
1033 self.saturating_neg()
1041 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1042 numeric bounds instead of overflowing.
1049 ", $Feature, "use std::", stringify!($SelfT), ";
1051 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1052 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1053 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1056 #[stable(feature = "wrapping", since = "1.7.0")]
1057 #[must_use = "this returns the result of the operation, \
1058 without modifying the original"]
1060 pub fn saturating_mul(self, rhs: Self) -> Self {
1061 self.checked_mul(rhs).unwrap_or_else(|| {
1062 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
1072 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1073 saturating at the numeric bounds instead of overflowing.
1080 ", $Feature, "use std::", stringify!($SelfT), ";
1082 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1083 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1084 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1087 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1088 #[must_use = "this returns the result of the operation, \
1089 without modifying the original"]
1091 pub fn saturating_pow(self, exp: u32) -> Self {
1092 match self.checked_pow(exp) {
1094 None if self < 0 && exp % 2 == 1 => Self::min_value(),
1095 None => Self::max_value(),
1101 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1102 boundary of the type.
1109 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1110 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
1111 "::min_value() + 1);",
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 #[must_use = "this returns the result of the operation, \
1116 without modifying the original"]
1118 pub const fn wrapping_add(self, rhs: Self) -> Self {
1119 intrinsics::overflowing_add(self, rhs)
1124 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1125 boundary of the type.
1132 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1133 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1134 stringify!($SelfT), "::max_value());",
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 #[must_use = "this returns the result of the operation, \
1139 without modifying the original"]
1141 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1142 intrinsics::overflowing_sub(self, rhs)
1147 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1148 the boundary of the type.
1155 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1156 assert_eq!(11i8.wrapping_mul(12), -124);",
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 #[must_use = "this returns the result of the operation, \
1161 without modifying the original"]
1163 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1164 intrinsics::overflowing_mul(self, rhs)
1169 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1170 boundary of the type.
1172 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1173 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1174 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1178 This function will panic if `rhs` is 0.
1185 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1186 assert_eq!((-128i8).wrapping_div(-1), -128);",
1189 #[stable(feature = "num_wrapping", since = "1.2.0")]
1190 #[must_use = "this returns the result of the operation, \
1191 without modifying the original"]
1193 pub fn wrapping_div(self, rhs: Self) -> Self {
1194 self.overflowing_div(rhs).0
1199 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1200 wrapping around at the boundary of the type.
1202 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1203 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1204 type. In this case, this method returns `MIN` itself.
1208 This function will panic if `rhs` is 0.
1215 #![feature(euclidean_division)]
1216 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1217 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1219 #[unstable(feature = "euclidean_division", issue = "49048")]
1220 #[must_use = "this returns the result of the operation, \
1221 without modifying the original"]
1223 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
1224 self.overflowing_div_euclid(rhs).0
1229 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1230 boundary of the type.
1232 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1233 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1234 this function returns `0`.
1238 This function will panic if `rhs` is 0.
1245 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1246 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1249 #[stable(feature = "num_wrapping", since = "1.2.0")]
1250 #[must_use = "this returns the result of the operation, \
1251 without modifying the original"]
1253 pub fn wrapping_rem(self, rhs: Self) -> Self {
1254 self.overflowing_rem(rhs).0
1259 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1260 at the boundary of the type.
1262 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1263 for the type). In this case, this method returns 0.
1267 This function will panic if `rhs` is 0.
1274 #![feature(euclidean_division)]
1275 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1276 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1278 #[unstable(feature = "euclidean_division", issue = "49048")]
1279 #[must_use = "this returns the result of the operation, \
1280 without modifying the original"]
1282 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1283 self.overflowing_rem_euclid(rhs).0
1288 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1291 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1292 is the negative minimal value for the type); this is a positive value that is too large to represent
1293 in the type. In such a case, this function returns `MIN` itself.
1300 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1301 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1305 #[stable(feature = "num_wrapping", since = "1.2.0")]
1307 pub const fn wrapping_neg(self) -> Self {
1308 self.overflowing_neg().0
1313 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1314 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1316 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1317 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1318 The primitive integer types all implement a `rotate_left` function, which may be what you want
1326 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1327 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1330 #[stable(feature = "num_wrapping", since = "1.2.0")]
1331 #[must_use = "this returns the result of the operation, \
1332 without modifying the original"]
1334 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1336 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1342 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1343 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1345 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1346 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1347 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1355 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1356 assert_eq!((-128i16).wrapping_shr(64), -128);",
1359 #[stable(feature = "num_wrapping", since = "1.2.0")]
1360 #[must_use = "this returns the result of the operation, \
1361 without modifying the original"]
1363 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1365 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1371 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1372 the boundary of the type.
1374 The only case where such wrapping can occur is when one takes the absolute value of the negative
1375 minimal value for the type this is a positive value that is too large to represent in the type. In
1376 such a case, this function returns `MIN` itself.
1383 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1384 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1385 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1387 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1390 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1392 pub fn wrapping_abs(self) -> Self {
1393 if self.is_negative() {
1402 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1403 wrapping around at the boundary of the type.
1410 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1411 assert_eq!(3i8.wrapping_pow(5), -13);
1412 assert_eq!(3i8.wrapping_pow(6), -39);",
1415 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1416 #[must_use = "this returns the result of the operation, \
1417 without modifying the original"]
1419 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1420 let mut base = self;
1421 let mut acc: Self = 1;
1425 acc = acc.wrapping_mul(base);
1428 base = base.wrapping_mul(base);
1431 // Deal with the final bit of the exponent separately, since
1432 // squaring the base afterwards is not necessary and may cause a
1433 // needless overflow.
1435 acc = acc.wrapping_mul(base);
1443 concat!("Calculates `self` + `rhs`
1445 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1446 occur. If an overflow would have occurred then the wrapped value is returned.
1453 ", $Feature, "use std::", stringify!($SelfT), ";
1455 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1456 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1457 "::MIN, true));", $EndFeature, "
1459 #[stable(feature = "wrapping", since = "1.7.0")]
1460 #[must_use = "this returns the result of the operation, \
1461 without modifying the original"]
1463 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1464 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1470 concat!("Calculates `self` - `rhs`
1472 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1473 would occur. If an overflow would have occurred then the wrapped value is returned.
1480 ", $Feature, "use std::", stringify!($SelfT), ";
1482 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1483 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1484 "::MAX, true));", $EndFeature, "
1486 #[stable(feature = "wrapping", since = "1.7.0")]
1487 #[must_use = "this returns the result of the operation, \
1488 without modifying the original"]
1490 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1491 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1497 concat!("Calculates the multiplication of `self` and `rhs`.
1499 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1500 would occur. If an overflow would have occurred then the wrapped value is returned.
1507 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1508 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1511 #[stable(feature = "wrapping", since = "1.7.0")]
1512 #[must_use = "this returns the result of the operation, \
1513 without modifying the original"]
1515 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1516 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1522 concat!("Calculates the divisor when `self` is divided by `rhs`.
1524 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1525 occur. If an overflow would occur then self is returned.
1529 This function will panic if `rhs` is 0.
1536 ", $Feature, "use std::", stringify!($SelfT), ";
1538 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1539 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1544 #[stable(feature = "wrapping", since = "1.7.0")]
1545 #[must_use = "this returns the result of the operation, \
1546 without modifying the original"]
1547 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1548 if self == Self::min_value() && rhs == -1 {
1557 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1559 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1560 occur. If an overflow would occur then `self` is returned.
1564 This function will panic if `rhs` is 0.
1571 #![feature(euclidean_division)]
1572 use std::", stringify!($SelfT), ";
1574 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1575 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1579 #[unstable(feature = "euclidean_division", issue = "49048")]
1580 #[must_use = "this returns the result of the operation, \
1581 without modifying the original"]
1582 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1583 if self == Self::min_value() && rhs == -1 {
1586 (self.div_euclid(rhs), false)
1592 concat!("Calculates the remainder when `self` is divided by `rhs`.
1594 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1595 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1599 This function will panic if `rhs` is 0.
1606 ", $Feature, "use std::", stringify!($SelfT), ";
1608 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1609 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1613 #[stable(feature = "wrapping", since = "1.7.0")]
1614 #[must_use = "this returns the result of the operation, \
1615 without modifying the original"]
1616 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1617 if self == Self::min_value() && rhs == -1 {
1627 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1629 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1630 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1634 This function will panic if `rhs` is 0.
1641 #![feature(euclidean_division)]
1642 use std::", stringify!($SelfT), ";
1644 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1645 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1647 #[unstable(feature = "euclidean_division", issue = "49048")]
1648 #[must_use = "this returns the result of the operation, \
1649 without modifying the original"]
1651 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1652 if self == Self::min_value() && rhs == -1 {
1655 (self.rem_euclid(rhs), false)
1662 concat!("Negates self, overflowing if this is equal to the minimum value.
1664 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1665 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1666 minimum value will be returned again and `true` will be returned for an overflow happening.
1673 ", $Feature, "use std::", stringify!($SelfT), ";
1675 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1676 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1677 "::MIN, true));", $EndFeature, "
1680 #[stable(feature = "wrapping", since = "1.7.0")]
1681 pub const fn overflowing_neg(self) -> (Self, bool) {
1682 ((!self).wrapping_add(1), self == Self::min_value())
1687 concat!("Shifts self left by `rhs` bits.
1689 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1690 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1691 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1698 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1699 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1702 #[stable(feature = "wrapping", since = "1.7.0")]
1703 #[must_use = "this returns the result of the operation, \
1704 without modifying the original"]
1706 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1707 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1712 concat!("Shifts self right by `rhs` bits.
1714 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1715 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1716 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1723 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1724 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1727 #[stable(feature = "wrapping", since = "1.7.0")]
1728 #[must_use = "this returns the result of the operation, \
1729 without modifying the original"]
1731 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1732 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1737 concat!("Computes the absolute value of `self`.
1739 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1740 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1741 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1742 for an overflow happening.
1749 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1750 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1751 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1752 "::min_value(), true));",
1755 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1757 pub fn overflowing_abs(self) -> (Self, bool) {
1758 if self.is_negative() {
1759 self.overflowing_neg()
1767 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1769 Returns a tuple of the exponentiation along with a bool indicating
1770 whether an overflow happened.
1777 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1778 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1781 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1782 #[must_use = "this returns the result of the operation, \
1783 without modifying the original"]
1785 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1786 let mut base = self;
1787 let mut acc: Self = 1;
1788 let mut overflown = false;
1789 // Scratch space for storing results of overflowing_mul.
1794 r = acc.overflowing_mul(base);
1799 r = base.overflowing_mul(base);
1804 // Deal with the final bit of the exponent separately, since
1805 // squaring the base afterwards is not necessary and may cause a
1806 // needless overflow.
1808 r = acc.overflowing_mul(base);
1818 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1825 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1827 assert_eq!(x.pow(5), 32);",
1830 #[stable(feature = "rust1", since = "1.0.0")]
1831 #[must_use = "this returns the result of the operation, \
1832 without modifying the original"]
1834 #[rustc_inherit_overflow_checks]
1835 pub fn pow(self, mut exp: u32) -> Self {
1836 let mut base = self;
1847 // Deal with the final bit of the exponent separately, since
1848 // squaring the base afterwards is not necessary and may cause a
1849 // needless overflow.
1859 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1861 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
1862 with `0 <= self.rem_euclid(rhs) < rhs`.
1864 In other words, the result is `self / rhs` rounded to the integer `n`
1865 such that `self >= n * rhs`.
1866 If `self > 0`, this is equal to round towards zero (the default in Rust);
1867 if `self < 0`, this is equal to round towards +/- infinity.
1871 This function will panic if `rhs` is 0.
1878 #![feature(euclidean_division)]
1879 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1882 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
1883 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
1884 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
1885 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
1887 #[unstable(feature = "euclidean_division", issue = "49048")]
1888 #[must_use = "this returns the result of the operation, \
1889 without modifying the original"]
1891 #[rustc_inherit_overflow_checks]
1892 pub fn div_euclid(self, rhs: Self) -> Self {
1895 return if rhs > 0 { q - 1 } else { q + 1 }
1903 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
1905 This is done as if by the Euclidean division algorithm -- given
1906 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
1907 `0 <= r < abs(rhs)`.
1911 This function will panic if `rhs` is 0.
1918 #![feature(euclidean_division)]
1919 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1922 assert_eq!(a.rem_euclid(b), 3);
1923 assert_eq!((-a).rem_euclid(b), 1);
1924 assert_eq!(a.rem_euclid(-b), 3);
1925 assert_eq!((-a).rem_euclid(-b), 1);
1927 #[unstable(feature = "euclidean_division", issue = "49048")]
1928 #[must_use = "this returns the result of the operation, \
1929 without modifying the original"]
1931 #[rustc_inherit_overflow_checks]
1932 pub fn rem_euclid(self, rhs: Self) -> Self {
1947 concat!("Computes the absolute value of `self`.
1951 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1952 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1953 code in debug mode will trigger a panic on this case and optimized code will return `",
1954 stringify!($SelfT), "::min_value()` without a panic.
1961 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1962 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1965 #[stable(feature = "rust1", since = "1.0.0")]
1967 #[rustc_inherit_overflow_checks]
1968 pub fn abs(self) -> Self {
1969 if self.is_negative() {
1970 // Note that the #[inline] above means that the overflow
1971 // semantics of this negation depend on the crate we're being
1981 concat!("Returns a number representing sign of `self`.
1983 - `0` if the number is zero
1984 - `1` if the number is positive
1985 - `-1` if the number is negative
1992 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1993 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1994 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1997 #[stable(feature = "rust1", since = "1.0.0")]
1999 pub fn signum(self) -> Self {
2009 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2017 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2018 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2021 #[stable(feature = "rust1", since = "1.0.0")]
2023 pub const fn is_positive(self) -> bool { self > 0 }
2027 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2035 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2036 assert!(!10", stringify!($SelfT), ".is_negative());",
2039 #[stable(feature = "rust1", since = "1.0.0")]
2041 pub const fn is_negative(self) -> bool { self < 0 }
2045 concat!("Return the memory representation of this integer as a byte array in
2046 big-endian (network) byte order.
2053 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2054 assert_eq!(bytes, ", $be_bytes, ");
2056 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2057 #[rustc_const_unstable(feature = "const_int_conversion")]
2059 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2060 self.to_be().to_ne_bytes()
2065 concat!("Return the memory representation of this integer as a byte array in
2066 little-endian byte order.
2073 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2074 assert_eq!(bytes, ", $le_bytes, ");
2076 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2077 #[rustc_const_unstable(feature = "const_int_conversion")]
2079 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2080 self.to_le().to_ne_bytes()
2086 Return the memory representation of this integer as a byte array in
2089 As the target platform's native endianness is used, portable code
2090 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2095 [`to_be_bytes`]: #method.to_be_bytes
2096 [`to_le_bytes`]: #method.to_le_bytes
2101 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2102 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
2108 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2109 #[rustc_const_unstable(feature = "const_int_conversion")]
2111 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2112 unsafe { mem::transmute(self) }
2117 concat!("Create an integer value from its representation as a byte array in
2125 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2126 assert_eq!(value, ", $swap_op, ");
2129 When starting from a slice rather than an array, fallible conversion APIs can be used:
2132 use std::convert::TryInto;
2134 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2135 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2137 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2140 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2141 #[rustc_const_unstable(feature = "const_int_conversion")]
2143 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2144 Self::from_be(Self::from_ne_bytes(bytes))
2150 Create an integer value from its representation as a byte array in
2158 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2159 assert_eq!(value, ", $swap_op, ");
2162 When starting from a slice rather than an array, fallible conversion APIs can be used:
2165 use std::convert::TryInto;
2167 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2168 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2170 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2173 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2174 #[rustc_const_unstable(feature = "const_int_conversion")]
2176 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2177 Self::from_le(Self::from_ne_bytes(bytes))
2182 concat!("Create an integer value from its memory representation as a byte
2183 array in native endianness.
2185 As the target platform's native endianness is used, portable code
2186 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2187 appropriate instead.
2189 [`from_be_bytes`]: #method.from_be_bytes
2190 [`from_le_bytes`]: #method.from_le_bytes
2197 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2202 assert_eq!(value, ", $swap_op, ");
2205 When starting from a slice rather than an array, fallible conversion APIs can be used:
2208 use std::convert::TryInto;
2210 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2211 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2213 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2216 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2217 #[rustc_const_unstable(feature = "const_int_conversion")]
2219 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2220 unsafe { mem::transmute(bytes) }
2228 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2229 "[0x12]", "[0x12]", "", "" }
2234 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2235 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2240 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2241 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2242 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2247 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2248 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2249 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2250 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2255 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2256 170141183460469231731687303715884105727, "", "", 16,
2257 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2258 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2259 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2260 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2261 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2262 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2265 #[cfg(target_pointer_width = "16")]
2268 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2269 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2270 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2273 #[cfg(target_pointer_width = "32")]
2276 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2277 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2278 "[0x12, 0x34, 0x56, 0x78]",
2279 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2282 #[cfg(target_pointer_width = "64")]
2285 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2286 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2287 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2288 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2289 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2292 // `Int` + `UnsignedInt` implemented for unsigned integers
2293 macro_rules! uint_impl {
2294 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2295 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2296 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2297 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2299 concat!("Returns the smallest value that can be represented by this integer type.
2306 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2308 #[stable(feature = "rust1", since = "1.0.0")]
2311 pub const fn min_value() -> Self { 0 }
2315 concat!("Returns the largest value that can be represented by this integer type.
2322 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2323 stringify!($MaxV), ");", $EndFeature, "
2325 #[stable(feature = "rust1", since = "1.0.0")]
2328 pub const fn max_value() -> Self { !0 }
2332 concat!("Converts a string slice in a given base to an integer.
2334 The string is expected to be an optional `+` sign
2336 Leading and trailing whitespace represent an error.
2337 Digits are a subset of these characters, depending on `radix`:
2345 This function panics if `radix` is not in the range from 2 to 36.
2352 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2355 #[stable(feature = "rust1", since = "1.0.0")]
2356 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2357 from_str_radix(src, radix)
2362 concat!("Returns the number of ones in the binary representation of `self`.
2369 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2371 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2373 #[stable(feature = "rust1", since = "1.0.0")]
2375 pub const fn count_ones(self) -> u32 {
2376 intrinsics::ctpop(self as $ActualT) as u32
2381 concat!("Returns the number of zeros in the binary representation of `self`.
2388 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2390 #[stable(feature = "rust1", since = "1.0.0")]
2392 pub const fn count_zeros(self) -> u32 {
2393 (!self).count_ones()
2398 concat!("Returns the number of leading zeros in the binary representation of `self`.
2405 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2407 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2409 #[stable(feature = "rust1", since = "1.0.0")]
2411 pub const fn leading_zeros(self) -> u32 {
2412 intrinsics::ctlz(self as $ActualT) as u32
2417 concat!("Returns the number of trailing zeros in the binary representation
2425 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2427 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2429 #[stable(feature = "rust1", since = "1.0.0")]
2431 pub const fn trailing_zeros(self) -> u32 {
2432 intrinsics::cttz(self) as u32
2437 concat!("Shifts the bits to the left by a specified amount, `n`,
2438 wrapping the truncated bits to the end of the resulting integer.
2440 Please note this isn't the same operation as the `<<` shifting operator!
2447 let n = ", $rot_op, stringify!($SelfT), ";
2448 let m = ", $rot_result, ";
2450 assert_eq!(n.rotate_left(", $rot, "), m);
2452 #[stable(feature = "rust1", since = "1.0.0")]
2453 #[must_use = "this returns the result of the operation, \
2454 without modifying the original"]
2456 pub const fn rotate_left(self, n: u32) -> Self {
2457 intrinsics::rotate_left(self, n as $SelfT)
2462 concat!("Shifts the bits to the right by a specified amount, `n`,
2463 wrapping the truncated bits to the beginning of the resulting
2466 Please note this isn't the same operation as the `>>` shifting operator!
2473 let n = ", $rot_result, stringify!($SelfT), ";
2474 let m = ", $rot_op, ";
2476 assert_eq!(n.rotate_right(", $rot, "), m);
2478 #[stable(feature = "rust1", since = "1.0.0")]
2479 #[must_use = "this returns the result of the operation, \
2480 without modifying the original"]
2482 pub const fn rotate_right(self, n: u32) -> Self {
2483 intrinsics::rotate_right(self, n as $SelfT)
2489 Reverses the byte order of the integer.
2496 let n = ", $swap_op, stringify!($SelfT), ";
2497 let m = n.swap_bytes();
2499 assert_eq!(m, ", $swapped, ");
2501 #[stable(feature = "rust1", since = "1.0.0")]
2503 pub const fn swap_bytes(self) -> Self {
2504 intrinsics::bswap(self as $ActualT) as Self
2509 concat!("Reverses the bit pattern of the integer.
2516 #![feature(reverse_bits)]
2518 let n = ", $swap_op, stringify!($SelfT), ";
2519 let m = n.reverse_bits();
2521 assert_eq!(m, ", $reversed, ");
2523 #[unstable(feature = "reverse_bits", issue = "48763")]
2525 pub const fn reverse_bits(self) -> Self {
2526 intrinsics::bitreverse(self as $ActualT) as Self
2531 concat!("Converts an integer from big endian to the target's endianness.
2533 On big endian this is a no-op. On little endian the bytes are
2541 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2543 if cfg!(target_endian = \"big\") {
2544 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2546 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2549 #[stable(feature = "rust1", since = "1.0.0")]
2551 pub const fn from_be(x: Self) -> Self {
2552 #[cfg(target_endian = "big")]
2556 #[cfg(not(target_endian = "big"))]
2564 concat!("Converts an integer from little endian to the target's endianness.
2566 On little endian this is a no-op. On big endian the bytes are
2574 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2576 if cfg!(target_endian = \"little\") {
2577 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2579 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2582 #[stable(feature = "rust1", since = "1.0.0")]
2584 pub const fn from_le(x: Self) -> Self {
2585 #[cfg(target_endian = "little")]
2589 #[cfg(not(target_endian = "little"))]
2597 concat!("Converts `self` to big endian from the target's endianness.
2599 On big endian this is a no-op. On little endian the bytes are
2607 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2609 if cfg!(target_endian = \"big\") {
2610 assert_eq!(n.to_be(), n)
2612 assert_eq!(n.to_be(), n.swap_bytes())
2615 #[stable(feature = "rust1", since = "1.0.0")]
2617 pub const fn to_be(self) -> Self { // or not to be?
2618 #[cfg(target_endian = "big")]
2622 #[cfg(not(target_endian = "big"))]
2630 concat!("Converts `self` to little endian from the target's endianness.
2632 On little endian this is a no-op. On big endian the bytes are
2640 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2642 if cfg!(target_endian = \"little\") {
2643 assert_eq!(n.to_le(), n)
2645 assert_eq!(n.to_le(), n.swap_bytes())
2648 #[stable(feature = "rust1", since = "1.0.0")]
2650 pub const fn to_le(self) -> Self {
2651 #[cfg(target_endian = "little")]
2655 #[cfg(not(target_endian = "little"))]
2663 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2664 if overflow occurred.
2671 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2672 "Some(", stringify!($SelfT), "::max_value() - 1));
2673 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2675 #[stable(feature = "rust1", since = "1.0.0")]
2676 #[must_use = "this returns the result of the operation, \
2677 without modifying the original"]
2679 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2680 let (a, b) = self.overflowing_add(rhs);
2681 if b {None} else {Some(a)}
2686 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2687 `None` if overflow occurred.
2694 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2695 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2697 #[stable(feature = "rust1", since = "1.0.0")]
2698 #[must_use = "this returns the result of the operation, \
2699 without modifying the original"]
2701 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2702 let (a, b) = self.overflowing_sub(rhs);
2703 if b {None} else {Some(a)}
2708 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2709 `None` if overflow occurred.
2716 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2717 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2719 #[stable(feature = "rust1", since = "1.0.0")]
2720 #[must_use = "this returns the result of the operation, \
2721 without modifying the original"]
2723 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2724 let (a, b) = self.overflowing_mul(rhs);
2725 if b {None} else {Some(a)}
2730 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2738 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2739 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2741 #[stable(feature = "rust1", since = "1.0.0")]
2742 #[must_use = "this returns the result of the operation, \
2743 without modifying the original"]
2745 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2748 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2754 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2762 #![feature(euclidean_division)]
2763 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
2764 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
2766 #[unstable(feature = "euclidean_division", issue = "49048")]
2767 #[must_use = "this returns the result of the operation, \
2768 without modifying the original"]
2770 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
2774 Some(self.div_euclid(rhs))
2781 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2789 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2790 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2792 #[stable(feature = "wrapping", since = "1.7.0")]
2793 #[must_use = "this returns the result of the operation, \
2794 without modifying the original"]
2796 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2800 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2806 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
2814 #![feature(euclidean_division)]
2815 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
2816 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
2818 #[unstable(feature = "euclidean_division", issue = "49048")]
2819 #[must_use = "this returns the result of the operation, \
2820 without modifying the original"]
2822 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
2826 Some(self.rem_euclid(rhs))
2832 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2835 Note that negating any positive integer will overflow.
2842 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2843 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2845 #[stable(feature = "wrapping", since = "1.7.0")]
2847 pub fn checked_neg(self) -> Option<Self> {
2848 let (a, b) = self.overflowing_neg();
2849 if b {None} else {Some(a)}
2854 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2855 if `rhs` is larger than or equal to the number of bits in `self`.
2862 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2863 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2865 #[stable(feature = "wrapping", since = "1.7.0")]
2866 #[must_use = "this returns the result of the operation, \
2867 without modifying the original"]
2869 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2870 let (a, b) = self.overflowing_shl(rhs);
2871 if b {None} else {Some(a)}
2876 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2877 if `rhs` is larger than or equal to the number of bits in `self`.
2884 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2885 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2887 #[stable(feature = "wrapping", since = "1.7.0")]
2888 #[must_use = "this returns the result of the operation, \
2889 without modifying the original"]
2891 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2892 let (a, b) = self.overflowing_shr(rhs);
2893 if b {None} else {Some(a)}
2898 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2906 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2907 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2909 #[stable(feature = "no_panic_pow", since = "1.34.0")]
2910 #[must_use = "this returns the result of the operation, \
2911 without modifying the original"]
2913 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2914 let mut base = self;
2915 let mut acc: Self = 1;
2919 acc = acc.checked_mul(base)?;
2922 base = base.checked_mul(base)?;
2925 // Deal with the final bit of the exponent separately, since
2926 // squaring the base afterwards is not necessary and may cause a
2927 // needless overflow.
2929 acc = acc.checked_mul(base)?;
2937 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2938 the numeric bounds instead of overflowing.
2945 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2946 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2949 #[stable(feature = "rust1", since = "1.0.0")]
2950 #[must_use = "this returns the result of the operation, \
2951 without modifying the original"]
2952 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
2954 pub const fn saturating_add(self, rhs: Self) -> Self {
2955 intrinsics::saturating_add(self, rhs)
2960 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2961 at the numeric bounds instead of overflowing.
2968 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2969 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2971 #[stable(feature = "rust1", since = "1.0.0")]
2972 #[must_use = "this returns the result of the operation, \
2973 without modifying the original"]
2974 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
2976 pub const fn saturating_sub(self, rhs: Self) -> Self {
2977 intrinsics::saturating_sub(self, rhs)
2982 concat!("Saturating integer multiplication. Computes `self * rhs`,
2983 saturating at the numeric bounds instead of overflowing.
2990 ", $Feature, "use std::", stringify!($SelfT), ";
2992 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2993 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2994 "::MAX);", $EndFeature, "
2996 #[stable(feature = "wrapping", since = "1.7.0")]
2997 #[must_use = "this returns the result of the operation, \
2998 without modifying the original"]
3000 pub fn saturating_mul(self, rhs: Self) -> Self {
3001 self.checked_mul(rhs).unwrap_or(Self::max_value())
3006 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3007 saturating at the numeric bounds instead of overflowing.
3014 ", $Feature, "use std::", stringify!($SelfT), ";
3016 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3017 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3020 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3021 #[must_use = "this returns the result of the operation, \
3022 without modifying the original"]
3024 pub fn saturating_pow(self, exp: u32) -> Self {
3025 match self.checked_pow(exp) {
3027 None => Self::max_value(),
3033 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3034 wrapping around at the boundary of the type.
3041 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3042 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
3045 #[stable(feature = "rust1", since = "1.0.0")]
3046 #[must_use = "this returns the result of the operation, \
3047 without modifying the original"]
3049 pub const fn wrapping_add(self, rhs: Self) -> Self {
3050 intrinsics::overflowing_add(self, rhs)
3055 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3056 wrapping around at the boundary of the type.
3063 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3064 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
3067 #[stable(feature = "rust1", since = "1.0.0")]
3068 #[must_use = "this returns the result of the operation, \
3069 without modifying the original"]
3071 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3072 intrinsics::overflowing_sub(self, rhs)
3076 /// Wrapping (modular) multiplication. Computes `self *
3077 /// rhs`, wrapping around at the boundary of the type.
3083 /// Please note that this example is shared between integer types.
3084 /// Which explains why `u8` is used here.
3087 /// assert_eq!(10u8.wrapping_mul(12), 120);
3088 /// assert_eq!(25u8.wrapping_mul(12), 44);
3090 #[stable(feature = "rust1", since = "1.0.0")]
3091 #[must_use = "this returns the result of the operation, \
3092 without modifying the original"]
3094 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3095 intrinsics::overflowing_mul(self, rhs)
3099 concat!("Wrapping (modular) division. Computes `self / rhs`.
3100 Wrapped division on unsigned types is just normal division.
3101 There's no way wrapping could ever happen.
3102 This function exists, so that all operations
3103 are accounted for in the wrapping operations.
3110 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3112 #[stable(feature = "num_wrapping", since = "1.2.0")]
3113 #[must_use = "this returns the result of the operation, \
3114 without modifying the original"]
3116 pub fn wrapping_div(self, rhs: Self) -> Self {
3122 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3123 Wrapped division on unsigned types is just normal division.
3124 There's no way wrapping could ever happen.
3125 This function exists, so that all operations
3126 are accounted for in the wrapping operations.
3127 Since, for the positive integers, all common
3128 definitions of division are equal, this
3129 is exactly equal to `self.wrapping_div(rhs)`.
3136 #![feature(euclidean_division)]
3137 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3139 #[unstable(feature = "euclidean_division", issue = "49048")]
3140 #[must_use = "this returns the result of the operation, \
3141 without modifying the original"]
3143 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
3149 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3150 Wrapped remainder calculation on unsigned types is
3151 just the regular remainder calculation.
3152 There's no way wrapping could ever happen.
3153 This function exists, so that all operations
3154 are accounted for in the wrapping operations.
3161 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3163 #[stable(feature = "num_wrapping", since = "1.2.0")]
3164 #[must_use = "this returns the result of the operation, \
3165 without modifying the original"]
3167 pub fn wrapping_rem(self, rhs: Self) -> Self {
3173 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3174 Wrapped modulo calculation on unsigned types is
3175 just the regular remainder calculation.
3176 There's no way wrapping could ever happen.
3177 This function exists, so that all operations
3178 are accounted for in the wrapping operations.
3179 Since, for the positive integers, all common
3180 definitions of division are equal, this
3181 is exactly equal to `self.wrapping_rem(rhs)`.
3188 #![feature(euclidean_division)]
3189 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3191 #[unstable(feature = "euclidean_division", issue = "49048")]
3192 #[must_use = "this returns the result of the operation, \
3193 without modifying the original"]
3195 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3200 /// Wrapping (modular) negation. Computes `-self`,
3201 /// wrapping around at the boundary of the type.
3203 /// Since unsigned types do not have negative equivalents
3204 /// all applications of this function will wrap (except for `-0`).
3205 /// For values smaller than the corresponding signed type's maximum
3206 /// the result is the same as casting the corresponding signed value.
3207 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3208 /// `MAX` is the corresponding signed type's maximum.
3214 /// Please note that this example is shared between integer types.
3215 /// Which explains why `i8` is used here.
3218 /// assert_eq!(100i8.wrapping_neg(), -100);
3219 /// assert_eq!((-128i8).wrapping_neg(), -128);
3221 #[stable(feature = "num_wrapping", since = "1.2.0")]
3223 pub const fn wrapping_neg(self) -> Self {
3224 self.overflowing_neg().0
3228 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3229 where `mask` removes any high-order bits of `rhs` that
3230 would cause the shift to exceed the bitwidth of the type.
3232 Note that this is *not* the same as a rotate-left; the
3233 RHS of a wrapping shift-left is restricted to the range
3234 of the type, rather than the bits shifted out of the LHS
3235 being returned to the other end. The primitive integer
3236 types all implement a `rotate_left` function, which may
3237 be what you want instead.
3244 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3245 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3247 #[stable(feature = "num_wrapping", since = "1.2.0")]
3248 #[must_use = "this returns the result of the operation, \
3249 without modifying the original"]
3251 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3253 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3259 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3260 where `mask` removes any high-order bits of `rhs` that
3261 would cause the shift to exceed the bitwidth of the type.
3263 Note that this is *not* the same as a rotate-right; the
3264 RHS of a wrapping shift-right is restricted to the range
3265 of the type, rather than the bits shifted out of the LHS
3266 being returned to the other end. The primitive integer
3267 types all implement a `rotate_right` function, which may
3268 be what you want instead.
3275 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3276 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3278 #[stable(feature = "num_wrapping", since = "1.2.0")]
3279 #[must_use = "this returns the result of the operation, \
3280 without modifying the original"]
3282 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3284 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3290 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3291 wrapping around at the boundary of the type.
3298 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3299 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3301 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3302 #[must_use = "this returns the result of the operation, \
3303 without modifying the original"]
3305 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3306 let mut base = self;
3307 let mut acc: Self = 1;
3311 acc = acc.wrapping_mul(base);
3314 base = base.wrapping_mul(base);
3317 // Deal with the final bit of the exponent separately, since
3318 // squaring the base afterwards is not necessary and may cause a
3319 // needless overflow.
3321 acc = acc.wrapping_mul(base);
3329 concat!("Calculates `self` + `rhs`
3331 Returns a tuple of the addition along with a boolean indicating
3332 whether an arithmetic overflow would occur. If an overflow would
3333 have occurred then the wrapped value is returned.
3340 ", $Feature, "use std::", stringify!($SelfT), ";
3342 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3343 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3345 #[stable(feature = "wrapping", since = "1.7.0")]
3346 #[must_use = "this returns the result of the operation, \
3347 without modifying the original"]
3349 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3350 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3356 concat!("Calculates `self` - `rhs`
3358 Returns a tuple of the subtraction along with a boolean indicating
3359 whether an arithmetic overflow would occur. If an overflow would
3360 have occurred then the wrapped value is returned.
3367 ", $Feature, "use std::", stringify!($SelfT), ";
3369 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3370 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3373 #[stable(feature = "wrapping", since = "1.7.0")]
3374 #[must_use = "this returns the result of the operation, \
3375 without modifying the original"]
3377 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3378 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3383 /// Calculates the multiplication of `self` and `rhs`.
3385 /// Returns a tuple of the multiplication along with a boolean
3386 /// indicating whether an arithmetic overflow would occur. If an
3387 /// overflow would have occurred then the wrapped value is returned.
3393 /// Please note that this example is shared between integer types.
3394 /// Which explains why `u32` is used here.
3397 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3398 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3400 #[stable(feature = "wrapping", since = "1.7.0")]
3401 #[must_use = "this returns the result of the operation, \
3402 without modifying the original"]
3404 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3405 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3410 concat!("Calculates the divisor when `self` is divided by `rhs`.
3412 Returns a tuple of the divisor along with a boolean indicating
3413 whether an arithmetic overflow would occur. Note that for unsigned
3414 integers overflow never occurs, so the second value is always
3419 This function will panic if `rhs` is 0.
3426 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3429 #[stable(feature = "wrapping", since = "1.7.0")]
3430 #[must_use = "this returns the result of the operation, \
3431 without modifying the original"]
3432 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3438 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3440 Returns a tuple of the divisor along with a boolean indicating
3441 whether an arithmetic overflow would occur. Note that for unsigned
3442 integers overflow never occurs, so the second value is always
3444 Since, for the positive integers, all common
3445 definitions of division are equal, this
3446 is exactly equal to `self.overflowing_div(rhs)`.
3450 This function will panic if `rhs` is 0.
3457 #![feature(euclidean_division)]
3458 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3461 #[unstable(feature = "euclidean_division", issue = "49048")]
3462 #[must_use = "this returns the result of the operation, \
3463 without modifying the original"]
3464 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3470 concat!("Calculates the remainder when `self` is divided by `rhs`.
3472 Returns a tuple of the remainder after dividing along with a boolean
3473 indicating whether an arithmetic overflow would occur. Note that for
3474 unsigned integers overflow never occurs, so the second value is
3479 This function will panic if `rhs` is 0.
3486 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3489 #[stable(feature = "wrapping", since = "1.7.0")]
3490 #[must_use = "this returns the result of the operation, \
3491 without modifying the original"]
3492 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3498 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3500 Returns a tuple of the modulo after dividing along with a boolean
3501 indicating whether an arithmetic overflow would occur. Note that for
3502 unsigned integers overflow never occurs, so the second value is
3504 Since, for the positive integers, all common
3505 definitions of division are equal, this operation
3506 is exactly equal to `self.overflowing_rem(rhs)`.
3510 This function will panic if `rhs` is 0.
3517 #![feature(euclidean_division)]
3518 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3521 #[unstable(feature = "euclidean_division", issue = "49048")]
3522 #[must_use = "this returns the result of the operation, \
3523 without modifying the original"]
3524 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3530 concat!("Negates self in an overflowing fashion.
3532 Returns `!self + 1` using wrapping operations to return the value
3533 that represents the negation of this unsigned value. Note that for
3534 positive unsigned values overflow always occurs, but negating 0 does
3542 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3543 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3544 ", true));", $EndFeature, "
3547 #[stable(feature = "wrapping", since = "1.7.0")]
3548 pub const fn overflowing_neg(self) -> (Self, bool) {
3549 ((!self).wrapping_add(1), self != 0)
3554 concat!("Shifts self left by `rhs` bits.
3556 Returns a tuple of the shifted version of self along with a boolean
3557 indicating whether the shift value was larger than or equal to the
3558 number of bits. If the shift value is too large, then value is
3559 masked (N-1) where N is the number of bits, and this value is then
3560 used to perform the shift.
3567 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3568 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3570 #[stable(feature = "wrapping", since = "1.7.0")]
3571 #[must_use = "this returns the result of the operation, \
3572 without modifying the original"]
3574 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3575 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3580 concat!("Shifts self right by `rhs` bits.
3582 Returns a tuple of the shifted version of self along with a boolean
3583 indicating whether the shift value was larger than or equal to the
3584 number of bits. If the shift value is too large, then value is
3585 masked (N-1) where N is the number of bits, and this value is then
3586 used to perform the shift.
3593 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3594 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3596 #[stable(feature = "wrapping", since = "1.7.0")]
3597 #[must_use = "this returns the result of the operation, \
3598 without modifying the original"]
3600 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3601 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3606 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3608 Returns a tuple of the exponentiation along with a bool indicating
3609 whether an overflow happened.
3616 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3617 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3619 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3620 #[must_use = "this returns the result of the operation, \
3621 without modifying the original"]
3623 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3624 let mut base = self;
3625 let mut acc: Self = 1;
3626 let mut overflown = false;
3627 // Scratch space for storing results of overflowing_mul.
3632 r = acc.overflowing_mul(base);
3637 r = base.overflowing_mul(base);
3642 // Deal with the final bit of the exponent separately, since
3643 // squaring the base afterwards is not necessary and may cause a
3644 // needless overflow.
3646 r = acc.overflowing_mul(base);
3656 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3663 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3665 #[stable(feature = "rust1", since = "1.0.0")]
3666 #[must_use = "this returns the result of the operation, \
3667 without modifying the original"]
3669 #[rustc_inherit_overflow_checks]
3670 pub fn pow(self, mut exp: u32) -> Self {
3671 let mut base = self;
3682 // Deal with the final bit of the exponent separately, since
3683 // squaring the base afterwards is not necessary and may cause a
3684 // needless overflow.
3694 concat!("Performs Euclidean division.
3696 Since, for the positive integers, all common
3697 definitions of division are equal, this
3698 is exactly equal to `self / rhs`.
3705 #![feature(euclidean_division)]
3706 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
3708 #[unstable(feature = "euclidean_division", issue = "49048")]
3709 #[must_use = "this returns the result of the operation, \
3710 without modifying the original"]
3712 #[rustc_inherit_overflow_checks]
3713 pub fn div_euclid(self, rhs: Self) -> Self {
3720 concat!("Calculates the least remainder of `self (mod rhs)`.
3722 Since, for the positive integers, all common
3723 definitions of division are equal, this
3724 is exactly equal to `self % rhs`.
3731 #![feature(euclidean_division)]
3732 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
3734 #[unstable(feature = "euclidean_division", issue = "49048")]
3735 #[must_use = "this returns the result of the operation, \
3736 without modifying the original"]
3738 #[rustc_inherit_overflow_checks]
3739 pub fn rem_euclid(self, rhs: Self) -> Self {
3745 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3752 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3753 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3755 #[stable(feature = "rust1", since = "1.0.0")]
3757 pub fn is_power_of_two(self) -> bool {
3758 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3762 // Returns one less than next power of two.
3763 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3765 // 8u8.one_less_than_next_power_of_two() == 7
3766 // 6u8.one_less_than_next_power_of_two() == 7
3768 // This method cannot overflow, as in the `next_power_of_two`
3769 // overflow cases it instead ends up returning the maximum value
3770 // of the type, and can return 0 for 0.
3772 fn one_less_than_next_power_of_two(self) -> Self {
3773 if self <= 1 { return 0; }
3775 // Because `p > 0`, it cannot consist entirely of leading zeros.
3776 // That means the shift is always in-bounds, and some processors
3777 // (such as intel pre-haswell) have more efficient ctlz
3778 // intrinsics when the argument is non-zero.
3780 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3781 <$SelfT>::max_value() >> z
3785 concat!("Returns the smallest power of two greater than or equal to `self`.
3787 When return value overflows (i.e., `self > (1 << (N-1))` for type
3788 `uN`), it panics in debug mode and return value is wrapped to 0 in
3789 release mode (the only situation in which method can return 0).
3796 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3797 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3799 #[stable(feature = "rust1", since = "1.0.0")]
3801 pub fn next_power_of_two(self) -> Self {
3802 // Call the trait to get overflow checks
3803 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3808 concat!("Returns the smallest power of two greater than or equal to `n`. If
3809 the next power of two is greater than the type's maximum value,
3810 `None` is returned, otherwise the power of two is wrapped in `Some`.
3817 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3818 ".checked_next_power_of_two(), Some(2));
3819 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3820 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3824 #[stable(feature = "rust1", since = "1.0.0")]
3825 pub fn checked_next_power_of_two(self) -> Option<Self> {
3826 self.one_less_than_next_power_of_two().checked_add(1)
3831 concat!("Returns the smallest power of two greater than or equal to `n`. If
3832 the next power of two is greater than the type's maximum value,
3833 the return value is wrapped to `0`.
3840 #![feature(wrapping_next_power_of_two)]
3842 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3843 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3844 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3847 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3848 reason = "needs decision on wrapping behaviour")]
3849 pub fn wrapping_next_power_of_two(self) -> Self {
3850 self.one_less_than_next_power_of_two().wrapping_add(1)
3855 concat!("Return the memory representation of this integer as a byte array in
3856 big-endian (network) byte order.
3863 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
3864 assert_eq!(bytes, ", $be_bytes, ");
3866 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3867 #[rustc_const_unstable(feature = "const_int_conversion")]
3869 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
3870 self.to_be().to_ne_bytes()
3875 concat!("Return the memory representation of this integer as a byte array in
3876 little-endian byte order.
3883 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
3884 assert_eq!(bytes, ", $le_bytes, ");
3886 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3887 #[rustc_const_unstable(feature = "const_int_conversion")]
3889 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
3890 self.to_le().to_ne_bytes()
3896 Return the memory representation of this integer as a byte array in
3899 As the target platform's native endianness is used, portable code
3900 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3905 [`to_be_bytes`]: #method.to_be_bytes
3906 [`to_le_bytes`]: #method.to_le_bytes
3911 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
3912 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
3918 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3919 #[rustc_const_unstable(feature = "const_int_conversion")]
3921 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
3922 unsafe { mem::transmute(self) }
3927 concat!("Create an integer value from its representation as a byte array in
3935 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
3936 assert_eq!(value, ", $swap_op, ");
3939 When starting from a slice rather than an array, fallible conversion APIs can be used:
3942 use std::convert::TryInto;
3944 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3945 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3947 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
3950 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3951 #[rustc_const_unstable(feature = "const_int_conversion")]
3953 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3954 Self::from_be(Self::from_ne_bytes(bytes))
3960 Create an integer value from its representation as a byte array in
3968 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
3969 assert_eq!(value, ", $swap_op, ");
3972 When starting from a slice rather than an array, fallible conversion APIs can be used:
3975 use std::convert::TryInto;
3977 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3978 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3980 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
3983 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3984 #[rustc_const_unstable(feature = "const_int_conversion")]
3986 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3987 Self::from_le(Self::from_ne_bytes(bytes))
3992 concat!("Create an integer value from its memory representation as a byte
3993 array in native endianness.
3995 As the target platform's native endianness is used, portable code
3996 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3997 appropriate instead.
3999 [`from_be_bytes`]: #method.from_be_bytes
4000 [`from_le_bytes`]: #method.from_le_bytes
4007 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4012 assert_eq!(value, ", $swap_op, ");
4015 When starting from a slice rather than an array, fallible conversion APIs can be used:
4018 use std::convert::TryInto;
4020 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4021 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4023 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4026 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4027 #[rustc_const_unstable(feature = "const_int_conversion")]
4029 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4030 unsafe { mem::transmute(bytes) }
4038 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4042 /// Checks if the value is within the ASCII range.
4047 /// let ascii = 97u8;
4048 /// let non_ascii = 150u8;
4050 /// assert!(ascii.is_ascii());
4051 /// assert!(!non_ascii.is_ascii());
4053 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4055 pub fn is_ascii(&self) -> bool {
4059 /// Makes a copy of the value in its ASCII upper case equivalent.
4061 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4062 /// but non-ASCII letters are unchanged.
4064 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4069 /// let lowercase_a = 97u8;
4071 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4074 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4075 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4077 pub fn to_ascii_uppercase(&self) -> u8 {
4078 // Unset the fith bit if this is a lowercase letter
4079 *self & !((self.is_ascii_lowercase() as u8) << 5)
4082 /// Makes a copy of the value in its ASCII lower case equivalent.
4084 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4085 /// but non-ASCII letters are unchanged.
4087 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4092 /// let uppercase_a = 65u8;
4094 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4097 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4098 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4100 pub fn to_ascii_lowercase(&self) -> u8 {
4101 // Set the fith bit if this is an uppercase letter
4102 *self | ((self.is_ascii_uppercase() as u8) << 5)
4105 /// Checks that two values are an ASCII case-insensitive match.
4107 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4112 /// let lowercase_a = 97u8;
4113 /// let uppercase_a = 65u8;
4115 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4117 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4119 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4120 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4123 /// Converts this value to its ASCII upper case equivalent in-place.
4125 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4126 /// but non-ASCII letters are unchanged.
4128 /// To return a new uppercased value without modifying the existing one, use
4129 /// [`to_ascii_uppercase`].
4134 /// let mut byte = b'a';
4136 /// byte.make_ascii_uppercase();
4138 /// assert_eq!(b'A', byte);
4141 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4142 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4144 pub fn make_ascii_uppercase(&mut self) {
4145 *self = self.to_ascii_uppercase();
4148 /// Converts this value to its ASCII lower case equivalent in-place.
4150 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4151 /// but non-ASCII letters are unchanged.
4153 /// To return a new lowercased value without modifying the existing one, use
4154 /// [`to_ascii_lowercase`].
4159 /// let mut byte = b'A';
4161 /// byte.make_ascii_lowercase();
4163 /// assert_eq!(b'a', byte);
4166 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4167 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4169 pub fn make_ascii_lowercase(&mut self) {
4170 *self = self.to_ascii_lowercase();
4173 /// Checks if the value is an ASCII alphabetic character:
4175 /// - U+0041 'A' ... U+005A 'Z', or
4176 /// - U+0061 'a' ... U+007A 'z'.
4181 /// let uppercase_a = b'A';
4182 /// let uppercase_g = b'G';
4185 /// let zero = b'0';
4186 /// let percent = b'%';
4187 /// let space = b' ';
4189 /// let esc = 0x1b_u8;
4191 /// assert!(uppercase_a.is_ascii_alphabetic());
4192 /// assert!(uppercase_g.is_ascii_alphabetic());
4193 /// assert!(a.is_ascii_alphabetic());
4194 /// assert!(g.is_ascii_alphabetic());
4195 /// assert!(!zero.is_ascii_alphabetic());
4196 /// assert!(!percent.is_ascii_alphabetic());
4197 /// assert!(!space.is_ascii_alphabetic());
4198 /// assert!(!lf.is_ascii_alphabetic());
4199 /// assert!(!esc.is_ascii_alphabetic());
4201 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4203 pub fn is_ascii_alphabetic(&self) -> bool {
4205 b'A'..=b'Z' | b'a'..=b'z' => true,
4210 /// Checks if the value is an ASCII uppercase character:
4211 /// U+0041 'A' ... U+005A 'Z'.
4216 /// let uppercase_a = b'A';
4217 /// let uppercase_g = b'G';
4220 /// let zero = b'0';
4221 /// let percent = b'%';
4222 /// let space = b' ';
4224 /// let esc = 0x1b_u8;
4226 /// assert!(uppercase_a.is_ascii_uppercase());
4227 /// assert!(uppercase_g.is_ascii_uppercase());
4228 /// assert!(!a.is_ascii_uppercase());
4229 /// assert!(!g.is_ascii_uppercase());
4230 /// assert!(!zero.is_ascii_uppercase());
4231 /// assert!(!percent.is_ascii_uppercase());
4232 /// assert!(!space.is_ascii_uppercase());
4233 /// assert!(!lf.is_ascii_uppercase());
4234 /// assert!(!esc.is_ascii_uppercase());
4236 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4238 pub fn is_ascii_uppercase(&self) -> bool {
4240 b'A'..=b'Z' => true,
4245 /// Checks if the value is an ASCII lowercase character:
4246 /// U+0061 'a' ... U+007A 'z'.
4251 /// let uppercase_a = b'A';
4252 /// let uppercase_g = b'G';
4255 /// let zero = b'0';
4256 /// let percent = b'%';
4257 /// let space = b' ';
4259 /// let esc = 0x1b_u8;
4261 /// assert!(!uppercase_a.is_ascii_lowercase());
4262 /// assert!(!uppercase_g.is_ascii_lowercase());
4263 /// assert!(a.is_ascii_lowercase());
4264 /// assert!(g.is_ascii_lowercase());
4265 /// assert!(!zero.is_ascii_lowercase());
4266 /// assert!(!percent.is_ascii_lowercase());
4267 /// assert!(!space.is_ascii_lowercase());
4268 /// assert!(!lf.is_ascii_lowercase());
4269 /// assert!(!esc.is_ascii_lowercase());
4271 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4273 pub fn is_ascii_lowercase(&self) -> bool {
4275 b'a'..=b'z' => true,
4280 /// Checks if the value is an ASCII alphanumeric character:
4282 /// - U+0041 'A' ... U+005A 'Z', or
4283 /// - U+0061 'a' ... U+007A 'z', or
4284 /// - U+0030 '0' ... U+0039 '9'.
4289 /// let uppercase_a = b'A';
4290 /// let uppercase_g = b'G';
4293 /// let zero = b'0';
4294 /// let percent = b'%';
4295 /// let space = b' ';
4297 /// let esc = 0x1b_u8;
4299 /// assert!(uppercase_a.is_ascii_alphanumeric());
4300 /// assert!(uppercase_g.is_ascii_alphanumeric());
4301 /// assert!(a.is_ascii_alphanumeric());
4302 /// assert!(g.is_ascii_alphanumeric());
4303 /// assert!(zero.is_ascii_alphanumeric());
4304 /// assert!(!percent.is_ascii_alphanumeric());
4305 /// assert!(!space.is_ascii_alphanumeric());
4306 /// assert!(!lf.is_ascii_alphanumeric());
4307 /// assert!(!esc.is_ascii_alphanumeric());
4309 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4311 pub fn is_ascii_alphanumeric(&self) -> bool {
4313 b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' => true,
4318 /// Checks if the value is an ASCII decimal digit:
4319 /// U+0030 '0' ... U+0039 '9'.
4324 /// let uppercase_a = b'A';
4325 /// let uppercase_g = b'G';
4328 /// let zero = b'0';
4329 /// let percent = b'%';
4330 /// let space = b' ';
4332 /// let esc = 0x1b_u8;
4334 /// assert!(!uppercase_a.is_ascii_digit());
4335 /// assert!(!uppercase_g.is_ascii_digit());
4336 /// assert!(!a.is_ascii_digit());
4337 /// assert!(!g.is_ascii_digit());
4338 /// assert!(zero.is_ascii_digit());
4339 /// assert!(!percent.is_ascii_digit());
4340 /// assert!(!space.is_ascii_digit());
4341 /// assert!(!lf.is_ascii_digit());
4342 /// assert!(!esc.is_ascii_digit());
4344 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4346 pub fn is_ascii_digit(&self) -> bool {
4348 b'0'..=b'9' => true,
4353 /// Checks if the value is an ASCII hexadecimal digit:
4355 /// - U+0030 '0' ... U+0039 '9', or
4356 /// - U+0041 'A' ... U+0046 'F', or
4357 /// - U+0061 'a' ... U+0066 'f'.
4362 /// let uppercase_a = b'A';
4363 /// let uppercase_g = b'G';
4366 /// let zero = b'0';
4367 /// let percent = b'%';
4368 /// let space = b' ';
4370 /// let esc = 0x1b_u8;
4372 /// assert!(uppercase_a.is_ascii_hexdigit());
4373 /// assert!(!uppercase_g.is_ascii_hexdigit());
4374 /// assert!(a.is_ascii_hexdigit());
4375 /// assert!(!g.is_ascii_hexdigit());
4376 /// assert!(zero.is_ascii_hexdigit());
4377 /// assert!(!percent.is_ascii_hexdigit());
4378 /// assert!(!space.is_ascii_hexdigit());
4379 /// assert!(!lf.is_ascii_hexdigit());
4380 /// assert!(!esc.is_ascii_hexdigit());
4382 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4384 pub fn is_ascii_hexdigit(&self) -> bool {
4386 b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f' => true,
4391 /// Checks if the value is an ASCII punctuation character:
4393 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
4394 /// - U+003A ... U+0040 `: ; < = > ? @`, or
4395 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
4396 /// - U+007B ... U+007E `{ | } ~`
4401 /// let uppercase_a = b'A';
4402 /// let uppercase_g = b'G';
4405 /// let zero = b'0';
4406 /// let percent = b'%';
4407 /// let space = b' ';
4409 /// let esc = 0x1b_u8;
4411 /// assert!(!uppercase_a.is_ascii_punctuation());
4412 /// assert!(!uppercase_g.is_ascii_punctuation());
4413 /// assert!(!a.is_ascii_punctuation());
4414 /// assert!(!g.is_ascii_punctuation());
4415 /// assert!(!zero.is_ascii_punctuation());
4416 /// assert!(percent.is_ascii_punctuation());
4417 /// assert!(!space.is_ascii_punctuation());
4418 /// assert!(!lf.is_ascii_punctuation());
4419 /// assert!(!esc.is_ascii_punctuation());
4421 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4423 pub fn is_ascii_punctuation(&self) -> bool {
4425 b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~' => true,
4430 /// Checks if the value is an ASCII graphic character:
4431 /// U+0021 '!' ... U+007E '~'.
4436 /// let uppercase_a = b'A';
4437 /// let uppercase_g = b'G';
4440 /// let zero = b'0';
4441 /// let percent = b'%';
4442 /// let space = b' ';
4444 /// let esc = 0x1b_u8;
4446 /// assert!(uppercase_a.is_ascii_graphic());
4447 /// assert!(uppercase_g.is_ascii_graphic());
4448 /// assert!(a.is_ascii_graphic());
4449 /// assert!(g.is_ascii_graphic());
4450 /// assert!(zero.is_ascii_graphic());
4451 /// assert!(percent.is_ascii_graphic());
4452 /// assert!(!space.is_ascii_graphic());
4453 /// assert!(!lf.is_ascii_graphic());
4454 /// assert!(!esc.is_ascii_graphic());
4456 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4458 pub fn is_ascii_graphic(&self) -> bool {
4460 b'!'..=b'~' => true,
4465 /// Checks if the value is an ASCII whitespace character:
4466 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4467 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4469 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4470 /// whitespace][infra-aw]. There are several other definitions in
4471 /// wide use. For instance, [the POSIX locale][pct] includes
4472 /// U+000B VERTICAL TAB as well as all the above characters,
4473 /// but—from the very same specification—[the default rule for
4474 /// "field splitting" in the Bourne shell][bfs] considers *only*
4475 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4477 /// If you are writing a program that will process an existing
4478 /// file format, check what that format's definition of whitespace is
4479 /// before using this function.
4481 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4482 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4483 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4488 /// let uppercase_a = b'A';
4489 /// let uppercase_g = b'G';
4492 /// let zero = b'0';
4493 /// let percent = b'%';
4494 /// let space = b' ';
4496 /// let esc = 0x1b_u8;
4498 /// assert!(!uppercase_a.is_ascii_whitespace());
4499 /// assert!(!uppercase_g.is_ascii_whitespace());
4500 /// assert!(!a.is_ascii_whitespace());
4501 /// assert!(!g.is_ascii_whitespace());
4502 /// assert!(!zero.is_ascii_whitespace());
4503 /// assert!(!percent.is_ascii_whitespace());
4504 /// assert!(space.is_ascii_whitespace());
4505 /// assert!(lf.is_ascii_whitespace());
4506 /// assert!(!esc.is_ascii_whitespace());
4508 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4510 pub fn is_ascii_whitespace(&self) -> bool {
4512 b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' => true,
4517 /// Checks if the value is an ASCII control character:
4518 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4519 /// Note that most ASCII whitespace characters are control
4520 /// characters, but SPACE is not.
4525 /// let uppercase_a = b'A';
4526 /// let uppercase_g = b'G';
4529 /// let zero = b'0';
4530 /// let percent = b'%';
4531 /// let space = b' ';
4533 /// let esc = 0x1b_u8;
4535 /// assert!(!uppercase_a.is_ascii_control());
4536 /// assert!(!uppercase_g.is_ascii_control());
4537 /// assert!(!a.is_ascii_control());
4538 /// assert!(!g.is_ascii_control());
4539 /// assert!(!zero.is_ascii_control());
4540 /// assert!(!percent.is_ascii_control());
4541 /// assert!(!space.is_ascii_control());
4542 /// assert!(lf.is_ascii_control());
4543 /// assert!(esc.is_ascii_control());
4545 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4547 pub fn is_ascii_control(&self) -> bool {
4549 b'\0'..=b'\x1F' | b'\x7F' => true,
4557 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4558 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4563 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4564 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4569 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4570 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4571 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4572 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4578 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4579 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4580 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4581 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4582 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4583 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4584 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4588 #[cfg(target_pointer_width = "16")]
4591 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4592 "[0x34, 0x12]", "[0x12, 0x34]",
4593 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4595 #[cfg(target_pointer_width = "32")]
4598 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4599 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4600 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4603 #[cfg(target_pointer_width = "64")]
4606 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4607 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4608 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4609 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4610 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4613 /// A classification of floating point numbers.
4615 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4616 /// their documentation for more.
4618 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4619 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4624 /// use std::num::FpCategory;
4627 /// let num = 12.4_f32;
4628 /// let inf = f32::INFINITY;
4629 /// let zero = 0f32;
4630 /// let sub: f32 = 1.1754942e-38;
4631 /// let nan = f32::NAN;
4633 /// assert_eq!(num.classify(), FpCategory::Normal);
4634 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4635 /// assert_eq!(zero.classify(), FpCategory::Zero);
4636 /// assert_eq!(nan.classify(), FpCategory::Nan);
4637 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4639 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4640 #[stable(feature = "rust1", since = "1.0.0")]
4641 pub enum FpCategory {
4642 /// "Not a Number", often obtained by dividing by zero.
4643 #[stable(feature = "rust1", since = "1.0.0")]
4646 /// Positive or negative infinity.
4647 #[stable(feature = "rust1", since = "1.0.0")]
4650 /// Positive or negative zero.
4651 #[stable(feature = "rust1", since = "1.0.0")]
4654 /// De-normalized floating point representation (less precise than `Normal`).
4655 #[stable(feature = "rust1", since = "1.0.0")]
4658 /// A regular floating point number.
4659 #[stable(feature = "rust1", since = "1.0.0")]
4663 macro_rules! from_str_radix_int_impl {
4665 #[stable(feature = "rust1", since = "1.0.0")]
4666 impl FromStr for $t {
4667 type Err = ParseIntError;
4668 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4669 from_str_radix(src, 10)
4674 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4676 /// The error type returned when a checked integral type conversion fails.
4677 #[stable(feature = "try_from", since = "1.34.0")]
4678 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4679 pub struct TryFromIntError(());
4681 impl TryFromIntError {
4682 #[unstable(feature = "int_error_internals",
4683 reason = "available through Error trait and this method should \
4684 not be exposed publicly",
4687 pub fn __description(&self) -> &str {
4688 "out of range integral type conversion attempted"
4692 #[stable(feature = "try_from", since = "1.34.0")]
4693 impl fmt::Display for TryFromIntError {
4694 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
4695 self.__description().fmt(fmt)
4699 #[stable(feature = "try_from", since = "1.34.0")]
4700 impl From<Infallible> for TryFromIntError {
4701 fn from(x: Infallible) -> TryFromIntError {
4706 #[unstable(feature = "never_type", issue = "35121")]
4707 impl From<!> for TryFromIntError {
4708 fn from(never: !) -> TryFromIntError {
4709 // Match rather than coerce to make sure that code like
4710 // `From<Infallible> for TryFromIntError` above will keep working
4711 // when `Infallible` becomes an alias to `!`.
4716 // no possible bounds violation
4717 macro_rules! try_from_unbounded {
4718 ($source:ty, $($target:ty),*) => {$(
4719 #[stable(feature = "try_from", since = "1.34.0")]
4720 impl TryFrom<$source> for $target {
4721 type Error = TryFromIntError;
4723 /// Try to create the target number type from a source
4724 /// number type. This returns an error if the source value
4725 /// is outside of the range of the target type.
4727 fn try_from(value: $source) -> Result<Self, Self::Error> {
4728 Ok(value as $target)
4734 // only negative bounds
4735 macro_rules! try_from_lower_bounded {
4736 ($source:ty, $($target:ty),*) => {$(
4737 #[stable(feature = "try_from", since = "1.34.0")]
4738 impl TryFrom<$source> for $target {
4739 type Error = TryFromIntError;
4741 /// Try to create the target number type from a source
4742 /// number type. This returns an error if the source value
4743 /// is outside of the range of the target type.
4745 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4749 Err(TryFromIntError(()))
4756 // unsigned to signed (only positive bound)
4757 macro_rules! try_from_upper_bounded {
4758 ($source:ty, $($target:ty),*) => {$(
4759 #[stable(feature = "try_from", since = "1.34.0")]
4760 impl TryFrom<$source> for $target {
4761 type Error = TryFromIntError;
4763 /// Try to create the target number type from a source
4764 /// number type. This returns an error if the source value
4765 /// is outside of the range of the target type.
4767 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4768 if u > (<$target>::max_value() as $source) {
4769 Err(TryFromIntError(()))
4779 macro_rules! try_from_both_bounded {
4780 ($source:ty, $($target:ty),*) => {$(
4781 #[stable(feature = "try_from", since = "1.34.0")]
4782 impl TryFrom<$source> for $target {
4783 type Error = TryFromIntError;
4785 /// Try to create the target number type from a source
4786 /// number type. This returns an error if the source value
4787 /// is outside of the range of the target type.
4789 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4790 let min = <$target>::min_value() as $source;
4791 let max = <$target>::max_value() as $source;
4792 if u < min || u > max {
4793 Err(TryFromIntError(()))
4803 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4804 $mac!($target, $source);
4808 // intra-sign conversions
4809 try_from_upper_bounded!(u16, u8);
4810 try_from_upper_bounded!(u32, u16, u8);
4811 try_from_upper_bounded!(u64, u32, u16, u8);
4812 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4814 try_from_both_bounded!(i16, i8);
4815 try_from_both_bounded!(i32, i16, i8);
4816 try_from_both_bounded!(i64, i32, i16, i8);
4817 try_from_both_bounded!(i128, i64, i32, i16, i8);
4819 // unsigned-to-signed
4820 try_from_upper_bounded!(u8, i8);
4821 try_from_upper_bounded!(u16, i8, i16);
4822 try_from_upper_bounded!(u32, i8, i16, i32);
4823 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4824 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4826 // signed-to-unsigned
4827 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4828 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4829 try_from_lower_bounded!(i32, u32, u64, u128);
4830 try_from_lower_bounded!(i64, u64, u128);
4831 try_from_lower_bounded!(i128, u128);
4832 try_from_both_bounded!(i16, u8);
4833 try_from_both_bounded!(i32, u16, u8);
4834 try_from_both_bounded!(i64, u32, u16, u8);
4835 try_from_both_bounded!(i128, u64, u32, u16, u8);
4838 try_from_upper_bounded!(usize, isize);
4839 try_from_lower_bounded!(isize, usize);
4841 #[cfg(target_pointer_width = "16")]
4842 mod ptr_try_from_impls {
4843 use super::TryFromIntError;
4844 use crate::convert::TryFrom;
4846 try_from_upper_bounded!(usize, u8);
4847 try_from_unbounded!(usize, u16, u32, u64, u128);
4848 try_from_upper_bounded!(usize, i8, i16);
4849 try_from_unbounded!(usize, i32, i64, i128);
4851 try_from_both_bounded!(isize, u8);
4852 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4853 try_from_both_bounded!(isize, i8);
4854 try_from_unbounded!(isize, i16, i32, i64, i128);
4856 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4857 rev!(try_from_lower_bounded, usize, i8, i16);
4858 rev!(try_from_both_bounded, usize, i32, i64, i128);
4860 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4861 rev!(try_from_both_bounded, isize, i32, i64, i128);
4864 #[cfg(target_pointer_width = "32")]
4865 mod ptr_try_from_impls {
4866 use super::TryFromIntError;
4867 use crate::convert::TryFrom;
4869 try_from_upper_bounded!(usize, u8, u16);
4870 try_from_unbounded!(usize, u32, u64, u128);
4871 try_from_upper_bounded!(usize, i8, i16, i32);
4872 try_from_unbounded!(usize, i64, i128);
4874 try_from_both_bounded!(isize, u8, u16);
4875 try_from_lower_bounded!(isize, u32, u64, u128);
4876 try_from_both_bounded!(isize, i8, i16);
4877 try_from_unbounded!(isize, i32, i64, i128);
4879 rev!(try_from_unbounded, usize, u32);
4880 rev!(try_from_upper_bounded, usize, u64, u128);
4881 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4882 rev!(try_from_both_bounded, usize, i64, i128);
4884 rev!(try_from_unbounded, isize, u16);
4885 rev!(try_from_upper_bounded, isize, u32, u64, u128);
4886 rev!(try_from_unbounded, isize, i32);
4887 rev!(try_from_both_bounded, isize, i64, i128);
4890 #[cfg(target_pointer_width = "64")]
4891 mod ptr_try_from_impls {
4892 use super::TryFromIntError;
4893 use crate::convert::TryFrom;
4895 try_from_upper_bounded!(usize, u8, u16, u32);
4896 try_from_unbounded!(usize, u64, u128);
4897 try_from_upper_bounded!(usize, i8, i16, i32, i64);
4898 try_from_unbounded!(usize, i128);
4900 try_from_both_bounded!(isize, u8, u16, u32);
4901 try_from_lower_bounded!(isize, u64, u128);
4902 try_from_both_bounded!(isize, i8, i16, i32);
4903 try_from_unbounded!(isize, i64, i128);
4905 rev!(try_from_unbounded, usize, u32, u64);
4906 rev!(try_from_upper_bounded, usize, u128);
4907 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4908 rev!(try_from_both_bounded, usize, i128);
4910 rev!(try_from_unbounded, isize, u16, u32);
4911 rev!(try_from_upper_bounded, isize, u64, u128);
4912 rev!(try_from_unbounded, isize, i32, i64);
4913 rev!(try_from_both_bounded, isize, i128);
4917 trait FromStrRadixHelper: PartialOrd + Copy {
4918 fn min_value() -> Self;
4919 fn max_value() -> Self;
4920 fn from_u32(u: u32) -> Self;
4921 fn checked_mul(&self, other: u32) -> Option<Self>;
4922 fn checked_sub(&self, other: u32) -> Option<Self>;
4923 fn checked_add(&self, other: u32) -> Option<Self>;
4927 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4929 fn min_value() -> Self { Self::min_value() }
4931 fn max_value() -> Self { Self::max_value() }
4933 fn from_u32(u: u32) -> Self { u as Self }
4935 fn checked_mul(&self, other: u32) -> Option<Self> {
4936 Self::checked_mul(*self, other as Self)
4939 fn checked_sub(&self, other: u32) -> Option<Self> {
4940 Self::checked_sub(*self, other as Self)
4943 fn checked_add(&self, other: u32) -> Option<Self> {
4944 Self::checked_add(*self, other as Self)
4948 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4950 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4951 use self::IntErrorKind::*;
4952 use self::ParseIntError as PIE;
4954 assert!(radix >= 2 && radix <= 36,
4955 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4959 return Err(PIE { kind: Empty });
4962 let is_signed_ty = T::from_u32(0) > T::min_value();
4964 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4965 // and cast them to chars. .to_digit() will safely return None for anything
4966 // other than a valid ascii digit for the given radix, including the first-byte
4967 // of multi-byte sequences
4968 let src = src.as_bytes();
4970 let (is_positive, digits) = match src[0] {
4971 b'+' => (true, &src[1..]),
4972 b'-' if is_signed_ty => (false, &src[1..]),
4976 if digits.is_empty() {
4977 return Err(PIE { kind: Empty });
4980 let mut result = T::from_u32(0);
4982 // The number is positive
4984 let x = match (c as char).to_digit(radix) {
4986 None => return Err(PIE { kind: InvalidDigit }),
4988 result = match result.checked_mul(radix) {
4989 Some(result) => result,
4990 None => return Err(PIE { kind: Overflow }),
4992 result = match result.checked_add(x) {
4993 Some(result) => result,
4994 None => return Err(PIE { kind: Overflow }),
4998 // The number is negative
5000 let x = match (c as char).to_digit(radix) {
5002 None => return Err(PIE { kind: InvalidDigit }),
5004 result = match result.checked_mul(radix) {
5005 Some(result) => result,
5006 None => return Err(PIE { kind: Underflow }),
5008 result = match result.checked_sub(x) {
5009 Some(result) => result,
5010 None => return Err(PIE { kind: Underflow }),
5017 /// An error which can be returned when parsing an integer.
5019 /// This error is used as the error type for the `from_str_radix()` functions
5020 /// on the primitive integer types, such as [`i8::from_str_radix`].
5022 /// # Potential causes
5024 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5025 /// in the string e.g., when it is obtained from the standard input.
5026 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5028 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5029 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5030 #[derive(Debug, Clone, PartialEq, Eq)]
5031 #[stable(feature = "rust1", since = "1.0.0")]
5032 pub struct ParseIntError {
5036 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5037 #[unstable(feature = "int_error_matching",
5038 reason = "it can be useful to match errors when making error messages \
5039 for integer parsing",
5041 #[derive(Debug, Clone, PartialEq, Eq)]
5043 pub enum IntErrorKind {
5044 /// Value being parsed is empty.
5046 /// Among other causes, this variant will be constructed when parsing an empty string.
5048 /// Contains an invalid digit.
5050 /// Among other causes, this variant will be constructed when parsing a string that
5051 /// contains a letter.
5053 /// Integer is too large to store in target integer type.
5055 /// Integer is too small to store in target integer type.
5059 /// This variant will be emitted when the parsing string has a value of zero, which
5060 /// would be illegal for non-zero types.
5064 impl ParseIntError {
5065 /// Outputs the detailed cause of parsing an integer failing.
5066 #[unstable(feature = "int_error_matching",
5067 reason = "it can be useful to match errors when making error messages \
5068 for integer parsing",
5070 pub fn kind(&self) -> &IntErrorKind {
5073 #[unstable(feature = "int_error_internals",
5074 reason = "available through Error trait and this method should \
5075 not be exposed publicly",
5078 pub fn __description(&self) -> &str {
5080 IntErrorKind::Empty => "cannot parse integer from empty string",
5081 IntErrorKind::InvalidDigit => "invalid digit found in string",
5082 IntErrorKind::Overflow => "number too large to fit in target type",
5083 IntErrorKind::Underflow => "number too small to fit in target type",
5084 IntErrorKind::Zero => "number would be zero for non-zero type",
5089 #[stable(feature = "rust1", since = "1.0.0")]
5090 impl fmt::Display for ParseIntError {
5091 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5092 self.__description().fmt(f)
5096 #[stable(feature = "rust1", since = "1.0.0")]
5097 pub use crate::num::dec2flt::ParseFloatError;
5099 // Conversion traits for primitive integer and float types
5100 // Conversions T -> T are covered by a blanket impl and therefore excluded
5101 // Some conversions from and to usize/isize are not implemented due to portability concerns
5102 macro_rules! impl_from {
5103 ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
5106 impl From<$Small> for $Large {
5108 fn from(small: $Small) -> $Large {
5113 ($Small: ty, $Large: ty, #[$attr:meta]) => {
5117 concat!("Converts `",
5125 macro_rules! impl_from_bool {
5126 ($target: ty, #[$attr:meta]) => {
5127 impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
5128 stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
5134 assert_eq!(", stringify!($target), "::from(true), 1);
5135 assert_eq!(", stringify!($target), "::from(false), 0);
5141 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
5142 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
5143 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
5144 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
5145 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
5146 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
5147 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
5148 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
5149 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
5150 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
5151 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
5152 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
5154 // Unsigned -> Unsigned
5155 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5156 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5157 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5158 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
5159 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5160 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5161 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5162 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
5163 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5164 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
5165 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
5168 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5169 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5170 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5171 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5172 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5173 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5174 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5175 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5176 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5177 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5178 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5180 // Unsigned -> Signed
5181 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5182 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5183 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5184 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5185 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5186 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5187 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5188 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5189 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5190 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5192 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
5193 // which imply that pointer-sized integers must be at least 16 bits:
5194 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
5195 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5196 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5197 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5199 // RISC-V defines the possibility of a 128-bit address space (RV128).
5201 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
5202 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
5203 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
5206 // Note: integers can only be represented with full precision in a float if
5207 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
5208 // Lossy float conversions are not implemented at this time.
5211 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5212 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5213 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5214 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5215 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5217 // Unsigned -> Float
5218 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5219 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5220 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5221 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5222 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5225 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }